Example #1
0
    def get_queryset(self):
        workbasket = WorkBasket.current(self.request)
        tx = None
        if workbasket:
            tx = workbasket.transactions.order_by("order").last()

        return models.CertificateDescription.objects.approved_up_to_transaction(tx)
Example #2
0
    def get_object(self, queryset: Optional[QuerySet] = None) -> Model:
        if queryset is None:
            queryset = self.get_queryset()

        required_url_kwargs = self.required_url_kwargs or self.model.identifying_fields

        if any(key not in self.kwargs for key in required_url_kwargs):
            raise AttributeError(
                f"{self.__class__.__name__} must be called with {', '.join(required_url_kwargs)} in the URLconf.",
            )

        queryset = queryset.filter(**self.kwargs)

        try:
            obj = queryset.get()
        except queryset.model.DoesNotExist:
            raise Http404(f"No {self.model.__name__} matching the query {self.kwargs}")

        if self.request.method == "POST":
            obj = obj.new_draft(
                WorkBasket.current(self.request),
                save=False,
            )

        return obj
Example #3
0
    def get_queryset(self):
        workbasket = WorkBasket.current(self.request)
        tx = None
        if workbasket:
            tx = workbasket.transactions.order_by("order").last()

        return AdditionalCode.objects.approved_up_to_transaction(
            tx).select_related("type", )
Example #4
0
    def check_for_current_workbasket(request, *args, **kwargs):
        if WorkBasket.current(request) is None:
            workbasket = WorkBasket.objects.editable().last()
            if not workbasket:
                workbasket = WorkBasket.objects.create(
                    author=request.user,
                )

            workbasket.save_to_session(request.session)

        return view_func(request, *args, **kwargs)
Example #5
0
def test_measure_update_get_footnotes(session_with_workbasket):
    association = factories.FootnoteAssociationMeasureFactory.create()
    view = MeasureUpdate(request=session_with_workbasket)
    footnotes = view.get_footnotes(association.footnoted_measure)

    assert len(footnotes) == 1

    association.new_version(
        WorkBasket.current(session_with_workbasket),
        update_type=UpdateType.DELETE,
    )

    footnotes = view.get_footnotes(association.footnoted_measure)

    assert len(footnotes) == 0
Example #6
0
    def save(self, commit=True):
        instance = super(FootnoteCreateForm, self).save(commit=False)

        workbasket = WorkBasket.current(self.request)
        tx = None
        if workbasket:
            tx = workbasket.transactions.order_by("order").last()

        instance.footnote_id = get_next_id(
            models.Footnote.objects.filter(
                footnote_type__footnote_type_id=instance.footnote_type.
                footnote_type_id, ).approved_up_to_transaction(tx),
            instance._meta.get_field("footnote_id"),
            max_len=3,
        )
        if commit:
            instance.save()
        return instance
Example #7
0
 def get_queryset(self):
     qs = super().get_queryset()
     return qs.with_workbasket(WorkBasket.current(self.request))
Example #8
0
    def save(self, commit=True):
        """Get the measure instance after form submission, get from session
        storage any footnote pks created via the Footnote formset and any pks
        not removed from the measure after editing and create footnotes via
        FootnoteAssociationMeasure."""
        instance = super().save(commit=False)
        if commit:
            instance.save()

        sid = instance.sid

        measure_creation_pattern = MeasureCreationPattern(
            workbasket=WorkBasket.current(self.request),
            base_date=instance.valid_between.lower,
            defaults={
                "generating_regulation": self.cleaned_data["generating_regulation"],
            },
        )

        if self.cleaned_data.get("exclusions"):
            for exclusion in self.cleaned_data.get("exclusions"):
                pattern = (
                    measure_creation_pattern.create_measure_excluded_geographical_areas(
                        instance,
                        exclusion,
                    )
                )
                [p for p in pattern]

        if (
            self.request.session[f"instance_duty_sentence_{self.instance.sid}"]
            != self.cleaned_data["duty_sentence"]
        ):
            diff_components(
                instance,
                self.cleaned_data["duty_sentence"],
                self.cleaned_data["valid_between"].lower,
                WorkBasket.current(self.request),
                # Creating components in the same transaction as the new version
                # of the measure minimises number of transaction and groups the
                # creation of measure and related objects in the same
                # transaction.
                instance.transaction,
                models.MeasureComponent,
                "component_measure",
            )

        footnote_pks = [
            dct["footnote"]
            for dct in self.request.session.get(f"formset_initial_{sid}", [])
        ]
        footnote_pks.extend(self.request.session.get(f"instance_footnotes_{sid}", []))

        self.request.session.pop(f"formset_initial_{sid}", None)
        self.request.session.pop(f"instance_footnotes_{sid}", None)

        for pk in footnote_pks:
            footnote = (
                Footnote.objects.filter(pk=pk)
                .approved_up_to_transaction(instance.transaction)
                .first()
            )

            existing_association = (
                models.FootnoteAssociationMeasure.objects.approved_up_to_transaction(
                    instance.transaction,
                )
                .filter(
                    footnoted_measure__sid=instance.sid,
                    associated_footnote__footnote_id=footnote.footnote_id,
                    associated_footnote__footnote_type__footnote_type_id=footnote.footnote_type.footnote_type_id,
                )
                .first()
            )
            if existing_association:
                existing_association.new_version(
                    workbasket=WorkBasket.current(self.request),
                    transaction=instance.transaction,
                    footnoted_measure=instance,
                )
            else:
                models.FootnoteAssociationMeasure.objects.create(
                    footnoted_measure=instance,
                    associated_footnote=footnote,
                    update_type=UpdateType.CREATE,
                    transaction=instance.transaction,
                )

        return instance
Example #9
0
 def workbasket(self) -> WorkBasket:
     return WorkBasket.current(self.request)
Example #10
0
 def get_transaction(self):
     transaction = super().get_transaction()
     transaction.workbasket = WorkBasket.current(self.request)
     return transaction
Example #11
0
    def create_conditions(self, obj):
        """
        Gets condition formset from context data, loops over these forms and
        validates the data, checking for the condition_sid field in the data to
        indicate whether an existing condition is being updated or a new one
        created from scratch.

        Then deletes any existing conditions that are not being updated,
        before calling the MeasureCreationPattern.create_condition_and_components with the appropriate parser and condition data.
        """
        formset = self.get_context_data()["conditions_formset"]
        excluded_sids = []
        conditions_data = []
        workbasket = WorkBasket.current(self.request)
        existing_conditions = obj.conditions.approved_up_to_transaction(
            workbasket.get_current_transaction(self.request), )

        for f in formset.forms:
            f.is_valid()
            condition_data = f.cleaned_data
            # If the form has changed and "condition_sid" is in the changed data,
            # this means that the condition is preexisting and needs to updated
            # so that its dependent_measure points to the latest version of measure
            if f.has_changed() and "condition_sid" in f.changed_data:
                excluded_sids.append(f.initial["condition_sid"])
                update_type = UpdateType.UPDATE
                condition_data["version_group"] = existing_conditions.get(
                    sid=f.initial["condition_sid"], ).version_group
                condition_data["sid"] = f.initial["condition_sid"]
            # If changed and condition_sid not in changed_data, then this is a newly created condition
            elif f.has_changed() and "condition_sid" not in f.changed_data:
                update_type = UpdateType.CREATE

            condition_data["update_type"] = update_type
            conditions_data.append(condition_data)

        workbasket = WorkBasket.current(self.request)

        # Delete all existing conditions from the measure instance, except those that need to be updated
        for condition in existing_conditions.exclude(sid__in=excluded_sids):
            condition.new_version(
                workbasket=workbasket,
                update_type=UpdateType.DELETE,
                transaction=obj.transaction,
            )

        if conditions_data:
            measure_creation_pattern = MeasureCreationPattern(
                workbasket=workbasket,
                base_date=obj.valid_between.lower,
            )
            parser = DutySentenceParser.get(
                obj.valid_between.lower,
                component_output=MeasureConditionComponent,
            )

            # Loop over conditions_data, starting at 1 because component_sequence_number has to start at 1
            for component_sequence_number, condition_data in enumerate(
                    conditions_data,
                    start=1,
            ):
                # Create conditions and measure condition components, using instance as `dependent_measure`
                measure_creation_pattern.create_condition_and_components(
                    condition_data,
                    component_sequence_number,
                    obj,
                    parser,
                    workbasket,
                )
Example #12
0
    def create_measures(self, data):
        """Returns a list of the created measures."""
        measure_start_date = data["valid_between"].lower
        workbasket = WorkBasket.current(self.request)
        measure_creation_pattern = MeasureCreationPattern(
            workbasket=workbasket,
            base_date=measure_start_date,
            defaults={
                "generating_regulation": data["generating_regulation"],
            },
        )

        measures_data = []

        for commodity_data in data.get("formset-commodities", []):
            if not commodity_data.get("DELETE"):
                for geo_area in data["geo_area_list"]:

                    measure_data = {
                        "measure_type":
                        data["measure_type"],
                        "geographical_area":
                        geo_area,
                        "exclusions":
                        data.get("geo_area_exclusions", None) or [],
                        "goods_nomenclature":
                        commodity_data["commodity"],
                        "additional_code":
                        data["additional_code"],
                        "order_number":
                        data["order_number"],
                        "validity_start":
                        measure_start_date,
                        "validity_end":
                        data["valid_between"].upper,
                        "footnotes": [
                            item["footnote"]
                            for item in data.get("formset-footnotes", [])
                            if not item.get("DELETE")
                        ],
                        # condition_sentence here, or handle separately and duty_sentence after?
                        "duty_sentence":
                        commodity_data["duties"],
                    }

                    measures_data.append(measure_data)

        created_measures = []

        for measure_data in measures_data:
            measure = measure_creation_pattern.create(**measure_data)
            parser = DutySentenceParser.get(
                measure.valid_between.lower,
                component_output=MeasureConditionComponent,
            )
            for component_sequence_number, condition_data in enumerate(
                    data.get("formset-conditions", []),
                    start=1,
            ):
                if not condition_data.get("DELETE"):

                    measure_creation_pattern.create_condition_and_components(
                        condition_data,
                        component_sequence_number,
                        measure,
                        parser,
                        workbasket,
                    )

            created_measures.append(measure)

        return created_measures
Example #13
0
 def check_for_current_workbasket(request, *args, **kwargs):
     if WorkBasket.current(request) is None:
         request.session["workbasket"] = (
             WorkBasket.objects.is_not_approved().get().to_json())
     return view_func(request, *args, **kwargs)