class OrganisationContactSerializer(serializers.ModelSerializer):
    user_status = CustomChoiceField(read_only=True)
    user_role = CustomChoiceField(read_only=True)

    class Meta:
        model = OrganisationContact
        fields = '__all__'
Exemple #2
0
class ArtifactSerializer(serializers.ModelSerializer):
    #custodian = EmailUserSerializer(read_only=True)
    #statement = DocumentArtifactStatementSerializer(read_only=True)
    status = CustomChoiceField(read_only=True)
    artifact_object_type = serializers.SerializerMethodField()

    class Meta:
        model = Artifact
        #fields = '__all__'
        fields = (
            'id',
            #'_file',
            'identifier',
            'description',
            #'custodian',
            'artifact_date',
            'artifact_time',
            'artifact_object_type',
            'status',
        )
        read_only_fields = ('id', )

    def get_artifact_object_type(self, artifact_obj):
        artifact_object_type = None
        pa = PhysicalArtifact.objects.filter(artifact_ptr_id=artifact_obj.id)
        if pa and pa.first().id:
            artifact_object_type = 'physical'

        da = DocumentArtifact.objects.filter(artifact_ptr_id=artifact_obj.id)
        if da and da.first().id:
            artifact_object_type = 'document'

        return artifact_object_type
class OrganisationRequestSerializer(serializers.ModelSerializer):
    # assigned_officer = serializers.CharField(
    #     source='assigned_officer.get_full_name')
    identification = serializers.FileField()
    requester = OrgRequestRequesterSerializer(read_only=True)
    status = CustomChoiceField(read_only=True)
    can_be_processed = serializers.SerializerMethodField()
    user_can_process_org_access_requests = serializers.SerializerMethodField()

    class Meta:
        model = OrganisationRequest
        fields = ('id', 'identification', 'requester', 'status', 'name', 'abn',
                  'role', 'lodgement_number', 'lodgement_date',
                  'assigned_officer', 'can_be_processed',
                  'user_can_process_org_access_requests')
        read_only_fields = ('requester', 'lodgement_date')

    def get_can_be_processed(self, obj):
        return obj.status == OrganisationRequest.ORG_REQUEST_STATUS_WITH_ASSESSOR

    def get_user_can_process_org_access_requests(self, obj):
        if self.context['request'].user and self.context['request'].\
                user.has_perm('wildlifecompliance.organisation_access_request'):
            return True
        return False
class OffenceDatatableSerializer(serializers.ModelSerializer):
    status = CustomChoiceField(read_only=True)
    user_action = serializers.SerializerMethodField()
    alleged_offences = SectionRegulationSerializer(read_only=True, many=True)
    offenders = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = Offence
        fields = (
            'id',
            'identifier',
            'status',
            'lodgement_number',
            'offenders',
            'alleged_offences',
            'occurrence_from_to',
            'occurrence_datetime_from',
            'occurrence_datetime_to',
            'details',
            'user_action',
        )
        read_only_fields = ()

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

    def get_offenders(self, obj):
        offenders = Offender.active_offenders.filter(offence__exact=obj)
        return [ OffenderSerializer(offender).data for offender in offenders ]
class CreateCallEmailSerializer(serializers.ModelSerializer):
    # status_display = serializers.CharField(source='get_status_display')
    status = CustomChoiceField(read_only=True)
    # customer_status = CustomChoiceField(read_only=True)

    lodgement_date = serializers.CharField(source='lodged_on')
    classification_id = serializers.IntegerField(required=False,
                                                 write_only=True,
                                                 allow_null=True)
    report_type_id = serializers.IntegerField(required=False,
                                              write_only=True,
                                              allow_null=True)
    location_id = serializers.IntegerField(required=False,
                                           write_only=True,
                                           allow_null=True)
    #referrer_id = serializers.IntegerField(
    #   required=False, write_only=True, allow_null=True)
    region_id = serializers.IntegerField(required=False,
                                         write_only=True,
                                         allow_null=True)
    district_id = serializers.IntegerField(required=False,
                                           write_only=True,
                                           allow_null=True)
    # allocated_to = serializers.ListField(
    #     required=False, write_only=True, allow_empty=True)
    assigned_to_id = serializers.IntegerField(required=False,
                                              write_only=True,
                                              allow_null=True)
    allocated_group_id = serializers.IntegerField(required=False,
                                                  write_only=True,
                                                  allow_null=True)

    class Meta:
        model = CallEmail
        fields = (
            'id',
            'status',
            'assigned_to_id',
            # 'allocated_to',
            'allocated_group_id',
            'location_id',
            'classification_id',
            'lodgement_date',
            'caller',
            'report_type_id',
            'caller_phone_number',
            'anonymous_call',
            'caller_wishes_to_remain_anonymous',
            'occurrence_from_to',
            'occurrence_date_from',
            'occurrence_time_start',
            'occurrence_date_to',
            'occurrence_time_end',
            'advice_given',
            'advice_details',
            #'referrer_id',
            'region_id',
            'district_id',
        )
        read_only_fields = ('id', )
class InspectionDatatableSerializer(serializers.ModelSerializer):
    user_action = serializers.SerializerMethodField()
    inspection_type = InspectionTypeSerializer()
    planned_for = serializers.SerializerMethodField()
    status = CustomChoiceField(read_only=True)
    assigned_to = ComplianceUserDetailsOptimisedSerializer(read_only=True)
    inspection_team_lead = EmailUserSerializer()

    class Meta:
        model = Inspection
        fields = (
            'number',
            'title',
            'inspection_type',
            'status',
            'planned_for',
            'inspection_team_lead',
            'user_action',
            'assigned_to',
            'assigned_to_id',
        )

    def get_user_action(self, obj):
        user_id = self.context.get('request', {}).user.id
        view_url = '<a href=/internal/inspection/' + str(obj.id) + '>View</a>'
        process_url = '<a href=/internal/inspection/' + str(
            obj.id) + '>Process</a>'
        returned_url = ''

        if obj.status == 'closed':
            returned_url = view_url
        elif user_id == obj.assigned_to_id:
            returned_url = process_url
        if obj.status == 'open' and obj.inspection_team and not obj.assigned_to_id:
            for member in obj.inspection_team.all():
                if user_id == member.id:
                    returned_url = process_url
        elif (obj.allocated_group and not obj.assigned_to_id):
            for member in obj.allocated_group.members:
                if user_id == member.id:
                    returned_url = process_url

        if not returned_url:
            returned_url = view_url

        return returned_url

    def get_planned_for(self, obj):
        if obj.planned_for_date:
            if obj.planned_for_time:
                return obj.planned_for_date.strftime(
                    "%d/%m/%Y") + '  ' + obj.planned_for_time.strftime('%H:%M')
            else:
                return obj.planned_for_date.strftime("%d/%m/%Y")
        else:
            return None
class PhysicalArtifactSerializer(serializers.ModelSerializer):
    statement = DocumentArtifactSerializer(read_only=True)
    physical_artifact_type = PhysicalArtifactTypeSerializer(read_only=True)
    officer = EmailUserSerializer(read_only=True)
    disposal_method = PhysicalArtifactDisposalMethodSerializer(read_only=True)
    related_items = serializers.SerializerMethodField()
    associated_legal_case_id_list = serializers.SerializerMethodField()
    data = PhysicalArtifactFormDataRecordSerializer(many=True)
    status = CustomChoiceField(read_only=True)
    legal_case_links = serializers.SerializerMethodField()
    custodian = EmailUserSerializer(read_only=True)

    class Meta:
        model = PhysicalArtifact
        fields = (
            'id',
            'number',
            'identifier',
            'description',
            'artifact_date',
            'artifact_time',
            'statement',
            'statement_id',
            'physical_artifact_type',
            'physical_artifact_type_id',
            'disposal_method',
            'description',
            'officer',
            'disposal_date',
            'disposal_details',
            'disposal_method',
            'related_items',
            'associated_legal_case_id_list',
            'custodian',
            'status',
            'created_at',
            'data',
            'legal_case_links',
        )
        read_only_fields = ('id', )

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

    def get_legal_case_links(self, obj):
        legal_case_links = []
        for legal_case_link in obj.physicalartifactlegalcases_set.all():
            serializer = PhysicalArtifactLegalCasesSerializer(legal_case_link)
            legal_case_links.append(serializer.data)
        return legal_case_links

    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)
        return legal_case_id_list
class OffenceDatatableSerializer(serializers.ModelSerializer):
    status = CustomChoiceField(read_only=True)
    user_action = serializers.SerializerMethodField()
    alleged_offences = SectionRegulationSerializer(read_only=True, many=True)
    offenders = serializers.SerializerMethodField(read_only=True)
    documents = serializers.SerializerMethodField()

    class Meta:
        model = Offence
        fields = (
            'id',
            'identifier',
            'status',
            'lodgement_number',
            'offenders',
            'alleged_offences',
            'occurrence_from_to',
            'occurrence_datetime_from',
            'occurrence_datetime_to',
            'details',
            'user_action',
            'documents',
        )
        read_only_fields = ()

    def get_documents(self, obj):
        from wildlifecompliance.helpers import is_internal
        url_list = []

        if obj.documents.all().count():
            # Paper notices
            request = self.context.get('request', None)
            if request and is_internal(request):
                for doc in obj.documents.all():
                    url = '<a href="{}" target="_blank">{}</a>'.format(doc._file.url, doc.name)  # + viewed_text
                    url_list.append(url)
        urls = '<br />'.join(url_list)
        return urls

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

    def get_offenders(self, obj):
        offenders = Offender.active_offenders.filter(offence__exact=obj)
        return [ OffenderSerializer(offender).data for offender in offenders ]
class ReturnTypeSerializer(serializers.ModelSerializer):
    data_format = CustomChoiceField(read_only=True)
    name = serializers.SerializerMethodField()

    class Meta:
        model = ReturnType
        fields = (
            'id',
            'resources',
            'data_format',
            'name',
        )

    def get_name(self, _return_type):
        """
        Present name with versioning.
        :param _return_type: Return_Type instance.
        :return: formatted name.
        """
        return '{0} - v{1}'.format(_return_type.name, _return_type.version)
class InspectionSerializer(serializers.ModelSerializer):
    allocated_group = serializers.SerializerMethodField()
    inspection_team = serializers.SerializerMethodField()
    all_officers = serializers.SerializerMethodField()
    user_in_group = serializers.SerializerMethodField()
    can_user_action = serializers.SerializerMethodField()
    user_is_assignee = serializers.SerializerMethodField()
    status = CustomChoiceField(read_only=True)
    #inspection_team = EmailUserSerializer(many=True, read_only=True)
    individual_inspected = IndividualSerializer()
    organisation_inspected = OrganisationSerializer(read_only=True)
    #inspection_type = InspectionTypeSerializer()
    related_items = serializers.SerializerMethodField()
    inspection_report = serializers.SerializerMethodField()
    data = InspectionFormDataRecordSerializer(many=True)
    location = LocationSerializer(read_only=True)

    class Meta:
        model = Inspection
        fields = (
            'id',
            'number',
            'status',
            'title',
            'details',
            'planned_for_date',
            'planned_for_time',
            'party_inspected',
            'assigned_to_id',
            'allocated_group',
            'allocated_group_id',
            'user_in_group',
            'can_user_action',
            'user_is_assignee',
            'inspection_type_id',
            'inspection_team',
            'inspection_team_lead_id',
            'individual_inspected',
            'organisation_inspected',
            'individual_inspected_id',
            'organisation_inspected_id',
            'related_items',
            'inform_party_being_inspected',
            'call_email_id',
            'legal_case_id',
            'inspection_report',
            'schema',
            'region_id',
            'district_id',
            'data',
            'all_officers',
            'location',
        )
        read_only_fields = ('id', )

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

    def get_user_in_group(self, obj):
        return_val = False
        user_id = self.context.get('request', {}).user.id
        # inspection team should apply if status is 'open'
        if obj.status == 'open' and obj.inspection_team:
            for member in obj.inspection_team.all():
                if user_id == member.id:
                    return_val = True
        elif obj.allocated_group:
            for member in obj.allocated_group.members:
                if user_id == member.id:
                    return_val = True
        return return_val

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

        if user_id == obj.assigned_to_id:
            return_val = True
        if obj.status == 'open' and obj.inspection_team and not obj.assigned_to_id:
            for member in obj.inspection_team.all():
                if user_id == member.id:
                    return_val = True
        elif obj.allocated_group and not obj.assigned_to_id:
            for member in obj.allocated_group.members:
                if user_id == member.id:
                    return_val = True
        return return_val

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

        return return_val

    def get_inspection_team(self, obj):
        team = [{'id': None, 'full_name': '', 'member_role': '', 'action': ''}]

        returned_inspection_team = EmailUserSerializer(
            obj.inspection_team.all(),
            context={'inspection_team_lead_id': obj.inspection_team_lead_id},
            many=True)
        for member in returned_inspection_team.data:
            team.append(member)
        return team

    def get_allocated_group(self, obj):
        return ''
        #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_all_officers(self, obj):
        return []
        #all_officer_objs = []
        #compliance_content_type = ContentType.objects.get(model="compliancepermissiongroup")
        #permission = Permission.objects.filter(codename='officer').filter(content_type_id=compliance_content_type.id).first()
        #for group in permission.group_set.all():
        #    for user in group.user_set.all():
        #        all_officer_objs.append(user)

        #unique_officers = list(set(all_officer_objs))
        #sorted_unique_officers = sorted(unique_officers, key=lambda officer: officer.last_name)

        #serialized_officers = IndividualSerializer(sorted_unique_officers, many=True)
        #returned_data = serialized_officers.data
        #blank_field = [{
        #    'dob': '',
        #    'email': '',
        #    'full_name': '',
        #    'id': None,
        #    }]

        #returned_data.insert(0, blank_field)
        #print(returned_data)
        #return returned_data

    def get_inspection_report(self, obj):
        return [[r.name, r._file.url] for r in obj.report.all()]
class OffenceSerializer(serializers.ModelSerializer):
    status = CustomChoiceField(read_only=True)
    location = LocationSerializer(read_only=True)
    alleged_offences = serializers.SerializerMethodField()
    offenders = serializers.SerializerMethodField()
    allocated_group = serializers.SerializerMethodField()
    user_in_group = serializers.SerializerMethodField()
    can_user_action = serializers.SerializerMethodField()
    # can_user_edit = serializers.SerializerMethodField()
    user_is_assignee = serializers.SerializerMethodField()
    related_items = serializers.SerializerMethodField()
    in_editable_status = serializers.SerializerMethodField()
    user_action = serializers.SerializerMethodField()

    class Meta:
        model = Offence
        fields = (
            'id',
            'identifier',
            'lodgement_number',
            'status',
            'legal_case_id',
            'call_email', # TODO: should be call_email_id ?
            'region_id',
            'district_id',
            'assigned_to_id',
            'allocated_group',
            'allocated_group_id',
            'user_in_group',
            'can_user_action',
            # 'can_user_edit',
            'user_is_assignee',
            'related_items',
            'district',
            'inspection_id',
            'occurrence_from_to',
            'occurrence_datetime_from',
            'occurrence_datetime_to',
            'details',
            'location',
            'alleged_offences',
            'offenders',
            'in_editable_status',
            'user_action',
        )
        read_only_fields = (

        )

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

    def get_in_editable_status(self, obj):
        return obj.status in (Offence.STATUS_DRAFT, Offence.STATUS_OPEN)

    def get_alleged_offences(self, offence):
        alleged_offences = AllegedOffence.objects.filter(offence=offence)
        ret_list = []
        for alleged_offence in alleged_offences:
            ret_obj = {}

            section_regulation_serializer = SectionRegulationSerializer(alleged_offence.section_regulation)
            ret_obj['section_regulation'] = section_regulation_serializer.data
            ret_obj['id'] = alleged_offence.id
            ret_obj['removed'] = alleged_offence.removed
            ret_obj['removed_by_id'] = alleged_offence.removed_by.id if alleged_offence.removed_by else None
            ret_obj['reason_for_removal'] = alleged_offence.reason_for_removal

            # number_linked_to_sanction_outcomes
            ret_obj['number_linked_sanction_outcomes_total'] = AllegedCommittedOffence.objects.filter(
                Q(alleged_offence=alleged_offence)
            ).count()

            # number_linked_to_sanction_outcomes which includes alleged offence and its status is other than draft
            qs = AllegedCommittedOffence.get_active_alleged_committed_offences(alleged_offence)
            ret_obj['number_linked_sanction_outcomes_active'] = qs.count()
            connected_offenders = []
            for aco in qs:
                if aco.sanction_outcome and aco.sanction_outcome.offender:
                    serializer = EmailUserSerializer(aco.sanction_outcome.offender.person)
                    connected_offenders.append(serializer.data)
            ret_obj['connected_offenders'] = connected_offenders

            ret_list.append(ret_obj)
        return ret_list

    def get_offenders(self, obj):
        offenders = Offender.objects.filter(offence__exact=obj)
        offenders_list = [ OffenderSerializer(offender).data for offender in offenders ]
        return offenders_list

    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_edit(self, obj):
    #     can_edit = False
    #     if self.get_can_user_action(obj):
    #         if obj.status in Offence.EDITABLE_STATUSES:
    #             can_edit = True
    #     return can_edit

    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)
Exemple #12
0
class RemediationActionSerializer(serializers.ModelSerializer):
    user_action = serializers.SerializerMethodField()
    action_taken_editable = serializers.SerializerMethodField()
    documents = serializers.SerializerMethodField()
    status = CustomChoiceField(read_only=True)
    amendment_requests = AmendmentRequestForRemediationActionSerializer(read_only=True, many=True)

    class Meta:
        model = RemediationAction
        fields = (
            'id',
            'action',
            'status',
            'due_date',
            'user_action',
            'action_taken',
            'documents',
            'action_taken_editable',
            'remediation_action_id',
            'amendment_requests',
        )

    def can_user_approve(self, obj, user):
        return can_user_approve(obj, user)

    def get_action_taken_editable(self, obj):
        req = self.context.get('request', {})

        if req.user == obj.sanction_outcome.get_offender()[0] and obj.status in (RemediationAction.STATUS_OPEN):
            # if user is the offender
            # then editable
            return True
        return False

    def get_user_action(self, obj):
        req = self.context.get('request', {})

        view_url = '<a href="/external/remediation_action/' + str(obj.id) + '">View</a>'
        submit_url = '<a href="/external/remediation_action/' + str(obj.id) + '">Submit</a>'
        # accept_url = '<a href="/api/remediation_action/' + str(obj.id) + '/accept">Accept</a>'
        # request_amendment_url = '<a href="/api/remediation_action/' + str(obj.id) + '/request_amendment">Request Amendment</a>'
        accept_url = '<a data-id="{}" data-action="{}" class="accept_remediation_action">Accept</a>'.format(str(obj.id), 'accept')
        request_amendment_url = '<a data-id="{}" data-action="{}" class="request_amendment_remediation_action">Request Amendment</a>'.format(str(obj.id), 'request_amendment')

        url_list = []

        if is_internal(req):
            if self.can_user_approve(obj, req.user) and obj.status == RemediationAction.STATUS_SUBMITTED:
                # If User is one of the officers of the obj.sanction_outcome and if obj.status is submitted
                # then 'accept' and 'request amendment'
                url_list.append(accept_url)
                url_list.append(request_amendment_url)
        else:
            if req.user == obj.sanction_outcome.get_offender()[0]:
                if obj.status == RemediationAction.STATUS_OPEN:
                    url_list.append(submit_url)
                else:
                    url_list.append(view_url)

        urls = '<br />'.join(url_list)
        return urls

    def get_documents(self, obj):
        url_list = []

        if obj.documents.all().count():
            # Paper notices
            for doc in obj.documents.all():
                url = '<a href="{}" target="_blank">{}</a>'.format(doc._file.url, doc.name)
                url_list.append(url)

        urls = '<br />'.join(url_list)
        return urls
Exemple #13
0
class SanctionOutcomeDatatableSerializer(serializers.ModelSerializer):
    payment_status = CustomChoiceField(read_only=True)
    # payment_status = serializers.ReadOnlyField()
    status = CustomChoiceField(read_only=True)
    type = CustomChoiceField(read_only=True)
    user_action = serializers.SerializerMethodField()
    # offender = OffenderSerializer(read_only=True,)
    offender = serializers.SerializerMethodField()
    paper_notices = serializers.SerializerMethodField()
    coming_due_date = serializers.ReadOnlyField()
    # remediation_actions = serializers.SerializerMethodField()
    # remediation_actions = RemediationActionSerializer(read_only=True, many=True)  # This is related field
    remediation_actions = serializers.SerializerMethodField()

    class Meta:
        model = SanctionOutcome
        fields = (
            'id',
            'type',
            'payment_status',
            'status',
            'lodgement_number',
            'region',
            'district',
            'identifier',
            'offence',
            'offender',
            'alleged_offences',
            'issued_on_paper',
            'paper_id',
            'description',
            'date_of_issue',
            'time_of_issue',
            'user_action',
            'paper_notices',
            'coming_due_date',
            'remediation_actions',
        )
        read_only_fields = ()

    def get_remediation_actions(self, obj):
        r_actions = obj.remediation_actions.all().order_by('due_date')
        remes = RemediationActionSerializer(r_actions, many=True, context={'request': self.context.get('request', {})})
        return remes.data

    def get_offender(self, obj):
        if obj.driver:
            serializer = EmailUserSerializer(obj.driver)
            return serializer.data
        elif obj.registration_holder:
            serializer = EmailUserSerializer(obj.registration_holder)
            return serializer.data
        elif obj.offender:
            serializer = OffenderSerializer(obj.offender)
            return serializer.data
        else:
            return ''

    def get_paper_notices(self, obj):
        url_list = []

        if obj.documents.all().count():
            # Paper notices
            for doc in obj.documents.all():
                if self.context.get('internal', False):
                    count_logs = doc.access_logs.count()
                    viewed_text = ' Viewed by offender: <i class="fa fa-check-circle fa-lg viewed-by-offender" aria-hidden="true"></i>' if count_logs else ''
                    url = '<a href="{}" target="_blank">{}</a>'.format(doc._file.url, doc.name) + viewed_text
                else:
                    # To detect if the external user accessing the pdf file, we make Django serve the pdf file
                    url = '<a href="/api/sanction_outcome/{}/doc?name={}" target="_blank">{}</a>'.format(obj.id, doc.name, doc.name)
                url_list.append(url)

        urls = '<br />'.join(url_list)
        return urls

    def get_user_action(self, obj):
        url_list = []

        # Retrieve existing invoice if there is
        inv_ref = ''
        if obj.infringement_penalty:
            ipi = obj.infringement_penalty.infringement_penalty_invoices.all().last()
            if ipi:
                inv_ref = ipi.invoice_reference

        user = self.context.get('request', {}).user
        view_url = '<a href=/internal/sanction_outcome/' + str(obj.id) + '>View</a>'
        process_url = '<a href=/internal/sanction_outcome/' + str(obj.id) + '>Process</a>'
        view_payment_url = '<a href="/ledger/payments/invoice/payment?invoice=' + inv_ref + '">View Payment</a>' if inv_ref else ''
        cc_payment_url = '<a href="#" data-pay-infringement-penalty="' + str(obj.id) + '">Pay</a>'

        record_payment_url = '<a href="' + reverse('payments:invoice-payment') + '?invoice={}'.format(inv_ref) + '">Record Payment</a>' if inv_ref \
            else '<a href="' + reverse('preview_deferred_invoicing', kwargs={'sanction_outcome_pk': obj.id}) + '">Record Payment</a>'

        if user == obj.get_offender()[0]:
            # If offender
            if obj.payment_status == 'unpaid' and obj.status == SanctionOutcome.STATUS_AWAITING_PAYMENT:
                url_list.append(cc_payment_url)
        elif is_internal(self.context.get('request')):
            if obj.status not in SanctionOutcome.FINAL_STATUSES:
                # infringement notice is not in the final statuses
                if user.id == obj.assigned_to_id:
                    # if user is assigned to the object, the user can process it
                    url_list.append(process_url)
                elif (obj.allocated_group and not obj.assigned_to_id) and user.id in [member.id for member in obj.allocated_group.members]:
                    # if user belongs to the same group of the object
                    # and no one is assigned to the object,
                    # the user can process it
                    url_list.append(process_url)

                if is_payment_admin(user):
                    if inv_ref:
                        # There is an invoice
                        if obj.payment_status != SanctionOutcome.PAYMENT_STATUS_PAID:
                            if obj.payment_status == SanctionOutcome.PAYMENT_STATUS_PARTIALLY_PAID:
                                # Partially paid
                                url_list.append(record_payment_url)
                            elif obj.payment_status == SanctionOutcome.PAYMENT_STATUS_UNPAID:
                                url_list.append(cc_payment_url)
                                url_list.append(record_payment_url)
                        else:
                            # Paid
                            url_list.append(view_payment_url)
                    else:
                        if obj.payment_status != SanctionOutcome.PAYMENT_STATUS_PAID and obj.status == SanctionOutcome.STATUS_AWAITING_PAYMENT:
                            url_list.append(cc_payment_url)
                            url_list.append(record_payment_url)
                        else:
                            # Should not reach here
                            logger.warn('Sanction Outcome: {} payment status is PAID, but no invoices found.')

            if not url_list:
                # In other case user can view
                url_list.append(view_url)

        urls = '<br />'.join(url_list)
        return urls
class SaveCallEmailSerializer(serializers.ModelSerializer):
    status = CustomChoiceField(read_only=True)
    classification = ClassificationSerializer(read_only=True)
    location = LocationSerializer(read_only=True)
    report_type = ReportTypeSerializer(read_only=True)
    referrer = ReferrerSerializer(read_only=True)
    email_user = EmailUserSerializer(read_only=True)
    classification_id = serializers.IntegerField(required=False,
                                                 write_only=True,
                                                 allow_null=True)
    report_type_id = serializers.IntegerField(required=False,
                                              write_only=True,
                                              allow_null=True)
    location_id = serializers.IntegerField(required=False,
                                           write_only=True,
                                           allow_null=True)
    #referrer_id = serializers.IntegerField(
    #   required=False, write_only=True, allow_null=True)
    #referrers_selected = serializer.ListField(
    #   required=False, write_only=True, blank=True)
    email_user_id = serializers.IntegerField(required=False,
                                             write_only=True,
                                             allow_null=True)
    region_id = serializers.IntegerField(required=False,
                                         write_only=True,
                                         allow_null=True)
    district_id = serializers.IntegerField(required=False,
                                           write_only=True,
                                           allow_null=True)
    assigned_to_id = serializers.IntegerField(required=False,
                                              write_only=True,
                                              allow_null=True)
    allocated_group_id = serializers.IntegerField(required=False,
                                                  write_only=True,
                                                  allow_null=True)
    volunteer_id = serializers.IntegerField(required=False,
                                            write_only=True,
                                            allow_null=True)

    class Meta:
        model = CallEmail
        fields = (
            'id',
            'number',
            'status',
            'assigned_to_id',
            # 'allocated_to',
            'allocated_group_id',
            # 'status_display',
            'schema',
            'location',
            'classification',
            'report_type',
            'location_id',
            'classification_id',
            'report_type_id',
            'caller',

            #'referrer_selected',
            'referrer',
            'caller_phone_number',
            'anonymous_call',
            'caller_wishes_to_remain_anonymous',
            'occurrence_from_to',
            'occurrence_date_from',
            'occurrence_time_start',
            'occurrence_date_to',
            'occurrence_time_end',
            'date_of_call',
            'time_of_call',
            'advice_given',
            'advice_details',
            'email_user',
            'email_user_id',
            'region_id',
            'district_id',
            'volunteer_id',
        )
        read_only_fields = (
            'id',
            # 'status_display',
            'number',
            'location',
            'classification',
            'report_type',
            'referrer',
            'email_user',
        )
class CallEmailDatatableSerializer(serializers.ModelSerializer):
    status = CustomChoiceField(read_only=True)
    #classification = CustomChoiceField(read_only=True)
    classification = ClassificationSerializer(read_only=True)
    #lodgement_date = serializers.CharField(source='lodged_on')
    user_is_assignee = serializers.SerializerMethodField()
    assigned_to = ComplianceUserDetailsOptimisedSerializer(read_only=True)
    user_action = serializers.SerializerMethodField()
    user_is_volunteer = serializers.SerializerMethodField()

    class Meta:
        model = CallEmail
        fields = (
            'id',
            'status',
            'user_is_assignee',
            'classification',
            'classification_id',
            'lodged_on',
            'number',
            'caller',
            'assigned_to',
            'assigned_to_id',
            'user_action',
            'user_is_volunteer',
            'volunteer_id',
        )
        read_only_fields = ('id', )

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

    def get_user_action(self, obj):
        user_id = self.context.get('request', {}).user.id
        view_url = '<a href=/internal/call_email/' + str(obj.id) + '>View</a>'
        process_url = '<a href=/internal/call_email/' + str(
            obj.id) + '>Process</a>'
        returned_url = ''

        if obj.status == 'closed':
            returned_url = view_url
        elif user_id == obj.assigned_to_id:
            returned_url = process_url
        elif (obj.allocated_group and not obj.assigned_to_id):
            for member in obj.allocated_group.members:
                if user_id == member.id:
                    returned_url = process_url

        if not returned_url:
            returned_url = view_url

        return returned_url

    def get_user_is_volunteer(self, obj):
        user = EmailUser.objects.get(
            id=self.context.get('request', {}).user.id)
        for group in user.groups.all():
            for permission in group.permissions.all():
                if permission.codename == 'volunteer':
                    return True
        # return false if 'volunteer' is not a permission of any group the user belongs to
        return False
class CallEmailSerializer(serializers.ModelSerializer):
    status = CustomChoiceField(read_only=True)
    classification = ClassificationSerializer(read_only=True)
    lodgement_date = serializers.CharField(source='lodged_on')
    report_type = ReportTypeSerializer(read_only=True)
    location = LocationSerializer(read_only=True)
    referrer = ReferrerSerializer(many=True)
    data = ComplianceFormDataRecordSerializer(many=True)
    email_user = EmailUserSerializer(read_only=True)
    # allocated_group = CallEmailAllocatedGroupSerializer(many=True)
    # allocated_group = CompliancePermissionGroupMembersSerializer()
    allocated_group = serializers.SerializerMethodField()
    user_in_group = serializers.SerializerMethodField()
    related_items = serializers.SerializerMethodField()
    selected_referrers = serializers.SerializerMethodField()
    user_is_assignee = serializers.SerializerMethodField()
    can_user_action = serializers.SerializerMethodField()
    can_user_edit_form = serializers.SerializerMethodField()
    can_user_search_person = serializers.SerializerMethodField()
    user_is_volunteer = serializers.SerializerMethodField()
    volunteer_list = serializers.SerializerMethodField()
    current_user_id = serializers.SerializerMethodField()

    class Meta:
        model = CallEmail
        fields = (
            'id',
            'status',
            # 'status_display',
            'assigned_to_id',
            'allocated_group',
            'allocated_group_id',
            'location',
            'location_id',
            'classification',
            'classification_id',
            'schema',
            'lodgement_date',
            'number',
            'caller',
            'report_type',
            'report_type_id',
            'data',
            'caller_phone_number',
            'anonymous_call',
            'caller_wishes_to_remain_anonymous',
            'occurrence_from_to',
            'occurrence_date_from',
            'occurrence_time_start',
            'occurrence_date_to',
            'occurrence_time_end',
            'date_of_call',
            'time_of_call',
            'referrer',
            # 'referrer_id',
            'advice_given',
            'advice_details',
            'email_user',
            'region_id',
            'district_id',
            'user_in_group',
            'related_items',
            'selected_referrers',
            'user_is_assignee',
            'can_user_action',
            'can_user_edit_form',
            'can_user_search_person',
            'user_is_volunteer',
            'volunteer_list',
            'volunteer_id',
            'current_user_id',
        )
        read_only_fields = ('id', )

    def get_current_user_id(self, obj):
        return self.context.get('request', {}).user.id

    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_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:
            for member in obj.allocated_group.members:
                if user_id == member.id:
                    return True

        return False

    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_related_items(self, obj):
        return get_related_items(obj)

    def get_selected_referrers(self, obj):
        referrers_selected = []
        #returned_referrers = ReferrerSerializer(obj.referrer)
        #print(returned_referrers.data)
        for referrer in obj.referrer.all():
            print(referrer)
            referrers_selected.append(str(referrer.id))

        return referrers_selected

    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_can_user_edit_form(self, obj):
        user_id = self.context.get('request', {}).user.id

        if obj.status == 'draft':
            if user_id == obj.assigned_to_id:
                return True
            elif obj.allocated_group and not obj.assigned_to_id:
                for member in obj.allocated_group.members:
                    if user_id == member.id:
                        return True

        return False

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

        if obj.status == 'open':
            if user_id == obj.assigned_to_id:
                return True
            elif obj.allocated_group and not obj.assigned_to_id:
                for member in obj.allocated_group.members:
                    if user_id == member.id:
                        return True

        return False

    def get_user_is_volunteer(self, obj):
        user = EmailUser.objects.get(
            id=self.context.get('request', {}).user.id)
        for group in user.groups.all():
            for permission in group.permissions.all():
                if permission.codename == 'volunteer':
                    return True
        # return false if 'volunteer' is not a permission of any group the user belongs to
        return False

    def get_volunteer_list(self, obj):
        volunteer_list = [{
            'email': '',
            'first_name': '',
            'full_name': '',
            'id': None,
            'last_name': '',
            'title': '',
        }]
        compliance_content_type = ContentType.objects.get(
            model="compliancepermissiongroup")
        # user = EmailUser.objects.get(id=self.context.get('request', {}).user.id)
        permission = Permission.objects.filter(codename='volunteer').filter(
            content_type_id=compliance_content_type.id).first()
        group = CompliancePermissionGroup.objects.filter(
            permissions=permission).first()

        returned_volunteer_list = CompliancePermissionGroupMembersSerializer(
            instance=group)
        for member in returned_volunteer_list.data['members']:
            volunteer_list.append(member)

        return volunteer_list
Exemple #17
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
class ReturnRequestSerializer(serializers.ModelSerializer):
    reason = CustomChoiceField()

    class Meta:
        model = ReturnRequest
        fields = '__all__'
Exemple #19
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]