Beispiel #1
0
class OrderSerializer(serializers.ModelSerializer):
    responsible = UserSerializer(read_only=True,
                                 default=serializers.CurrentUserDefault())
    type = OrderTypeSerializer()
    consign_method = ConsignMethodSerializer()

    information_packages = serializers.HyperlinkedRelatedField(
        many=True,
        required=False,
        view_name='informationpackage-detail',
        queryset=InformationPackage.objects.filter(
            package_type=InformationPackage.DIP))

    class Meta:
        model = Order
        fields = (
            'id',
            'label',
            'responsible',
            'information_packages',
            'type',
            'personal_number',
            'first_name',
            'family_name',
            'address',
            'postal_code',
            'city',
            'phone',
            'order_content',
            'consign_method',
        )
Beispiel #2
0
class MaintenanceJobSerializer(serializers.ModelSerializer):
    user = UserSerializer(read_only=True,
                          default=serializers.CurrentUserDefault())
    label = serializers.CharField(required=False, allow_blank=True, default="")
    has_report = serializers.SerializerMethodField()

    def create(self, validated_data):
        validated_data['user'] = self.context['request'].user
        return super().create(validated_data)

    def update(self, instance, validated_data):
        if instance.status == celery_states.STARTED:
            raise Locked
        return super().update(instance, validated_data)

    def get_has_report(self, obj):
        return os.path.isfile(obj.get_report_pdf_path())

    class Meta:
        model = MaintenanceJob
        fields = (
            'id',
            'label',
            'purpose',
            'template',
            'status',
            'start_date',
            'end_date',
            'user',
            'has_report',
        )
        read_only_fields = ('end_date', )
Beispiel #3
0
class WorkareaSerializer(serializers.ModelSerializer):
    extracted = serializers.SerializerMethodField()
    packaged = serializers.SerializerMethodField()
    user = UserSerializer(read_only=True, default=serializers.CurrentUserDefault())
    type_name = serializers.SerializerMethodField()
    successfully_validated = serializers.JSONField(required=False, allow_null=True)

    def get_extracted(self, obj):
        return os.path.isdir(obj.path)

    def get_packaged(self, obj):
        return os.path.isfile(obj.path + '.tar')

    def get_type_name(self, obj):
        return obj.get_type_display()

    def create(self, validated_data):
        if 'user' not in validated_data:
            validated_data['user'] = self.context['request'].user
        return super().create(validated_data)

    class Meta:
        model = Workarea
        fields = (
            'id', 'user', 'ip', 'read_only', 'type', 'type_name',
            'extracted', 'packaged', 'successfully_validated',
        )
Beispiel #4
0
class StructureSerializer(serializers.ModelSerializer):
    type = StructureTypeSerializer()
    rule_convention_type = RuleConventionTypeSerializer()
    specification = serializers.JSONField(default={})
    created_by = UserSerializer(read_only=True,
                                default=serializers.CurrentUserDefault())
    revised_by = UserSerializer(read_only=True,
                                default=serializers.CurrentUserDefault())
    related_structures = StructureRelationSerializer(
        source='structure_relations_a', many=True, required=False)

    class Meta:
        model = Structure
        fields = (
            'id',
            'name',
            'type',
            'description',
            'template',
            'is_template',
            'version',
            'create_date',
            'revise_date',
            'start_date',
            'end_date',
            'specification',
            'rule_convention_type',
            'created_by',
            'revised_by',
            'published',
            'published_date',
            'related_structures',
            'is_editable',
        )
        extra_kwargs = {
            'is_template': {
                'read_only': True
            },
            'template': {
                'read_only': True
            },
        }
Beispiel #5
0
class RobotQueueSerializer(serializers.ModelSerializer):
    io_queue_entry = IOQueueSerializer(read_only=True)
    robot = RobotSerializer(read_only=True)
    storage_medium = StorageMediumSerializer(read_only=True)
    user = UserSerializer(read_only=True)
    req_type = serializers.SerializerMethodField()
    status = serializers.SerializerMethodField()

    def get_req_type(self, obj):
        return obj.get_req_type_display()

    def get_status(self, obj):
        return obj.get_status_display()

    class Meta:
        model = RobotQueue
        fields = ('id', 'user', 'posted', 'robot', 'io_queue_entry',
                  'storage_medium', 'req_type', 'status')
Beispiel #6
0
class MaintenanceJobSerializer(serializers.ModelSerializer):
    user = UserSerializer(read_only=True,
                          default=serializers.CurrentUserDefault())

    def create(self, validated_data):
        if 'user' not in validated_data:
            validated_data['user'] = self.context['request'].user
        return super().create(validated_data)

    class Meta:
        model = MaintenanceJob
        fields = (
            'id',
            'rule',
            'status',
            'start_date',
            'end_date',
            'user',
        )
Beispiel #7
0
class IOQueueSerializer(DynamicModelSerializer):
    ip = InformationPackageDetailSerializer()
    result = serializers.ModelField(
        model_field=IOQueue()._meta.get_field('result'), read_only=False)
    user = UserSerializer()
    storage_method_target = serializers.PrimaryKeyRelatedField(
        pk_field=serializers.UUIDField(format='hex_verbose'),
        allow_null=True,
        queryset=StorageMethodTargetRelation.objects.all())
    storage_medium = serializers.PrimaryKeyRelatedField(
        pk_field=serializers.UUIDField(format='hex_verbose'),
        allow_null=True,
        queryset=StorageMedium.objects.all())
    storage_object = StorageObjectNestedSerializer(allow_null=True,
                                                   required=False)

    req_type_display = serializers.SerializerMethodField()
    status_display = serializers.SerializerMethodField()

    def get_req_type_display(self, obj):
        return obj.get_req_type_display()

    def get_status_display(self, obj):
        return obj.get_status_display()

    class Meta:
        model = IOQueue
        fields = ('id', 'req_type', 'req_type_display', 'req_purpose', 'user',
                  'object_path', 'write_size', 'result', 'status',
                  'status_display', 'task_id', 'posted', 'ip',
                  'storage_method_target', 'storage_medium', 'storage_object',
                  'access_queue', 'remote_status', 'transfer_task_id')
        extra_kwargs = {
            'id': {
                'read_only':
                False,
                'validators':
                [validators.UniqueValidator(queryset=IOQueue.objects.all())],
            },
        }
Beispiel #8
0
class MaintenanceTemplateSerializer(serializers.ModelSerializer):
    user = UserSerializer(read_only=True,
                          default=serializers.CurrentUserDefault())
    public = serializers.BooleanField(default=True)

    def validate(self, data):
        user = self.context['request'].user

        if self.instance is not None:
            public = data.get('public', self.instance.public)
        else:
            public = data['public']

        if user.user_profile.current_organization is None and not public:
            raise serializers.ValidationError(
                "You must be in an organization to create non-public templates"
            )

        return data

    def create(self, validated_data):
        validated_data['user'] = self.context['request'].user

        instance = super().create(validated_data)
        if not instance.public:
            org = validated_data['user'].user_profile.current_organization
            org.add_object(instance)

        return instance

    class Meta:
        model = MaintenanceTemplate
        fields = (
            'id',
            'name',
            'description',
            'user',
            'public',
        )
Beispiel #9
0
class MaintenanceRuleSerializer(serializers.ModelSerializer):
    user = UserSerializer(read_only=True,
                          default=serializers.CurrentUserDefault())
    public = serializers.BooleanField(default=True)
    specification = serializers.JSONField(allow_null=True, default=None)

    def validate(self, data):
        user = self.context['request'].user
        if user.user_profile.current_organization is None and not data[
                'public']:
            raise serializers.ValidationError(
                "You must be in an organization to create non-public rules")

        return data

    def create(self, validated_data):
        if 'user' not in validated_data:
            validated_data['user'] = self.context['request'].user

        instance = super().create(validated_data)
        if not instance.public:
            org = validated_data['user'].user_profile.current_organization
            org.add_object(instance)

        return instance

    class Meta:
        model = MaintenanceRule
        fields = (
            'id',
            'name',
            'description',
            'frequency',
            'specification',
            'user',
            'public',
        )
Beispiel #10
0
class OrderSerializer(serializers.HyperlinkedModelSerializer):
    responsible = UserSerializer(read_only=True,
                                 default=serializers.CurrentUserDefault())

    information_packages = serializers.HyperlinkedRelatedField(
        many=True,
        required=False,
        view_name='informationpackage-detail',
        queryset=InformationPackage.objects.filter(
            package_type=InformationPackage.DIP))

    def save(self, **kwargs):
        kwargs["responsible"] = self.fields["responsible"].get_default()
        return super().save(**kwargs)

    class Meta:
        model = Order
        fields = (
            'url',
            'id',
            'label',
            'responsible',
            'information_packages',
        )
Beispiel #11
0
class InformationPackageSerializer(serializers.ModelSerializer):
    responsible = UserSerializer(read_only=True)
    agents = serializers.SerializerMethodField()
    permissions = serializers.SerializerMethodField()
    package_type = serializers.ChoiceField(choices=InformationPackage.PACKAGE_TYPE_CHOICES)
    package_type_display = serializers.CharField(source='get_package_type_display')
    profiles = ProfileIPSerializer(source='profileip_set', many=True)
    workarea = serializers.SerializerMethodField()
    aic = serializers.PrimaryKeyRelatedField(
        queryset=InformationPackage.objects.filter(package_type=InformationPackage.AIC)
    )
    first_generation = serializers.SerializerMethodField()
    last_generation = serializers.SerializerMethodField()
    organization = serializers.SerializerMethodField()
    new_version_in_progress = serializers.SerializerMethodField()
    submission_agreement_data = serializers.SerializerMethodField()
    submission_agreement_data_versions = serializers.SerializerMethodField()

    def get_organization(self, obj):
        try:
            ctype = ContentType.objects.get_for_model(obj)
            group = GroupGenericObjects.objects.get(object_id=obj.pk, content_type=ctype).group
            serializer = GroupSerializer(instance=group)
            return serializer.data
        except GroupGenericObjects.DoesNotExist:
            return None

    def get_agents(self, obj):
        try:
            agent_objs = obj.prefetched_agents
        except AttributeError:
            agent_objs = obj.agents.all()
        agents = AgentSerializer(agent_objs, many=True).data
        return {'{role}_{type}'.format(role=a['role'], type=a['type']): a for a in agents}

    def get_permissions(self, obj):
        user = getattr(self.context.get('request'), 'user', None)
        if user is None:
            return None

        checker = self.context.get('perm_checker')
        return obj.get_permissions(user=user, checker=checker)

    def to_representation(self, obj):
        data = super().to_representation(obj)
        profiles = data['profiles']
        data['profiles'] = {}

        for ptype in profile_types:
            data['profile_%s' % ptype] = None

        for p in profiles:
            data['profile_%s' % p['profile_type']] = p

        data.pop('profiles', None)

        return data

    def get_first_generation(self, obj):
        if hasattr(obj, 'first_generation'):
            return obj.first_generation

        return obj.is_first_generation()

    def get_last_generation(self, obj):
        if hasattr(obj, 'last_generation'):
            return obj.last_generation

        return obj.is_last_generation()

    def get_workarea(self, obj):
        try:
            workareas = obj.prefetched_workareas
        except AttributeError:
            request = self.context.get('request')
            if request is None:
                return []
            see_all = request.user.has_perm('ip.see_all_in_workspaces')
            workareas = obj.workareas.all()

            if not see_all:
                workareas = workareas.filter(user=request.user)

        return WorkareaSerializer(workareas, many=True, context=self.context).data

    def get_new_version_in_progress(self, obj):
        new = obj.new_version_in_progress()
        if new is None:
            return None
        return WorkareaSerializer(new, context=self.context).data

    def get_submission_agreement_data(self, obj):
        if obj.submission_agreement_data is not None:
            serializer = SubmissionAgreementIPDataSerializer(obj.submission_agreement_data)
            data = serializer.data
        else:
            data = {'data': {}}

        extra_data = fill_specification_data(ip=obj, sa=obj.submission_agreement)

        for field in getattr(obj.submission_agreement, 'template', []):
            if field['key'] in extra_data:
                data['data'][field['key']] = extra_data[field['key']]

        return data

    def get_submission_agreement_data_versions(self, obj):
        return SubmissionAgreementIPData.objects.filter(
            information_package=obj,
            submission_agreement=obj.submission_agreement,
        ).order_by('created').values_list('pk', flat=True)

    def validate(self, data):
        if 'submission_agreement_data' in data:
            sa = data.get('submission_agreement', getattr(self.instance, 'submission_agreement', None))
            if sa != data['submission_agreement_data'].submission_agreement:
                raise serializers.ValidationError('SubmissionAgreement and its data does not match')

        return data

    def update(self, instance, validated_data):
        if 'submission_agreement' in validated_data:
            if 'submission_agreement_data' not in validated_data:
                sa = validated_data['submission_agreement']
                try:
                    data = SubmissionAgreementIPData.objects.filter(
                        submission_agreement=sa,
                        information_package=instance,
                    ).latest(field_name='created')
                except SubmissionAgreementIPData.DoesNotExist:
                    data = None

                validated_data['submission_agreement_data'] = data

        return super().update(instance, validated_data)

    class Meta:
        model = InformationPackage
        fields = (
            'id', 'label', 'object_identifier_value', 'object_size', 'object_path',
            'submission_agreement', 'submission_agreement_locked', 'submission_agreement_data',
            'submission_agreement_data_versions',
            'package_type', 'package_type_display', 'responsible', 'create_date',
            'object_num_items', 'entry_date', 'state', 'status', 'step_state',
            'archived', 'cached', 'aic', 'generation', 'agents',
            'policy', 'message_digest', 'message_digest_algorithm',
            'content_mets_create_date', 'content_mets_size', 'content_mets_digest_algorithm', 'content_mets_digest',
            'package_mets_create_date', 'package_mets_size', 'package_mets_digest_algorithm', 'package_mets_digest',
            'start_date', 'end_date', 'permissions', 'appraisal_date', 'profiles',
            'workarea', 'first_generation', 'last_generation', 'organization', 'new_version_in_progress',
        )
        extra_kwargs = {
            'id': {
                'read_only': False,
                'validators': [],
            },
            'object_identifier_value': {
                'read_only': False,
                'validators': [],
            },
        }
Beispiel #12
0
class InformationPackageSerializer(serializers.ModelSerializer):
    responsible = UserSerializer(read_only=True)
    agents = serializers.SerializerMethodField()
    permissions = serializers.SerializerMethodField()
    package_type = serializers.ChoiceField(
        choices=InformationPackage.PACKAGE_TYPE_CHOICES)
    package_type_display = serializers.CharField(
        source='get_package_type_display')

    def get_agents(self, obj):
        agents = AgentSerializer(obj.agents.all(), many=True).data
        return {
            '{role}_{type}'.format(role=a['role'], type=a['type']): a
            for a in agents
        }

    def get_permissions(self, obj):
        user = getattr(self.context.get('request'), 'user', None)
        checker = self.context.get('perm_checker')
        return obj.get_permissions(user=user, checker=checker)

    class Meta:
        model = InformationPackage
        fields = (
            'url',
            'id',
            'label',
            'object_identifier_value',
            'object_size',
            'object_path',
            'submission_agreement',
            'submission_agreement_locked',
            'package_type',
            'package_type_display',
            'responsible',
            'create_date',
            'object_num_items',
            'entry_date',
            'state',
            'status',
            'step_state',
            'archived',
            'cached',
            'aic',
            'generation',
            'agents',
            'policy',
            'message_digest',
            'message_digest_algorithm',
            'content_mets_create_date',
            'content_mets_size',
            'content_mets_digest_algorithm',
            'content_mets_digest',
            'package_mets_create_date',
            'package_mets_size',
            'package_mets_digest_algorithm',
            'package_mets_digest',
            'start_date',
            'end_date',
            'permissions',
            'appraisal_date',
        )
Beispiel #13
0
class NestedInformationPackageSerializer(DynamicHyperlinkedModelSerializer):
    responsible = UserSerializer(read_only=True)
    package_type = serializers.ChoiceField(
        choices=InformationPackage.PACKAGE_TYPE_CHOICES)
    package_type_display = serializers.SerializerMethodField()
    information_packages = serializers.SerializerMethodField()
    aic = serializers.PrimaryKeyRelatedField(
        queryset=InformationPackage.objects.all())
    submission_agreement = serializers.PrimaryKeyRelatedField(
        queryset=SubmissionAgreement.objects.all())
    workarea = serializers.SerializerMethodField()
    first_generation = serializers.SerializerMethodField()
    last_generation = serializers.SerializerMethodField()
    new_version_in_progress = serializers.SerializerMethodField()
    permissions = serializers.SerializerMethodField()
    agents = serializers.SerializerMethodField()

    search_filter = filters.SearchFilter()

    def get_package_type_display(self, obj):
        return obj.get_package_type_display()

    def get_permissions(self, obj):
        user = getattr(self.context.get('request'), 'user', None)
        checker = self.context.get('perm_checker')
        return obj.get_permissions(user=user, checker=checker)

    def get_agents(self, obj):
        try:
            agent_objs = obj.prefetched_agents
        except AttributeError:
            agent_objs = obj.agents.all()
        agents = AgentSerializer(agent_objs, many=True).data
        return {
            '{role}_{type}'.format(role=a['role'], type=a['type']): a
            for a in agents
        }

    def get_information_packages(self, obj):
        request = self.context['request']
        return InformationPackageSerializer(
            obj.related_ips(),
            many=True,
            context={
                'request': request,
                'perm_checker': self.context.get('perm_checker')
            }).data

    def get_workarea(self, obj):
        try:
            workareas = obj.prefetched_workareas
        except AttributeError:
            request = self.context.get('request')
            see_all = request.user.has_perm('ip.see_all_in_workspaces')
            workareas = obj.workareas.all()

            if not see_all:
                workareas = workareas.filter(user=request.user)

        return WorkareaSerializer(workareas, many=True,
                                  context=self.context).data

    def get_first_generation(self, obj):
        if hasattr(obj, 'first_generation'):
            return obj.first_generation

        return obj.is_first_generation()

    def get_last_generation(self, obj):
        if hasattr(obj, 'last_generation'):
            return obj.last_generation

        return obj.is_last_generation()

    def get_new_version_in_progress(self, obj):
        new = obj.new_version_in_progress()
        if new is None:
            return None
        return WorkareaSerializer(new, context=self.context).data

    class Meta:
        model = InformationPackage
        fields = (
            'url',
            'id',
            'label',
            'object_identifier_value',
            'package_type',
            'package_type_display',
            'responsible',
            'create_date',
            'entry_date',
            'state',
            'status',
            'step_state',
            'archived',
            'cached',
            'aic',
            'information_packages',
            'generation',
            'policy',
            'message_digest',
            'agents',
            'message_digest_algorithm',
            'submission_agreement',
            'submission_agreement_locked',
            'workarea',
            'object_size',
            'first_generation',
            'last_generation',
            'start_date',
            'end_date',
            'new_version_in_progress',
            'appraisal_date',
            'permissions',
        )
        extra_kwargs = {
            'id': {
                'read_only': False,
                'validators': [],
            },
            'object_identifier_value': {
                'read_only': False,
                'validators': [],
            },
        }