diff options
Diffstat (limited to 'archaeological_files/models.py')
| -rw-r--r-- | archaeological_files/models.py | 248 | 
1 files changed, 126 insertions, 122 deletions
| diff --git a/archaeological_files/models.py b/archaeological_files/models.py index 8e871e000..f79de4f98 100644 --- a/archaeological_files/models.py +++ b/archaeological_files/models.py @@ -34,6 +34,7 @@ from ishtar_common.models import GeneralType, BaseHistorizedItem, \  from archaeological_operations.models import get_values_town_related +  class FileType(GeneralType):      class Meta:          verbose_name = _(u"Archaeological file type") @@ -49,6 +50,7 @@ class FileType(GeneralType):          except FileType.DoesNotExist:              return False +  class PermitType(GeneralType):      class Meta:          verbose_name = _(u"Permit type") @@ -58,19 +60,21 @@ class PermitType(GeneralType):  if settings.COUNTRY == 'fr':      class SaisineType(GeneralType, ValueGetter):          delay = models.IntegerField(_(u"Delay (in days)"), default=30) +          class Meta:              verbose_name = u"Type Saisine"              verbose_name_plural = u"Types Saisine"              ordering = ('label',) +  class File(BaseHistorizedItem, OwnPerms, ValueGetter, ShortMenuItem,             DashboardFormItem):      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"), blank=True, -                                            null=True) +                               default=lambda: datetime.datetime.now().year) +    numeric_reference = models.IntegerField( +        _(u"Numeric reference"), blank=True, null=True)      internal_reference = models.CharField(_(u"Internal reference"), blank=True,                                            null=True, max_length=60)      name = models.CharField(_(u"Name"), max_length=100, blank=True, null=True) @@ -79,33 +83,35 @@ class File(BaseHistorizedItem, OwnPerms, ValueGetter, ShortMenuItem,                                    verbose_name=_(u"Person in charge"),                                    on_delete=models.SET_NULL,                                    blank=True, null=True) -    general_contractor = models.ForeignKey(Person, -               related_name='general_contractor_files', -               verbose_name=_(u"General contractor"), blank=True, null=True, -               on_delete=models.SET_NULL,) # aménageur - personne -    raw_general_contractor = models.CharField(_(u"General contractor (raw)"), -                                        max_length=200, blank=True, null=True) -    corporation_general_contractor = models.ForeignKey(Organization, -           related_name='general_contractor_files', -           verbose_name=_(u"General contractor - corporation"), blank=True, -           null=True, on_delete=models.SET_NULL,) # aménageur -    responsible_town_planning_service = models.ForeignKey(Person, -               related_name='responsible_town_planning_service_files', -               blank=True, null=True, -               verbose_name=_(u"Responsible for town planning service"), -               on_delete=models.SET_NULL,) # service instructeur - personne +    general_contractor = models.ForeignKey( +        Person, related_name='general_contractor_files', +        verbose_name=_(u"General contractor"), blank=True, null=True, +        on_delete=models.SET_NULL,)  # aménageur - personne +    raw_general_contractor = models.CharField(_( +        u"General contractor (raw)"), max_length=200, blank=True, null=True) +    corporation_general_contractor = models.ForeignKey( +        Organization, +        related_name='general_contractor_files', +        verbose_name=_(u"General contractor - corporation"), blank=True, +        null=True, on_delete=models.SET_NULL,)  # aménageur +    responsible_town_planning_service = models.ForeignKey( +        Person, related_name='responsible_town_planning_service_files', +        blank=True, null=True, +        verbose_name=_(u"Responsible for town planning service"), +        on_delete=models.SET_NULL,)  # service instructeur - personne      raw_town_planning_service = models.CharField( -                        _(u"Town planning service (raw)"), max_length=200, -                        blank=True, null=True) -    planning_service = models.ForeignKey( Organization, -           related_name='planning_service_files', -           blank=True, null=True, -           verbose_name=_(u"Planning service - corporation"), -           on_delete=models.SET_NULL,) # service instructeur -    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) +        _(u"Town planning service (raw)"), max_length=200, +        blank=True, null=True) +    planning_service = models.ForeignKey( +        Organization, +        related_name='planning_service_files', +        blank=True, null=True, +        verbose_name=_(u"Planning service - corporation"), +        on_delete=models.SET_NULL,)  # service instructeur +    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)      main_town = models.ForeignKey(Town, verbose_name=_(u"Town"), null=True,                                    blank=True, related_name='file_main') @@ -118,8 +124,9 @@ class File(BaseHistorizedItem, OwnPerms, ValueGetter, ShortMenuItem,      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") +        saisine_type = models.ForeignKey( +            SaisineType, blank=True, null=True, +            verbose_name=u"Type de saisine")          reference_number = models.IntegerField(_(u"Ref. number"),                                                 blank=True, null=True)          instruction_deadline = models.DateField(_(u'Instruction deadline'), @@ -127,7 +134,7 @@ class File(BaseHistorizedItem, OwnPerms, ValueGetter, ShortMenuItem,      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) +        _(u"Total developed surface (m²)"), blank=True, null=True)      locality = models.CharField(_(u"Locality"),                                  max_length=100, null=True, blank=True)      address = models.TextField(_(u"Main address"), null=True, blank=True) @@ -135,37 +142,35 @@ class File(BaseHistorizedItem, OwnPerms, ValueGetter, ShortMenuItem,                                     max_length=10, null=True, blank=True)      comment = models.TextField(_(u"Comment"), null=True, blank=True)      # research archaeology --> -    departments = models.ManyToManyField(Department, -                          verbose_name=_(u"Departments"), -                          null=True, blank=True) +    departments = models.ManyToManyField( +        Department, verbose_name=_(u"Departments"), null=True, blank=True)      requested_operation_type = models.ForeignKey( -                          'archaeological_operations.OperationType', -                          related_name='+', null=True, blank=True, -                          verbose_name=_(u"Requested operation type")) -    organization = models.ForeignKey(Organization, blank=True, null=True, -                          verbose_name=_(u"Organization"), -                          related_name='files', -                          on_delete=models.SET_NULL) -    scientist = models.ForeignKey(Person, blank=True, null=True, -                    related_name='scientist', on_delete=models.SET_NULL, -                    verbose_name=_(u"Scientist in charge")) +        'archaeological_operations.OperationType', related_name='+', null=True, +        blank=True, verbose_name=_(u"Requested operation type")) +    organization = models.ForeignKey( +        Organization, blank=True, null=True, verbose_name=_(u"Organization"), +        related_name='files', on_delete=models.SET_NULL) +    scientist = models.ForeignKey( +        Person, blank=True, null=True, related_name='scientist', +        on_delete=models.SET_NULL, verbose_name=_(u"Scientist in charge"))      research_comment = models.TextField(_(u"Research archaeology comment"),                                          null=True, blank=True)      classified_area = models.NullBooleanField( -                      _(u"Classified area"), blank=True, null=True) +        _(u"Classified area"), blank=True, null=True)      protected_area = models.NullBooleanField( -                      _(u"Protected area"), blank=True, null=True) +        _(u"Protected area"), blank=True, null=True)      if settings.COUNTRY == 'fr':          cira_advised = models.NullBooleanField( -                     u"Passage en CIRA", blank=True, null=True) +            u"Passage en CIRA", blank=True, null=True)          mh_register = models.NullBooleanField( -                     u"Sur Monument Historique classé", blank=True, null=True) +            u"Sur Monument Historique classé", blank=True, null=True)          mh_listing = models.NullBooleanField( -                     u"Sur Monument Historique inscrit", blank=True, null=True) +            u"Sur Monument Historique inscrit", blank=True, null=True)      # <-- research archaeology      cached_label = models.CharField(_(u"Cached name"), max_length=500,                                      null=True, blank=True) -    imported_line = models.TextField(_(u"Imported line"), null=True, blank=True) +    imported_line = models.TextField(_(u"Imported line"), null=True, +                                     blank=True)      history = HistoricalRecords()      class Meta: @@ -175,8 +180,10 @@ class File(BaseHistorizedItem, OwnPerms, ValueGetter, ShortMenuItem,              ("view_file", ugettext(u"Can view all Archaelogical file")),              ("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")), +            ("change_own_file", +             ugettext(u"Can change own Archaelogical file")), +            ("delete_own_file", +             ugettext(u"Can delete own Archaelogical file")),              ("close_file", ugettext(u"Can close File")),          )          ordering = ('cached_label',) @@ -200,7 +207,7 @@ class File(BaseHistorizedItem, OwnPerms, ValueGetter, ShortMenuItem,          if not date:              date = datetime.date(2500, 1, 1)          elif settings.COUNTRY == 'fr' and self.saisine_type \ -           and self.saisine_type.delay: +                and self.saisine_type.delay:              date += datetime.timedelta(days=self.saisine_type.delay)          cache.set(cache_key, date, settings.CACHE_TIMEOUT)          return date @@ -216,10 +223,9 @@ class File(BaseHistorizedItem, OwnPerms, ValueGetter, ShortMenuItem,      def update_has_admin_act(self, cache_key=None):          if not cache_key:              cache_key, val = get_cache(self.__class__, [self.pk, -                                                    'has_adminact']) +                                                        'has_adminact'])          has_adminact = self.administrative_act.exclude( -                          act_type__txt_idx='a_receipt').count() \ -                       or self.operations.count() +            act_type__txt_idx='a_receipt').count() or self.operations.count()          cache.set(cache_key, has_adminact, settings.CACHE_TIMEOUT)          return has_adminact @@ -233,7 +239,7 @@ class File(BaseHistorizedItem, OwnPerms, ValueGetter, ShortMenuItem,      def update_short_menu_class(self, cache_key=None):          if not cache_key:              cache_key, val = get_cache(self.__class__, [self.pk, -                                                    'short_class_name']) +                                                        'short_class_name'])          cls = 'normal'          if not self.has_adminact and self.reception_date:              delta = datetime.date.today() - self.reception_date @@ -249,7 +255,7 @@ class File(BaseHistorizedItem, OwnPerms, ValueGetter, ShortMenuItem,      @classmethod      def get_owns(cls, user):          owns = super(File, cls).get_owns(user) -        return sorted(owns.all(), key=lambda x:x.cached_label) +        return sorted(owns.all(), key=lambda x: x.cached_label)      def get_values(self, prefix=''):          values = super(File, self).get_values(prefix=prefix) @@ -271,8 +277,8 @@ class File(BaseHistorizedItem, OwnPerms, ValueGetter, ShortMenuItem,      @property      def reference(self): -        return settings.FILE_PREFIX+u"-".join((unicode(self.year), -                          unicode(self.numeric_reference or '0'))) +        return settings.FILE_PREFIX+u"-".join( +            (unicode(self.year), unicode(self.numeric_reference or '0')))      def _generate_cached_label(self):          items = [self.get_town_label(), self.reference] @@ -293,7 +299,6 @@ class File(BaseHistorizedItem, OwnPerms, ValueGetter, ShortMenuItem,          return lbl      def get_department(self): -        q = self.towns          if not self.towns.count():              return '00'          return self.towns.all()[0].numero_insee[:2] @@ -302,7 +307,7 @@ class File(BaseHistorizedItem, OwnPerms, ValueGetter, ShortMenuItem,      def get_query_owns(cls, user):          return (Q(history_creator=user) |                  Q(in_charge__ishtaruser=user.ishtaruser)) \ -              & Q(end_date__isnull=True) +            & Q(end_date__isnull=True)      def is_active(self):          return not bool(self.end_date) @@ -316,12 +321,12 @@ class File(BaseHistorizedItem, OwnPerms, ValueGetter, ShortMenuItem,              return          q = self.history          if not q.count(): -            return {'date':None, 'user':None} +            return {'date': None, 'user': None}          for item in q.all():              if not item.end_date:                  break -        return {'date':item.history_date, -                'user':IshtarUser.objects.get(pk=item.history_modifier_id)} +        return {'date': item.history_date, +                'user': IshtarUser.objects.get(pk=item.history_modifier_id)}      def total_surface_ha(self):          if self.total_surface: @@ -339,8 +344,8 @@ class File(BaseHistorizedItem, OwnPerms, ValueGetter, ShortMenuItem,          return acts      def update_raw_town_planning_service(self): -        if (self.raw_town_planning_service and not \ -           self.responsible_town_planning_service) or \ +        if (self.raw_town_planning_service and not +            self.responsible_town_planning_service) or \             not self.responsible_town_planning_service:              return False          current_lbl = "" @@ -358,11 +363,11 @@ class File(BaseHistorizedItem, OwnPerms, ValueGetter, ShortMenuItem,             == self.planning_service:              return False          self.planning_service = \ -                            self.responsible_town_planning_service.attached_to +            self.responsible_town_planning_service.attached_to          return True      def update_raw_general_contractor(self): -        if (self.raw_general_contractor and not \ +        if (self.raw_general_contractor and not             self.general_contractor) or \             not self.general_contractor:              return False @@ -381,12 +386,12 @@ class File(BaseHistorizedItem, OwnPerms, ValueGetter, ShortMenuItem,             == self.corporation_general_contractor:              return False          self.corporation_general_contractor = \ -                            self.general_contractor.attached_to +            self.general_contractor.attached_to          return True      def save(self, *args, **kwargs):          returned = super(File, self).save(*args, **kwargs) -        if self.main_town and not self.main_town in list(self.towns.all()): +        if self.main_town and self.main_town not in list(self.towns.all()):              self.towns.add(self.main_town)          updated = self.update_raw_town_planning_service()          updated += self.update_planning_service() @@ -404,6 +409,7 @@ class File(BaseHistorizedItem, OwnPerms, ValueGetter, ShortMenuItem,  m2m_changed.connect(cached_label_changed, sender=File.towns.through)  post_save.connect(cached_label_changed, sender=File) +  class FileByDepartment(models.Model):      '''      Database view for dashboard @@ -411,10 +417,12 @@ class FileByDepartment(models.Model):      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' +  class FileDashboard:      def __init__(self):          from archaeological_operations.models import AdministrativeAct @@ -426,14 +434,14 @@ class FileDashboard:          self.types = types.annotate(number=Count('pk')).order_by('file_type')          by_year = File.objects.extra( -                        {'date':"date_trunc('year', creation_date)"}) +            {'date': "date_trunc('year', creation_date)"})          self.by_year = by_year.values('date')\                                .annotate(number=Count('pk')).order_by('-date')          now = datetime.date.today()          limit = datetime.date(now.year, now.month, 1) - datetime.timedelta(365)          by_month = File.objects.filter(creation_date__gt=limit).extra( -                        {'date':"date_trunc('month', creation_date)"}) +            {'date': "date_trunc('month', creation_date)"})          self.by_month = by_month.values('date')\                                  .annotate(number=Count('pk')).order_by('-date') @@ -442,28 +450,29 @@ class FileDashboard:          prog_type = FileType.objects.get(txt_idx='prog')          researchs = File.objects.filter(file_type=prog_type)          self.research['total_number'] = researchs.count() -        by_year = researchs.extra({'date':"date_trunc('year', creation_date)"}) +        by_year = researchs.extra( +            {'date': "date_trunc('year', creation_date)"} +        )          self.research['by_year'] = by_year.values('date')\                                            .annotate(number=Count('pk'))\                                            .order_by('-date')          by_month = researchs.filter(creation_date__gt=limit)\ -                           .extra({'date':"date_trunc('month', creation_date)"}) +            .extra({'date': "date_trunc('month', creation_date)"})          self.research['by_month'] = by_month.values('date')\                                              .annotate(number=Count('pk'))\                                              .order_by('-date')          self.research['by_dpt'] = FileByDepartment.objects\ -                        .filter(file__file_type=prog_type, -                                department__isnull=False)\ -                        .values('department__label')\ -                        .annotate(number=Count('file'))\ -                        .order_by('department__label') +            .filter(file__file_type=prog_type, department__isnull=False)\ +            .values('department__label')\ +            .annotate(number=Count('file'))\ +            .order_by('department__label')          FileTown = File.towns.through          self.research['towns'] = FileTown.objects\ -                        .filter(file__file_type=prog_type)\ -                        .values('town__name')\ -                        .annotate(number=Count('file'))\ -                        .order_by('-number','town__name')[:10] +            .filter(file__file_type=prog_type)\ +            .values('town__name')\ +            .annotate(number=Count('file'))\ +            .order_by('-number', 'town__name')[:10]          # rescue          rescue_type = FileType.objects.get(txt_idx='preventive') @@ -471,50 +480,46 @@ class FileDashboard:          self.rescue = {}          self.rescue['total_number'] = rescues.count()          self.rescue['saisine'] = rescues.values('saisine_type__label')\ -                                          .annotate(number=Count('pk'))\ -                                          .order_by('saisine_type__label') +            .annotate(number=Count('pk')).order_by('saisine_type__label')          self.rescue['administrative_act'] = AdministrativeAct.objects\ -                        .filter(associated_file__isnull=False)\ -                        .values('act_type__label')\ -                        .annotate(number=Count('pk'))\ -                        .order_by('act_type__pk') +            .filter(associated_file__isnull=False)\ +            .values('act_type__label')\ +            .annotate(number=Count('pk'))\ +            .order_by('act_type__pk') -        by_year = rescues.extra({'date':"date_trunc('year', creation_date)"}) +        by_year = rescues.extra({'date': "date_trunc('year', creation_date)"})          self.rescue['by_year'] = by_year.values('date')\ -                                          .annotate(number=Count('pk'))\ -                                          .order_by('-date') +            .annotate(number=Count('pk')).order_by('-date')          by_month = rescues.filter(creation_date__gt=limit)\ -                          .extra({'date':"date_trunc('month', creation_date)"}) +            .extra({'date': "date_trunc('month', creation_date)"})          self.rescue['by_month'] = by_month.values('date')\                                            .annotate(number=Count('pk'))\                                            .order_by('-date')          self.rescue['by_dpt'] = FileByDepartment.objects\ -                        .filter(file__file_type=rescue_type, -                                department__isnull=False)\ -                        .values('department__label')\ -                        .annotate(number=Count('file'))\ -                        .order_by('department__label') +            .filter(file__file_type=rescue_type, department__isnull=False)\ +            .values('department__label')\ +            .annotate(number=Count('file'))\ +            .order_by('department__label')          self.rescue['towns'] = FileTown.objects\ -                        .filter(file__file_type=rescue_type)\ -                        .values('town__name')\ -                        .annotate(number=Count('file'))\ -                        .order_by('-number','town__name')[:10] +            .filter(file__file_type=rescue_type)\ +            .values('town__name')\ +            .annotate(number=Count('file'))\ +            .order_by('-number', 'town__name')[:10]          self.rescue['with_associated_operation'] = rescues\ -                        .filter(operations__isnull=False).count() +            .filter(operations__isnull=False).count()          if self.rescue['total_number']:              self.rescue['with_associated_operation_percent'] = round( -                float(self.rescue['with_associated_operation'])\ -                /self.rescue['total_number']*100, 2) +                float(self.rescue['with_associated_operation']) +                / self.rescue['total_number']*100, 2)          by_year_operationnal = rescues.filter(operations__isnull=False)\ -                .extra({'date':'date_trunc(\'year\', '\ -                                '"archaeological_files_file".creation_date)'}) +            .extra({'date': 'date_trunc(\'year\', ' +                            '"archaeological_files_file".creation_date)'})          by_year_operationnal = by_year_operationnal.values('date')\ -                                          .annotate(number=Count('pk'))\ -                                          .order_by('-date') +            .annotate(number=Count('pk')).order_by('-date')          percents, idx = [], 0          for dct in self.rescue['by_year']:              if idx >= len(by_year_operationnal): @@ -522,19 +527,18 @@ class FileDashboard:              if by_year_operationnal[idx]['date'] != dct['date'] or\                 not dct['number']:                  continue -            val = round(float(by_year_operationnal[idx]['number'])/\ +            val = round(float(by_year_operationnal[idx]['number']) /                          dct['number']*100, 2) -            percents.append({'date':dct['date'], 'number':val}) +            percents.append({'date': dct['date'], 'number': val})          self.rescue['operational_by_year'] = percents          self.rescue['surface_by_town'] = FileTown.objects\ -                        .filter(file__file_type=rescue_type)\ -                        .values('town__name')\ -                        .annotate(number=Sum('file__total_surface'))\ -                        .order_by('-number','town__name')[:10] +            .filter(file__file_type=rescue_type)\ +            .values('town__name')\ +            .annotate(number=Sum('file__total_surface'))\ +            .order_by('-number', 'town__name')[:10]          self.rescue['surface_by_dpt'] = FileByDepartment.objects\ -                        .filter(file__file_type=rescue_type, -                                department__isnull=False)\ -                        .values('department__label')\ -                        .annotate(number=Sum('file__total_surface'))\ -                        .order_by('department__label') +            .filter(file__file_type=rescue_type, department__isnull=False)\ +            .values('department__label')\ +            .annotate(number=Sum('file__total_surface'))\ +            .order_by('department__label') | 
