summaryrefslogtreecommitdiff
path: root/archaeological_files/forms.py
blob: 17b918ca93191c2b18a3053f2ba2f0ddd294ed42 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (C) 2010-2013  Étienne Loks  <etienne.loks_AT_peacefrogsDOTnet>

# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.

# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.

# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

# See the file COPYING for details.

"""
Files forms definitions
"""
import datetime

from django import forms
from django.conf import settings
from django.core import validators
from django.core.exceptions import ObjectDoesNotExist
from django.db.models import Max
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.utils.translation import ugettext_lazy as _
from django.utils.safestring import mark_safe

from ishtar_common.models import Person, PersonType, Town, Organization, \
                         OrganizationType, valid_id, is_unique, DocumentTemplate
from archaeological_operations.models import ActType, AdministrativeAct
import models
from ishtar_common.forms import FinalForm, FormSet, ClosingDateFormSelection, \
    formset_factory, get_now, reverse_lazy, TableSelect
from ishtar_common.forms_common import get_town_field, get_person_field
from archaeological_operations.forms import AdministrativeActOpeForm, \
    AdministrativeActOpeFormSelection, FinalAdministrativeActDeleteForm, \
    ParcelField
from ishtar_common import widgets

class FileSelect(TableSelect):
    towns = get_town_field()
    in_charge = get_person_field(label=_(u"Person in charge"),
                                 person_types=['sra_agent'])
    file_type = forms.ChoiceField(label=_("File type"), choices=[])
    saisine_type = forms.ChoiceField(label=_("Saisine type"), choices=[])
    year = forms.IntegerField(label=_("Year"))
    parcel = ParcelField(label=_("Parcel (section/number)"))
    end_date = forms.NullBooleanField(label=_(u"Is active?"), initial=True)

    def __init__(self, *args, **kwargs):
        super(FileSelect, self).__init__(*args, **kwargs)
        self.fields['saisine_type'].choices = models.SaisineType.get_types()
        self.fields['saisine_type'].help_text = models.SaisineType.get_help()
        self.fields['file_type'].choices = models.FileType.get_types()
        self.fields['file_type'].help_text = models.FileType.get_help()

    def get_input_ids(self):
        ids = super(FileSelect, self).get_input_ids()
        ids.pop(ids.index('parcel'))
        ids.append('parcel_0')
        ids.append('parcel_1')
        return ids

class FileFormSelection(forms.Form):
    form_label = _("Archaeological file search")
    associated_models = {'pk':models.File}
    currents = {'pk':models.File}
    pk = forms.IntegerField(label="", required=False,
       widget=widgets.JQueryJqGrid(reverse_lazy('get-file'),
        FileSelect, models.File, source_full=reverse_lazy('get-file-full')),
       validators=[valid_id(models.File)])

    def clean(self):
        cleaned_data = self.cleaned_data
        if 'pk' not in cleaned_data or not cleaned_data['pk']:
            raise forms.ValidationError(_(u"You should select a file."))
        return cleaned_data

class FileFormGeneral(forms.Form):
    form_label = _("General")
    associated_models = {'in_charge':Person,
                         'related_file':models.File,
                         'file_type':models.FileType}
    in_charge = forms.IntegerField(label=_("Person in charge"),
        widget=widgets.JQueryAutoComplete(reverse_lazy('autocomplete-person',
          args=[PersonType.objects.get(txt_idx='sra_agent').pk]),
        associated_model=Person, new=True),
        validators=[valid_id(Person)])
    year = forms.IntegerField(label=_("Year"),
                              initial=lambda:datetime.datetime.now().year,
                              validators=[validators.MinValueValidator(1900),
                                          validators.MaxValueValidator(2100)])
    numeric_reference = forms.IntegerField(label=_("Numeric reference"),
                widget=forms.HiddenInput, required=False)
    internal_reference = forms.CharField(label=_(u"Other reference"),
            max_length=60,
            validators=[is_unique(models.File, 'internal_reference')],
            required=False)
    name = forms.CharField(label=_(u"Name"), required=False)
    creation_date = forms.DateField(label=_(u"Creation date"),
                                    initial=get_now, widget=widgets.JQueryDate)
    file_type = forms.ChoiceField(label=_("File type"), choices=[])
    related_file = forms.IntegerField(label=_("Related file"), required=False,
         widget=widgets.JQueryAutoComplete(reverse_lazy('autocomplete-file'),
                                           associated_model=models.File),
         validators=[valid_id(models.File)])
    comment = forms.CharField(label=_(u"Comment"), widget=forms.Textarea,
                              required=False)

    def __init__(self, *args, **kwargs):
        super(FileFormGeneral, self).__init__(*args, **kwargs)
        self.fields['file_type'].choices = models.FileType.get_types()
        self.fields['file_type'].help_text = models.FileType.get_help()
        q = models.File.objects.filter(internal_reference__isnull=False
                       ).order_by('-pk')
        if q.count():
            lbl = self.fields['internal_reference'].label
            lbl += _(u"<br/>(last recorded: %s)") % (
                                    q.all()[0].internal_reference)
            self.fields['internal_reference'].label = mark_safe(lbl)

class FileFormGeneralRO(FileFormGeneral):
    year = forms.IntegerField(label=_(u"Year"),
                        widget=forms.TextInput(attrs={'readonly':True}))
    numeric_reference = forms.IntegerField(label=_(u"Numeric reference"),
                        widget=forms.TextInput(attrs={'readonly':True}))
    internal_reference = forms.CharField(label=_(u"Internal reference"),
                        widget=forms.TextInput(attrs={'readonly':True},))

class FileFormAddress(forms.Form):
    form_label = _(u"Address") 
    associated_models = {'town':Town}
    total_surface = forms.IntegerField(required=False,
                           widget=widgets.AreaWidget,
                           label=_(u"Total surface (m²)"),
                           validators=[validators.MinValueValidator(0),
                                       validators.MaxValueValidator(999999999)])
    address = forms.CharField(label=_(u"Main address"), widget=forms.Textarea)
    address_complement = forms.CharField(label=_(u"Main address - complement"),
                                         required=False)
    postal_code = forms.CharField(label=_(u"Main address - postal code"),
                                  max_length=10)

class FileFormPreventive(forms.Form):
    form_label = _(u"Preventive informations")
    associated_models = {'general_contractor':Person,
                         'saisine_type':models.SaisineType,
                         'permit_type':models.PermitType,
                         'responsible_town_planning_service':Person}
    general_contractor = forms.IntegerField(label=_(u"General contractor"),
            widget=widgets.JQueryAutoComplete(
                reverse_lazy('autocomplete-person',
                args=[PersonType.objects.get(txt_idx='general_contractor').pk]),
                associated_model=Person, new=True),
            validators=[valid_id(Person)])
    responsible_town_planning_service = forms.IntegerField(required=False,
            label=_(u"Responsible for town planning service"),
            widget=widgets.JQueryAutoComplete(
                reverse_lazy('autocomplete-person',
                    args=[PersonType.objects.get(
                        txt_idx='responsible_planning_service').pk]),
                    associated_model=Person, new=True),
            validators=[valid_id(Person)])
    permit_type = forms.ChoiceField(label=_(u"Permit type"), required=False,
                                    choices=[])
    permit_reference = forms.CharField(label=_(u"Permit reference"),
            required=False, validators=[validators.MaxLengthValidator(60)])
    total_developed_surface = forms.IntegerField(widget=widgets.AreaWidget,
           label=_(u"Total developed surface (m²)"),
           required=False, validators=[validators.MinValueValidator(0),
                                       validators.MaxValueValidator(999999999)])
    if settings.COUNTRY == 'fr':
        saisine_type = forms.ChoiceField(label=_(u"Saisine type"),
                                         choices=[])
    reception_date = forms.DateField(label=_(u"Reception date"),
                                     initial=get_now, widget=widgets.JQueryDate)
    def __init__(self, *args, **kwargs):
        super(FileFormPreventive, self).__init__(*args, **kwargs)
        self.fields['saisine_type'].choices = models.SaisineType.get_types()
        self.fields['saisine_type'].help_text = models.SaisineType.get_help()
        self.fields['permit_type'].choices = models.PermitType.get_types(
                                                              default='NP')
        self.fields['permit_type'].help_text = models.PermitType.get_help()

class FinalFileClosingForm(FinalForm):
    confirm_msg = " "
    confirm_end_msg = _(u"Would you like to close this archaeological file?")

class FinalFileDeleteForm(FinalForm):
    confirm_msg = " "
    confirm_end_msg = _(u"Would you like to delete this archaelogical file ?")

class DocumentGenerationAdminActForm(forms.Form):
    _associated_model = AdministrativeAct
    document_template = forms.ChoiceField(label=_("Template"), choices=[])

    def __init__(self, *args, **kwargs):
        super(DocumentGenerationAdminActForm, self).__init__(*args, **kwargs)
        self.fields['document_template'].choices = DocumentTemplate.get_tuples(
                    dct={'associated_object_name':
                         'archaeological_operations.models.AdministrativeAct'})

    def save(self, object_pk):
        try:
            c_object = self._associated_model.objects.get(pk=object_pk)
        except self._associated_model.DoesNotExist:
            return
        try:
            template = DocumentTemplate.objects.get(
                            pk=self.cleaned_data.get('document_template'))
        except DocumentTemplate.DoesNotExist:
            return
        return template.publish(c_object)

class AdministrativeActFileSelect(TableSelect):
    associated_file__towns = get_town_field()
    act_type = forms.ChoiceField(label=_("Act type"), choices=[])

    def __init__(self, *args, **kwargs):
        super(AdministrativeActFileSelect, self).__init__(*args, **kwargs)
        self.fields['act_type'].choices = ActType.get_types(
                                                   dct={'intented_to':'F'})
        self.fields['act_type'].help_text = ActType.get_help(
                                                   dct={'intented_to':'F'})

class AdministrativeActFileFormSelection(AdministrativeActOpeFormSelection):
    pk = forms.IntegerField(label="", required=False,
       widget=widgets.JQueryJqGrid(reverse_lazy('get-administrativeactfile'),
                      AdministrativeActFileSelect, AdministrativeAct,
                      table_cols='TABLE_COLS_FILE'),
       validators=[valid_id(AdministrativeAct)])

class AdministrativeActFileForm(AdministrativeActOpeForm):
    act_type = forms.ChoiceField(label=_(u"Act type"), choices=[])

    def __init__(self, *args, **kwargs):
        super(AdministrativeActFileForm, self).__init__(*args, **kwargs)
        self.fields['act_type'].choices = ActType.get_types(
                                                   dct={'intented_to':'F'})
        self.fields['act_type'].help_text = ActType.get_help(
                                                   dct={'intented_to':'F'})