summaryrefslogtreecommitdiff
path: root/archaeological_finds/forms.py
blob: 41eeaef3bda10b895c389f6223948586c9a8288b (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
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
#!/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.

"""
Finds 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.safestring import mark_safe
from django.utils.translation import ugettext_lazy as _

from ishtar_common.models import Person, valid_id, valid_ids
from archaeological_operations.models import Period, OperationType
from archaeological_context_records.models import DatingType, DatingQuality
from archaeological_warehouse.models import Warehouse
import models

from ishtar_common import widgets
from ishtar_common.forms import FinalForm, FormSet, FloatField, \
    formset_factory, get_now, get_form_selection, reverse_lazy, TableSelect
from ishtar_common.forms_common import get_town_field, \
    SourceForm, SourceSelect, SourceDeletionForm, AuthorFormset
from archaeological_context_records.forms import RecordFormSelection


class FindForm(forms.Form):
    file_upload = True
    form_label = _("Find")
    base_model = 'base_finds'
    associated_models = {'material_type':models.MaterialType,
                         'conservatory_state':models.ConservatoryState}
    label = forms.CharField(label=_(u"ID"),
                      validators=[validators.MaxLengthValidator(60)])
    description = forms.CharField(label=_("Description"),
                                  widget=forms.Textarea)
    base_finds__is_isolated = forms.NullBooleanField(label=_(u"Is isolated?"),
                                         required=False)
    material_type = forms.ChoiceField(label=_("Material type"), choices=[])
    conservatory_state = forms.ChoiceField(label=_(u"Conservatory state"),
                                           choices=[], required=False)
    volume = FloatField(label=_(u"Volume (l)"), required=False)
    weight = FloatField(label=_(u"Weight (g)"), required=False)
    find_number = forms.IntegerField(label=_(u"Find number"), required=False)
    image = forms.ImageField(label=_(u"Image"), help_text=mark_safe(
                   _(u"<p>Heavy images are resized to: %(width)dx%(height)d "
                     u"(ratio is preserved).</p>") % {
                                          'width':settings.IMAGE_MAX_SIZE[0],
                                          'height':settings.IMAGE_MAX_SIZE[1]}),
                             required=False, widget=widgets.ImageFileInput())

    def __init__(self, *args, **kwargs):
        super(FindForm, self).__init__(*args, **kwargs)
        self.fields['material_type'].choices = models.MaterialType.get_types()
        self.fields['material_type'].help_text = models.MaterialType.get_help()
        self.fields['conservatory_state'].choices = \
                                            models.ConservatoryState.get_types()
        self.fields['conservatory_state'].help_text = \
                                            models.ConservatoryState.get_help()

class DateForm(forms.Form):
    form_label = _("Dating")
    base_model = 'dating'
    associated_models = {'dating__dating_type':DatingType,
                         'dating__quality':DatingQuality,
                         'dating__period':Period}
    dating__period = forms.ChoiceField(label=_("Period"), choices=[])
    dating__start_date = forms.IntegerField(label=_(u"Start date"),
                                            required=False)
    dating__end_date = forms.IntegerField(label=_(u"End date"), required=False)
    dating__quality = forms.ChoiceField(label=_("Quality"), required=False,
                                        choices=[])
    dating__dating_type = forms.ChoiceField(label=_("Dating type"),
                                            required=False, choices=[])

    def __init__(self, *args, **kwargs):
        super(DateForm, self).__init__(*args, **kwargs)
        self.fields['dating__dating_type'].choices = DatingType.get_types()
        self.fields['dating__dating_type'].help_text = DatingType.get_help()
        self.fields['dating__period'].choices = Period.get_types()
        self.fields['dating__period'].help_text = Period.get_help()
        self.fields['dating__quality'].choices = DatingQuality.get_types()
        self.fields['dating__quality'].help_text = DatingQuality.get_help()

class FindSelect(TableSelect):
    base_finds__context_record__parcel__town = get_town_field()
    base_finds__context_record__operation__year = forms.IntegerField(
                                                             label=_(u"Year"))
    base_finds__context_record__operation__code_patriarche = \
                                 forms.IntegerField(label=_(u"Code PATRIARCHE"))
    dating__period = forms.ChoiceField(label=_(u"Period"), choices=[])
    # TODO search by warehouse
    material_type = forms.ChoiceField(label=_(u"Material type"), choices=[])
    conservatory_state = forms.ChoiceField(label=_(u"Conservatory state"),
                                           choices=[])
    base_finds__find__description = forms.CharField(label=_(u"Description"))
    base_finds__is_isolated = forms.NullBooleanField(label=_(u"Is isolated?"))
    image = forms.NullBooleanField(label=_(u"Has an image?"))

    def __init__(self, *args, **kwargs):
        super(FindSelect, self).__init__(*args, **kwargs)
        self.fields['dating__period'].choices = Period.get_types()
        self.fields['dating__period'].help_text = Period.get_help()
        self.fields['material_type'].choices = \
                                            models.MaterialType.get_types()
        self.fields['material_type'].help_text = \
                                            models.MaterialType.get_help()
        self.fields['conservatory_state'].choices = \
                                            models.ConservatoryState.get_types()
        self.fields['conservatory_state'].help_text = \
                                            models.ConservatoryState.get_help()

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

class BaseTreatmentForm(forms.Form):
    form_label = _(u"Base treatment")
    associated_models = {'treatment_type':models.TreatmentType,
                         'person':Person,
                         'location':Warehouse}
    treatment_type = forms.ChoiceField(label=_(u"Treatment type"), choices=[])
    person = forms.IntegerField(label=_(u"Person"),
         widget=widgets.JQueryAutoComplete(reverse_lazy('autocomplete-person'),
                                      associated_model=Person, new=True),
           validators=[valid_id(Person)])
    location = forms.IntegerField(label=_(u"Location"),
         widget=widgets.JQueryAutoComplete(
     reverse_lazy('autocomplete-warehouse'), associated_model=Warehouse,
     new=True),
     validators=[valid_id(Warehouse)])
    description = forms.CharField(label=_(u"Description"),
                                  widget=forms.Textarea, required=False)
    start_date = forms.DateField(label=_(u"Start date"), required=False,
                               widget=widgets.JQueryDate)
    end_date = forms.DateField(label=_(u"End date"), required=False,
                               widget=widgets.JQueryDate)

    def __init__(self, *args, **kwargs):
        super(BaseTreatmentForm, self).__init__(*args, **kwargs)
        self.fields['treatment_type'].choices = models.TreatmentType.get_types(
                                                exclude=['packaging'])
        self.fields['treatment_type'].help_text = models.TreatmentType.get_help(
                                                exclude=['packaging'])

class FindMultipleFormSelection(forms.Form):
    form_label = _(u"Upstream finds")
    associated_models = {'finds':models.Find}
    associated_labels = {'finds':_(u"Finds")}
    finds = forms.CharField(label="", required=False,
       widget=widgets.JQueryJqGrid(reverse_lazy('get-find'),
             FindSelect, models.Find, multiple=True, multiple_cols=[2, 3, 4]),
       validators=[valid_ids(models.Find)])

    def clean(self):
        if not 'finds' in self.cleaned_data or not self.cleaned_data['finds']:
            raise forms.ValidationError(_(u"You should at least select one "
                                          u"archaeological find."))
        return self.cleaned_data

def check_treatment(form_name, type_key, type_list=[], not_type_list=[]):
    type_list = [models.TreatmentType.objects.get(txt_idx=tpe).pk
                 for tpe in type_list]
    not_type_list = [models.TreatmentType.objects.get(txt_idx=tpe).pk
                 for tpe in not_type_list]
    def func(self, request, storage):
        if storage.prefix not in request.session or \
           'step_data' not in request.session[storage.prefix] or \
           form_name not in request.session[storage.prefix]['step_data'] or\
           form_name + '-' + type_key not in \
                     request.session[storage.prefix]['step_data'][form_name]:
            return False
        try:
            type = int(request.session[storage.prefix]['step_data']\
                                      [form_name][form_name+'-'+type_key])
            return (not type_list or type in type_list) \
                    and type not in not_type_list
        except ValueError:
            return False
    return func

class ResultFindForm(forms.Form):
    form_label = _(u"Resulting find")
    associated_models = {'material_type':models.MaterialType}
    label = forms.CharField(label=_(u"ID"),
                      validators=[validators.MaxLengthValidator(60)])
    description = forms.CharField(label=_(u"Precise description"),
                                  widget=forms.Textarea)
    material_type = forms.ChoiceField(label=_(u"Material type"), choices=[])
    volume = forms.IntegerField(label=_(u"Volume (l)"))
    weight = forms.IntegerField(label=_(u"Weight (g)"))
    find_number = forms.IntegerField(label=_(u"Find number"))

    def __init__(self, *args, **kwargs):
        super(ResultFindForm, self).__init__(*args, **kwargs)
        self.fields['material_type'].choices = models.MaterialType.get_types()
        self.fields['material_type'].help_text = models.MaterialType.get_help()

ResultFindFormSet = formset_factory(ResultFindForm, can_delete=True,
                                    formset=FormSet)
ResultFindFormSet.form_label = _(u"Resulting finds")

class UpstreamFindFormSelection(FindFormSelection):
    form_label = _(u"Upstream find")

#############################################
# Source management for archaelogical finds #
#############################################

SourceFindFormSelection = get_form_selection(
    'SourceFindFormSelection', _(u"Archaelogical find search"), 'find',
    models.Find, FindSelect, 'get-find',
    _(u"You should select an archaelogical find."))

class FindSourceSelect(SourceSelect):
    find__base_finds__context_record__operation__year = forms.IntegerField(
                                              label=_(u"Year of the operation"))
    find__dating__period = forms.ChoiceField(
            label=_(u"Period of the archaelogical find"), choices=[])
    find__material_type = forms.ChoiceField(
            label=_("Material type of the archaelogical find"), choices=[])
    find__description = forms.CharField(
            label=_(u"Description of the archaelogical find"))

    def __init__(self, *args, **kwargs):
        super(FindSourceSelect, self).__init__(*args, **kwargs)
        self.fields['find__dating__period'].choices = Period.get_types()
        self.fields['find__dating__period'].help_text = Period.get_help()
        self.fields['find__material_type'].choices = \
                                            models.MaterialType.get_types()
        self.fields['find__material_type'].help_text = \
                                            models.MaterialType.get_help()

FindSourceFormSelection = get_form_selection(
    'FindSourceFormSelection', _(u"Documentation search"), 'pk',
    models.FindSource, FindSourceSelect, 'get-findsource',
    _(u"You should select a document."))


"""
####################################
# Source management for treatments #
####################################

SourceTreatementFormSelection = get_form_selection(
    'SourceTreatmentFormSelection', _(u"Treatment search"), 'operation',
    models.Treatment, TreatmentSelect, 'get-treatment',
    _(u"You should select a treatment."))

class TreatmentSourceSelect(SourceSelect):
    operation__towns = get_town_field(label=_(u"Operation's town"))
    treatment__treatment_type = forms.ChoiceField(label=_(u"Operation type"),
                                                  choices=[])
    operation__year = forms.IntegerField(label=_(u"Operation's year"))

    def __init__(self, *args, **kwargs):
        super(OperationSourceSelect, self).__init__(*args, **kwargs)
        self.fields['operation__operation_type'].choices = \
                                                 OperationType.get_types()
        self.fields['operation__operation_type'].help_text = \
                                                 OperationType.get_help()

"""

"""
OperationSourceFormSelection = get_form_selection(
    'OperationSourceFormSelection', _(u"Documentation search"), 'pk',
    models.OperationSource, OperationSourceSelect, 'get-operationsource',
    _(u"You should select a document."))

operation_source_modification_wizard = OperationSourceWizard([
         ('selec-operation_source_modification', OperationSourceFormSelection),
         ('source-operation_source_modification', SourceForm),
         ('authors-operation_source_modification', AuthorFormset),
         ('final-operation_source_modification', FinalForm)],
          url_name='operation_source_modification',)

class OperationSourceDeletionWizard(DeletionWizard):
    model = models.OperationSource
    fields = ['operation', 'title', 'source_type', 'authors',]

operation_source_deletion_wizard = OperationSourceDeletionWizard([
         ('selec-operation_source_deletion', OperationSourceFormSelection),
         ('final-operation_source_deletion', SourceDeletionForm)],
          url_name='operation_source_deletion',)
"""