Beispiel #1
0
    def post(self, request):
        data = request.data
        item_pk = data.get('item', None)
        status_ = data.get('status', None)
        location = data.get('location', None)

        try:
            item_obj = Item.objects.get(id=item_pk)
        except Item.DoesNotExist:
            return Response('Item doesnt exist',
                            status=status.HTTP_400_BAD_REQUEST)

        transactions = Transaction.objects.filter(item__pk=item_pk)
        if transactions.filter(is_active=True):
            return Response('There is an active transaction for this item',
                            status=status.HTTP_400_BAD_REQUEST)
        elif transactions.filter(status=Transaction.COMPLETED):
            return Response('Item transaction completed',
                            status=status.HTTP_400_BAD_REQUEST)
        elif transactions.filter(status=Transaction.REFUNDED):
            return Response('Item transaction refunded',
                            status=status.HTTP_400_BAD_REQUEST)

        # Ensure for each new transaction status = processing and location = origin on creation
        if status_ != Transaction.PROCESSING or location != Transaction.ORIGIN:
            return Response('Transactions should have status = processing' +
                            ' and location = origination_bank',
                            status=status.HTTP_400_BAD_REQUEST)

        serializer = TransactionSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)

        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Beispiel #2
0
def make_payment(request):
    """
    A buyer begins the process of purchasing a swipe on the frontend, create a Stripe PaymentIntent
    Create  Transaction object to track the purchase

    Args:
        request (Request): specifies the price of the transaction, swipe_id, type("BID" or "ASK") and user_id

    Returns:
        JSON: an object with the client_secret for the frontend to use to complete the purchase
    """

    data = request.data
    if 'amount' not in data:
        return Response({'STATUS': '1', 'REASON': 'MISSING REQUIRED amount ARGUMENT'}, status=status.HTTP_400_BAD_REQUEST)
    if 'swipe_id' not in data:
        return Response({'STATUS': '1', 'REASON': 'MISSING REQUIRED swipe_id ARGUMENT'}, status=status.HTTP_400_BAD_REQUEST)
    if 'user_id' not in data:
        return Response({'STATUS': '1', 'REASON': 'MISSING REQUIRED user_id ARGUMENT'}, status=status.HTTP_400_BAD_REQUEST)
    if 'type' not in data:
        return Response({'STATUS': '1', 'REASON': 'MISSING REQUIRED type ARGUMENT'}, status=status.HTTP_400_BAD_REQUEST)

    price  = data["amount"]
    swipe  = data['swipe_id']
    sender = data["user_id"]
    type   = data["type"]

    intent = stripe.PaymentIntent.create(
      amount   = price,
      currency = 'usd',
    )
    client_secret = intent.client_secret

    res = {"client_secret": client_secret}

    # Get reciepient of money
    recipient = ""
    if type == "ASK":
        # get seller user_id
        swipe_obj = Swipe.objects.filter(swipe_id=swipe)
        if len(swipe_obj) != 0:
            recipient = swipe_obj[0].seller.user_id
        else:
            return Response({'STATUS': 'swipe_id does not exist'}, status=status.HTTP_400_BAD_REQUEST)

    # Make Transaction object
    transaction = {"sender": sender, "total": price, "details": client_secret, "recipient": recipient}
    transaction_serializer = TransactionSerializer(data=transaction)
    if transaction_serializer.is_valid():
        t = transaction_serializer.save()
    else:
        print(transaction_serializer.errors)

    return Response(json.dumps(res), status=status.HTTP_200_OK)
Beispiel #3
0
    def create(self, request):
        serializer = TransactionSerializer(data=request.data)

        if serializer.is_valid():
            serializer.save()

            self.update_balances_on_create(request)

            return Response(serializer.data, status=201)

        return Response(serializer.errors, status=400)
    def pay(self, transaction_data):
        transaction_serializer = TransactionSerializer(data=transaction_data)
        if not transaction_serializer.is_valid():
            raise Exception('invalid transaction data')
        transaction = Transaction(**transaction_serializer.validated_data)

        if transaction.type == 'authorisation':
            return self._authorize(transaction)
        elif transaction.type == 'presentment':
            return self._execute_presentment(transaction)
        else:
            raise Exception(transaction.type +
                            " transaction type was not implemented yet!")
Beispiel #5
0
    def post(self, request):
        # TODO validate and parse file
        csv_file = TextIOWrapper(request.data['file'])
        # movements = CSVParser.convert_to(file, serializer=TransactionSerializer)
        reader = csv.DictReader(csv_file)
        for row in reader:
            row['categories'] = []
            row['user'] = request.user.id
            serializer = TransactionSerializer(data=row)
            if serializer.is_valid():
                serializer.save(user=self.request.user)

        return Response()
Beispiel #6
0
    def post(self, request):

        serializer = self.serializer_class(data=request.data,
                                           context={'request': request})
        if serializer.is_valid():
            user_wallet = Wallet.objects.get(user=request.user)
            if user_wallet.balance < serializer.validated_data['amount']:
                return Response({
                    "status":
                    "failed",
                    "errors":
                    "Amount should be less than wallet balance"
                })
            transaction_object = Transaction.objects.create(
                user=request.user,
                amount=serializer.validated_data['amount'],
                reference_id=serializer.validated_data['reference_id'],
                transaction_type=Transaction.WITHDRAW)
            serializer = TransactionSerializer(transaction_object)
            return Response({
                "status": "success",
                "data": {
                    'withdrawal': serializer.data
                }
            })
        return Response({"status": "failed", "errors": serializer.errors})
Beispiel #7
0
 def get(self, request, format=None):
     access_key_check(request)
     token = Token.objects.get(
         token=request.META.get('HTTP_AUTHORIZATION')[6:]
     )
     profile = Profile.objects.get(token=token)
     transactions = Transaction.objects.filter(
         recipient=profile
     ).order_by('-time')
     serializer = TransactionSerializer(transactions, many=True)
     return Response(serializer.data, status=status.HTTP_200_OK)
Beispiel #8
0
 def post(self, request):
     serializer = self.serializer_class(data=request.data,
                                        context={'request': request})
     if serializer.is_valid():
         transaction_object = Transaction.objects.create(
             user=request.user,
             amount=serializer.validated_data['amount'],
             reference_id=serializer.validated_data['reference_id'],
             transaction_type=Transaction.DEPOSIT)
         serializer = TransactionSerializer(transaction_object)
         return Response({
             "status": "success",
             "data": {
                 'deposit': serializer.data
             }
         })
     return Response({"status": "failed", "errors": serializer.errors})
Beispiel #9
0
    def get(self, request):
        t = Transaction.objects.all()

        if request.GET.get('fromAddress'):
            t = t.filter(from_address__iexact=request.GET.get('fromAddress'))

        if request.GET.get('toAddress'):
            t = t.filter(to_address__iexact=request.GET.get('toAddress'))

        if request.GET.get('fromDate'):
            t = t.filter(timestamp__gte=request.GET.get('fromDate'))

        if request.GET.get('toDate'):
            t = t.filter(timestamp__lt=request.GET.get('toDate'))

        serializer = TransactionSerializer(t, many=True)

        return Response(serializer.data)
Beispiel #10
0
 def get(self, request, user_id):
     current_user = User.objects.get(id=user_id)
     user = None
     user = self.check_admin(user_id)
     txn = None
     if user is not None:
         txn = Transaction.objects.all()
     else:
         txn = Transaction.objects.filter(
             (Q(from_user__user=current_user, to_user__user=current_user)
              | Q(to_user__user=current_user)
              | Q(from_user__user=current_user)))
     if txn is not None:
         serializer = TransactionSerializer(
             txn, many=True if isinstance(txn, QuerySet) else False)
         return Response(serializer.data)
     return Response(data=json.dumps({'error': 'User Not found'}),
                     status=status.HTTP_404_NOT_FOUND)
 def get(self, request, *args, **kwargs):
     owner = request.GET.get('owner')
     transactions = Transaction.objects.filter(owner=owner)
     serializer = TransactionSerializer(transactions, many=True)
     # print(serializer.data)
     return Response(serializer.data)
Beispiel #12
0
    def post(self, request, user_id):
        current_user = User.objects.get(id=user_id)
        form_data = request.data.dict()
        print current_user, form_data, ">>>>>>>>>>>>>>>>>>>>>"
        if 'type' not in form_data:
            print 'Transaction type not specified'
            return Response(data=json.dumps(
                {'error': 'Transaction type not specified'}),
                            status=status.HTTP_400_BAD_REQUEST)
        elif form_data.get('type') not in [
                'unload', 'transfer', 'load', 'pay'
        ]:
            print 'Transaction type inappropriate'
            return Response(data=json.dumps(
                {'error': 'Transaction type inappropriate'}),
                            status=status.HTTP_400_BAD_REQUEST)
        if form_data.get('type') == 'unload':
            print ">>>>>>>>>>>>>>>>??????????????"
            biller = self.check_biller(current_user.id)
            print ">>>>>>>>>>>>>>>>??????????????", biller
            if biller is not None and biller.biller.wallet > 0.0:
                mywallet = Mywallet.objects.filter(
                    user__is_superuser=True).first()
                commission = biller.commission * float(
                    form_data.get('amount', 0.0))

                mywallet.wallet -= float(form_data.get('amount', 0.0))
                biller.unloaded_amount += float(form_data.get(
                    'amount', 0.0)) - commission
                biller.save()

                print mywallet.wallet, "::::::::"
                print ".............", commission

                mywallet_user = Mywallet.objects.get(user__id=current_user.id)
                print mywallet, mywallet_user

                mywallet.wallet += commission
                mywallet.save()
                txn = Transaction.objects.create(
                    from_user=mywallet_user,
                    to_user=mywallet_user,
                    amount=float(form_data.get('amount', 0.0)),
                    note=form_data.get('note', ''))
                serializer = TransactionSerializer(txn)
                return Response(serializer.data)
        elif form_data.get('type') == 'transfer':
            print ">>>>>>>>>>>>>>>>LLLLLLL"
            from_customer = self.check_customer(current_user.id)
            print ">>>>>>>>>>>>>>>>LLLLLLL", from_customer
            if from_customer.check_password(form_data.get('password')):
                to_customer = self.check_customer(int(form_data('to_id')))
                if to_customer is not None and from_customer is not None and from_customer.customer.wallet > 0.0:
                    from_customer.customer.wallet -= float(
                        form_data.get('amount', 0))
                    commission = .01 * float(form_data.get('amount', 0))
                    to_customer.customer.wallet += float(
                        form_data.get('amount', 0)) - commission
                    to_customer.save()
                    from_customer.save()
                    mywallet = Mywallet.objects.filter(
                        user__is_superuser=True).first()
                    mywallet.wallet += commission
                    mywallet.save()
                    txn = Transaction.objects.create(
                        from_user=Mywallet.objects.get(
                            user__id=current_user.id),
                        to_user=Mywallet.objects.get(
                            user__id=int(form_data.get('to_id'))),
                        amount=float(form_data.get('amount', 0)),
                        note=form_data.get('note', ''))
                    serializer = TransactionSerializer(txn)
                    return Response(serializer.data)
        elif form_data.get('type') == 'pay':
            print ">>>>>>>>>>>>>>>>MMMMMMMM"
            customer = self.check_customer(current_user.id)
            print ">>>>>>>>>>>>>>>>MMMMMMMM", customer
            biller = self.check_biller(int(form_data.get('biller_id')))
            if customer is not None and customer.customer.wallet > 0.0:
                customer.customer.wallet -= float(form_data.get('amount', 0.0))
                biller.biller.wallet += float(form_data.get('amount', 0))
                customer.save()
                biller.save()
                txn = Transaction.objects.create(
                    from_user=Mywallet.objects.get(
                        user__id=customer.customer.user.id),
                    to_user=Mywallet.objects.get(
                        user__id=biller.biller.user.id),
                    amount=float(form_data.get('amount', 0)),
                    note=form_data.get('note', ''))
                serializer = TransactionSerializer(txn)
                return Response(serializer.data)
        elif form_data.get('type') == 'load':
            print ">>>>>>>>>>>>>>>>PPPPPP"
            customer = self.check_customer(current_user.id)
            print ">>>>>>>>>>>>>>>>MMMMMMMM", customer
            if customer is not None:
                mywallet_user = Mywallet.objects.get(user__id=current_user.id)
                mywallet_user.wallet += float(form_data.get('amount', 0.0))
                mywallet_user.save()
                txn = Transaction.objects.create(
                    from_user=mywallet_user,
                    to_user=mywallet_user,
                    amount=float(form_data.get('amount', 0.0)),
                    note=form_data.get('note', ''))
                print txn.amount
                serializer = TransactionSerializer(txn)
                return Response(serializer.data)
        print "XXXXXXXXXXxxx"
        return Response(data=json.dumps({'error': 'Unauthorized'}),
                        status=status.HTTP_404_UNAUTHORIZED)
Beispiel #13
0
def create_transaction(*,
                       paymentID=None,
                       borrower=None,
                       borrowRequestSlug=None):
    try:
        payment = Payment.find(paymentID)
    except ResourceNotFound:
        return False, "Wrong PayPal Payment code. Payment not found."
    except ServerError:
        # Save to another model for later attempting.
        failed_transaction = TransactionFailedToCreate(
            borrower=borrower, paypal_payment_id=paymentID)
        failed_transaction.save()
        return False, "Internal Server Error on PayPal's behalf."

    payment_details = payment.to_dict()

    if not payment_details['transactions']:
        # raise ValueError("PayPal error: No transaction found.")
        return False, "Paypal error: No transaction found"

    if not payment_details['transactions'][0]['item_list']['items']:
        return False, "PayPal error: No items found as part of that transaction."

    item_details = payment_details['transactions'][0]['item_list']['items'][0]
    item_id = item_details['sku']

    try:
        item = Item.objects.get(id=item_id)
    except Item.DoesNotExist:
        return False, "Item not found"

    try:
        borrower = User.objects.get(pk=borrower.id)
    except:
        return False, "Borrower not found"

    try:
        custom_field = payment_details['transactions'][0]['custom']
        try:
            paypal_payee_id, start_date, end_date, request_slug = custom_field.split(
                ',')
            start_date = parse_datetime(start_date)
            end_date = parse_datetime(end_date)
        except:
            return False, "Paypal Custom Field if not of format User,Start,End,RequestSlug."

        try:
            paypal_payee = User.objects.get(pk=paypal_payee_id)
        except:
            return False, "Paypal payee id not found."

        if not paypal_payee == borrower:
            # print('borrower is not person who paid for paypal transaction')
            return False, "User is not payer in paypal transaction"
    except:
        # print("paypal payee id not found. Check for 'custom' field in transaction")
        return False, "Custom Field not working."

    try:
        borrow_request = BorrowRequest.objects.get(slug=request_slug)
    except BorrowRequest.DoesNotExist:
        return False, 'Borrow Request not found'

    try:
        transaction = Transaction.objects.get(payment_id=paymentID)
        return False, 'Transaction already exists'

    except Transaction.DoesNotExist:
        borrow_request.paid = True
        borrow_request.save()

        transaction = Transaction(
            lender=item.user,
            borrower=borrower,
            item=item,
            payment_id=payment.id,
            date_used_start=start_date,
            date_used_end=end_date,
            days_borrowed=item_details['quantity'],
            total_price=payment_details['transactions'][0]['amount']['total'],
            borrow_request=borrow_request)

        transaction.save()
        serializer = TransactionSerializer(transaction)

        send_fcm_message(recipient=borrow_request.lender,
                         title="Payment Received!",
                         body="%s has paid for %s" %
                         (borrow_request.borrower.username, item.title),
                         tag="REQUEST UPDATE")
        send_request_paid_email(recipient=item.user,
                                sender=borrower,
                                item_name=item.title)

        return True, serializer.data
Beispiel #14
0
 def get(self, request):
     transactions = request.user.transactions_as_borrower.all().order_by(
         '-date_created')
     serializer = TransactionSerializer(transactions, many=True)
     return Response({'items_borrowed': serializer.data},
                     status=status.HTTP_200_OK)