Exemplo n.º 1
0
class PartnerOrganizationDetailSerializer(serializers.ModelSerializer):

    staff_members = PartnerStaffMemberDetailSerializer(many=True,
                                                       read_only=True)
    assessments = AssessmentDetailSerializer(many=True, read_only=True)
    planned_engagement = PlannedEngagementSerializer(read_only=True)
    hact_values = serializers.SerializerMethodField(read_only=True)
    core_values_assessment_file = serializers.FileField(
        source='core_values_assessment', read_only=True)
    core_values_assessment_attachment = AttachmentSingleFileField(
        read_only=True)
    interventions = serializers.SerializerMethodField(read_only=True)
    hact_min_requirements = serializers.JSONField(read_only=True)
    hidden = serializers.BooleanField(read_only=True)

    def get_hact_values(self, obj):
        return json.loads(obj.hact_values) if isinstance(
            obj.hact_values, six.text_type) else obj.hact_values

    def get_interventions(self, obj):
        interventions = InterventionListSerializer(
            self.get_related_interventions(obj), many=True)
        return interventions.data

    def get_related_interventions(self, partner):
        qs = Intervention.objects.frs_qs()\
            .filter(agreement__partner=partner)\
            .exclude(status='draft')
        return qs

    class Meta:
        model = PartnerOrganization
        fields = "__all__"
Exemplo n.º 2
0
class AgreementDetailSerializer(serializers.ModelSerializer):

    partner_name = serializers.CharField(source='partner.name', read_only=True)
    authorized_officers = PartnerStaffMemberNestedSerializer(many=True,
                                                             read_only=True)
    amendments = AgreementAmendmentCreateUpdateSerializer(many=True,
                                                          read_only=True)
    unicef_signatory = SimpleUserSerializer(source='signed_by')
    partner_signatory = SimpleStaffMemberSerializer(source='partner_manager')
    attached_agreement_file = serializers.FileField(
        source="attached_agreement", read_only=True)
    attachment = AttachmentSingleFileField(read_only=True)
    permissions = serializers.SerializerMethodField(read_only=True)

    def get_permissions(self, obj):
        user = self.context['request'].user
        ps = Agreement.permission_structure()
        permissions = AgreementPermissions(user=user,
                                           instance=self.instance,
                                           permission_structure=ps)
        return permissions.get_permissions()

    class Meta:
        model = Agreement
        fields = "__all__"
Exemplo n.º 3
0
class AgreementCreateUpdateSerializer(SnapshotModelSerializer):

    partner_name = serializers.CharField(source='partner.name', read_only=True)
    agreement_type = serializers.CharField(required=True)
    amendments = AgreementAmendmentCreateUpdateSerializer(many=True,
                                                          read_only=True)
    country_programme = serializers.PrimaryKeyRelatedField(
        queryset=CountryProgramme.objects.all(),
        required=False,
        allow_null=True)
    unicef_signatory = SimpleUserSerializer(source='signed_by', read_only=True)
    partner_signatory = SimpleStaffMemberSerializer(source='partner_manager',
                                                    read_only=True)
    agreement_number = serializers.CharField(read_only=True)
    attached_agreement_file = serializers.FileField(
        source="attached_agreement", read_only=True)
    attachment = AttachmentSingleFileField(read_only=True)

    class Meta:
        model = Agreement
        fields = "__all__"

    def validate(self, data):
        data = super(AgreementCreateUpdateSerializer, self).validate(data)
        agreement_type = data.get('agreement_type',
                                  None) or self.instance.agreement_type

        if agreement_type == Agreement.PCA:
            # Look for country programme in data and on instance.
            country_programme = data.get('country_programme')
            if not country_programme and self.instance:
                country_programme = self.instance.country_programme

            if country_programme is None:
                raise ValidationError({
                    'country_programme':
                    'Country Programme is required for PCAs!'
                })

        # When running validations in the serializer.. keep in mind that the
        # related fields have not been updated and therefore not accessible on old_instance.relatedfield_old.
        # If you want to run validation only after related fields have been updated. please run it in the view
        if self.context.get('skip_global_validator', None):
            return data
        validator = AgreementValid(data,
                                   old=self.instance,
                                   user=self.context['request'].user)

        if not validator.is_valid:
            raise serializers.ValidationError({'errors': validator.errors})
        return data
Exemplo n.º 4
0
class AssessmentDetailSerializer(serializers.ModelSerializer):
    report_attachment = AttachmentSingleFileField(read_only=True)
    report_file = serializers.FileField(source='report', read_only=True)
    report = serializers.FileField(required=True)
    completed_date = serializers.DateField(required=True)

    class Meta:
        model = Assessment
        fields = "__all__"

    def validate_completed_date(self, completed_date):
        today = timezone.now().date()
        if completed_date > today:
            raise serializers.ValidationError(
                'The Date of Report cannot be in the future')
        return completed_date
Exemplo n.º 5
0
class InterventionAttachmentSerializer(serializers.ModelSerializer):
    attachment_file = serializers.FileField(source="attachment",
                                            read_only=True)
    attachment_document = AttachmentSingleFileField(source="attachment_file",
                                                    read_only=True)

    class Meta:
        model = InterventionAttachment
        fields = (
            'id',
            'intervention',
            'created',
            'type',
            'attachment',
            'attachment_file',
            'attachment_document',
        )
Exemplo n.º 6
0
class InterventionAmendmentCUSerializer(serializers.ModelSerializer):
    amendment_number = serializers.CharField(read_only=True)
    signed_amendment_file = serializers.FileField(source="signed_amendment",
                                                  read_only=True)
    signed_amendment_attachment = AttachmentSingleFileField(read_only=True)

    class Meta:
        model = InterventionAmendment
        fields = "__all__"

    def validate(self, data):
        data = super(InterventionAmendmentCUSerializer, self).validate(data)

        if 'signed_date' in data and data['signed_date'] > date.today():
            raise ValidationError("Date cannot be in the future!")

        if 'intervention' in data and data['intervention'].in_amendment is True:
            raise ValidationError(
                "Cannot add a new amendment while another amendment is in progress."
            )

        return data
Exemplo n.º 7
0
class InterventionDetailSerializer(serializers.ModelSerializer):
    planned_budget = InterventionBudgetCUSerializer(read_only=True)
    partner = serializers.CharField(source='agreement.partner.name')
    partner_id = serializers.CharField(source='agreement.partner.id',
                                       read_only=True)
    prc_review_document_file = serializers.FileField(
        source='prc_review_document', read_only=True)
    prc_review_attachment = AttachmentSingleFileField(read_only=True)
    signed_pd_document_file = serializers.FileField(
        source='signed_pd_document', read_only=True)
    signed_pd_attachment = AttachmentSingleFileField(read_only=True)
    amendments = InterventionAmendmentCUSerializer(many=True,
                                                   read_only=True,
                                                   required=False)
    planned_visits = PlannedVisitsNestedSerializer(many=True,
                                                   read_only=True,
                                                   required=False)
    attachments = InterventionAttachmentSerializer(many=True,
                                                   read_only=True,
                                                   required=False)
    result_links = InterventionResultNestedSerializer(many=True,
                                                      read_only=True,
                                                      required=False)
    submitted_to_prc = serializers.ReadOnlyField()
    frs_details = FRsSerializer(source='frs', read_only=True)
    permissions = serializers.SerializerMethodField(read_only=True)
    flagged_sections = serializers.SerializerMethodField(read_only=True)
    section_names = serializers.SerializerMethodField(read_only=True)
    locations = serializers.SerializerMethodField()
    location_names = serializers.SerializerMethodField()
    cluster_names = serializers.SerializerMethodField()

    def get_permissions(self, obj):
        user = self.context['request'].user
        ps = Intervention.permission_structure()
        permissions = InterventionPermissions(user=user,
                                              instance=self.instance,
                                              permission_structure=ps)
        return permissions.get_permissions()

    def get_locations(self, obj):
        return [l.id for l in obj.intervention_locations]

    def get_location_names(self, obj):
        return [
            '{} [{} - {}]'.format(l.name, l.gateway.name, l.p_code)
            for l in obj.intervention_locations
        ]

    def get_section_names(self, obj):
        return [l.name for l in obj.flagged_sections]

    def get_flagged_sections(self, obj):
        return [l.id for l in obj.flagged_sections]

    def get_cluster_names(self, obj):
        return [c for c in obj.intervention_clusters]

    class Meta:
        model = Intervention
        fields = (
            "id",
            'frs',
            "partner",
            "agreement",
            "document_type",
            "number",
            "prc_review_document_file",
            "frs_details",
            "signed_pd_document_file",
            "title",
            "status",
            "start",
            "end",
            "submission_date_prc",
            "review_date_prc",
            "submission_date",
            "prc_review_document",
            "submitted_to_prc",
            "signed_pd_document",
            "signed_by_unicef_date",
            "unicef_signatory",
            "unicef_focal_points",
            "partner_focal_points",
            "partner_authorized_officer_signatory",
            "offices",
            "planned_visits",
            "population_focus",
            "signed_by_partner_date",
            "created",
            "modified",
            "planned_budget",
            "result_links",
            'country_programme',
            'metadata',
            'contingency_pd',
            "amendments",
            "planned_visits",
            "attachments",
            'permissions',
            'partner_id',
            "sections",
            "locations",
            "location_names",
            "cluster_names",
            "flat_locations",
            "flagged_sections",
            "section_names",
            "in_amendment",
            "prc_review_attachment",
            "signed_pd_attachment",
        )
Exemplo n.º 8
0
class InterventionCreateUpdateSerializer(SnapshotModelSerializer):

    planned_budget = InterventionBudgetCUSerializer(read_only=True)
    partner = serializers.CharField(source='agreement.partner.name',
                                    read_only=True)
    prc_review_document_file = serializers.FileField(
        source='prc_review_document', read_only=True)
    prc_review_attachment = AttachmentSingleFileField(read_only=True)
    signed_pd_document_file = serializers.FileField(
        source='signed_pd_document', read_only=True)
    signed_pd_attachment = AttachmentSingleFileField(read_only=True)
    planned_visits = PlannedVisitsNestedSerializer(many=True,
                                                   read_only=True,
                                                   required=False)
    attachments = InterventionAttachmentSerializer(many=True,
                                                   read_only=True,
                                                   required=False)
    result_links = InterventionResultCUSerializer(many=True,
                                                  read_only=True,
                                                  required=False)
    frs = serializers.PrimaryKeyRelatedField(
        many=True,
        queryset=FundsReservationHeader.objects.prefetch_related(
            'intervention').all(),
        required=False)

    class Meta:
        model = Intervention
        fields = "__all__"

    def to_internal_value(self, data):
        if 'frs' in data:
            if data['frs'] is None:
                data['frs'] = []
        return super(InterventionCreateUpdateSerializer,
                     self).to_internal_value(data)

    def validate_frs(self, frs):
        for fr in frs:
            if fr.intervention:
                if (self.instance is None) or (not self.instance.id) or (
                        fr.intervention.id != self.instance.id):
                    raise ValidationError({
                        'error':
                        'One or more of the FRs selected is related to a different PD/SSFA,'
                        ' {}'.format(fr.fr_number)
                    })
            else:
                pass
                # unicef/etools-issues:779
                # TODO: add this validation back after all legacy data has been handled.
                # make sure it's not expired
                # if fr.expired:
                #     raise ValidationError({'error': 'One or more selected FRs is expired,'
                #                                     ' {}'.format(fr.fr_number)})
        return frs

    @transaction.atomic
    def update(self, instance, validated_data):
        updated = super(InterventionCreateUpdateSerializer,
                        self).update(instance, validated_data)
        return updated