summaryrefslogtreecommitdiff
path: root/archaeological_operations/views.py
blob: 0c4609181c794f1307636c5cd47c0cf73696f7ce (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
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
#!/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.

import json
import os

from django.core.urlresolvers import reverse
from django.db.models import Q
from django.http import HttpResponse
from django.shortcuts import render_to_response, redirect
from django.template.defaultfilters import slugify
from django.utils.translation import ugettext_lazy as _, pgettext_lazy

from ishtar_common.views import get_item, show_item, revert_item, new_item
from ishtar_common.wizards import SearchWizard
from wizards import *
from forms import *
import models

def autocomplete_patriarche(request, non_closed=True):
    if (not request.user.has_perm('ishtar_common.view_operation',
                                  models.Operation)
        and not request.user.has_perm('ishtar_common.view_own_operation',
                                      models.Operation)
        and not request.user.ishtaruser.has_right('operation_search')):
        return HttpResponse(mimetype='text/plain')
    if not request.GET.get('term'):
        return HttpResponse(mimetype='text/plain')
    q = request.GET.get('term')
    query = Q()
    for q in q.split(' '):
        query = query & Q(code_patriarche__startswith=q)
    if non_closed:
        query = query & Q(end_date__isnull=True)
    limit = 15
    operations = models.Operation.objects.filter(query).order_by('code_patriarche')[:limit]
    data = json.dumps([{'id':operation.code_patriarche,
                        'value':operation.code_patriarche}
                         for operation in operations])
    return HttpResponse(data, mimetype='text/plain')

def autocomplete_archaeologicalsite(request):
    if (not request.user.has_perm(
                      'archaeological_operations.view_archaeologicalsite',
                      models.ArchaeologicalSite)
        and not request.user.has_perm(
                      'archaeological_operations.view_own_archaeologicalsite',
                      models.ArchaeologicalSite)):
        return HttpResponse(mimetype='text/plain')
    if not request.GET.get('term'):
        return HttpResponse(mimetype='text/plain')
    q = request.GET.get('term')
    query = Q()
    for q in q.split(' '):
        qt = Q(reference__icontains=q) | Q(name__icontains=q)
        query = query & qt
    limit = 15
    sites = models.ArchaeologicalSite.objects.filter(query
                                        ).order_by('reference')[:limit]
    data = json.dumps([{'id':site.pk,
                        'value':unicode(site)[:60]}
                         for site in sites])
    return HttpResponse(data, mimetype='text/plain')

new_archaeologicalsite = new_item(models.ArchaeologicalSite,
                                  ArchaeologicalSiteForm)

def autocomplete_operation(request, non_closed=True):
    person_types = request.user.ishtaruser.person.person_type
    if (not request.user.has_perm('ishtar_common.view_operation',
                                  models.Operation)
        and not request.user.has_perm('ishtar_common.view_own_operation',
                                      models.Operation)
        and not request.user.ishtaruser.has_right('operation_search')):
        return HttpResponse(mimetype='text/plain')
    if not request.GET.get('term'):
        return HttpResponse(mimetype='text/plain')
    q = request.GET.get('term')
    query = Q()
    for q in q.split(' '):
        extra = Q(towns__name__icontains=q)
        try:
            value = int(q)
            extra = extra | Q(year=q) | Q(operation_code=q)
        except ValueError:
            pass
        query = query & extra
    if non_closed:
        query = query & Q(end_date__isnull=True)
    limit = 15
    operations = models.Operation.objects.filter(query)[:limit]
    data = json.dumps([{'id':operation.pk, 'value':unicode(operation)}
                                          for operation in operations])
    return HttpResponse(data, mimetype='text/plain')

def get_available_operation_code(request, year=None):
    if not request.user.has_perm('ishtar_common.view_operation',
                                 models.Operation)\
       and not request.user.has_perm('ishtar_common.view_own_operation',
                                     models.Operation):
        return HttpResponse(mimetype='text/plain')
    data = json.dumps({'id':models.Operation.get_available_operation_code(year)})
    return HttpResponse(data, mimetype='text/plain')

get_operation = get_item(models.Operation, 'get_operation', 'operation',
    bool_fields = ['end_date__isnull'],
    dated_fields = ['start_date__lte', 'start_date__gte',
                    'excavation_end_date__lte', 'excavation_end_date__gte'],
    extra_request_keys={'common_name':'common_name__icontains',
                        'end_date':'end_date__isnull',
                        'year_index':('year', 'operation_code'),
                        'start_before':'start_date__lte',
                        'start_after':'start_date__gte',
                        'end_before':'excavation_end_date__lte',
                        'end_after':'excavation_end_date__gte',
                        'parcel_0':('parcels__section',
                                    'associated_file__parcels__section'),
                        'parcel_1':('parcels__parcel_number',
                                    'associated_file__parcels__parcel_number'),
                        },
    )
show_operation = show_item(models.Operation, 'operation')
revert_operation = revert_item(models.Operation)

get_operationsource = get_item(models.OperationSource,
    'get_operationsource', 'operationsource',
    extra_request_keys={'operation__towns':'operation__towns__pk',
                  'operation__operation_type':'operation__operation_type__pk',
                  'operation__year':'operation__year'})

get_administrativeactop = get_item(models.AdministrativeAct,
    'get_administrativeactop', 'administrativeactop',
    extra_request_keys={'associated_file__towns':'associated_file__towns__pk',
                        'operation__towns':'operation__towns__pk',
                        'act_type__intented_to':'act_type__intented_to'})

get_administrativeact = get_item(models.AdministrativeAct,
    'get_administrativeact', 'administrativeact',
    extra_request_keys={})

def dashboard_operation(request, *args, **kwargs):
    """
    Operation dashboard
    """
    dct = {'dashboard': models.OperationDashboard()}
    return render_to_response('ishtar/dashboards/dashboard_operation.html', dct,
                              context_instance=RequestContext(request))

operation_search_wizard = SearchWizard.as_view([
    ('general-operation_search', OperationFormSelection)],
    label=_(u"Operation search"),
    url_name='operation_search',)

operation_creation_wizard = OperationWizard.as_view([
    ('general-operation_creation', OperationFormGeneral),
    ('preventive-operation_creation', OperationFormPreventive),
    ('preventivediag-operation_creation', OperationFormPreventiveDiag),
    ('townsgeneral-operation_creation', TownFormset),
    ('towns-operation_creation', SelectedTownFormset),
    ('parcelsgeneral-operation_creation', SelectedParcelGeneralFormSet),
    ('parcels-operation_creation', SelectedParcelFormSet),
    ('remains-operation_creation', RemainFormset),
    ('periods-operation_creation', PeriodFormset),
    ('final-operation_creation', FinalForm)],
    label=_(u"New operation"),
    condition_dict={
        'preventive-operation_creation':\
            is_preventive('general-operation_creation', models.OperationType,
            'operation_type', 'prev_excavation'),
        'preventivediag-operation_creation':\
            is_preventive('general-operation_creation', models.OperationType,
            'operation_type', 'arch_diagnostic'),
        'townsgeneral-operation_creation':has_associated_file(
            'general-operation_creation', negate=True),
        'towns-operation_creation':has_associated_file(
            'general-operation_creation'),
        'parcelsgeneral-operation_creation':has_associated_file(
            'general-operation_creation', negate=True),
        'parcels-operation_creation':has_associated_file(
            'general-operation_creation'),
    },
    url_name='operation_creation',)

operation_modification_wizard = OperationModificationWizard.as_view([
    ('selec-operation_modification', OperationFormSelection),
    ('general-operation_modification', OperationFormGeneral),
    ('preventive-operation_modification', OperationFormPreventive),
    ('preventivediag-operation_modification', OperationFormPreventiveDiag),
    ('towns-operation_modification', SelectedTownFormset),
    ('townsgeneral-operation_modification', TownFormset),
    ('parcels-operation_modification', SelectedParcelFormSet),
    ('parcelsgeneral-operation_modification', SelectedParcelGeneralFormSet),
    ('remains-operation_modification', RemainFormset),
    ('periods-operation_modification', PeriodFormset),
    ('final-operation_modification', FinalForm)],
    label=_(u"Operation modification"),
    condition_dict={
        'preventive-operation_modification':is_preventive(
            'general-operation_modification', models.OperationType,
            'operation_type', 'prev_excavation'),
        'preventivediag-operation_modification':is_preventive(
            'general-operation_modification', models.OperationType,
            'operation_type', 'arch_diagnostic'),
        'townsgeneral-operation_modification':has_associated_file(
            'general-operation_modification', negate=True),
        'towns-operation_modification':has_associated_file(
            'general-operation_modification'),
        'parcelsgeneral-operation_modification':has_associated_file(
            'general-operation_modification', negate=True),
        'parcels-operation_modification':has_associated_file(
            'general-operation_modification'),
         },
    url_name='operation_modification',)

def operation_modify(request, pk):
    view = operation_modification_wizard(request)
    OperationModificationWizard.session_set_value(request,
                        'selec-operation_modification', 'pk', pk, reset=True)
    return redirect(reverse('operation_modification',
                            kwargs={'step':'general-operation_modification'}))

operation_closing_wizard = OperationClosingWizard.as_view([
    ('selec-operation_closing', OperationFormSelection),
    ('date-operation_closing', ClosingDateFormSelection),
    ('final-operation_closing', FinalOperationClosingForm)],
    label=_(u"Operation closing"),
    url_name='operation_closing',)

operation_deletion_wizard = OperationDeletionWizard.as_view([
    ('selec-operation_deletion', OperationFormSelection),
    ('final-operation_deletion', OperationDeletionForm)],
    label=_(u"Operation deletion"),
    url_name='operation_deletion',)

operation_source_creation_wizard = OperationSourceWizard.as_view([
    ('selec-operation_source_creation', SourceOperationFormSelection),
    ('source-operation_source_creation',OperationSourceForm),
    ('authors-operation_source_creation', AuthorFormset),
    ('final-operation_source_creation', FinalForm)],
    label=_(u"Operation: source creation"),
    url_name='operation_source_creation',)

operation_source_modification_wizard = OperationSourceWizard.as_view([
    ('selec-operation_source_modification', OperationSourceFormSelection),
    ('source-operation_source_modification', OperationSourceForm),
    ('authors-operation_source_modification', AuthorFormset),
    ('final-operation_source_modification', FinalForm)],
    label=_(u"Operation: source modification"),
    url_name='operation_source_modification',)

operation_source_deletion_wizard = OperationSourceDeletionWizard.as_view([
    ('selec-operation_source_deletion', OperationSourceFormSelection),
    ('final-operation_source_deletion', SourceDeletionForm)],
    label=_(u"Operation: source deletion"),
    url_name='operation_source_deletion',)

operation_administrativeactop_wizard = \
                                OperationAdministrativeActWizard.as_view([
    ('selec-operation_administrativeactop', OperationFormSelection),
    ('administrativeact-operation_administrativeactop',
     AdministrativeActOpeForm),
    ('final-operation_administrativeactop', FinalForm)],
    label=_(u"Operation: new administrative act"),
    url_name='operation_administrativeactop',)

operation_administrativeactop_modification_wizard = \
                                OperationEditAdministrativeActWizard.as_view([
    ('selec-operation_administrativeactop_modification',
     AdministrativeActOpeFormSelection),
    ('administrativeact-operation_administrativeactop_modification',
     AdministrativeActOpeForm),
    ('final-operation_administrativeactop_modification', FinalForm)],
    label=_(u"Operation: administrative act modification"),
    url_name='operation_administrativeactop_modification',)

operation_administrativeactop_deletion_wizard = \
                                AdministrativeActDeletionWizard.as_view([
    ('selec-operation_administrativeactop_deletion',
     AdministrativeActOpeFormSelection),
    ('final-operation_administrativeactop_deletion',
     FinalAdministrativeActDeleteForm)],
    label=_(u"Operation: administrative act deletion"),
    url_name='operation_administrativeactop_deletion',)

administrativact_register_wizard = SearchWizard.as_view([
    ('general-administrativact_register',
                AdministrativeActRegisterFormSelection)],
    label=pgettext_lazy('admin act register',u"Register"),
    url_name='administrativact_register',)

def generatedoc_administrativeactop(request, pk, template_pk=None):
    if (not request.user.has_perm('ishtar_common.view_operation',
                                  models.Operation)
        and not request.user.has_perm('ishtar_common.view_own_operation',
                                      models.Operation)):
        return HttpResponse(mimetype='text/plain')
    try:
        act_file = models.AdministrativeAct.objects.get(pk=pk)
        doc = act_file.publish(template_pk)
    except models.AdministrativeAct.DoesNotExist:
        doc = None
    if doc:
        MIMES = {'odt':'application/vnd.oasis.opendocument.text',
                 'ods':'application/vnd.oasis.opendocument.spreadsheet'}
        ext = doc.split('.')[-1]
        doc_name = act_file.get_filename() + "." + ext
        mimetype = 'text/csv'
        if ext in MIMES:
            mimetype = MIMES[ext]
        response = HttpResponse(open(doc), mimetype=mimetype)
        response['Content-Disposition'] = 'attachment; filename=%s' % \
                                                                doc_name
        return response
    return HttpResponse(mimetype='text/plain')

def administrativeactfile_document(request, operation=True):
    dct = {}
    if request.POST:
        dct['search_form'] = AdministrativeActOperationFormSelection(
                                                              request.POST)
        dct['template_form'] = DocumentGenerationAdminActForm(request.POST,
                                                          operation=operation)
        if dct['search_form'].is_valid() and dct['template_form'].is_valid():
            return generatedoc_administrativeactop(request,
                    dct['search_form'].cleaned_data.get('pk'),
                    dct['template_form'].cleaned_data.get('document_template'))
    else:
        dct['search_form'] = AdministrativeActOpeFormSelection()
        dct['template_form'] = DocumentGenerationAdminActForm(
                                                        operation=operation)
    return render_to_response('ishtar/administrativeact_document.html', dct,
                              context_instance=RequestContext(request))