Esempio n. 1
0
class CampaingBodySearch(serializers.ModelSerializer):
    """campaing serializer"""

    header = CampaingHeaderSerializer()
    profile = PersonalSerializer()
    currency = CurrencySerializer()

    class Meta:
        model = CampaingBody
        fields = (
            "id",
            "title",
            "video_main",
            "imagen_main",
            "slug",
            "excerpt",
            "description",
            "created_at",
            "updated_at",
            "public_at",
            "ended_at",
            "status",
            "header",
            "profile",
            "profile_ca",
            "currency",
            "short_url",
            "slogan_campaing",
        )
        read_only_fields = ("id", )
Esempio n. 2
0
def currencies_list(request):
    """
    List all code currencies.
    """
    currencies = Currency.objects.all()
    serializer = CurrencySerializer(currencies, many=True)
    return Response(data=serializer.data)
Esempio n. 3
0
 def test_get_all_currencies(self):
     # get API response
     response = client.get(reverse('api:currencies_list'))
     # get data from db
     currencies = Currency.objects.all()
     serializer = CurrencySerializer(currencies, many=True)
     self.assertEqual(response.data, serializer.data)
     self.assertEqual(response.status_code, status.HTTP_200_OK)
Esempio n. 4
0
class TripSerializer(serializers.ModelSerializer):
    expenses = ExpenseSerializer(many=True, read_only=True)
    currencies = CurrencySerializer(many=True, read_only=True)

    class Meta:
        model = Trip
        fields = ('trip_uid', 'user', 'name', 'total_budget', 'length',
                  'home_currency', 'currencies', 'expenses', 'start_date',
                  'end_date')
Esempio n. 5
0
    def create(self, request, *args, **kwargs):
        try:
            serializer = self.get_serializer(data=request.data)
            serializer.is_valid(raise_exception=True)
            domain = serializer.data['domain']
            codomain = serializer.data['codomain']
            date = serializer.data['date']
            rate = serializer.data['rate']
            currency_query_result = Currency.objects.filter(
                domain=domain, codomain=codomain).first()
            currency_rate_serializer_data = {}

            if currency_query_result is None:
                currency_rate_serializer_data = self._insert_currency_and_rate(
                    domain=domain, codomain=codomain, date=date, rate=rate)
            else:
                currency_id = CurrencySerializer(
                    currency_query_result).data['currency_id']
                currency_rate_serializer_data = self._insert_rate(
                    currency_id=currency_id, date=date, rate=rate)

            stat = st.HTTP_201_CREATED
            res = {'status': stat, 'message': 'Created'}
            res.update(currency_rate_serializer_data)
            return Response(res, status=stat)
        except (exceptions.ValidationError, exceptions.ParseError) as exc:
            details = exc.detail
            status = exc.status_code
            res = {
                'status': status,
                'message': 'Bad Request',
                'details': details
            }
            return Response(res, status=status)
        except Exception as exc:
            details = []
            stat = st.HTTP_500_INTERNAL_SERVER_ERROR
            res = {
                'status': stat,
                'message': 'Internal Server Error',
                'details': details
            }
            return Response(res, status=stat)
Esempio n. 6
0
def last_seven_days_rates(domain, codomain, date=None):
    if domain is None or codomain is None:
        raise exceptions.ParseError

    queryset = Currency.objects.all()
    queryset = queryset.filter(domain=domain, codomain=codomain)

    if queryset.first() is None:
        raise exceptions.NotFound

    currency_id = CurrencySerializer(queryset.first()).data['currency_id']
    queryset = CurrencyRate.objects.all()
    how_many_days = 7

    if date is None:
        date = datetime.now()

    queryset = queryset.filter(currency_id=currency_id)
    queryset = queryset.filter(date__gt=date - timedelta(days=how_many_days))

    return queryset
Esempio n. 7
0
    def _insert_currency_and_rate(self, domain, codomain, date, rate):
        currency_data = {'domain': domain, 'codomain': codomain}
        currency_serializer = CurrencySerializer(data=currency_data)
        currency_serializer.is_valid(raise_exception=True)
        currency_serializer.save()

        currency_id = currency_serializer.data['currency_id']
        currency_rate_data = {
            'currency_id': currency_id,
            'rate': rate,
            'date': date
        }
        currency_rate_serializer = CurrencyRateSerializer(
            data=currency_rate_data)
        currency_rate_serializer.is_valid(raise_exception=True)
        currency_rate_serializer.save()

        return currency_rate_serializer.data
Esempio n. 8
0
class AccountSerializer(serializers.ModelSerializer):
    currency = CurrencySerializer(read_only=True)

    class Meta:
        model = Account
        fields = ('amount', 'currency')
Esempio n. 9
0
 def test_post_single_currency(self):
     data = {'name': 'Yen'}
     resp = self.client.post('/currencies/', data).json()
     cur = Currency.objects.get(name="Yen")
     assert resp == CurrencySerializer(cur).data
Esempio n. 10
0
 def test_get_single_currency(self):
     cur = CurrencyTestFactory()
     resp = self.client.get(f'/currencies/{cur.pk}/').json()
     assert CurrencySerializer(cur).data == resp
Esempio n. 11
0
 def test_get_currencies(self):
     curs = CurrencyTestFactory.create_batch(3)
     resp = self.client.get('/currencies/').json()
     assert [CurrencySerializer(x).data for x in curs] == resp
Esempio n. 12
0
 def create(self):
     ser = CurrencySerializer(data=self.data)
     ser.is_valid(True)
     return ser.save()
Esempio n. 13
0
    def list(self, request, *args, **kwargs):
        try:
            queryset = self.filter_queryset(self.get_queryset())
            currency_serializer_list = [
                CurrencySerializer(obj) for obj in queryset
            ]
            currency_id_domain_codomain_list = \
                [{ 'currency_id': obj.data['currency_id'],'domain': obj.data['domain'], 'codomain': obj.data['codomain']} \
                    for obj in currency_serializer_list]
            rows = []

            date = self.request.query_params.get('date', None)
            format_str = '%Y-%m-%d'  # The format
            datetime_obj = datetime.strptime(date, format_str)

            for obj in currency_id_domain_codomain_list:
                currency_id = obj['currency_id']
                domain = obj['domain']
                codomain = obj['codomain']
                queryset = last_seven_days_rates(domain,
                                                 codomain,
                                                 date=datetime_obj)
                rate = CurrencyRateSerializer(
                    queryset.filter(currency_id=currency_id,
                                    date=datetime.now()).first()).data['rate']
                average = queryset.aggregate(Avg('rate'))['rate__avg']
                rows.append({
                    'currency_id': currency_id,
                    'domain': domain,
                    'codomain': codomain,
                    'rate': rate,
                    'average': average
                })

            serializer = self.get_serializer(queryset, many=True)
            stat = st.HTTP_200_OK
            res = {'status': stat, 'date': date, 'message': 'OK', 'rows': rows}
            return Response(res, status=stat)
        except (exceptions.ValidationError, exceptions.ParseError) as exc:
            details = exc.detail
            status = exc.status_code
            res = {
                'status': status,
                'message': 'Bad Request',
                'details': details
            }
            return Response(res, status=status)
        except exceptions.NotFound as exc:
            details = exc.detail
            status = exc.status_code
            res = {
                'status': status,
                'message': 'Not Found',
                'details': details
            }
            return Response(res, status=status)
        except Exception as exc:
            details = []
            stat = st.HTTP_500_INTERNAL_SERVER_ERROR
            res = {
                'status': stat,
                'message': 'Internal Server Error',
                'details': details
            }
            return Response(res, status=stat)