Esempio n. 1
0
class TransactionViewSet(
        mixins.CreateModelMixin,
        viewsets.GenericViewSet,
):
    permission_classes = [permissions.IsAuthenticated]
    queryset = Transaction.objects.all()
    serializer_class = TransactionSerializer

    @swagger_auto_schema(
        request_body=TransactionSerializer(many=True),
        responses={status.HTTP_201_CREATED: TransactionSerializer(many=True)},
    )
    def create(self, request):
        """
        Bulk creation

        create multiple transactions at once
        """
        serializer = TransactionSerializer(many=True, data=request.data)
        serializer.is_valid(raise_exception=True)
        transactions = serializer.save()
        return Response(
            TransactionSerializer(transactions, many=True).data,
            status=status.HTTP_201_CREATED,
        )
Esempio n. 2
0
    def create(self, request):
        """
        Bulk creation

        create multiple transactions at once
        """
        serializer = TransactionSerializer(many=True, data=request.data)
        serializer.is_valid(raise_exception=True)
        transactions = serializer.save()
        return Response(
            TransactionSerializer(transactions, many=True).data,
            status=status.HTTP_201_CREATED,
        )
Esempio n. 3
0
def getDepositTransactions(request):
    user = request.user
    order = request.data.get('order')
    if order == 'desc':
        order = ''
    else:
        order = '-'
    sort = "%s%s" % (order, request.data.get('sort'))
    page = request.data.get('page')
    maxPerPage = request.data.get('maxPerPage')
    try:
        profile = Profile.objects.get(user=user)
        transactions = Transaction.objects.filter(
            wallet__profile=profile,
            transactionpaypal__isnull=True).order_by(sort)
        paginator = Paginator(transactions, maxPerPage)
        transactions = TransactionSerializer(paginator.page(page),
                                             many=True,
                                             context={'request': request})
        return Response({
            'success': True,
            'transactions': transactions.data,
            'transactionsCount': paginator.count
        })
    except Profile.DoesNotExist:
        return Response({'success': False, 'error': 'profile.notfound'})
Esempio n. 4
0
 def create(self, request, format=None):
     serializer = TransactionSerializer(data=request.data,
                                        context={'request': request})
     if serializer.is_valid():
         self.save_transaction(serializer)
         return Response(serializer.data, status=status.HTTP_201_CREATED)
     return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Esempio n. 5
0
    def _serialize_data(self, data):
        for group in data:
            for date_group in group:
                group[date_group] = [
                    TransactionSerializer(x).data for x in group[date_group]
                ]

        return data
Esempio n. 6
0
 def all_transactions(self, request, pk=None):
     user = self.get_object()
     all_transactions = Transaction.objects.all().filter(
         Q(buyer=user)).distinct()
     if not all_transactions:
         return Response(status=status.HTTP_204_NO_CONTENT)
     serialized = TransactionSerializer(all_transactions, many=True)
     return Response(serialized.data)
Esempio n. 7
0
 def create(self, request, *args, **kwargs):
     data = request.data
     transaction = TransactionSerializer(data=data)
     if transaction.is_valid():
         try:
             transaction.save()
         except ValidationError:
             return Response({'error': 'not enough bts'},
                             status.HTTP_400_BAD_REQUEST)
         return Response(status=status.HTTP_201_CREATED)
     else:
         return Response(status=status.HTTP_400_BAD_REQUEST)
Esempio n. 8
0
 def create(self, request, *args, **kwargs):
     request.data['user'] = request.user.id
     Serializer = ReviewSerializer(data=request.data)
     Serializer.is_valid(raise_exception=True)
     Serializer.save()
     context = Serializer.data
     transaction_item_current = Transaction_item.objects.get(
         id=request.data['transaction_item_id'])
     transaction_item_current.review = Review.objects.get(
         id=Serializer.data["id"])
     transaction_item_current.save()
     transaction_current = Transaction.objects.get(
         id=request.data['transaction_id'])
     return Response(TransactionSerializer(transaction_current).data,
                     status=status.HTTP_201_CREATED)
 def validate(cls, data):
     """
     Validate transaction data
     :param data: json, dict, xml
     :return: dict with validation result and errors
     """
     if cls.is_valid_json(data):
         data = json.loads(data)
     if cls.is_valid_xml(data):
         data = XMLParser().parse(data)
     serializer_data = TransactionSerializer(data=data)
     return {
         'is_valid': serializer_data.is_valid(),
         'errors': serializer_data.errors
     }
Esempio n. 10
0
def make_transaction(request):
    user = UserSerializer(User.objects.get(username=request.user))
    balance = UserBalance.objects.get(user=user.data['id'])
    if request.data['transaction_type'] == 1 and balance.balance < request.data[
            'price'] * request.data['amount']:
        return Response({"details": "Your balance is not enough."},
                        status=status.HTTP_400_BAD_REQUEST)

    newBalance = balance.balance
    if request.data['transaction_type'] == 1:
        newBalance -= request.data['price'] * request.data['amount']
    else:
        newBalance += request.data['price'] * request.data['amount']
    balance.balance = newBalance
    balance.save()

    serializer = TransactionSerializer(data=request.data)
    if serializer.is_valid():
        serializer.save(owner=request.user)
        return JsonResponse(serializer.data, status=status.HTTP_201_CREATED)
    return JsonResponse(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Esempio n. 11
0
    def test_retrieve_transactions_list(self):
        """Test if authenticated user can retrieve a transaction list"""
        t1 = Transaction.objects.create(wallet=self.wallet,
                                        title='banany',
                                        amount=8.50,
                                        type='exp',
                                        category='food')
        t2 = Transaction.objects.create(wallet=self.wallet,
                                        title='warzywa',
                                        amount=20,
                                        type='exp',
                                        category='food')
        t1.user.add(self.user)
        t2.user.add(self.user)

        res = self.client.get(TRANSACTIONS_URL)

        transactions = Transaction.objects.all().order_by('title')
        serializer = TransactionSerializer(transactions, many=True)
        self.assertEqual(res.status_code, status.HTTP_200_OK)
        self.assertEqual(len(res.data), 2)
        self.assertEqual(res.json(), serializer.data)
Esempio n. 12
0
class OrderSerializer(serializers.ModelSerializer):
    products = TransactionSerializer(many=True)
    delivery_date = serializers.DateTimeField(source='offer.delivery_date')
    total = serializers.SerializerMethodField()
    offer = OfferSerializer(read_only=True)

    class Meta:
        model = Order
        fields = (
            'id',
            'user_id',
            'offer_id',
            'order_date',
            'products',
            'delivery_date',
            'total',
            'offer',
        )

    @staticmethod
    def get_total(obj):
        return obj.total
Esempio n. 13
0
 def get(self, request, format=None):
     queryset = Transaction.objects.filter(user=request.user)
     serializer = TransactionSerializer(queryset, many=True)
     return Response(serializer.data)
Esempio n. 14
0
 def test_serializer_all_fields_validates(self):
     serializer = TransactionSerializer(data=self.get_full_data(), context=self.serializer_context)
     self.assertTrue(serializer.is_valid(raise_exception=True))
Esempio n. 15
0
 def test_serializer_value_should_not_allows_expense_positive(self):
     data = self.get_data(value=10, kind=HasKind.EXPENSE_KIND)        
     serializer = TransactionSerializer(data=data, context=self.serializer_context)
     self.assert_has_field_error(serializer)
Esempio n. 16
0
 def test_serializer_periodic_cant_be_set_on_put(self):
     data = self.get_data_with_periodic()
     context = self.get_context(request_method='PUT')
     serializer = TransactionSerializer(data=data, context=context)
     self.assert_has_field_error(serializer, 'periodic')
Esempio n. 17
0
 def all_transactions(self, request, pk=None):
     user = self.get_object()
     all_transactions = Transaction.objects.all().filter(
         Q(buyer=user)).exclude(Q(given_to=user)).distinct()
     serialized = TransactionSerializer(all_transactions, many=True)
     return Response(serialized.data)
Esempio n. 18
0
 def get_updated_periodic_dto(self, index, **kwargs):
     dto = TransactionSerializer(self.periodics[index]).data
     dto.update(kwargs)
     return dto
Esempio n. 19
0
 def test_serializer_create_regular(self, super_create_mock):
     dummy = {}
     serializer = TransactionSerializer()
     serializer.create(dummy)
     super_create_mock.assert_called_with(dummy)
Esempio n. 20
0
 def test_serializer_create_periodic(self, create_mock):
     dummy = { 'periodic': None }
     serializer = TransactionSerializer()
     serializer.create(dummy)
     create_mock.assert_called_with(**dummy)
Esempio n. 21
0
 def test_serializer_returns_list(self):
     serializer = TransactionSerializer()
     falsy = {}
     truthy = { 'periodic': None }
     self.assertFalse(serializer.is_return_data_list(falsy))
     self.assertTrue(serializer.is_return_data_list(truthy))
Esempio n. 22
0
 def test_serializer_should_not_allows_periodic_with_until_before_due_date(self):
     data = self.get_data_with_periodic(until=date(2018, 1, 1))
     serializer = TransactionSerializer(data=data, context=self.serializer_context)
     self.assert_has_field_error(serializer)
Esempio n. 23
0
 def test_serializer_should_not_allows_category_kind_different_of_transaction(self):
     data = self.get_data(kind=HasKind.INCOME_KIND)
     serializer = TransactionSerializer(data=data, context=self.serializer_context)
     self.assert_has_field_error(serializer)
Esempio n. 24
0
def serialize_dict(obj):
    serializer = TransactionSerializer(data=obj)
    if serializer.is_valid():
        serializer.save()
        return JsonResponse(serializer.data, status=201)
Esempio n. 25
0
 def test_serializer_only_required_fields_validates(self):
     serializer = TransactionSerializer(data=self.serializer_data, context=self.serializer_context)
     self.assertTrue(serializer.is_valid(raise_exception=True))
Esempio n. 26
0
 def test_serializer_category_should_not_allows_from_other_user(self):
     data = self.get_data(category=self.other_user_data['category'].id)
     serializer = TransactionSerializer(data=data, context=self.serializer_context)
     self.assert_has_field_error(serializer, 'category')
Esempio n. 27
0
class PendingSerializer(serializers.Serializer):
    overdue = TransactionSerializer(many=True, read_only=True)
    next = TransactionSerializer(many=True, read_only=True)
Esempio n. 28
0
 def test_serializer_value_should_not_allows_income_negative(self):
     data = self.get_data(value=-10, kind=HasKind.INCOME_KIND)        
     serializer = TransactionSerializer(data=data, context=self.serializer_context)
     self.assert_has_field_error(serializer)
Esempio n. 29
0
 def get_updated_dto(self, **kwargs):
     dto = TransactionSerializer(self.transaction).data
     dto.update(kwargs)
     return dto
Esempio n. 30
0
 def test_serializer_account_should_not_allows_from_other_user(self):
     data = self.get_data(account=self.other_user_data['account'].id)
     serializer = TransactionSerializer(data=data, context=self.serializer_context)
     self.assert_has_field_error(serializer, 'account')