예제 #1
0
class KeggModuleRetrieveSerializer(m_serializers.DynamicDocumentSerializer,
                                   serializers.HyperlinkedModelSerializer):

    url = serializers.HyperlinkedIdentityField(
        view_name='emgapi_v1:keggmodules-detail',
        lookup_field='accession',
    )

    completeness = serializers.FloatField(required=True)
    matching_kos = serializers.ListField()
    missing_kos = serializers.ListField()

    class Meta:
        model = m_models.KeggModule
        fields = '__all__'
예제 #2
0
class FlowResultsResponseSerializer(serializers.Serializer):
    """
    FlowResultsResponseSerializer for handling publishing of Flow Results
    Response package.
    """
    id = serializers.CharField()  # pylint: disable=invalid-name
    responses = serializers.ListField()

    class JSONAPIMeta:  # pylint: disable=old-style-class,no-init,R0903
        """
        JSON API metaclass.
        """
        resource_name = 'responses'

    def create(self, validated_data):
        request = self.context['request']
        responses = validated_data['responses']
        xform = get_object_or_404(XForm, uuid=validated_data['id'])
        processed = []
        for submission in parse_responses(responses):
            xml_file = BytesIO(dict2xform(
                submission, xform.id_string, 'data').encode('utf-8'))

            error, instance = safe_create_instance(
                request.user.username, xml_file, [], None, request)
            processed.append(instance.pk)
            if error:
                raise serializers.ValidationError(error)

        return FlowResultsResponse(xform.uuid, responses)

    def update(self, instance, validated_data):
        pass
예제 #3
0
class AntecedenteFamiliarCiudadanoSerializer(serializers.ModelSerializer):
    parentesco = serializers.ListField()
    parentesco_display = serializers.SerializerMethodField()

    class Meta:
        model = AntecedenteFamiliar
        fields = (
            'uuid',
            'ciex',
            'ciex_descripcion',
            'ciudadano',
            'codigo_antecedente_sugerido',
            'consulta_paciente',
            'es_removido',
            'fecha_fin',
            'fecha_inicio',
            'grupo_antecedente',
            'nombre_antecedente_sugerido',
            'observaciones',
            'parentesco',
            'parentesco_display',
            'registro_antecedente',
            'subgrupo_antecedente',
        )

    def get_parentesco_display(self, obj):
        parentescos = []
        for parentesco in obj.parentesco:
            parentescos.append(PARENTESCO_CHOICES_DICT.get(str(parentesco)))
        return parentescos
예제 #4
0
class PermissionLinkCreateSerializer(PermissionLinkSerializer):
    emails = serializers.ListField(child=serializers.EmailField(),
                                   min_length=0,
                                   required=False)

    class Meta:
        model = PermissionLink
        fields = ('name', 'expiration_date', 'emails')
        read_only = ('shipment', )
예제 #5
0
class FlowResultsResponseSerializer(serializers.Serializer):
    """
    FlowResultsResponseSerializer for handling publishing of Flow Results
    Response package.
    """
    id = serializers.CharField()  # pylint: disable=invalid-name
    responses = serializers.ListField()
    duplicates = serializers.IntegerField(read_only=True)

    class JSONAPIMeta:  # pylint: disable=old-style-class,no-init,R0903
        """
        JSON API metaclass.
        """
        resource_name = 'responses'

    def create(self, validated_data):
        duplicates = 0
        request = self.context['request']
        responses = validated_data['responses']
        uuid = UUID(validated_data['id'])
        xform = get_object_or_404(XForm,
                                  Q(uuid=str(uuid)) | Q(uuid=uuid.hex),
                                  deleted_at__isnull=True)
        for submission in parse_responses(responses):
            xml_file = BytesIO(
                dict2xform(submission, xform.id_string,
                           'data').encode('utf-8'))

            error, _instance = safe_create_instance(request.user.username,
                                                    xml_file, [], None,
                                                    request)
            if error and error.status_code != 202:
                raise serializers.ValidationError(error)
            if error and error.status_code == 202:
                duplicates += 1

        return FlowResultsResponse(xform.uuid, responses, duplicates)

    def update(self, instance, validated_data):
        pass
예제 #6
0
class ShipmentCreateSerializer(ShipmentSerializer):
    device_id = serializers.CharField(max_length=36, required=False)
    ship_from_location = LocationSerializer(required=False)
    ship_to_location = LocationSerializer(required=False)
    bill_to_location = LocationSerializer(required=False)
    final_destination_location = LocationSerializer(required=False)
    device = DeviceSerializer(required=False)
    tags = serializers.ListField(
        child=serializers.DictField(child=serializers.CharField(max_length=50)),
        required=False
    )

    def create(self, validated_data):
        extra_args = {}

        with transaction.atomic():
            for location_field in ['ship_from_location', 'ship_to_location', 'bill_to_location']:
                if location_field in validated_data:
                    data = validated_data.pop(location_field)
                    extra_args[location_field] = Location.objects.create(**data)

            if 'device' in self.context:
                extra_args['device'] = self.context['device']

            shipment_tags = validated_data.pop('tags', [])
            shipment = Shipment.objects.create(**validated_data, **extra_args)

            for shipment_tag in shipment_tags:
                ShipmentTag.objects.create(
                    tag_type=shipment_tag['tag_type'],
                    tag_value=shipment_tag['tag_value'],
                    shipment_id=shipment.id,
                    owner_id=shipment.owner_id
                )

            return shipment

    def validate_tags(self, tags):
        tag_list = set()
        for tag_dict in tags:
            if 'tag_value' not in tag_dict or 'tag_type' not in tag_dict:
                raise serializers.ValidationError('Tags items must contain `tag_value` and `tag_type`.')

            tag_list.add(tuple(tag_dict.items()))

        if len(tags) != len(tag_list):
            raise serializers.ValidationError('Tags field cannot contain duplicates')

        return tags

    def validate_device_id(self, device_id):
        device = Device.get_or_create_with_permission(self.auth, device_id)
        device.prepare_for_reassignment()

        self.context['device'] = device

        return device_id

    def validate_shipper_wallet_id(self, shipper_wallet_id):
        if settings.PROFILES_ENABLED:
            response = settings.REQUESTS_SESSION.get(f'{settings.PROFILES_URL}/api/v1/wallet/{shipper_wallet_id}/',
                                                     headers={'Authorization': 'JWT {}'.format(self.auth)})

            if response.status_code != status.HTTP_200_OK:
                raise serializers.ValidationError('User does not have access to this wallet in ShipChain Profiles')

        return shipper_wallet_id

    def validate_storage_credentials_id(self, storage_credentials_id):
        if settings.PROFILES_ENABLED:
            response = settings.REQUESTS_SESSION.get(
                f'{settings.PROFILES_URL}/api/v1/storage_credentials/{storage_credentials_id}/',
                headers={'Authorization': 'JWT {}'.format(self.auth)})

            if response.status_code != status.HTTP_200_OK:
                raise serializers.ValidationError(
                    'User does not have access to this storage credential in ShipChain Profiles')

        return storage_credentials_id

    def validate_gtx_required(self, gtx_required):
        if settings.PROFILES_ENABLED:
            if gtx_required and not self.user.has_perm('gtx.shipment_use'):
                raise PermissionDenied('User does not have access to enable GTX for this shipment')
        return gtx_required

    def validate_quickadd_tracking(self, quickadd_tracking):
        response = requests.post(f'{settings.AFTERSHIP_URL}couriers/detect',
                                 headers={'aftership-api-key': settings.AFTERSHIP_API_KEY},
                                 json={'tracking': {'tracking_number': quickadd_tracking}})
        if not response.ok:
            raise serializers.ValidationError('Invalid quickadd_tracking value')

        return quickadd_tracking
예제 #7
0
class UpdateSerializer(serializers.ModelSerializer):

    included_serializers = {
        'person': 'contacts.serializers.PersonSerializer',
        'notes': 'service.serializers.NoteSerializer'
    }

    ticket = ResourceRelatedField(queryset=Ticket.objects.all(),
                                  self_link_view_name='update-relationships')
    notes = ResourceRelatedField(many=True,
                                 read_only=True,
                                 self_link_view_name='update-relationships',
                                 related_link_view_name='update-notes-list',
                                 related_link_url_kwarg='update_pk')
    ticket_changes = serializers.ListField(child=serializers.DictField(),
                                           required=False,
                                           read_only=True)
    changed_fields = ChangedFieldSerializer(required=False, write_only=True)

    def __init__(self, *args, from_ticket=False, **kwargs):
        super(UpdateSerializer, self).__init__(*args, **kwargs)
        if not from_ticket:
            # when instantiated by TicketSerializer, keep changed_fields field
            # otherwise, from_ticket is false and we remove the changed_fields field
            # because it shouldn't be externally available
            self.fields.pop('changed_fields', None)

    def validate(self, data):
        if 'changed_fields' in data:
            self._remove_dummy_changed_fields(data)
            if len(data['changed_fields']) == 0:
                del data['changed_fields']

        return data

    def _remove_dummy_changed_fields(self, data):
        ticket = data['ticket']
        for field, new_value in data['changed_fields'].items():
            old_value = getattr(ticket, field)
            if old_value == new_value:
                del data['changed_fields'][field]

    def create(self, validated_data):
        with transaction.atomic():
            changed_fields = validated_data.pop('changed_fields', {})
            person = self.context['request'].user.person
            update = Update.objects.create(person=person, **validated_data)
            self._apply_ticket_changes(validated_data['ticket'],
                                       changed_fields, update)
            return update

    def _apply_ticket_changes(self, ticket, changed_fields, update):
        for field, new_value in changed_fields.items():
            TicketChange.objects.create(field=field,
                                        update=update,
                                        old_value=getattr(ticket, field),
                                        new_value=new_value)
            setattr(ticket, field, new_value)
        ticket.save()

    # def update(self, instance, validated_data):
    #     editable_fields_on_update = ('display_time', 'body', 'duration', 'billable_hours')
    #

    class Meta:
        model = Update
        fields = ('ticket', 'display_time', 'body', 'person', 'duration',
                  'billable_hours', 'ticket_changes', 'changed_fields',
                  'notes')
예제 #8
0
class RoomNodeInstallationSerializer(serializers.HyperlinkedModelSerializer):
    included_serializers = {
        "node": "core.serializers.NodeSerializer",
        "room": "core.serializers.RoomSerializer",
        # "timeseries": "core.serializers.TimeseriesSerializer",
    }

    node = ResourceRelatedField(
        queryset=Node.objects.all(),
        related_link_url_kwarg="installation_pk",
        related_link_view_name="installation-related-node",
    )

    room = ResourceRelatedField(
        queryset=Room.objects.all(), related_link_view_name="installation-related"
    )

    to_timestamp_s = serializers.IntegerField(required=False)
    # Image of the installation (optional). Handle upload in a separate serializer.
    image = serializers.ImageField(required=False, read_only=True)

    # Additional fields to merge the node installation with its samples.
    timeseries = serializers.ListField(child=SimpleSampleSerializer(), read_only=True)
    query_timestamp_s = serializers.IntegerField(read_only=True)
    sample_count = serializers.IntegerField(read_only=True)
    url = serializers.HyperlinkedIdentityField(view_name="installation-detail")

    class Meta:
        model = RoomNodeInstallation
        fields = [
            "room",
            "node",
            "timeseries",
            "query_timestamp_s",
            "from_timestamp_s",
            "to_timestamp_s",
            "sample_count",
            "description",
            "image",
            "is_public",
            "url",
        ]

    def __init__(self, *args, **kwargs):
        # Don't pass the "include_timeseries" arg up to the superclass
        include_timeseries = kwargs.pop("include_timeseries", None)
        # Instantiate the superclass normally
        super().__init__(*args, **kwargs)

        if not include_timeseries:
            self.fields.pop("timeseries")

    def get_owner(self):
        """Return the owner of the resource, once data is validated."""
        room = self.validated_data["room"]
        site = room.site
        owner = site.operator
        return owner

    def validate(self, attrs):
        """
        Ensure that the node is owned by the same organization as the room.
        """
        logger.debug(
            "For a new or updated installation, validate that node and room belong to the same owner."
        )
        try:
            room = attrs["room"]
            node = attrs["node"]
        except KeyError:
            raise serializers.ValidationError(
                "Both the Room reference and the node reference must be provided."
            )
        if room.site.operator != node.owner:
            raise serializers.ValidationError(
                "In an installation, Node and room must belong to the same owner."
            )
        return attrs
예제 #9
0
class NodeSerializer(serializers.HyperlinkedModelSerializer):
    related_serializers = {
        "protocol": "core.serializers.NodeProtocolSerializer",
        "model": "core.serializers.NodeModelSerializer",
        "owner": "core.serializers.OrganizationSerializer",
        "installations": "core.serializers.RoomNodeInstallationSerializer",
    }

    protocol = ResourceRelatedField(
        queryset=NodeProtocol.objects.all(), related_link_view_name="node-related"
    )

    model = ResourceRelatedField(
        queryset=NodeModel.objects.all(), related_link_view_name="node-related"
    )

    owner = ResourceRelatedField(
        queryset=Organization.objects.all(), related_link_view_name="node-related"
    )

    # A Node is installed in one or more rooms over its lifetime.
    installations = HyperlinkedRelatedField(
        many=True,
        read_only=True,
        related_link_view_name="node-related",
    )

    # Additional fields to merge the node model with its samples.
    timeseries = serializers.ListField(child=SimpleSampleSerializer(), read_only=True)
    query_timestamp_s = serializers.IntegerField(read_only=True)
    sample_count = serializers.IntegerField(read_only=True)
    from_timestamp_s = serializers.IntegerField(read_only=True)
    to_timestamp_s = serializers.IntegerField(read_only=True)

    class Meta:
        model = Node
        fields = (
            "id",
            "eui64",
            "alias",
            "description",
            "query_timestamp_s",
            "from_timestamp_s",
            "to_timestamp_s",
            "sample_count",
            "timeseries",
            "protocol",
            "model",
            "owner",
            "installations",
            "url",
        )

    def __init__(self, *args, **kwargs):
        # Don't pass the "include_timeseries" arg up to the superclass
        include_timeseries = kwargs.pop("include_timeseries", None)
        # Instantiate the superclass normally
        super().__init__(*args, **kwargs)

        if not include_timeseries:
            self.fields.pop("timeseries")

    def get_owner(self):
        """Return the owner of the resource, once data is validated."""
        return self.validated_data["owner"]