Пример #1
0
class ExclusionReportDetailSerializer(serializers.ModelSerializer):
    """
    Detail Serializer for the Exclusion Report
    """
    status = ComplianceReportWorkflowStateSerializer(read_only=True)
    type = ComplianceReportTypeSerializer(read_only=True)
    organization = OrganizationMinSerializer(read_only=True)
    compliance_period = CompliancePeriodSerializer(read_only=True)
    exclusion_agreement = ExclusionAgreementSerializer(read_only=True)
    history = serializers.SerializerMethodField()

    def get_history(self, obj):
        """
        Returns all the previous status changes for the credit trade
        """
        from .ComplianceReportHistory import ComplianceReportHistorySerializer

        history = obj.get_history(["Submitted"])

        serializer = ComplianceReportHistorySerializer(history, many=True)

        return serializer.data

    class Meta:
        model = ComplianceReport
        fields = [
            'id', 'status', 'type', 'organization', 'compliance_period',
            'exclusion_agreement', 'read_only', 'history'
        ]
Пример #2
0
class ComplianceReportHistorySerializer(serializers.ModelSerializer):
    from .Role import RoleMinSerializer

    status = ComplianceReportWorkflowStateSerializer(read_only=True)
    user = SerializerMethodField()
    user_role = RoleMinSerializer(read_only=True)

    def get_user(self, obj):
        serializer = UserMinSerializer(
            obj.user,
            read_only=True)

        return serializer.data

    class Meta:
        model = ComplianceReportHistory
        fields = ('id', 'user', 'status', 'user', 'user_role')
Пример #3
0
class ComplianceReportHistorySerializer(serializers.ModelSerializer):
    from .Role import RoleMinSerializer

    status = ComplianceReportWorkflowStateSerializer(read_only=True)
    user = SerializerMethodField()
    user_role = RoleMinSerializer(read_only=True)
    display_name = SerializerMethodField()
    compliance_report = PrimaryKeyRelatedField(read_only=True)

    def get_display_name(self, obj):
        if obj.compliance_report.nickname is not None and obj.compliance_report.nickname is not '':
            return obj.compliance_report.nickname
        return obj.compliance_report.generated_nickname

    def get_user(self, obj):
        serializer = UserMinSerializer(obj.user, read_only=True)

        return serializer.data

    class Meta:
        model = ComplianceReportHistory
        fields = ('id', 'compliance_report', 'display_name', 'user', 'status',
                  'user', 'user_role', 'create_timestamp')
Пример #4
0
class ExclusionReportUpdateSerializer(serializers.ModelSerializer):
    """
    Update Serializer for the Compliance Report
    """
    status = ComplianceReportWorkflowStateSerializer(required=False)
    type = SlugRelatedField(slug_field='the_type', read_only=True)
    compliance_period = SlugRelatedField(slug_field='description',
                                         read_only=True)
    organization = OrganizationMinSerializer(read_only=True)
    exclusion_agreement = ExclusionAgreementSerializer(allow_null=True,
                                                       required=False)

    def validate_exclusion_agreement(self, data):
        return data

    def update(self, instance, validated_data):
        request = self.context.get('request')

        if 'status' in validated_data:
            status_data = validated_data.pop('status')
            can_change = ComplianceReportPermissions.user_can_change_status(
                request.user,
                instance,
                new_fuel_supplier_status=status_data['fuel_supplier_status'].
                status if 'fuel_supplier_status' in status_data else None,
                new_analyst_status=status_data['analyst_status'].status
                if 'analyst_status' in status_data else None,
                new_director_status=status_data['director_status'].status
                if 'director_status' in status_data else None,
                new_manager_status=status_data['manager_status'].status
                if 'manager_status' in status_data else None)
            if not can_change:
                raise PermissionDenied('Invalid status change')

            if 'fuel_supplier_status' in status_data:
                instance.status.fuel_supplier_status = status_data[
                    'fuel_supplier_status']
            if 'analyst_status' in status_data:
                instance.status.analyst_status = status_data['analyst_status']
            if 'manager_status' in status_data:
                instance.status.manager_status = status_data['manager_status']
            if 'director_status' in status_data:
                instance.status.director_status = status_data[
                    'director_status']

            instance.status.save()

        if 'exclusion_agreement' in validated_data:
            agreement_data = validated_data.pop('exclusion_agreement')

            if instance.exclusion_agreement:
                ExclusionAgreementRecord.objects.filter(
                    exclusion_agreement=instance.exclusion_agreement).delete()

                exclusion_agreement = instance.exclusion_agreement

            if 'records' in agreement_data:
                records_data = agreement_data.pop('records')

                if not instance.exclusion_agreement:
                    exclusion_agreement = ExclusionAgreement.objects.create(
                        **agreement_data, compliance_report=instance)
                    instance.exclusion_agreement = exclusion_agreement

                for record_data in records_data:
                    record = ExclusionAgreementRecord.objects.create(
                        **record_data, exclusion_agreement=exclusion_agreement)
                    exclusion_agreement.records.add(record)
                    exclusion_agreement.save()

        if request:
            instance.update_user = request.user

        instance.save()

        # all other fields are read-only
        return instance

    class Meta:
        model = ComplianceReport
        fields = ('status', 'type', 'compliance_period', 'organization',
                  'exclusion_agreement', 'read_only')
        read_only_fields = ('compliance_period', 'read_only', 'organization')
Пример #5
0
class ExclusionReportUpdateSerializer(serializers.ModelSerializer,
                                      ExclusionReportValidator):
    """
    Update Serializer for the Exclusion Report
    """
    actions = serializers.SerializerMethodField()
    actor = serializers.SerializerMethodField()
    compliance_period = SlugRelatedField(slug_field='description',
                                         read_only=True)
    exclusion_agreement = ExclusionAgreementSerializer(allow_null=True,
                                                       required=False)
    organization = OrganizationDisplaySerializer(read_only=True)
    status = ComplianceReportWorkflowStateSerializer(required=False)
    type = SlugRelatedField(slug_field='the_type', read_only=True)
    supplemental_note = serializers.CharField(max_length=500,
                                              min_length=1,
                                              required=False,
                                              allow_null=True)
    display_name = serializers.SerializerMethodField()

    def get_display_name(self, obj):
        if obj.nickname is not None and obj.nickname is not '':
            return obj.nickname
        return obj.generated_nickname

    def get_actions(self, obj):
        relationship = ComplianceReportPermissions.get_relationship(
            obj, self.context['request'].user)

        return ComplianceReportPermissions.get_available_actions(
            obj, relationship)

    def get_actor(self, obj):
        return ComplianceReportPermissions.get_relationship(
            obj, self.context['request'].user).value

    def update(self, instance, validated_data):
        request = self.context.get('request')

        if 'status' in validated_data:
            status_data = validated_data.pop('status')
            can_change = ComplianceReportPermissions.user_can_change_status(
                request.user,
                instance,
                new_fuel_supplier_status=status_data['fuel_supplier_status'].
                status if 'fuel_supplier_status' in status_data else None,
                new_analyst_status=status_data['analyst_status'].status
                if 'analyst_status' in status_data else None,
                new_director_status=status_data['director_status'].status
                if 'director_status' in status_data else None,
                new_manager_status=status_data['manager_status'].status
                if 'manager_status' in status_data else None)
            if not can_change:
                raise PermissionDenied('Invalid status change')

            if 'fuel_supplier_status' in status_data:
                instance.status.fuel_supplier_status = status_data[
                    'fuel_supplier_status']
                if instance.supplements is not None and instance.status.fuel_supplier_status.status in [
                        'Submitted'
                ]:
                    # supplemental note is required
                    if 'supplemental_note' not in validated_data:
                        raise serializers.ValidationError(
                            'supplemental note is required when submitting a '
                            'supplemental report')
                    instance.supplemental_note = validated_data.pop(
                        'supplemental_note')
            if 'analyst_status' in status_data:
                instance.status.analyst_status = status_data['analyst_status']
            if 'manager_status' in status_data:
                instance.status.manager_status = status_data['manager_status']
            if 'director_status' in status_data:
                instance.status.director_status = status_data[
                    'director_status']

            instance.status.save()

        if 'exclusion_agreement' in validated_data:
            agreement_data = validated_data.pop('exclusion_agreement')

            if instance.exclusion_agreement:
                ExclusionAgreementRecord.objects.filter(
                    exclusion_agreement=instance.exclusion_agreement).delete()

                exclusion_agreement = instance.exclusion_agreement

            if 'records' in agreement_data:
                records_data = agreement_data.pop('records')

                if not instance.exclusion_agreement:
                    exclusion_agreement = ExclusionAgreement.objects.create(
                        **agreement_data, compliance_report=instance)
                    instance.exclusion_agreement = exclusion_agreement

                for record_data in records_data:
                    record = ExclusionAgreementRecord.objects.create(
                        **record_data, exclusion_agreement=exclusion_agreement)
                    exclusion_agreement.records.add(record)
                    exclusion_agreement.save()

        if instance.status.fuel_supplier_status.status in ['Submitted'] and \
                not instance.has_snapshot:
            # Create a snapshot
            request = self.context.get('request')
            snap = dict(
                ExclusionReportDetailSerializer(instance,
                                                context=self.context).data)
            snap['version'] = 1  # to track deserialization version
            snap['timestamp'] = datetime.now()

            ComplianceReportSnapshot.objects.filter(
                compliance_report=instance).delete()
            ComplianceReportSnapshot.objects.create(
                compliance_report=instance,
                create_user=request.user,
                create_timestamp=datetime.now(),
                snapshot=snap)

        if request:
            instance.update_user = request.user

        instance.save()

        # all other fields are read-only
        return instance

    class Meta:
        model = ComplianceReport
        fields = ('status', 'type', 'compliance_period', 'organization',
                  'exclusion_agreement', 'read_only', 'actions', 'actor',
                  'display_name', 'supplemental_note', 'is_supplemental')
        read_only_fields = ('compliance_period', 'read_only', 'organization',
                            'actions', 'actor', 'is_supplemental',
                            'display_name')
Пример #6
0
class ExclusionReportDetailSerializer(serializers.ModelSerializer):
    """
    Detail Serializer for the Exclusion Report
    """
    actions = serializers.SerializerMethodField()
    actor = serializers.SerializerMethodField()
    compliance_period = CompliancePeriodSerializer(read_only=True)
    exclusion_agreement = ExclusionAgreementSerializer(read_only=True)
    history = serializers.SerializerMethodField()
    organization = OrganizationDisplaySerializer(read_only=True)
    status = ComplianceReportWorkflowStateSerializer(read_only=True)
    type = ComplianceReportTypeSerializer(read_only=True)
    deltas = serializers.SerializerMethodField()
    display_name = serializers.SerializerMethodField()

    skip_deltas = False

    def get_display_name(self, obj):
        if obj.nickname is not None and obj.nickname is not '':
            return obj.nickname
        return obj.generated_nickname

    def get_deltas(self, obj):

        deltas = []

        if self.skip_deltas:
            return deltas

        current = obj

        while current:
            if current.supplements:
                ancestor = current.supplements

                qs = ComplianceReportSnapshot.objects.filter(
                    compliance_report=ancestor)

                if qs.exists():
                    ancestor_snapshot = qs.first().snapshot
                    ancestor_computed = False
                else:
                    # no snapshot. make one.
                    ser = ExclusionReportDetailSerializer(ancestor,
                                                          context=self.context)
                    ser.skip_deltas = True
                    ancestor_snapshot = ser.data
                    ancestor_computed = True

                qs = ComplianceReportSnapshot.objects.filter(
                    compliance_report=current)

                if qs.exists():
                    current_snapshot = qs.first().snapshot
                else:
                    # no snapshot
                    ser = ExclusionReportDetailSerializer(current,
                                                          context=self.context)
                    ser.skip_deltas = True
                    current_snapshot = ser.data

                deltas += [{
                    'levels_up':
                    1,
                    'ancestor_id':
                    ancestor.id,
                    'ancestor_display_name':
                    ancestor.nickname if
                    (ancestor.nickname is not None and ancestor.nickname != '')
                    else ancestor.generated_nickname,
                    'delta':
                    ComplianceReportService.compute_delta(
                        current_snapshot, ancestor_snapshot),
                    'snapshot': {
                        'data': ancestor_snapshot,
                        'computed': ancestor_computed
                    }
                }]

            current = current.supplements

        return deltas

    def get_actor(self, obj):
        return ComplianceReportPermissions.get_relationship(
            obj, self.context['request'].user).value

    def get_actions(self, obj):
        relationship = ComplianceReportPermissions.get_relationship(
            obj, self.context['request'].user)

        return ComplianceReportPermissions.get_available_actions(
            obj, relationship)

    def get_history(self, obj):
        """
        Returns all the previous status changes for the credit trade
        """
        from .ComplianceReportHistory import ComplianceReportHistorySerializer
        user = self.context['request'].user \
            if 'request' in self.context else None

        if user and user.is_government_user:
            history = obj.get_history(include_government_statuses=True)

            serializer = ComplianceReportHistorySerializer(
                history, many=True, context=self.context)

            return serializer.data
        elif user and not user.is_government_user:
            history = obj.get_history()

            serializer = ComplianceReportHistorySerializer(
                history, many=True, context=self.context)

            return serializer.data
        else:
            return None

    class Meta:
        model = ComplianceReport
        fields = [
            'id', 'status', 'type', 'organization', 'compliance_period',
            'exclusion_agreement', 'read_only', 'history', 'actions', 'actor',
            'has_snapshot', 'deltas', 'display_name', 'supplemental_note',
            'is_supplemental'
        ]