示例#1
0
def test_edit_after_submit(
    upload,
    valid_user_client,
    date_ranges,
    other_statuses,
    should_reuse,
):
    # submit a workbasket containing a newly created footnote
    workbasket = factories.WorkBasketFactory.create()
    with workbasket.new_transaction():
        footnote = factories.FootnoteFactory.create(
            update_type=UpdateType.CREATE,
        )
    assert footnote.transaction.workbasket == workbasket

    assert_workbasket_valid(workbasket)

    # create workbaskets in different unapproved states
    # to check that the system doesn't select these
    other_baskets = [
        factories.WorkBasketFactory.create(status=other_status)
        for other_status in other_statuses
    ]

    response = valid_user_client.get(
        reverse(
            "workbaskets:workbasket-ui-submit",
            kwargs={"pk": workbasket.pk},
        ),
    )
    assert response.status_code == 302

    # edit the footnote description start date, to avoid FO4 violation
    description = footnote.descriptions.first()
    description.validity_start = date_ranges.later.lower
    description.save(force_write=True)

    # edit the footnote
    response = valid_user_client.post(
        footnote.get_url("edit"),
        validity_period_post_data(
            date_ranges.later.lower,
            date_ranges.later.upper,
        ),
    )
    assert response.status_code == 302

    # check that the session workbasket has been replaced by a new one
    session_workbasket = WorkBasket.load_from_session(valid_user_client.session)
    assert session_workbasket.id != workbasket.id
    assert session_workbasket.status == WorkflowStatus.EDITING
    assert (session_workbasket in other_baskets) == should_reuse

    # check that the footnote edit is in the new session workbasket
    assert session_workbasket.transactions.count() == 1
    tx = session_workbasket.transactions.first()
    assert tx.tracked_models.count() == 1
    new_footnote_version = tx.tracked_models.first()
    assert new_footnote_version.pk != footnote.pk
    assert new_footnote_version.version_group == footnote.version_group
示例#2
0
    def save(self, commit=True):
        instance = super(CertificateCreateForm, self).save(commit=False)

        self.cleaned_data[
            "certificate_description"] = models.CertificateDescription(
                description=self.cleaned_data["description"],
                validity_start=self.cleaned_data["valid_between"].lower,
            )

        if not instance.sid:
            current_transaction = WorkBasket.get_current_transaction(
                self.request)
            # Filter certificate by type and find the highest sid, using regex to ignore legacy, non-numeric identifiers
            instance.sid = get_next_id(
                models.Certificate.objects.filter(
                    sid__regex=r"^[0-9]*$",
                    certificate_type__sid=instance.certificate_type.sid,
                ).approved_up_to_transaction(current_transaction),
                instance._meta.get_field("sid"),
                max_len=3,
            )

        if commit:
            instance.save()
        return instance
示例#3
0
文件: views.py 项目: uktrade/tamato
 def get_conditions(self, measure):
     tx = WorkBasket.get_current_transaction(self.request)
     return (
         measure.conditions.with_reference_price_string().approved_up_to_transaction(
             tx,
         )
     )
示例#4
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)
示例#5
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
示例#6
0
文件: views.py 项目: uktrade/tamato
 def get_queryset(self):
     tx = WorkBasket.get_current_transaction(self.request)
     return (
         models.Footnote.objects.approved_up_to_transaction(tx)
         .select_related("footnote_type")
         .prefetch_related("descriptions")
     )
示例#7
0
文件: utils.py 项目: uktrade/tamato
    def __call__(self, request):
        from workbaskets.models import WorkBasket

        with override_current_transaction(
                WorkBasket.get_current_transaction(request), ):
            response = self.get_response(request)
        # No post-view processing required.
        return response
示例#8
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", )
示例#9
0
文件: views.py 项目: uktrade/tamato
    def get_footnotes(self, measure):
        tx = WorkBasket.get_current_transaction(self.request)
        associations = FootnoteAssociationMeasure.objects.approved_up_to_transaction(
            tx,
        ).filter(
            footnoted_measure__sid=measure.sid,
        )

        return [a.associated_footnote for a in associations]
示例#10
0
def test_current_transaction_returns_last_approved_transaction(
    session_request,
    approved_transaction,
):
    """Check that when no workbasket is saved on the request session
    get_current_transaction returns the latest approved transaction instead."""
    current = WorkBasket.get_current_transaction(session_request)

    assert current == approved_transaction
示例#11
0
文件: views.py 项目: uktrade/tamato
    def get_form(self, form_class=None):
        form = super().get_form(form_class=form_class)
        tx = WorkBasket.get_current_transaction(self.request)

        if hasattr(form, "field"):
            for field in form.fields.values():
                if hasattr(field, "queryset"):
                    field.queryset = field.queryset.approved_up_to_transaction(tx)

        return form
示例#12
0
    def get_queryset(self):
        """
        API endpoint for autocomplete as used by the MeasureCreationWizard.

        Only return valid names that are products (suffix=80)
        """
        tx = WorkBasket.get_current_transaction(self.request)
        return (GoodsNomenclature.objects.approved_up_to_transaction(
            tx, ).prefetch_related("descriptions").as_at(
                date.today()).filter(suffix=80))
示例#13
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)
示例#14
0
    def __init__(self, *args, **kwargs):
        self.request = kwargs.pop("request", None)
        super().__init__(*args, **kwargs)

        tx = WorkBasket.get_current_transaction(self.request)

        if not hasattr(self.instance, "duty_sentence"):
            raise AttributeError(
                "Measure instance is missing `duty_sentence` attribute. Try calling `with_duty_sentence` queryset method",
            )

        self.initial["duty_sentence"] = self.instance.duty_sentence
        self.request.session[
            f"instance_duty_sentence_{self.instance.sid}"] = self.instance.duty_sentence

        if self.instance.geographical_area.is_all_countries():
            self.initial["geo_area"] = GeoAreaType.ERGA_OMNES.value

        elif self.instance.geographical_area.is_group():
            self.initial["geo_area"] = GeoAreaType.GROUP.value

        else:
            self.initial["geo_area"] = GeoAreaType.COUNTRY.value

        # If no footnote keys are stored in the session for a measure,
        # store all the pks of a measure's footnotes on the session, using the measure sid as key
        if f"instance_footnotes_{self.instance.sid}" not in self.request.session.keys(
        ):
            tx = WorkBasket.get_current_transaction(self.request)
            associations = (models.FootnoteAssociationMeasure.objects.
                            approved_up_to_transaction(tx, ).filter(
                                footnoted_measure=self.instance, ))
            self.request.session[f"instance_footnotes_{self.instance.sid}"] = [
                a.associated_footnote.pk for a in associations
            ]

        nested_forms_initial = {**self.initial}
        nested_forms_initial[
            "geographical_area"] = self.instance.geographical_area
        kwargs.pop("initial")
        self.bind_nested_forms(*args, initial=nested_forms_initial, **kwargs)
示例#15
0
文件: forms.py 项目: uktrade/tamato
    def save(self, commit=True):
        instance = super().save(commit=False)

        tx = WorkBasket.get_current_transaction(self.request)

        highest_sid = (models.AdditionalCode.
                       objects.approved_up_to_transaction(tx).aggregate(
                           Max("sid"), )["sid__max"]) or 0
        instance.sid = highest_sid + 1

        if commit:
            instance.save(commit)
        return instance
示例#16
0
    def clean_sid(self):
        sid = self.cleaned_data["sid"]
        if sid:
            certificate_type = self.cleaned_data["certificate_type"]
            tx = WorkBasket.get_current_transaction(self.request)
            if (models.Certificate.objects.approved_up_to_transaction(
                    tx).filter(sid=sid,
                               certificate_type=certificate_type).exists()):
                raise ValidationError(
                    f"Certificate with sid {sid} and type {certificate_type} already exists.",
                )

        return sid
示例#17
0
 def _get_next_part_value(self, partial_regulation_id):
     """Get the next available part value that can be appended to a partial
     regulation_id (see
     RegulationCreateForm._make_partial_regulation_id())."""
     tx = WorkBasket.get_current_transaction(self.request)
     last_matching_regulation = (Regulation.objects.filter(
         regulation_id__startswith=partial_regulation_id,
         role_type=FIXED_ROLE_TYPE,
     ).approved_up_to_transaction(tx).order_by("-regulation_id").first())
     if last_matching_regulation:
         highest_part_value = last_matching_regulation.regulation_id[-1]
         alphanum = string.digits + string.ascii_uppercase
         return alphanum[int(highest_part_value, 36) + 1]
     return 0
示例#18
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
示例#19
0
文件: views.py 项目: uktrade/tamato
    def get_form(self, step=None, data=None, files=None):
        form = super().get_form(step, data, files)
        tx = WorkBasket.get_current_transaction(self.request)
        forms = [form]
        if hasattr(form, "forms"):
            forms = form.forms
        for f in forms:
            if hasattr(f, "fields"):
                for field in f.fields.values():
                    if hasattr(field, "queryset"):
                        field.queryset = field.queryset.approved_up_to_transaction(tx)

        form.is_valid()
        if hasattr(form, "cleaned_data"):
            form.initial = form.cleaned_data

        return form
示例#20
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
示例#21
0
文件: views.py 项目: uktrade/tamato
 def get_queryset(self):
     tx = WorkBasket.get_current_transaction(self.request)
     return AdditionalCode.objects.approved_up_to_transaction(
         tx).select_related("type", )
示例#22
0
 def get_queryset(self):
     tx = WorkBasket.get_current_transaction(self.request)
     return MeasureType.objects.approved_up_to_transaction(tx).order_by(
         "description", )
示例#23
0
    def get_queryset(self):
        tx = WorkBasket.get_current_transaction(self.request)

        return Measure.objects.with_duty_sentence().approved_up_to_transaction(
            tx)
示例#24
0
 def get_queryset(self):
     tx = WorkBasket.get_current_transaction(self.request)
     return models.QuotaOrderNumber.objects.approved_up_to_transaction(tx)
示例#25
0
 def get_transaction(self):
     transaction = super().get_transaction()
     transaction.workbasket = WorkBasket.current(self.request)
     return transaction
示例#26
0
文件: views.py 项目: uktrade/tamato
 def get_queryset(self):
     tx = WorkBasket.get_current_transaction(self.request)
     return AdditionalCodeDescription.objects.approved_up_to_transaction(tx)
示例#27
0
 def get_queryset(self):
     qs = super().get_queryset()
     return qs.with_workbasket(WorkBasket.current(self.request))
示例#28
0
 def get_queryset(self):
     tx = WorkBasket.get_current_transaction(self.request)
     return Regulation.objects.approved_up_to_transaction(tx)
示例#29
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
示例#30
0
 def workbasket(self) -> WorkBasket:
     return WorkBasket.current(self.request)