Esempio n. 1
0
    def update_assigned_to_id(self, request, *args, **kwargs):
        try:
            instance = self.get_object()

            validation_serializer = OffenceSerializer(
                instance, context={'request': request})
            user_in_group = validation_serializer.data.get('user_in_group')

            if user_in_group:
                # current user is in the group
                if request.data.get('current_user'):
                    # current user is going to assign him or herself to the object
                    serializer_partial = UpdateAssignedToIdSerializer(
                        instance=instance,
                        data={
                            'assigned_to_id': request.user.id,
                        })
                else:
                    # current user is going to assign someone else to the object
                    serializer_partial = UpdateAssignedToIdSerializer(
                        instance=instance, data=request.data)

                if serializer_partial.is_valid(raise_exception=True):
                    # Update only assigned_to_id data
                    serializer_partial.save()

                # Construct return value
                return_serializer = OffenceSerializer(
                    instance=instance, context={'request': request})
                headers = self.get_success_headers(return_serializer.data)
                return Response(return_serializer.data,
                                status=status.HTTP_200_OK,
                                headers=headers)
            else:
                return Response(validation_serializer.data,
                                status=status.HTTP_200_OK)

        except serializers.ValidationError:
            print(traceback.print_exc())
            raise
        except ValidationError as e:
            print(traceback.print_exc())
            raise serializers.ValidationError(repr(e.error_dict))
        except Exception as e:
            print(traceback.print_exc())
            raise serializers.ValidationError(str(e))
Esempio n. 2
0
    def filter_by_legal_case(self, request, *args, **kwargs):
        legal_case_id = self.request.query_params.get('legal_case_id', None)

        try:
            legal_case = LegalCase.objects.get(id=legal_case_id)
            queryset = self.get_queryset().filter(legal_case__exact=legal_case)
        except:
            queryset = self.get_queryset()

        serializer = OffenceSerializer(queryset,
                                       many=True,
                                       context={'request': request})
        return Response(serializer.data)
Esempio n. 3
0
    def filter_by_inspection(self, request, *args, **kwargs):
        inspection_id = self.request.query_params.get('inspection_id', None)

        try:
            inspection = Inspection.objects.get(id=inspection_id)
            queryset = self.get_queryset().filter(inspection__exact=inspection)
        except:
            queryset = self.get_queryset()

        serializer = OffenceSerializer(queryset,
                                       many=True,
                                       context={'request': request})
        return Response(serializer.data)
Esempio n. 4
0
    def filter_by_call_email(self, request, *args, **kwargs):
        call_email_id = self.request.query_params.get('call_email_id', None)

        try:
            call_email = CallEmail.objects.get(id=call_email_id)
            queryset = self.get_queryset().filter(call_email__exact=call_email)
        except:
            queryset = self.get_queryset()

        serializer = OffenceSerializer(queryset,
                                       many=True,
                                       context={'request': request})
        return Response(serializer.data)
Esempio n. 5
0
class AllegedOffenceSerializer(serializers.ModelSerializer):
    offence = OffenceSerializer(read_only=True)
    section_regulation = SectionRegulationSerializer(read_only=True)

    class Meta:
        model = AllegedOffence
        fields = (
            'id',
            'offence',
            'section_regulation',
        )
        validators = [
            UniqueTogetherValidator(
                queryset=AllegedOffence.objects.filter(removed=False),
                fields=['offence', 'section_regulation'],
                message='Offence cannot associated with the sambe section regulation more than once'
            )
        ]

    def validate(self, data):
        # TODO: Add object level validation here if needed
        return data
Esempio n. 6
0
class DocumentArtifactSerializer(serializers.ModelSerializer):
    statement = DocumentArtifactStatementSerializer(read_only=True)
    #document_type = DocumentArtifactTypeSerializer(read_only=True)
    #document_type = CustomChoiceField(read_only=True)
    document_type_display = serializers.SerializerMethodField()
    person_providing_statement = EmailUserSerializer(read_only=True)
    officer_interviewer = EmailUserSerializer(read_only=True)
    interviewer = EmailUserSerializer(read_only=True)
    #people_attending = EmailUserSerializer(read_only=True, many=True)
    #legal_case = LegalCaseSerializer(read_only=True, many=True)
    people_attending_id_list = serializers.SerializerMethodField()
    #legal_case_id_list = serializers.SerializerMethodField()
    associated_legal_case_id_list = serializers.SerializerMethodField()
    offence = OffenceSerializer(read_only=True)
    offender = OffenderSerializer(read_only=True)
    related_items = serializers.SerializerMethodField()
    available_statement_artifacts = serializers.SerializerMethodField()
    primary_legal_case_id = serializers.SerializerMethodField()
    status = CustomChoiceField(read_only=True)

    class Meta:
        model = DocumentArtifact
        #fields = '__all__'
        fields = (
            'id',
            'number',
            'identifier',
            'description',
            #'custodian',
            'artifact_date',
            'artifact_time',
            'document_type',
            #'document_type_id',
            'statement',
            'statement_id',
            'person_providing_statement',
            'interviewer',
            'people_attending_id_list',
            #'legal_case_id_list',
            'associated_legal_case_id_list',
            #'legal_case_id',
            'primary_legal_case_id',
            'offence',
            'offender',
            'offence_id',
            'offender_id',
            'related_items',
            #'officer_interviewer_email',
            'officer_interviewer',
            'document_type_display',
            'status',
            'created_at',
            'available_statement_artifacts',
        )
        read_only_fields = ('id', )

    def get_related_items(self, obj):
        return get_related_items(obj)

    def get_primary_legal_case_id(self, obj):
        return obj.primary_legal_case_id

    #def get_legal_case_id_list(self, obj):
    #    legal_case_id_list = []
    #    for legal_case in obj.associated_legal_cases.all():
    #        legal_case_id_list.append(legal_case.id)
    #    if obj.legal_case:
    #        legal_case_id_list.append(obj.legal_case.id)
    #    return legal_case_id_list

    def get_associated_legal_case_id_list(self, obj):
        legal_case_id_list = []
        for legal_case in obj.legal_cases.all():
            legal_case_id_list.append(legal_case.id)
        #if obj.legal_case:
        #   legal_case_id_list.append(obj.legal_case.id)
        return legal_case_id_list

    def get_people_attending_id_list(self, obj):
        people_attending_id_list = []
        for person in obj.people_attending.all():
            people_attending_id_list.append(person.id)
        return people_attending_id_list

    def get_document_type_display(self, obj):
        display_name = ''
        for choice in DocumentArtifact.DOCUMENT_TYPE_CHOICES:
            if obj.document_type == choice[0]:
                display_name = choice[1]
            #res_obj.append({'id': choice[0], 'display': choice[1]});
        #res_json = json.dumps(res_obj)
        return display_name

    def get_available_statement_artifacts(self, obj):
        artifact_list = []
        primary_legal_case = None
        for link in obj.documentartifactlegalcases_set.all():
            if link.primary:
                primary_legal_case = link.legal_case
        # for legal_case in obj.legal_cases.all():
        #     if legal_case.primary:
        #         primary_legal_case = legal_case
        if primary_legal_case:
            for link in primary_legal_case.documentartifactlegalcases_set.all(
            ):
                if (link.primary and link.document_artifact.document_type
                        and link.document_artifact.document_type in [
                            'record_of_interview', 'witness_statement',
                            'expert_statement', 'officer_statement'
                        ]):
                    serialized_artifact = DocumentArtifactStatementSerializer(
                        link.document_artifact)
                    artifact_list.append(serialized_artifact.data)
            return artifact_list
Esempio n. 7
0
class SanctionOutcomeSerializer(serializers.ModelSerializer):
    status = CustomChoiceField(read_only=True)
    type = CustomChoiceField(read_only=True)
    payment_status = CustomChoiceField(read_only=True)
    # payment_status = serializers.ReadOnlyField()
    alleged_committed_offences = serializers.SerializerMethodField()
    offender = OffenderSerializer(read_only=True,)
    offence = OffenceSerializer(read_only=True,)
    allocated_group = serializers.SerializerMethodField()
    user_in_group = serializers.SerializerMethodField()
    can_user_action = serializers.SerializerMethodField()
    user_is_assignee = serializers.SerializerMethodField()
    related_items = serializers.SerializerMethodField()
    paper_notices = serializers.SerializerMethodField()
    due_dates = serializers.SerializerMethodField()
    is_parking_offence = serializers.ReadOnlyField()
    registration_holder = IndividualSerializer()
    driver = IndividualSerializer()
    remediation_actions = RemediationActionSerializer(read_only=True, many=True)  # This is related field

    class Meta:
        model = SanctionOutcome
        fields = (
            'id',
            'type',
            'status',
            'payment_status',
            'lodgement_number',
            'region_id',
            'district_id',
            'identifier',
            'offence',
            'offender',
            'alleged_committed_offences',
            'issued_on_paper',
            'paper_id',
            'paper_notices',
            'description',
            'date_of_issue',
            'time_of_issue',
            'assigned_to_id',
            'allocated_group',
            'allocated_group_id',
            'user_in_group',
            'can_user_action',
            'user_is_assignee',
            'related_items',
            'penalty_amount_1st',
            'penalty_amount_2nd',
            'due_date_extended_max',
            'due_dates',
            'is_parking_offence',
            'registration_holder',
            'driver',
            'registration_holder_id',
            'driver_id',
            'registration_number',
            'remediation_actions',
        )

    def get_due_dates(self, obj):
        ret = []

        for date in obj.due_dates.all():
            ret.append(SanctionOutcomeDueDateSerializer(date).data)

        return ret

    def get_paper_notices(self, obj):
        return [[r.name, r._file.url] for r in obj.documents.all()]

    def get_allocated_group(self, obj):
        allocated_group = [{
            'email': '',
            'first_name': '',
            'full_name': '',
            'id': None,
            'last_name': '',
            'title': '',
        }]
        returned_allocated_group = CompliancePermissionGroupMembersSerializer(instance=obj.allocated_group)
        for member in returned_allocated_group.data['members']:
            allocated_group.append(member)

        return allocated_group

    def get_user_in_group(self, obj):
        user_id = self.context.get('request', {}).user.id

        if obj.allocated_group:
            for member in obj.allocated_group.members:
                if user_id == member.id:
                    return True
        return False

    def get_can_user_action(self, obj):
        # User can have action buttons
        # when user is assigned to the target object or
        # when user is a member of the allocated group and no one is assigned to the target object
        user_id = self.context.get('request', {}).user.id
        if user_id == obj.assigned_to_id:
            return True
        elif obj.allocated_group and not obj.assigned_to_id:
            if user_id in [member.id for member in obj.allocated_group.members]:
                return True

        return False

    def get_user_is_assignee(self, obj):
        user_id = self.context.get('request', {}).user.id
        if user_id == obj.assigned_to_id:
            return True

        return False

    def get_related_items(self, obj):
        return get_related_items(obj)

    def get_alleged_committed_offences(self, so_obj):
        qs_allegedCommittedOffences = so_obj.retrieve_alleged_committed_offences()
        return [AllegedCommittedOffenceSerializer(item, context={'request': self.context.get('request', {})}).data for item in qs_allegedCommittedOffences]
Esempio n. 8
0
    def create(self, request, *args, **kwargs):
        try:
            with transaction.atomic():
                request_data = request.data

                # 1. Save Location
                if (request_data.get('location', {}).get('geometry', {}).get(
                        'coordinates', {})
                        or request_data.get('location', {}).get(
                            'properties', {}).get('postcode', {})
                        or request_data.get('location', {}).get(
                            'properties', {}).get('details', {})):
                    location_request_data = request.data.get('location')
                    returned_location = save_location(location_request_data)
                    if returned_location:
                        request_data.update(
                            {'location_id': returned_location.get('id')})

                # 2. Create Offence
                request_data['status'] = 'open'
                request_data['region_id'] = int(
                    request_data['region_id']
                ) if request_data['region_id'] else None
                request_data['district_id'] = int(
                    request_data['district_id']
                ) if request_data['district_id'] else None
                serializer = SaveOffenceSerializer(data=request_data)
                serializer.is_valid(raise_exception=True)
                saved_offence_instance = serializer.save(
                )  # Here, relations between this offence and location, and this offence and call_email/inspection are created

                # 2.1. Determine allocated group and save it
                new_group = Offence.get_compliance_permission_group(
                    saved_offence_instance.regionDistrictId)
                saved_offence_instance.allocated_group = new_group
                saved_offence_instance.assigned_to = None
                saved_offence_instance.responsible_officer = request.user
                saved_offence_instance.log_user_action(
                    OffenceUserAction.ACTION_CREATE.format(
                        saved_offence_instance.lodgement_number), request)
                saved_offence_instance.save()

                # 2.2. Update parents
                self.update_parent(request, saved_offence_instance)

                # Handle documents
                from wildlifecompliance.components.main.models import TemporaryDocumentCollection
                from wildlifecompliance.components.main.process_document import save_default_document_obj
                temporary_document_collection_dict = request_data.get(
                    'temporary_document_collection_id', None)
                if temporary_document_collection_dict:
                    temporary_document_collection_id = temporary_document_collection_dict.get(
                        'temp_doc_id', None)
                    if temporary_document_collection_id:
                        temp_doc_collection, created = TemporaryDocumentCollection.objects.get_or_create(
                            id=temporary_document_collection_id)
                        if temp_doc_collection:
                            for doc in temp_doc_collection.documents.all():
                                save_default_document_obj(
                                    saved_offence_instance, doc)
                                pass
                            temp_doc_collection.delete()

                ## 2a. Log it to the call email, if applicable
                #if saved_offence_instance.call_email:
                #    saved_offence_instance.call_email.log_user_action(
                #            CallEmailUserAction.ACTION_OFFENCE.format(
                #                saved_offence_instance.call_email.number),
                #                request)

                ## 2b. Log it to the inspection, if applicable
                #if saved_offence_instance.inspection:
                #    saved_offence_instance.inspection.log_user_action(
                #            InspectionUserAction.ACTION_OFFENCE.format(
                #                saved_offence_instance.inspection.number),
                #                request)

                # 3. Create relations between this offence and the alleged 0ffence(s)
                for alleged_offence in request_data['alleged_offences']:
                    section_regulation = SectionRegulation.objects.get(
                        id=alleged_offence['section_regulation']['id'])
                    # Insert a record into the through table
                    alleged_offence = AllegedOffence.objects.create(
                        section_regulation=section_regulation,
                        offence=saved_offence_instance,
                    )

                # 4. Create relations between this offence and offender(s)
                for dict in request_data['offenders']:
                    if dict['data_type'] == 'individual':
                        offender = EmailUser.objects.get(id=dict['id'])
                        serializer_offender = SaveOffenderSerializer(
                            data={
                                'offence_id': saved_offence_instance.id,
                                'person_id': offender.id
                            })
                        serializer_offender.is_valid(raise_exception=True)
                        serializer_offender.save()
                    elif dict['data_type'] == 'organisation':
                        offender = Organisation.objects.get(id=dict['id'])
                        serializer_offender = SaveOffenderSerializer(
                            data={
                                'offence_id': saved_offence_instance.id,
                                'organisation_id': offender.id
                            })
                        serializer_offender.is_valid(raise_exception=True)
                        serializer_offender.save()

                # 4. Return Json
                headers = self.get_success_headers(serializer.data)
                return_serializer = OffenceSerializer(
                    instance=saved_offence_instance,
                    context={'request': request})
                # return_serializer = InspectionSerializer(saved_instance, context={'request': request})
                ret = Response(return_serializer.data,
                               status=status.HTTP_201_CREATED,
                               headers=headers)
                return ret

        except serializers.ValidationError:
            print(traceback.print_exc())
            raise
        except ValidationError as e:
            print(traceback.print_exc())
            raise serializers.ValidationError(repr(e.error_dict))
        except Exception as e:
            print(traceback.print_exc())
            raise serializers.ValidationError(str(e))