Esempio n. 1
0
 def get_payload_recipients(self, passenger):
     trip = passenger.trip
     user = trip.user
     recipients = []
     payload = []
     for app in self.get_valid_apps(user):
         recipients.append(app.webhook_url)
         user_id = app.get_scoped_user_id(app, user)
         trip_id = trip.id
         payload.append({
             'user_id':
             user_id,
             'trip_id':
             trip_id,
             'resource_url':
             settings.ROOT_URL +
             reverse(local_versioned_url_name(
                 'api:driver-trips-passengers-detail', __file__, 2),
                     kwargs={
                         'trip_id':
                         trip.id,
                         'passenger_user_id':
                         app.get_scoped_user_id(app, passenger.user)
                     })
         })
     return payload, recipients
Esempio n. 2
0
class DriverTripListRetrieveSerializer(BaseTripListRetrieveSerializer):
    """Serializer for the viewing of trips by drivers"""

    url = serializers.HyperlinkedIdentityField(
        lookup_url_kwarg='id',
        label="URL para detalhes da carona",
        view_name=local_versioned_url_name('api:driver-trips-detail', __file__,
                                           2))
    passengers = serializers.HyperlinkedIdentityField(
        label="URL para lista de passageiros da carona",
        lookup_url_kwarg='trip_id',
        view_name=local_versioned_url_name('api:driver-trips-passengers-list',
                                           __file__, 2))

    class Meta(BaseTripListRetrieveSerializer.Meta):
        fields = ['url', 'passengers'
                  ] + BaseTripListRetrieveSerializer.Meta.fields
Esempio n. 3
0
class PassengerSerializer(QueryFieldsMixin, PrefetchMixin,
                          serializers.HyperlinkedModelSerializer):
    """
    Passenger serializer to drivers
    Shows up when a driver is viewing who asked to join their trip
    """
    user_id = ScopedUserIDField(source='user', label='ID do passageiro')
    url = NestedScopedUserIDHyperlinkedField(
        label="Detalhes do passageiro",
        lookup_url_kwarg='passenger_user_id',
        parent_lookup_kwargs={'trip_id': 'trip__id'},
        view_name=local_versioned_url_name(
            'api:driver-trips-passengers-detail', __file__, 2))
    trip = serializers.HyperlinkedRelatedField(
        label="Detalhes da carona",
        lookup_url_kwarg='id',
        read_only=True,
        view_name=local_versioned_url_name('api:driver-trips-detail', __file__,
                                           2))
    first_name = serializers.CharField(source='user.first_name',
                                       required=False)
    last_name = serializers.CharField(source='user.last_name', required=False)
    profile = NotPermissionedProfileSerializer(source='user.profile',
                                               label="Perfil do passageiro",
                                               required=False)
    student = BasicStudentSerializer(
        source='user.student',
        label="Informações de estudante do passageiro",
        required=False)

    class Meta:
        model = Passenger
        fields = [
            'url', 'trip', 'user_id', 'first_name', 'last_name', 'profile',
            'student', 'status', 'seats', 'book_time'
        ]
        select_related_fields = ['user', 'user__profile', 'user__student']
        extra_kwargs = {
            'status': {
                'label':
                'Status do passageiro na carona (aprovado, pendente ou negado)'
            }
        }
Esempio n. 4
0
class AlarmListRetrieveSerializer(QueryFieldsMixin, PrefetchMixin,
                                  serializers.HyperlinkedModelSerializer):
    """Alarm list and retrieve serializer
    """
    origin_coordinates = PointSerializer(label="Coordenadas da origem",
                                         source='origin_point',
                                         required=False)
    destination_coordinates = PointSerializer(label="Coordenadas do destino",
                                              source='destination_point',
                                              required=False)

    url = serializers.HyperlinkedIdentityField(
        lookup_url_kwarg='id',
        label="URL para detalhes do alarme",
        view_name=local_versioned_url_name('api:alarms-detail', __file__, 1))

    datetime__gte = serializers.DateTimeField(
        label="Datetime máxima de saída da carona",
        source="datetime_gte",
        required=False)
    datetime__lte = serializers.DateTimeField(
        label="Datetime máxima de saída da carona",
        source="datetime_lte",
        required=False)
    seats_left__gte = serializers.IntegerField(
        label='Mínimo número de assentos na carona',
        source="min_seats",
        required=False)
    price__lte = serializers.IntegerField(
        label='Preço máximo da carona em reais',
        source="price",
        required=False)

    class Meta:
        model = Alarm
        fields = [
            'url', 'id', 'origin', 'destination', 'origin_coordinates',
            'destination_coordinates', 'origin_radius', 'destination_radius',
            'price__lte', 'datetime__lte', 'datetime__gte', 'auto_approve',
            'seats_left__gte'
        ]
        extra_kwargs = {
            'origin': {
                'required': False
            },
            'destination': {
                'required': False
            },
            'auto_approve': {
                'required': False
            },
        }
Esempio n. 5
0
class AlarmListRetrieveSerializer(QueryFieldsMixin, PrefetchMixin,
                                  serializers.HyperlinkedModelSerializer):
    """Alarm list and retrieve serializer
    """
    origin_coordinates = PointSerializer(label="Coordenadas da origem",
                                         source='origin_point',
                                         required=False)
    destination_coordinates = PointSerializer(label="Coordenadas do destino",
                                              source='destination_point',
                                              required=False)

    url = serializers.HyperlinkedIdentityField(
        lookup_url_kwarg='id',
        label="URL para detalhes do alarme",
        view_name=local_versioned_url_name('api:alarms-detail', __file__, 1))

    class Meta:
        model = Alarm
        fields = [
            'url', 'origin', 'destination', 'origin_coordinates',
            'destination_coordinates', 'origin_radius', 'destination_radius',
            'price', 'datetime_lte', 'datetime_gte', 'auto_approve',
            'min_seats'
        ]
        extra_kwargs = {
            'origin': {
                'required': False
            },
            'destination': {
                'required': False
            },
            'price': {
                'required': False
            },
            'datetime_lte': {
                'required': False
            },
            'datetime_gte': {
                'required': False
            },
            'auto_approve': {
                'required': False
            },
            'min_seats': {
                'required': False
            },
        }
Esempio n. 6
0
 def get_payload_recipients(self, alarm, trip):
     user = alarm.user
     trip_url = settings.ROOT_URL + reverse(local_versioned_url_name(
         'api:search-trips-detail', __file__, 2),
                                            kwargs={'pk': trip.id})
     recipients = []
     payload = []
     for app in self.get_valid_apps(user):
         recipients.append(app.webhook_url)
         user_id = app.get_scoped_user_id(app, user)
         trip_id = trip.id
         payload.append({
             'user_id': user_id,
             'trip_id': trip_id,
             'resource_url': trip_url
         })
     return payload, recipients
Esempio n. 7
0
from django.db.models import Prefetch
Esempio n. 8
0
class PassengerTripListRetrieveSerializer(BaseTripListRetrieveSerializer):
    """
    Shows details of a trip and its driver to passenger who have been accepted into it
    """
    url = serializers.HyperlinkedIdentityField(
        label="URL para detalhes da carona",
        view_name=local_versioned_url_name('api:passenger-trips-detail',
                                           __file__, 2))
    driver = DriverDetailedInfo(
        help_text=
        "Dados completos do motorista. Disponível se o passageiro **tiver** sido aprovado na carona.",
        source='user',
        required=False)
    driver_basic = DriverBasic2Info(
        help_text=
        "Dados básicos do motorista. Disponível se o passageiro **não tiver** sido aprovado na carona.",
        source='user',
        required=False)
    status = serializers.SerializerMethodField(
        help_text="Status do passageiro na carona")
    seats = serializers.SerializerMethodField(
        help_text="Número de assentos reservados")
    approved_passengers = BasicPassengerSerializer(
        help_text=
        "Passageiros aprovados na carona. Disponível se o passageiro **tiver** sido aprovado na carona.",
        many=True,
        required=False)

    @swagger_serializer_method(
        serializer_or_field=serializers.ChoiceField(choices=STATUS_CHOICES))
    def get_status(self, obj):
        user = self.context['request'].user
        passenger = obj.passengers.filter(user=user).first()
        return passenger.status if passenger is not None else None

    @swagger_serializer_method(serializer_or_field=serializers.IntegerField())
    def get_seats(self, obj):
        user = self.context['request'].user
        passenger = obj.passengers.filter(user=user).first()
        return passenger.seats if passenger is not None else None

    @classmethod
    def setup_eager_loading(cls, queryset):
        queryset = super().setup_eager_loading(queryset)
        approved_passengers = Passenger.objects.filter(
            status='approved').select_related('user__driver', 'user__profile',
                                              'user__student')
        queryset = queryset.prefetch_related(
            Prefetch('passengers',
                     to_attr='approved_passengers',
                     queryset=approved_passengers))
        return queryset

    def to_representation(self, obj):
        # get the original representation
        representation = super().to_representation(obj)

        # If the user status is not approved, pop some fields
        if representation['status'] != 'approved':
            representation.pop('driver')
            representation.pop('approved_passengers')
        else:
            representation.pop('driver_basic')

        return representation

    class Meta(BaseTripListRetrieveSerializer.Meta):
        fields = BaseTripListRetrieveSerializer.Meta.fields + \
            ['url', 'status', 'seats', 'driver', 'driver_basic', 'approved_passengers']
        select_related_fields = [
            'user__driver', 'user__profile', 'user__student'
        ]