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
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (C) 2010-2016 É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.
"""
Context records forms definitions
"""
from itertools import groupby
from django import forms
from django.conf import settings
from django.core import validators
from django.forms.formsets import formset_factory
from django.utils.translation import ugettext_lazy as _
from ishtar_common.models import valid_id, IshtarSiteProfile, Town
from archaeological_context_records import models
from ishtar_common.forms import FinalForm, FormSet, \
reverse_lazy, get_form_selection, TableSelect, ManageOldType, CustomForm, \
FieldType, CustomFormSearch, IshtarForm, FormHeader, HistorySelect
from ishtar_common.forms_common import get_town_field
from archaeological_operations.forms import OperationSelect, ParcelField, \
RecordRelationsForm as OpeRecordRelationsForm, RecordRelationsFormSetBase
from archaeological_operations.models import Period, Parcel, Operation, \
ArchaeologicalSite, RelationType as OpeRelationType
from archaeological_operations.widgets import OAWidget
from bootstrap_datepicker.widgets import DatePicker
from ishtar_common import widgets
class OperationFormSelection(CustomForm, forms.Form):
form_label = _("Operation")
form_admin_name = _(u"Context record - 010 - Operation choice")
form_slug = "contextrecord-010-operationchoice"
associated_models = {'operation': Operation}
currents = {'operation': Operation}
operation = forms.IntegerField(
label=_(u"Operation"), required=False,
widget=widgets.JQueryAutoComplete(
reverse_lazy('autocomplete-operation'),
associated_model=Operation),
validators=[valid_id(Operation)])
class RecordSelect(HistorySelect):
_model = models.ContextRecord
form_admin_name = _(u"Context record - 001 - Search")
form_slug = "contextrecord-001-search"
search_vector = forms.CharField(
label=_(u"Full text search"), widget=widgets.SearchWidget(
'archaeological-context-records', 'contextrecord'
))
label = forms.CharField(label=_(u"ID"), max_length=100)
town = get_town_field()
if settings.COUNTRY == 'fr':
operation__code_patriarche = forms.CharField(
max_length=500,
widget=OAWidget,
label=_(u"Code PATRIARCHE"))
operation__year = forms.IntegerField(label=_(u"Operation's year"))
operation__operation_code = forms.IntegerField(
label=_(u"Operation's number (index by year)"))
archaeological_site = forms.IntegerField(
label=_("Archaeological site"),
widget=widgets.JQueryAutoComplete(
reverse_lazy('autocomplete-archaeologicalsite'),
associated_model=ArchaeologicalSite),
validators=[valid_id(ArchaeologicalSite)])
ope_relation_types = forms.ChoiceField(
label=_(u"Search within related operations"), choices=[])
datings__period = forms.ChoiceField(label=_(u"Period"), choices=[])
unit = forms.ChoiceField(label=_(u"Unit type"), choices=[])
parcel = forms.CharField(label=_(u"Parcel"))
cr_relation_types = forms.ChoiceField(
label=_(u"Search within relations"), choices=[])
TYPES = [
FieldType('datings__period', Period),
FieldType('unit', models.Unit),
FieldType('cr_relation_types', models.RelationType),
FieldType('ope_relation_types', OpeRelationType),
]
def get_input_ids(self):
ids = super(RecordSelect, self).get_input_ids()
if 'cr_relation_types' in ids:
ids.pop(ids.index('cr_relation_types'))
for idx, c in enumerate(self.fields['cr_relation_types'].choices):
ids.append('cr_relation_types_{}'.format(idx))
if 'ope_relation_types' in ids:
ids.pop(ids.index('ope_relation_types'))
for idx, c in enumerate(self.fields['ope_relation_types'].choices):
ids.append('ope_relation_types_{}'.format(idx))
return ids
class RecordFormSelection(CustomFormSearch):
SEARCH_AND_SELECT = True
form_label = _("Context record search")
associated_models = {'pk': models.ContextRecord}
currents = {'pk': models.ContextRecord}
pk = forms.IntegerField(
label="", required=False,
widget=widgets.DataTable(
reverse_lazy('get-contextrecord'),
RecordSelect, models.ContextRecord,
gallery=True, map=True,
source_full=reverse_lazy('get-contextrecord-full')),
validators=[valid_id(models.ContextRecord)])
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 at least select one "
u"context record."))
return cleaned_data
class RecordFormGeneral(CustomForm, ManageOldType):
HEADERS = {}
form_label = _("General")
form_admin_name = _(u"Context record - 020 - General")
form_slug = "contextrecord-020-general"
file_upload = True
base_models = ["documentation"]
associated_models = {
'archaeological_site': ArchaeologicalSite,
'parcel': Parcel, 'unit': models.Unit, 'town': Town,
'documentation': models.DocumentationType,
'excavation_technic': models.ExcavationTechnicType}
pk = forms.IntegerField(required=False, widget=forms.HiddenInput)
operation_id = forms.IntegerField(widget=forms.HiddenInput)
parcel = forms.ChoiceField(label=_(u"Parcel"), choices=[])
town = forms.ChoiceField(label=_(u"Town"), choices=[], required=False)
archaeological_site = forms.ChoiceField(
label=" ", choices=[], required=False,
help_text=_(u"Only the items associated to the operation can be "
u"selected.")
)
label = forms.CharField(label=_(u"ID"),
validators=[validators.MaxLengthValidator(200)])
unit = forms.ChoiceField(label=_(u"Context record type"), required=False,
choices=[])
description = forms.CharField(label=_(u"Description"),
widget=forms.Textarea, required=False)
comment = forms.CharField(label=_(u"General comment"),
widget=forms.Textarea, required=False)
excavation_technic = forms.ChoiceField(
label=_(u"Excavation technique"), choices=[], required=False)
length = forms.FloatField(label=_(u"Length (m)"), required=False)
width = forms.FloatField(label=_(u"Width (m)"), required=False)
thickness = forms.FloatField(label=_(u"Thickness (m)"), required=False)
diameter = forms.FloatField(label=_(u"Diameter (m)"), required=False)
depth = forms.FloatField(label=_(u"Depth (m)"), required=False)
depth_of_appearance = forms.FloatField(
label=_(u"Depth of appearance (m)"), required=False)
opening_date = forms.DateField(label=_(u"Opening date"),
widget=DatePicker, required=False)
closing_date = forms.DateField(label=_(u"Closing date"),
widget=DatePicker, required=False)
documentation = forms.MultipleChoiceField(
label=_("Documentation"), choices=[], required=False,
widget=forms.CheckboxSelectMultiple)
location = forms.CharField(
label=_(u"Location"), widget=forms.Textarea,
required=False, validators=[validators.MaxLengthValidator(200)])
HEADERS['x'] = FormHeader(_(u"Coordinates"))
x = forms.FloatField(label=_(u"X"), required=False)
estimated_error_x = forms.FloatField(label=_(u"Estimated error for X"),
required=False)
y = forms.FloatField(label=_(u"Y"), required=False)
estimated_error_y = forms.FloatField(label=_(u"Estimated error for Y"),
required=False)
z = forms.FloatField(label=_(u"Z"), required=False)
estimated_error_z = forms.FloatField(label=_(u"Estimated error for Z"),
required=False)
spatial_reference_system = forms.ChoiceField(
label=_(u"Spatial Reference System"), required=False, choices=[])
TYPES = [
FieldType('unit', models.Unit),
FieldType('excavation_technic', models.ExcavationTechnicType),
FieldType('documentation', models.DocumentationType, is_multiple=True)
]
PROFILE_FILTER = {
'mapping': [
'x', 'get_first_base_find__y',
'z', 'get_first_base_find__estimated_error_x',
'estimated_error_y',
'estimated_error_z',
'spatial_reference_system'
],
}
def __init__(self, *args, **kwargs):
# TODO: simplify
operation = None
if 'data' in kwargs and kwargs['data'] and \
('operation' in kwargs['data'] or
'context_record' in kwargs['data']):
if 'operation' in kwargs['data']:
operation = kwargs['data'].pop('operation')
if type(operation) in (list, tuple):
operation = operation[0]
if not hasattr(operation, 'id'):
operation_id = operation
try:
operation = Operation.objects.get(pk=operation_id)
except Operation.DoesNotExist:
operation = None
# force operation modification
# if posted
if operation and kwargs['data']:
if hasattr(operation, 'id'):
kwargs['data'][kwargs['prefix'] + '-operation_id'] = \
operation.id
else:
kwargs['data'][kwargs['prefix'] + '-operation_id'] = \
operation
if 'context_record' in kwargs['data'] and \
kwargs['data']['context_record']:
operation = kwargs['data']['context_record'].operation
# clean data if not "real" data
# prefix_value = kwargs['prefix']
if not [k for k in kwargs['data'].keys()
if k.startswith(kwargs['prefix']) and kwargs['data'][k]]:
kwargs['data'] = None
if 'files' in kwargs:
kwargs.pop('files')
super(RecordFormGeneral, self).__init__(*args, **kwargs)
profile = IshtarSiteProfile.get_current_profile()
self.fields['parcel'].choices = [('', '--')]
if not profile.parcel_mandatory:
self.fields['parcel'].required = False
self.fields['town'].choices = [('', '--')]
else:
self.fields.pop('town')
site_label = IshtarSiteProfile.get_default_site_label()
self.fields['archaeological_site'].label = site_label
self.fields['archaeological_site'].choices = [('', '--')]
if operation:
self.fields['operation_id'].initial = operation.pk
parcels = operation.parcels.all()
sort = lambda x: (x.town.name, x.section)
parcels = sorted(parcels, key=sort)
for key, gparcels in groupby(parcels, sort):
self.fields['parcel'].choices.append(
(" - ".join([k for k in key if k]),
[(parcel.pk, parcel.short_label) for parcel in gparcels])
)
if len(self.fields['parcel'].choices) == 1 and \
'town' in self.fields:
# only the empty choice is available
self.fields.pop('parcel')
self.fields['town'].required = True
if 'town' in self.fields:
if self.fields['town'].required:
self.fields['town'].choices = [] # remove the empty choice
self.fields['town'].choices += [(t.pk, unicode(t))
for t in operation.towns.all()]
self.fields['archaeological_site'].choices += [
(site.pk, unicode(site))
for site in operation.archaeological_sites.all()
]
def clean(self):
# manage unique context record ID
cleaned_data = self.cleaned_data
operation_id = cleaned_data.get("operation_id")
label = cleaned_data.get("label")
cr = models.ContextRecord.objects.filter(
label=label, parcel__operation__pk=operation_id)
if 'pk' in cleaned_data and cleaned_data['pk']:
cr = cr.exclude(pk=int(cleaned_data['pk']))
if cr.count():
raise forms.ValidationError(_(u"This ID already exists for "
u"this operation."))
if not self.cleaned_data.get('parcel', None) and not \
self.cleaned_data.get('town', None):
raise forms.ValidationError(_(u"You have to choose a town or a "
u"parcel."))
return cleaned_data
class DatingForm(ManageOldType, forms.Form):
form_label = _("Dating")
base_model = 'dating'
associated_models = {'dating_type': models.DatingType,
'quality': models.DatingQuality,
'period': models.Period}
period = forms.ChoiceField(label=_("Period"), choices=[])
start_date = forms.IntegerField(label=_(u"Start date"), required=False)
end_date = forms.IntegerField(label=_(u"End date"), required=False)
quality = forms.ChoiceField(label=_("Quality"), required=False, choices=[])
dating_type = forms.ChoiceField(label=_("Dating type"), required=False,
choices=[])
TYPES = [
FieldType('dating_type', models.DatingType),
FieldType('quality', models.DatingQuality),
FieldType('period', models.Period)
]
DatingFormSet = formset_factory(DatingForm, can_delete=True,
formset=FormSet)
DatingFormSet.form_label = _("Dating")
DatingFormSet.form_admin_name = _(u"Context record - 030 - Dating")
DatingFormSet.form_slug = "contextrecord-030-datings"
class RecordRelationsForm(OpeRecordRelationsForm):
current_model = models.RelationType
current_related_model = models.ContextRecord
associated_models = {'right_record': models.ContextRecord,
'relation_type': models.RelationType}
right_record = forms.ChoiceField(
label=_(u"Context record"), choices=[], required=False)
def __init__(self, *args, **kwargs):
crs = None
if 'data' in kwargs and 'CONTEXT_RECORDS' in kwargs['data']:
crs = kwargs['data']['CONTEXT_RECORDS']
super(RecordRelationsForm, self).__init__(*args, **kwargs)
self.fields['relation_type'].choices = \
models.RelationType.get_types(
initial=self.init_data.get('relation_type'))
if crs:
self.fields['right_record'].choices = [('', '-' * 2)] + crs
RecordRelationsFormSet = formset_factory(
RecordRelationsForm, can_delete=True, formset=RecordRelationsFormSetBase)
RecordRelationsFormSet.form_label = _(u"Relations")
RecordRelationsFormSet.form_admin_name = _(u"Context record - 050 - Relations")
RecordRelationsFormSet.form_slug = "contextrecord-050-recordrelations"
class RecordFormInterpretation(CustomForm, ManageOldType, forms.Form):
form_label = _(u"Interpretation")
form_admin_name = _(u"Context record - 040 - Interpretation")
form_slug = "contextrecord-040-interpretation"
associated_models = {'activity': models.ActivityType,
'identification': models.IdentificationType}
datings_comment = forms.CharField(
label=_(u"Comments on dating"), required=False,
widget=forms.Textarea)
filling = forms.CharField(label=_(u"Filling"),
widget=forms.Textarea, required=False)
interpretation = forms.CharField(label=_(u"Interpretation"),
widget=forms.Textarea, required=False)
activity = forms.ChoiceField(label=_(u"Activity"), required=False,
choices=[])
identification = forms.ChoiceField(label=_("Identification"),
required=False, choices=[])
taq = forms.IntegerField(label=_(u"TAQ"), required=False)
taq_estimated = forms.IntegerField(label=_(u"Estimated TAQ"),
required=False)
tpq = forms.IntegerField(label=_(u"TPQ"), required=False)
tpq_estimated = forms.IntegerField(label=_(u"Estimated TPQ"),
required=False)
TYPES = [
FieldType('activity', models.ActivityType),
FieldType('identification', models.IdentificationType),
]
OperationRecordFormSelection = get_form_selection(
'OperationRecordFormSelection', _(u"Operation search"), 'operation_id',
Operation, OperationSelect, 'get-operation',
_(u"You should select an operation."))
class RecordDeletionForm(FinalForm):
confirm_msg = " "
confirm_end_msg = _(u"Would you like to delete this context record?")
class QAOperationCR(IshtarForm):
town = forms.ChoiceField(label=_(u"Town"), choices=[])
archaeological_site = forms.ChoiceField(
label=" ", choices=[], required=False,
help_text=_(u"Only the items associated to the operation can be "
u"selected.")
)
label = forms.CharField(label=_(u"ID"),
validators=[validators.MaxLengthValidator(200)])
unit = forms.ChoiceField(label=_(u"Context record type"), required=False,
choices=[])
TYPES = [
FieldType('unit', models.Unit),
]
def __init__(self, *args, **kwargs):
self.items = kwargs.pop('items')
super(QAOperationCR, self).__init__(*args, **kwargs)
site_label = IshtarSiteProfile.get_default_site_label()
self.fields['archaeological_site'].label = site_label
self.fields['archaeological_site'].choices = [('', '--')]
if not self.items:
return
operation = self.items[0]
self.fields['town'].choices = [(t.pk, unicode(t))
for t in operation.towns.all()]
self.fields['archaeological_site'].choices += [
(site.pk, unicode(site))
for site in operation.archaeological_sites.all()
]
def save(self, items):
operation = items[0]
cr = models.ContextRecord.objects.create(
town_id=self.cleaned_data['town'], operation=operation,
archaeological_site_id=
self.cleaned_data['archaeological_site'] or None,
label=self.cleaned_data['label'],
unit_id=self.cleaned_data['unit'] or None
)
|