class OrderItemSerializer(AuditBaseSerializer):
    """
    Serializer for the **OrderItem** model.
    """
    order = DynamicRelationField('OrderSerializer')
    item = DynamicRelationField(InventorySerializer)
    total_price = serializers.DecimalField(
        decimal_places=2,
        max_digits=7,
        min_value=0,
        read_only=True
    )

    def __configure__(self) -> None:
        super().__configure__()
        order_field = self.fields.get('order', None)
        user = self.get_user_from_context()
        # None staff users shouldn't be able to view other user's orders
        if order_field and user and not user.is_staff:
            order_field.queryset = Order.objects.filter(customer__user=user)

    def create(self, validated_data) -> OrderItem:
        order: Order = validated_data.pop('order')
        user = self.get_user_from_context()

        # Only staff members should be allowed to change the price of an item
        if not(user and user.is_staff):
            validated_data.pop('unit_price', None)
        return order.add_item(user, **validated_data)

    class Meta:
        model = OrderItem
        name = 'order_item'
        fields = '__all__'
Esempio n. 2
0
class StorySerializer(BaseSerializer):
    class Meta:
        model = Story
        name = 'story'
        plural_name = 'stories'
        fields = (
            'character',
            'creator',
            'created_at',
            'cover_image',
            'duration',
            'id',
            'recording',
            'recordings',
            'scenes',
            'scene_durations',
            'title',
        )

    recording = FileField()
    recordings = DynamicRelationField(
        'bbook_backend.api.serializers.SceneRecordingSerializer',
        many=True,
    )
    scenes = DynamicRelationField(
        'bbook_backend.api.serializers.SceneSerializer',
        many=True,
    )
    character = DynamicRelationField(
        'bbook_backend.api.serializers.CharacterSerializer',
        required=True,
    )
    cover_image = DynamicMethodField(requires=['recordings.scene.', 'scenes.'])
    duration = DynamicMethodField(requires=['recordings.'])
    title = FileField(required=False)

    def get_cover_image(self, instance):
        image = None
        try:
            if instance.scene_durations is not None:
                scene_id = instance.scene_durations[0]['scene']
                # take advantage of prefetching
                image = next(scene.image for scene in instance.scenes.all()
                             if scene.id == scene_id)
            else:
                image = min(instance.recordings.all(),
                            key=lambda rec: rec.order).scene.image
        except Exception as e:
            print('get_cover_image failed', e)

        return FileField().to_representation(image)

    def get_duration(self, instance):
        try:
            if instance.recording is not None:
                return sum([r['duration'] for r in instance.scene_durations])
            return sum([r.duration for r in instance.recordings.all()])
        except Exception as e:
            print('get_duration failed', e)
Esempio n. 3
0
class OCSerializer(DynamicModelSerializer):
    class Meta:
        model = OrganismCasProtein
        fields = ('id', 'organism', 'casprotein', 'genomic_start',
                  'genomic_end', 'evalue')

    casprotein = DynamicRelationField('CasProteinSerializer')
    organism = DynamicRelationField('OrganismSerializer')
Esempio n. 4
0
class OSSSerializer(DynamicModelSerializer):
    class Meta:
        model = OrganismSelfSpacer
        fields = ('id', 'organism', 'spacer', 'genomic_start', 'genomic_end',
                  'evalue')

    spacer = DynamicRelationField('SpacerSerializer')
    organism = DynamicRelationField('OrganismSerializer')
Esempio n. 5
0
class LSRSerializer(DynamicModelSerializer):
    class Meta:
        model = LocusSpacerRepeat
        fields = ('id', 'locus', 'spacer', 'repeat', 'order')

    spacer = DynamicRelationField('SpacerSerializer')
    repeat = DynamicRelationField('RepeatSerializer')
    locus = DynamicRelationField('LocusSerializer')
Esempio n. 6
0
class RepeatSerializer(SequenceSerializer):
    class Meta:
        model = Repeat
        fields = ('id', 'length', 'sequence', 'loci', 'spacers')
        deferred_fields = ('loci', 'spacers')

    loci = DynamicRelationField('LocusSerializer', many=True)
    spacers = DynamicRelationField('SpacerSerializer', many=True)
Esempio n. 7
0
class SpacerSerializer(SequenceSerializer):
    class Meta:
        model = Spacer
        fields = ('id', 'sequence', 'length', 'sequence', 'loci', 'repeats')
        deferred_fields = ('loci', 'repeats')

    loci = DynamicRelationField('LocusSerializer', many=True, embed=True)
    repeats = DynamicRelationField('RepeatSerializer', many=True)
Esempio n. 8
0
class MapItemSerializer(DynamicModelSerializer):
    mapItemTemplate = DynamicRelationField(
        'web.serializers.MapItemTemplateSerializer')
    owner = DynamicRelationField('web.serializers.UserSerializer',
                                 read_only=True,
                                 default=CurrentUserDefault())

    def to_representation(self, instance):
        data = super(MapItemSerializer, self).to_representation(instance)

        if self.id_only():
            return data

        properties = {}

        # add everything to properties so client can find it where expected.
        for key in data:
            if key not in ('id', self.Meta.geo_field):
                properties[key] = data[key]

        for key in properties:
            # keep dynamic related fields at the top level so dynamic_rest can extract them properly
            if key in ('owner', 'mapItemTemplate'):
                # nest id only
                try:
                    properties[key] = int(properties[key])
                except:
                    properties[key] = properties[key]['id']
            else:
                data.pop(key)

        data['properties'] = properties
        data['geometry'] = data[self.Meta.geo_field]
        data['type'] = 'Feature'

        data.pop(self.Meta.geo_field)

        return data

    def to_internal_value(self, data):
        # add all the properties to the top level object so dynamic_rest picks them up
        attrs = data
        if 'properties' in data:
            attrs = data["properties"]

            if 'geometry' in data:
                attrs[self.Meta.geo_field] = data['geometry']

        return super(MapItemSerializer, self).to_internal_value(attrs)

    class Meta:
        model = MapItem
        name = 'mapItem'
        geo_field = 'point'
        fields = ('id', 'quantity', 'mapItemTemplate', 'point', 'owner',
                  'createdAt', 'updatedAt')
Esempio n. 9
0
class LocusSerializer(DynamicModelSerializer):
    class Meta:
        model = Locus
        fields = ('id', 'organism', 'genomic_start', 'genomic_end',
                  'spacerrepeats', 'spacers', 'repeats')
        deferred_fields = ('spacerrepeats', 'spacers', 'repeats')

    organism = DynamicRelationField('OrganismSerializer')
    spacers = DynamicRelationField('SpacerSerializer', embed=True, many=True)
    repeats = DynamicRelationField('RepeatSerializer', embed=True, many=True)
Esempio n. 10
0
class DataLayerSerializer(DynamicModelSerializer):
    reliefMap = DynamicRelationField('web.serializers.ReliefMapSerializer')
    owner = DynamicRelationField('web.serializers.UserSerializer',
                                 read_only=True,
                                 default=CurrentUserDefault())

    class Meta:
        model = DataLayer
        name = 'dataLayer'
        fields = ('id', 'name', 'shapeFile', 'reliefMap', 'owner', 'createdAt',
                  'updatedAt')
Esempio n. 11
0
class OrganismSerializer(DynamicModelSerializer):
    class Meta:
        model = Organism
        fields = ('id', 'name', 'accession', 'cas_proteins', 'loci')
        deferred_fields = ('cas_proteins', 'loci')

    loci = DynamicRelationField('LocusSerializer',
                                source='locus_set',
                                embed=True,
                                many=True)
    cas_proteins = DynamicRelationField('CasProteinSerializer', many=True)
Esempio n. 12
0
class MembershipSerializer(DynamicModelSerializer):
    user = DynamicRelationField('UserSerializer')
    memberable = DynamicRelationField('MemberableSerializer')
    memberableType = SerializerMethodField()

    def get_memberableType(self, obj):
        name = obj.memberable.get_instance_name()
        return name

    class Meta:
        model = Membership
        fields = ('id', 'type', 'memberable', 'memberableType', 'user',
                  'createdAt', 'updatedAt')
Esempio n. 13
0
class MapItemTemplateSerializer(DynamicModelSerializer):
    mapItems = DynamicRelationField('web.serializers.MapItemSerializer',
                                    many=True,
                                    source='mapitem_set')
    reliefMap = DynamicRelationField('web.serializers.ReliefMapSerializer')
    owner = DynamicRelationField('web.serializers.UserSerializer',
                                 read_only=True,
                                 default=CurrentUserDefault())

    class Meta:
        model = MapItemTemplate
        name = 'mapItemTemplate'
        fields = ('id', 'name', 'category', 'subCategory', 'reliefMap',
                  'mapItems', 'owner', 'createdAt', 'updatedAt')
class TemplatePresetSerializer(DynamicModelSerializer):
    owner = DynamicRelationField('web.serializers.UserSerializer', read_only=True, default=CurrentUserDefault())

    class Meta:
        model = TemplatePreset
        name = 'templatePreset'
        fields = ('id', 'name', 'rawTemplates', 'owner', 'createdAt', 'updatedAt')
Esempio n. 15
0
class SymptomSerializer(DynamicModelSerializer):
    user = DynamicRelationField('logit.serializers.UserSerializer')

    class Meta:
        model = Symptom
        name = 'symptom'
        fields = ('id', 'location', 'severity', 'pain_type', 'user', 'created_at', 'updated_at')
Esempio n. 16
0
class MedicationSerializer(DynamicModelSerializer):
    user = DynamicRelationField('logit.serializers.UserSerializer')

    class Meta:
        model = Medication
        name = 'medication'
        fields = ('id', 'name', 'time_period', 'user', 'created_at', 'updated_at')
Esempio n. 17
0
class DiagnosisSerializer(DynamicModelSerializer):
    user = DynamicRelationField('logit.serializers.UserSerializer')

    class Meta:
        model = Diagnosis
        name = 'diagnosis'
        fields = ('id', 'name', 'severity', 'user', 'created_at', 'updated_at')
Esempio n. 18
0
class TeamSerializer(DynamicModelSerializer):
    organization = DynamicRelationField('OrganizationSerializer',
                                        source='parent')
    owner = DynamicRelationField('UserSerializer',
                                 read_only=True,
                                 default=CurrentUserDefault())

    def create(self, validated_data):
        team = Team.objects.create(**validated_data)
        Membership.objects.create(type='admin',
                                  memberable=team,
                                  user=team.owner)
        return team

    class Meta:
        model = Team
        name = 'team'
        fields = ('id', 'name', 'organization', 'owner', 'createdAt',
                  'updatedAt')
Esempio n. 19
0
class StoryRecordingSerializer(DynamicEphemeralSerializer):
    class Meta:
        name = 'story_recording'
        fields = (
            'creator',
            'story',
            'recordings',
        )

    creator = DynamicRelationField(
        'bbook_backend.api.serializers.UserSerializer',
        required=False,
    )
    recordings = DynamicRelationField(
        'bbook_backend.api.serializers.SceneRecordingSerializer',
        many=True,
    )
    story = DynamicRelationField(
        'bbook_backend.api.serializers.StorySerializer',
        required=False,
    )
Esempio n. 20
0
class SceneSerializer(BaseSerializer):

    class Meta:
        model = Scene
        name = 'scene'
        fields = (
            'character',
            'creator',
            'created_at',
            'id',
            'image',
        )

    character = DynamicRelationField(
        'bbook_backend.api.serializers.CharacterSerializer',
        required=True,
    )
    creator = DynamicRelationField(
        'bbook_backend.api.serializers.UserSerializer',
    )

    image = FileField()
Esempio n. 21
0
class SceneRecordingSerializer(BaseSerializer):
    CREATOR_FIELD = None

    class Meta:
        model = SceneRecording
        name = 'scene_recording'
        fields = (
            'created_at',
            'duration',
            'id',
            'order',
            'recording',
            'scene',
            'story',
        )

    scene = DynamicRelationField(
        'bbook_backend.api.serializers.SceneSerializer', )
    story = DynamicRelationField(
        'bbook_backend.api.serializers.StorySerializer', )
    recording = FileField()
    order = IntegerField(required=True)
Esempio n. 22
0
class FilterPresetSerializer(DynamicModelSerializer):
    mapItemTemplates = DynamicRelationField(
        'web.serializers.MapItemTemplateSerializer', many=True)
    reliefMap = DynamicRelationField('web.serializers.ReliefMapSerializer')
    owner = DynamicRelationField('web.serializers.UserSerializer',
                                 read_only=True,
                                 default=CurrentUserDefault())

    def create(self, validated_data):
        mapItemTemplates = validated_data.pop('mapItemTemplates', [])

        preset = FilterPreset.objects.create(**validated_data)

        preset.mapItemTemplates = mapItemTemplates
        preset.save()

        return preset

    class Meta:
        model = FilterPreset
        name = 'filterPreset'
        fields = ('id', 'name', 'reliefMap', 'mapItemTemplates', 'owner',
                  'createdAt', 'updatedAt')
class OrderSerializer(AuditBaseSerializer):
    """
    Serializer for the **Order** model.
    """
    customer = DynamicRelationField('CustomerSerializer')
    handler = DynamicRelationField(EmployeeSerializer)
    order_items = OrderItemSerializer(
        embed=True,
        many=True,
        read_only=True,
        source='orderitem_set'
    )
    total_price = serializers.DecimalField(
        decimal_places=2,
        max_digits=7,
        min_value=0,
        read_only=True
    )

    class Meta:
        model = Order
        name = 'order'
        fields = '__all__'
        deferred_fields = ('order_items',)
Esempio n. 24
0
class CharacterSerializer(BaseSerializer):
    class Meta:
        model = Character
        name = 'character'
        fields = (
            'creator',
            'created_at',
            'id',
            'image',
            'name',
        )

    creator = DynamicRelationField(
        'bbook_backend.api.serializers.UserSerializer', )
    image = FileField()
Esempio n. 25
0
class OrganizationSerializer(DynamicModelSerializer):
    owner = DynamicRelationField('UserSerializer',
                                 read_only=True,
                                 default=CurrentUserDefault())

    def create(self, validated_data):
        org = Organization.objects.create(**validated_data)
        membership = Membership.objects.create(type='admin',
                                               memberable=org,
                                               user=org.owner)

        membership.memberable.get_instance_name()
        return org

    class Meta:
        model = Organization
        name = 'organization'
        fields = ('id', 'name', 'owner', 'createdAt', 'updatedAt')
Esempio n. 26
0
class ReportSerializer(DynamicModelSerializer):
    reportunit_set = DynamicRelationField(ReportUnitSerializer, many=True)

    class Meta:
        model = models.Report
        exclude = []
Esempio n. 27
0
class JobSerializer(DynamicModelSerializer):
    report_set = DynamicRelationField(ReportSerializer, many=True)

    class Meta:
        model = models.Job
        exclude = []
class ParentSerializer(DynamicModelSerializer):
    class Meta:
        model = Parent
        fields = '__all__'

    children = DynamicRelationField(ChildSerializer, many=True, deferred=True)
Esempio n. 29
0
class ReliefMapSerializer(DynamicModelSerializer):
    mapItemTemplates = DynamicRelationField(
        'web.serializers.MapItemTemplateSerializer',
        many=True,
        source='mapitemtemplate_set')
    dataLayers = DynamicRelationField('web.serializers.DataLayerSerializer',
                                      many=True,
                                      source='datalayer_set')
    owner = DynamicRelationField('web.serializers.UserSerializer',
                                 read_only=True,
                                 default=CurrentUserDefault())

    def create(self, validated_data):
        reliefMap = ReliefMap.objects.create(**validated_data)

        user = self.context['request'].user
        Membership.objects.create(type='admin',
                                  memberable=reliefMap,
                                  user=user)

        templateData = {
            'reliefMap': reliefMap,
            'owner': user,
        }

        MapItemTemplate.objects.bulk_create([
            MapItemTemplate(name='Water Well',
                            category='Resource',
                            subCategory='Water, Sanitation, and Hygiene',
                            **templateData),
            MapItemTemplate(name='Resevoir',
                            category='Resource',
                            subCategory='Water, Sanitation, and Hygiene',
                            **templateData),
            MapItemTemplate(name='Water Main',
                            category='Resource',
                            subCategory='Water, Sanitation, and Hygiene',
                            **templateData),
            MapItemTemplate(name='Water Purification Pill',
                            category='Resource',
                            subCategory='Water, Sanitation, and Hygiene',
                            **templateData),
            MapItemTemplate(name='Evacuation Bus',
                            category='Resource',
                            subCategory='Logistics',
                            **templateData),
            MapItemTemplate(name='ADRA Management Tent',
                            category='Resource',
                            subCategory='Logistics',
                            **templateData),
            MapItemTemplate(name='Check In Tent',
                            category='Resource',
                            subCategory='Logistics',
                            **templateData),
            MapItemTemplate(name='Malaria Kit',
                            category='Resource',
                            subCategory='Health',
                            **templateData),
            MapItemTemplate(name='Vaccination Kit',
                            category='Resource',
                            subCategory='Health',
                            **templateData),
            MapItemTemplate(name='Vitamins',
                            category='Resource',
                            subCategory='Nutrition',
                            **templateData),
            MapItemTemplate(name='Evacuation Safe Zone',
                            category='Resource',
                            subCategory='Protection',
                            **templateData),
            MapItemTemplate(name='Blanket',
                            category='Resource',
                            subCategory='Shelter',
                            **templateData),
            MapItemTemplate(
                name='Refugee Camp',
                category='Resource',
                subCategory='Camp Coordination and Camp Management',
                **templateData),
            MapItemTemplate(name='Debris Dump',
                            category='Resource',
                            subCategory='Early Recovery',
                            **templateData),
            MapItemTemplate(name='School',
                            category='Resource',
                            subCategory='Education',
                            **templateData),
            MapItemTemplate(name='Food Rations',
                            category='Resource',
                            subCategory='Food & Security',
                            **templateData),
            MapItemTemplate(name='Public Phone',
                            category='Resource',
                            subCategory='Emergency Telecommunications',
                            **templateData),
            MapItemTemplate(name='Sinkhole', category='Hazard',
                            **templateData),
            MapItemTemplate(name='Collapsed Powerline',
                            category='Hazard',
                            **templateData),
            MapItemTemplate(name='Gas leak', category='Hazard',
                            **templateData),
            MapItemTemplate(name='Oil Spill',
                            category='Hazard',
                            **templateData),
            MapItemTemplate(name='Collapsed Road',
                            category='Hazard',
                            **templateData),
            MapItemTemplate(name='Blocked Road',
                            category='Hazard',
                            **templateData),
            MapItemTemplate(name='Flooded Area',
                            category='Hazard',
                            **templateData),
            MapItemTemplate(name='Unstable building',
                            category='Hazard',
                            **templateData),
            MapItemTemplate(name='Crack in the Road',
                            category='Hazard',
                            **templateData),
            MapItemTemplate(name='Burnt Area',
                            category='Hazard',
                            **templateData),
            MapItemTemplate(name='Fallen Tree',
                            category='Hazard',
                            **templateData),
            MapItemTemplate(name='Garbage Dump Zone',
                            category='Community Involvement',
                            **templateData),
            MapItemTemplate(name='Rally point',
                            category='Community Involvement',
                            **templateData),
            MapItemTemplate(name='Vegetable Garden',
                            category='Other Resources',
                            **templateData),
            MapItemTemplate(name='Swimming Pool',
                            category='Other Resources',
                            **templateData),
            MapItemTemplate(name='Room Available',
                            category='Other Resources',
                            **templateData),
            MapItemTemplate(name='Doctor',
                            category='Other Resources',
                            **templateData),
            MapItemTemplate(name='Dump Truck Driver',
                            category='Other Resources',
                            **templateData),
        ])

        return reliefMap

    class Meta:
        model = ReliefMap
        name = 'reliefMap'
        fields = ('id', 'name', 'description', 'mapItemTemplates',
                  'dataLayers', 'public', 'owner', 'createdAt', 'updatedAt')