summaryrefslogtreecommitdiff
path: root/archaeological_files/models.py
blob: 68a65f6de6bdb33ae2b27b55023c272472cbd4f8 (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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (C) 2012 É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 datetime

from django.conf import settings
from django.contrib.gis.db import models
from django.utils.translation import ugettext_lazy as _, ugettext

from ishtar_common.models import GeneralType, BaseHistorizedItem, \
    HistoricalRecords, OwnPerms, Person, Organization, Department, Town

class FileType(GeneralType):
    class Meta:
        verbose_name = _(u"Archaeological file type")
        verbose_name_plural = _(u"Archaeological file types")

    @classmethod
    def is_preventive(cls, file_type_id, key=''):
        key = key or 'preventive'
        try:
            preventive = FileType.objects.get(txt_idx=key).pk
            return file_type_id == preventive
        except ObjectDoesNotExist:
            return False

class PermitType(GeneralType):
    class Meta:
        verbose_name = _(u"Permit type")
        verbose_name_plural = _(u"Permit types")

if settings.COUNTRY == 'fr':
    class SaisineType(GeneralType):
        delay = models.IntegerField(_(u"Delay (in days)"))
        class Meta:
            verbose_name = u"Type Saisine"
            verbose_name_plural = u"Types Saisine"

class File(BaseHistorizedItem, OwnPerms):
    TABLE_COLS = ['numeric_reference', 'year', 'internal_reference',
                  'file_type', 'saisine_type', 'towns', ]
    year = models.IntegerField(_(u"Year"),
                               default=lambda:datetime.datetime.now().year)
    numeric_reference = models.IntegerField(_(u"Numeric reference"))
    internal_reference = models.CharField(_(u"Internal reference"),
                                          max_length=60, unique=True)
    file_type = models.ForeignKey(FileType, verbose_name=_(u"File type"))
    in_charge = models.ForeignKey(Person, related_name='+',
                                  verbose_name=_(u"Person in charge"))
    general_contractor = models.ForeignKey(Person, related_name='+',
               verbose_name=_(u"General contractor"), blank=True, null=True)
    town_planning_service = models.ForeignKey(Organization, related_name='+',
               verbose_name=_(u"Town planning service"), blank=True, null=True)
    permit_type = models.ForeignKey(PermitType, verbose_name=_(u"Permit type"),
                                                          blank=True, null=True)
    permit_reference = models.CharField(_(u"Permit reference"),
                                          max_length=60, blank=True, null=True)
    end_date = models.DateField(_(u"Closing date"), null=True, blank=True)
    towns = models.ManyToManyField(Town, verbose_name=_(u"Towns"),
                                   related_name='file')
    creation_date = models.DateField(_(u"Creation date"),
                                     default=datetime.date.today)
    reception_date = models.DateField(_(u'Reception date'), blank=True,
                                      null=True)
    related_file = models.ForeignKey("File", verbose_name=_(u"Related file"),
                                     blank=True, null=True)
    if settings.COUNTRY == 'fr':
        saisine_type = models.ForeignKey(SaisineType, blank=True, null=True,
                                         verbose_name= u"Type de saisine")
        reference_number = models.IntegerField(_(u"Reference number"),
                                               blank=True, null=True)
    total_surface = models.IntegerField(_(u"Total surface (m²)"),
                                        blank=True, null=True)
    total_developed_surface = models.IntegerField(
            _(u"Total developed surface (m²)"), blank=True, null=True)
    address = models.TextField(_(u"Main address"), null=True, blank=True)
    address_complement = models.TextField(_(u"Main address - complement"),
                                          null=True, blank=True)
    postal_code = models.CharField(_(u"Main address - postal code"),
                                   max_length=10, null=True, blank=True)
    comment = models.TextField(_(u"Comment"), null=True, blank=True)
    history = HistoricalRecords()

    class Meta:
        verbose_name = _(u"Archaeological file")
        verbose_name_plural = _(u"Archaeological files")
        permissions = (
            ("view_own_file", ugettext(u"Can view own Archaelogical file")),
            ("add_own_file", ugettext(u"Can add own Archaelogical file")),
            ("change_own_file", ugettext(u"Can change own Archaelogical file")),
            ("delete_own_file", ugettext(u"Can delete own Archaelogical file")),
        )
        ordering = ['-year', '-numeric_reference']

    @classmethod
    def get_years(cls):
        return [res['year'] for res in list(cls.objects.values('year').annotate(
                                             Count("id")).order_by())]

    @classmethod
    def get_by_year(cls, year):
        return cls.objects.filter(year=year)

    @classmethod
    def get_total_number(cls):
        return cls.objects.count()

    def __unicode__(self):
        items = [unicode(_('Intercommunal'))]
        if self.towns.count() == 1:
            items[0] = unicode(self.towns.all()[0])
        items.append("-".join((unicode(self.year),
                               unicode(self.numeric_reference))))
        items += [unicode(getattr(self, k))[:36]
                  for k in ['internal_reference',] if getattr(self, k)]
        return JOINT.join(items)

    @classmethod
    def get_query_owns(cls, user):
        return Q(history_modifier=user) & Q(end_date__isnull=True)

    def is_active(self):
        return not bool(self.end_date)

    def closing(self):
        if self.is_active():
            return
        for item in self.history.all():
            if not item.end_date:
                break
        return {'date':item.history_date,
                'user':IshtarUser.objects.get(pk=item.history_modifier_id)}

    def total_surface_ha(self):
        if self.total_surface:
            return self.total_surface/10000.0

    def total_developed_surface_ha(self):
        if self.total_developed_surface:
            return self.total_developed_surface/10000.0

    def operation_acts(self):
        acts = []
        for ope in self.operations.all():
            for act in ope.administrative_act.all():
                acts.append(act)
        return acts

    def is_preventive(self):
        return FileType.is_preventive(self.file_type.pk)

class FileByDepartment(models.Model):
    '''
    Database view: don't forget to create it

    create view file_department (id, department_id, file_id) as
        select town."id", town."departement_id", file_towns."file_id"
            from ishtar_base_town town
        inner join ishtar_base_file_towns file_towns on
            file_towns."town_id"=town."id" order by town."departement_id";
    CREATE RULE file_department_delete
                            AS ON DELETE TO file_department DO INSTEAD();
    '''
    file = models.ForeignKey(File, verbose_name=_(u"File"))
    department = models.ForeignKey(Department, verbose_name=_(u"Department"),
                                   blank=True, null=True)
    class Meta:
        managed = False
        db_table = 'file_department'