Esempio n. 1
0
    def delete(self, request, pk, party_pk):
        """
        Removes a party from application.
        """
        application = get_application(pk)

        try:
            poa = application.active_parties.all().get(party__pk=party_pk)
        except PartyOnApplication.DoesNotExist:
            return HttpResponse(status=status.HTTP_404_NOT_FOUND)

        if not application.party_is_editable(poa.party):
            return JsonResponse(
                data={"errors": [strings.Applications.Generic.INVALID_OPERATION_FOR_READ_ONLY_CASE_ERROR]},
                status=status.HTTP_400_BAD_REQUEST,
            )

        # Delete party
        application.delete_party(poa)

        # Audit
        audit_trail_service.create(
            actor=request.user,
            verb=AuditType.REMOVE_PARTY,
            target=application.get_case(),
            payload={"party_type": poa.party.type.replace("_", " "), "party_name": poa.party.name,},
        )

        return JsonResponse(data={"party": PartySerializer(poa.party).data}, status=status.HTTP_200_OK)
Esempio n. 2
0
    def get(self, request, pk):
        destination = get_destination(pk)

        if isinstance(destination, Country):
            serializer = CountryWithFlagsSerializer(destination)
        else:
            serializer = PartySerializer(destination)

        return JsonResponse(data={"destination": serializer.data},
                            status=status.HTTP_200_OK)
Esempio n. 3
0
 def __init_cache(self, instance):
     """
     Initiate parties queryset cache, split parties by type including non data store type: inactive_parties
     """
     self.__cache = defaultdict(list)
     for poa in instance.all_parties():
         party = PartySerializer(poa.party).data
         if poa.deleted_at:
             self.__cache[PartyType.INACTIVE_PARTIES].append(party)
         else:
             self.__cache[party["type"]].append(party)
Esempio n. 4
0
    def create(self, validated_data):
        end_user_data = validated_data.pop("end_user")

        # We set the country and organisation back to their string IDs, otherwise
        # the end_user serializer struggles to save them
        end_user_data["country"] = end_user_data["country"].id
        end_user_data["organisation"] = end_user_data["organisation"].id

        end_user_serializer = PartySerializer(data=end_user_data)
        if end_user_serializer.is_valid():
            end_user = end_user_serializer.save()
        else:
            raise serializers.ValidationError(end_user_serializer.errors)
        validated_data["organisation_id"] = end_user_data["organisation"]
        validated_data["status"] = get_case_status_by_status(CaseStatusEnum.SUBMITTED)
        validated_data["submitted_at"] = timezone.localtime()
        validated_data["case_type_id"] = CaseTypeEnum.EUA.id
        end_user_advisory_query = EndUserAdvisoryQuery.objects.create(**validated_data, end_user=end_user)
        end_user_advisory_query.save()

        return end_user_advisory_query
Esempio n. 5
0
    def post(self, request, pk):
        """
        Add a party to an application
        """
        application = get_application(pk)

        data = request.data
        data["organisation"] = get_request_user_organisation_id(request)

        serializer = PartySerializer(data=data, application_type=application.case_type.sub_type)

        if serializer.is_valid(raise_exception=True):
            if str_to_bool(data.get("validate_only", False)):
                return JsonResponse(data={data["type"]: serializer.initial_data}, status=status.HTTP_200_OK)

            # Save party and add to application
            serializer.save()

            try:
                party, removed_party = application.add_party(serializer.instance)
            except ApplicationException as exc:
                return JsonResponse(data={"errors": exc.data}, status=status.HTTP_400_BAD_REQUEST)

            # Audit
            if removed_party:
                audit_trail_service.create(
                    actor=request.user,
                    verb=AuditType.REMOVE_PARTY,
                    target=application.get_case(),
                    payload={"party_type": removed_party.type.replace("_", " "), "party_name": removed_party.name},
                )
            audit_trail_service.create(
                actor=request.user,
                verb=AuditType.ADD_PARTY,
                target=application.get_case(),
                payload={"party_type": party.type.replace("_", " "), "party_name": party.name},
            )

            return JsonResponse(data={party.type: serializer.data}, status=status.HTTP_201_CREATED)
Esempio n. 6
0
    def get(self, request, pk):
        """
        Get parties for an application
        """
        application = get_application(pk)

        application_parties = application.active_parties.all().filter(deleted_at__isnull=True).select_related("party")

        if "type" in request.GET:
            application_parties = application_parties.filter(party__type=request.GET["type"])

        parties_data = PartySerializer([p.party for p in application_parties], many=True).data

        key = PartyType.api_key_name(request.GET["type"]) if "type" in request.GET else "parties"

        return JsonResponse(data={key: parties_data})
Esempio n. 7
0
    def get_ordered_parties(self, instance, party_type):
        """
        Order the parties based on destination flag priority and where the party has
        no flag, by destination (party/country depending on standard/open application) name.

        """
        parties_on_application = (
            instance.all_parties()
            .filter(party__type=party_type, deleted_at__isnull=True)
            .annotate(
                highest_flag_priority=Min("party__flags__priority"),
                contains_flags=Case(When(party__flags__isnull=True, then=0), default=1, output_field=BinaryField()),
            )
            .order_by("-contains_flags", "highest_flag_priority", "party__name")
        )

        parties = [PartySerializer(poa.party).data for poa in parties_on_application]

        return parties
Esempio n. 8
0
class EndUserAdvisoryViewSerializer(serializers.ModelSerializer):
    organisation = PrimaryKeyRelatedSerializerField(
        queryset=Organisation.objects.all(), serializer=OrganisationDetailSerializer
    )
    end_user = PartySerializer()
    reasoning = serializers.CharField(required=False, allow_blank=True, allow_null=True, max_length=2000)
    note = serializers.CharField(required=False, allow_blank=True, allow_null=True, max_length=2000)
    contact_email = serializers.EmailField()
    copy_of = serializers.PrimaryKeyRelatedField(queryset=EndUserAdvisoryQuery.objects.all(), required=False)
    status = serializers.SerializerMethodField()
    exporter_user_notification_count = serializers.SerializerMethodField()
    standard_blank_error_message = "This field may not be blank"

    class Meta:
        model = EndUserAdvisoryQuery
        fields = (
            "id",
            "end_user",
            "reasoning",
            "note",
            "organisation",
            "copy_of",
            "nature_of_business",
            "contact_name",
            "contact_email",
            "contact_job_title",
            "contact_telephone",
            "status",
            "exporter_user_notification_count",
            "reference_code",
            "case_officer",
            "created_at",
            "updated_at",
            "submitted_by",
        )

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        self.exporter_user = kwargs.get("context").get("exporter_user") if "context" in kwargs else None
        self.organisation_id = kwargs.get("context").get("organisation_id") if "context" in kwargs else None
        if not isinstance(self.exporter_user, ExporterUser):
            self.fields.pop("exporter_user_notification_count")

    def get_status(self, instance):
        if instance.status:
            return {
                "key": instance.status.status,
                "value": get_status_value_from_case_status_enum(instance.status.status),
            }
        return None

    def validate_nature_of_business(self, value):
        if self.initial_data.get("end_user").get("sub_type") == SubType.COMMERCIAL and not value:
            raise serializers.ValidationError(self.standard_blank_error_message)
        return value

    def validate_contact_name(self, value):
        if self.initial_data.get("end_user").get("sub_type") != SubType.INDIVIDUAL and not value:
            raise serializers.ValidationError(self.standard_blank_error_message)
        return value

    def validate_contact_job_title(self, value):
        if self.initial_data.get("end_user").get("sub_type") != SubType.INDIVIDUAL and not value:
            raise serializers.ValidationError(self.standard_blank_error_message)
        return value

    def create(self, validated_data):
        end_user_data = validated_data.pop("end_user")

        # We set the country and organisation back to their string IDs, otherwise
        # the end_user serializer struggles to save them
        end_user_data["country"] = end_user_data["country"].id
        end_user_data["organisation"] = end_user_data["organisation"].id

        end_user_serializer = PartySerializer(data=end_user_data)
        if end_user_serializer.is_valid():
            end_user = end_user_serializer.save()
        else:
            raise serializers.ValidationError(end_user_serializer.errors)
        validated_data["organisation_id"] = end_user_data["organisation"]
        validated_data["status"] = get_case_status_by_status(CaseStatusEnum.SUBMITTED)
        validated_data["submitted_at"] = timezone.localtime()
        validated_data["case_type_id"] = CaseTypeEnum.EUA.id
        end_user_advisory_query = EndUserAdvisoryQuery.objects.create(**validated_data, end_user=end_user)
        end_user_advisory_query.save()

        return end_user_advisory_query

    def get_exporter_user_notification_count(self, instance):
        return get_exporter_user_notification_individual_count(
            exporter_user=self.exporter_user, organisation_id=self.organisation_id, case=instance
        )
Esempio n. 9
0
 def get_destinations(self, application):
     if getattr(application, "end_user", None):
         serializer = PartySerializer(application.end_user.party)
         return {"type": "end_user", "data": serializer.data}
     else:
         return {"type": "end_user", "data": ""}