diff options
| author | Étienne Loks <etienne.loks@iggdrasil.net> | 2021-03-19 11:21:04 +0100 | 
|---|---|---|
| committer | Étienne Loks <etienne.loks@iggdrasil.net> | 2021-03-19 11:21:04 +0100 | 
| commit | ced270d071384046eb3b9a85572dc817c7ef042c (patch) | |
| tree | 1696a72b2ec46fa34981533484e0d67ec9d14e93 /archaeological_operations/wizards.py | |
| parent | baf29e1bb4b18fb9830956c53f3475db2f828e3f (diff) | |
| download | Ishtar-ced270d071384046eb3b9a85572dc817c7ef042c.tar.bz2 Ishtar-ced270d071384046eb3b9a85572dc817c7ef042c.zip | |
Format - black: operation
Diffstat (limited to 'archaeological_operations/wizards.py')
| -rw-r--r-- | archaeological_operations/wizards.py | 336 | 
1 files changed, 198 insertions, 138 deletions
| diff --git a/archaeological_operations/wizards.py b/archaeological_operations/wizards.py index c76bbd313..a58e7437d 100644 --- a/archaeological_operations/wizards.py +++ b/archaeological_operations/wizards.py @@ -1,4 +1,4 @@ -#!/usr/bin/env python +#!/usr/bin/env python3  # -*- coding: utf-8 -*-  # Copyright (C) 2012-2017  Étienne Loks  <etienne.loks_AT_peacefrogsDOTnet> @@ -31,8 +31,13 @@ from archaeological_operations import models  from .forms import GenerateDocForm  from ishtar_common.forms import reverse_lazy  from ishtar_common.models import get_current_profile -from ishtar_common.wizards import Wizard, ClosingWizard, DeletionWizard, \ -    SearchWizard, MultipleDeletionWizard +from ishtar_common.wizards import ( +    Wizard, +    ClosingWizard, +    DeletionWizard, +    SearchWizard, +    MultipleDeletionWizard, +)  logger = logging.getLogger(__name__) @@ -43,67 +48,63 @@ class OperationSearch(SearchWizard):  class OperationWizard(Wizard):      model = models.Operation -    object_parcel_type = 'operation' -    parcel_step_key = 'parcels' -    relations_step_key = 'relations' +    object_parcel_type = "operation" +    parcel_step_key = "parcels" +    relations_step_key = "relations"      # step including the current(s) town(s) -    town_step_keys = ['towns-', 'townsgeneral-'] -    town_input_id = 'town'  # input id of the current(s) town(s) +    town_step_keys = ["towns-", "townsgeneral-"] +    town_input_id = "town"  # input id of the current(s) town(s)      multi_towns = False  # true if current town are multi valued      towns_formset = True  # true if towns are managed with formset -    wizard_done_window = reverse_lazy('show-operation') +    wizard_done_window = reverse_lazy("show-operation")      redirect_url = "operation_modification"      def get_template_names(self):          templates = super(OperationWizard, self).get_template_names()          current_step = self.steps.current          if current_step.startswith(self.parcel_step_key): -            templates = ['ishtar/wizard/parcels_wizard.html'] + templates +            templates = ["ishtar/wizard/parcels_wizard.html"] + templates          elif current_step.startswith(self.relations_step_key): -            templates = ['ishtar/wizard/relations_wizard.html'] + templates +            templates = ["ishtar/wizard/relations_wizard.html"] + templates          return templates      def get_current_file(self):          step = self.steps.current          if not step:              return -        file_form_key = 'general-' + self.url_name -        if self.url_name == 'operation_creation': -            file_form_key = 'filechoice-' + self.url_name +        file_form_key = "general-" + self.url_name +        if self.url_name == "operation_creation": +            file_form_key = "filechoice-" + self.url_name          file_id = self.session_get_value(file_form_key, "associated_file")          try:              idx = int(file_id)              current_file = File.objects.get(pk=idx)              return current_file -        except(TypeError, ValueError, ObjectDoesNotExist): +        except (TypeError, ValueError, ObjectDoesNotExist):              pass      def get_reminder(self):          archaeological_file = self.get_current_file()          if archaeological_file: -            return ((_("Archaeological file"), -                     str(archaeological_file)),) +            return ((_("Archaeological file"), str(archaeological_file)),)      def get_context_data(self, form, **kwargs):          """          Return extra context for templates          """ -        context = super(OperationWizard, self).get_context_data(form, -                                                                **kwargs) +        context = super(OperationWizard, self).get_context_data(form, **kwargs)          step = self.steps.current -        if step.startswith('towns'): -            context['TOWNS'] = self.get_towns() -        elif step.startswith('parcels-') and self.get_current_file(): +        if step.startswith("towns"): +            context["TOWNS"] = self.get_towns() +        elif step.startswith("parcels-") and self.get_current_file():              # if a file is associated to the operation add the button "Add all" -            context['add_all'] = True -        if step.startswith('parcels') and \ -           hasattr(self, 'automatic_parcel_association'): -            context['automatic_parcel_association'] = \ -                self.automatic_parcel_association +            context["add_all"] = True +        if step.startswith("parcels") and hasattr(self, "automatic_parcel_association"): +            context["automatic_parcel_association"] = self.automatic_parcel_association          # reminder of the current file          reminder = self.get_reminder()          if reminder: -            context['reminders'] = reminder +            context["reminders"] = reminder          return context      def get_towns(self): @@ -127,8 +128,9 @@ class OperationWizard(Wizard):          operation = self.get_current_object()          if operation:              for parcel in operation.parcels.all(): -                current_parcels.append((parcel.town, parcel.section, -                                        parcel.parcel_number)) +                current_parcels.append( +                    (parcel.town, parcel.section, parcel.parcel_number) +                )                  parcels.append((parcel.pk, parcel.short_label))          try:              for parcel in file.parcels.all(): @@ -159,27 +161,31 @@ class OperationWizard(Wizard):          except KeyError:              raise Http404()          # manage the dynamic choice of towns -        if step.startswith('towns') and hasattr(form, 'management_form'): -            data['TOWNS'] = self.get_towns() -        elif step.startswith(self.parcel_step_key) \ -                and hasattr(form, 'management_form'): +        if step.startswith("towns") and hasattr(form, "management_form"): +            data["TOWNS"] = self.get_towns() +        elif step.startswith(self.parcel_step_key) and hasattr(form, "management_form"):              file = self.get_current_file()              if file: -                data['PARCELS'] = self.get_available_parcels(file) +                data["PARCELS"] = self.get_available_parcels(file)              else:                  town_ids = []                  for town_step_key in self.town_step_keys:                      town_form_key = town_step_key + self.url_name -                    town_ids = self.session_get_value( -                        town_form_key, self.town_input_id, -                        multi=self.towns_formset, -                        multi_value=self.multi_towns) or [] +                    town_ids = ( +                        self.session_get_value( +                            town_form_key, +                            self.town_input_id, +                            multi=self.towns_formset, +                            multi_value=self.multi_towns, +                        ) +                        or [] +                    )                      if town_ids:                          towns = []                          if type(town_ids) == str:                              town_ids = [town_ids]                          for ids in town_ids: -                            for d in ids.split(','): +                            for d in ids.split(","):                                  if d:                                      towns.append(d)                          town_ids = towns @@ -193,7 +199,7 @@ class OperationWizard(Wizard):                          towns.append((town.pk, str(town)))                      except (ValueError, ObjectDoesNotExist):                          pass -                data['TOWNS'] = sorted(towns, key=lambda x: x[1]) +                data["TOWNS"] = sorted(towns, key=lambda x: x[1])          data = data or None          form = super(OperationWizard, self).get_form(step, data, files)          return form @@ -204,18 +210,24 @@ class OperationWizard(Wizard):          """          datas = super(OperationWizard, self).get_formated_datas(forms)          # if the general town form is used the advertissement is relevant -        has_no_af = [form.prefix for form in forms -                     if form.prefix == 'townsgeneral-operation'] and True +        has_no_af = [ +            form.prefix for form in forms if form.prefix == "townsgeneral-operation" +        ] and True          if has_no_af: -            datas = [[ -                _("Warning: No Archaeological File is provided. " -                  "If you have forget it return to the first step."), []]]\ -                + datas +            datas = [ +                [ +                    _( +                        "Warning: No Archaeological File is provided. " +                        "If you have forget it return to the first step." +                    ), +                    [], +                ] +            ] + datas          return datas      def get_form_initial(self, step, data=None):          initial = super(OperationWizard, self).get_form_initial(step) -        if step == 'general-operation_creation': +        if step == "general-operation_creation":              initial.update(self._copy_from_associated_field())          return initial @@ -239,17 +251,19 @@ class OperationWizard(Wizard):          file = self.get_current_file()          if not file:              return initial -        keys = ((('in_charge', 'pk'), 'in_charge'), -                (('name',), 'common_name'), -                (('total_surface',), 'surface'), -                ) +        keys = ( +            (("in_charge", "pk"), "in_charge"), +            (("name",), "common_name"), +            (("total_surface",), "surface"), +        )          initial.update(self.__copy_fields(file, keys))          if file.is_preventive():              return initial -        keys = ((('scientist', 'pk'), 'scientist'), -                (('requested_operation_type', 'pk'), 'operation_type'), -                (('organization', 'pk'), 'operator'), -                ) +        keys = ( +            (("scientist", "pk"), "scientist"), +            (("requested_operation_type", "pk"), "operation_type"), +            (("organization", "pk"), "operator"), +        )          initial.update(self.__copy_fields(file, keys))          return initial @@ -258,7 +272,7 @@ class OperationWizard(Wizard):          post_data = request.POST.copy()          # add all parcel from available in the archaeological file -        if not post_data.get('add_all_parcels', None): +        if not post_data.get("add_all_parcels", None):              return super(OperationWizard, self).post(*args, **kwargs)          file = self.get_current_file() @@ -269,12 +283,12 @@ class OperationWizard(Wizard):          idx = -1          # remove non relevant deleted keys          for k in post_data.keys(): -            if k.startswith(parcel_form_key) and k.endswith('-DELETE'): +            if k.startswith(parcel_form_key) and k.endswith("-DELETE"):                  post_data.pop(k)          for idx, parcel in enumerate(self.get_available_parcels(file)):              parcel_pk, parcel_name = parcel              post_data["%s-%d-parcel" % (parcel_form_key, idx)] = parcel_pk -        post_data[parcel_form_key + '-TOTAL_FORMS'] = idx + 2 +        post_data[parcel_form_key + "-TOTAL_FORMS"] = idx + 2          request.POST = post_data          return super(OperationWizard, self).post(*args, **kwargs) @@ -284,11 +298,12 @@ class OperationWizard(Wizard):  class OperationModificationWizard(OperationWizard):      modification = True -    filter_owns = {'selec-operation_modification': ['pk']} +    filter_owns = {"selec-operation_modification": ["pk"]}      def get_form_kwargs(self, step, **kwargs):          kwargs = super(OperationModificationWizard, self).get_form_kwargs( -            step, **kwargs) +            step, **kwargs +        )          if step != "relations-operation_modification":              return kwargs          kwargs["left_record"] = self.get_current_object() @@ -297,35 +312,47 @@ class OperationModificationWizard(OperationWizard):  class OperationClosingWizard(ClosingWizard):      model = models.Operation -    fields = ['year', 'operation_code', 'operation_type', 'associated_file', -              'in_charge', 'scientist', 'start_date', 'excavation_end_date', -              'comment', 'towns', 'remains'] +    fields = [ +        "year", +        "operation_code", +        "operation_type", +        "associated_file", +        "in_charge", +        "scientist", +        "start_date", +        "excavation_end_date", +        "comment", +        "towns", +        "remains", +    ]  class OperationDeletionWizard(MultipleDeletionWizard):      model = models.Operation      fields = OperationClosingWizard.fields -    filter_owns = {'selec-operation_deletion': ['pks']} +    filter_owns = {"selec-operation_deletion": ["pks"]}      redirect_url = "operation_deletion"  class OperationAdministrativeActWizard(OperationWizard):      edit = False -    wizard_done_window = reverse_lazy('show-administrativeact') -    current_obj_slug = 'administrativeactop' -    ref_object_key = 'operation' +    wizard_done_window = reverse_lazy("show-administrativeact") +    current_obj_slug = "administrativeactop" +    ref_object_key = "operation"      redirect_url = "operation_administrativeactop_modification"      def get_reminder(self): -        form_key = 'selec-' + self.url_name -        if self.url_name.endswith('_administrativeactop'): +        form_key = "selec-" + self.url_name +        if self.url_name.endswith("_administrativeactop"):              # modification and deletion are suffixed with '_modification'              # and '_deletion' so it is creation              operation_id = self.session_get_value(form_key, "pk")              try:                  return ( -                    (_("Operation"), -                     str(models.Operation.objects.get(pk=operation_id))), +                    ( +                        _("Operation"), +                        str(models.Operation.objects.get(pk=operation_id)), +                    ),                  )              except models.Operation.DoesNotExist:                  return @@ -340,35 +367,37 @@ class OperationAdministrativeActWizard(OperationWizard):                  return      def get_extra_model(self, dct, m2m, form_list): -        dct['history_modifier'] = self.request.user +        dct["history_modifier"] = self.request.user          return dct      def get_context_data(self, form, **kwargs):          # manage document generation -        context = super(OperationAdministrativeActWizard, -                        self).get_context_data(form, **kwargs) +        context = super(OperationAdministrativeActWizard, self).get_context_data( +            form, **kwargs +        )          step = self.steps.current -        if step.startswith('final-'): -            general_form_key = 'administrativeact-' + self.url_name +        if step.startswith("final-"): +            general_form_key = "administrativeact-" + self.url_name              act_type = None              try:                  act_type = models.ActType.objects.get( -                    pk=self.session_get_value(general_form_key, "act_type")) +                    pk=self.session_get_value(general_form_key, "act_type") +                )              except models.ActType.DoesNotExist:                  pass              if act_type and act_type.associated_template.count(): -                context['extra_form'] = GenerateDocForm( -                    choices=act_type.associated_template.all()) +                context["extra_form"] = GenerateDocForm( +                    choices=act_type.associated_template.all() +                )          return context      def get_associated_item(self, dct):          return self.get_current_object() -    def save_model(self, dct, m2m, whole_associated_models, form_list, -                   return_object): -        dct['history_modifier'] = self.request.user -        if 'pk' in dct: -            dct.pop('pk') +    def save_model(self, dct, m2m, whole_associated_models, form_list, return_object): +        dct["history_modifier"] = self.request.user +        if "pk" in dct: +            dct.pop("pk")          if self.edit:              admact = self.get_current_object()              for k in dct: @@ -382,11 +411,15 @@ class OperationAdministrativeActWizard(OperationWizard):              dct[self.ref_object_key] = associated_item              admact = models.AdministrativeAct(**dct)          admact.save() -        dct['item'] = admact +        dct["item"] = admact          # check if a doc generation is required -        keys = [self.storage.prefix, 'step_data', 'final-' + self.url_name, -                'doc_generation'] +        keys = [ +            self.storage.prefix, +            "step_data", +            "final-" + self.url_name, +            "doc_generation", +        ]          r = self.request.session          for k in keys:              if k in r and r[k]: @@ -396,21 +429,27 @@ class OperationAdministrativeActWizard(OperationWizard):          if k == keys[-1]:  # the whole list as been traversed              wizard_done_window = str(self.wizard_done_window)              if wizard_done_window: -                dct['wizard_done_window'] = wizard_done_window +                dct["wizard_done_window"] = wizard_done_window              # redirect to the generated doc              if r and type(r) in (tuple, list) and r[0]: -                dct['redirect'] = reverse('generatedoc-administrativeactop', -                                          args=[admact.pk, r[0]]) +                dct["redirect"] = reverse( +                    "generatedoc-administrativeactop", args=[admact.pk, r[0]] +                )          # make the new object a default -        ishtaruser = self.request.user.ishtaruser \ -            if hasattr(self.request.user, 'ishtaruser') else None -        if ishtaruser and ishtaruser.current_profile \ -                and ishtaruser.current_profile.auto_pin: +        ishtaruser = ( +            self.request.user.ishtaruser +            if hasattr(self.request.user, "ishtaruser") +            else None +        ) +        if ( +            ishtaruser +            and ishtaruser.current_profile +            and ishtaruser.current_profile.auto_pin +        ):              self.request.session[self.current_obj_slug] = str(admact.pk) -            self.request.session[self.get_object_name(admact)] = str( -                admact.pk) +            self.request.session[self.get_object_name(admact)] = str(admact.pk) -        res = render(self.request, 'ishtar/wizard/wizard_done.html', dct) +        res = render(self.request, "ishtar/wizard/wizard_done.html", dct)          return res @@ -421,6 +460,7 @@ class OperationEditAdministrativeActWizard(OperationAdministrativeActWizard):      def get_associated_item(self, dct):          return self.get_current_object().operation +  ########  # Site #  ######## @@ -439,110 +479,130 @@ class SiteSearch(SiteLabel, SearchWizard):  class SiteWizard(SiteLabel, Wizard): -    SITE_KEY = 'new' +    SITE_KEY = "new"      model = models.ArchaeologicalSite -    wizard_done_window = reverse_lazy('show-site') +    wizard_done_window = reverse_lazy("show-site")      redirect_url = "site_modification"  class SiteModificationWizard(SiteWizard): -    SITE_KEY = 'modification' +    SITE_KEY = "modification"      modification = True  class SiteDeletionWizard(SiteLabel, MultipleDeletionWizard): -    SITE_KEY = 'deletion' +    SITE_KEY = "deletion"      model = models.ArchaeologicalSite -    fields = models.ArchaeologicalSite.TABLE_COLS + ['operations'] +    fields = models.ArchaeologicalSite.TABLE_COLS + ["operations"]      redirect_url = "site_deletion"  class AdministrativeActDeletionWizard(ClosingWizard):      model = models.AdministrativeAct      wizard_templates = { -        'final-operation_administrativeactop_deletion': -            'ishtar/wizard/wizard_adminact_deletion.html', -        'final-file_administrativeactfile_deletion': -            'ishtar/wizard/wizard_adminact_deletion.html'} -    fields = ['act_type', 'in_charge', 'operator', 'scientist', 'signatory', -              'operation', 'associated_file', 'signature_date', 'act_object'] -    if settings.COUNTRY == 'fr': -        fields += ['ref_sra'] +        "final-operation_administrativeactop_deletion": "ishtar/wizard/wizard_adminact_deletion.html", +        "final-file_administrativeactfile_deletion": "ishtar/wizard/wizard_adminact_deletion.html", +    } +    fields = [ +        "act_type", +        "in_charge", +        "operator", +        "scientist", +        "signatory", +        "operation", +        "associated_file", +        "signature_date", +        "act_object", +    ] +    if settings.COUNTRY == "fr": +        fields += ["ref_sra"]      def done(self, form_list, **kwargs):          obj = self.get_current_object()          obj.delete() -        return render( -            self.request, 'ishtar/wizard/wizard_delete_done.html', {}) +        return render(self.request, "ishtar/wizard/wizard_delete_done.html", {}) -def is_preventive(form_name, model, type_key='operation_type', key=''): +def is_preventive(form_name, model, type_key="operation_type", key=""):      def func(self):          request = self.request          storage = self.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]: +        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: -            typ = request.session[storage.prefix][ -                'step_data'][form_name][form_name + '-' + type_key] +            typ = request.session[storage.prefix]["step_data"][form_name][ +                form_name + "-" + type_key +            ]              if type(typ) in (list, tuple):                  typ = typ[0]              typ = int(typ)              return model.is_preventive(typ, key)          except ValueError:              return False +      return func -def is_not_preventive(form_name, model, type_key='operation_type', key=''): +def is_not_preventive(form_name, model, type_key="operation_type", key=""):      def func(self):          return not is_preventive(form_name, model, type_key, key)(self) +      return func -def is_judiciary(form_name, model, type_key='operation_type'): +def is_judiciary(form_name, model, type_key="operation_type"):      def func(self):          request = self.request          storage = self.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]: +        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: -            typ = request.session[storage.prefix][ -                'step_data'][form_name][form_name + '-' + type_key] +            typ = request.session[storage.prefix]["step_data"][form_name][ +                form_name + "-" + type_key +            ]              if type(typ) in (list, tuple):                  typ = typ[0]              typ = int(typ)              return model.is_judiciary(typ)          except ValueError:              return False +      return func -def has_associated_file(form_name, file_key='associated_file', negate=False): +def has_associated_file(form_name, file_key="associated_file", negate=False):      def func(self):          request = self.request          storage = self.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 + '-' + file_key not in \ -           request.session[storage.prefix]['step_data'][form_name]: +        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 + "-" + file_key +            not in request.session[storage.prefix]["step_data"][form_name] +        ):              return negate          try: -            file_id = request.session[storage.prefix][ -                'step_data'][form_name][form_name + '-' + file_key] +            file_id = request.session[storage.prefix]["step_data"][form_name][ +                form_name + "-" + file_key +            ]              if type(file_id) in (list, tuple):                  file_id = file_id[0]              int(file_id)              return not negate          except ValueError:              return negate +      return func | 
