Пример #1
0
    def post(self, request, format=None):
        start_date = request.data['start_date']
        end_date = request.data['end_date']
        item_id = request.data['item']

        print(start_date)
        print(end_date)

        try:
            i = Item.objects.get(id=item_id)
        except Item.DoesNotExist:
            return Response({
                "dates_valid": False,
                "error": "Item not found"
            },
                            status=status.HTTP_404_NOT_FOUND)

        d1 = parse_datetime(start_date)
        d2 = parse_datetime(end_date)
        l = ItemLockout(item=i, start_date=d1, end_date=d2)

        try:
            l.clean()
            return Response({"dates_valid": True}, status=status.HTTP_200_OK)
        except Exception as e:
            print("**** ERROR ****")
            print(e)
            return Response({
                "dates_valid": False,
                "error": e
            },
                            status=status.HTTP_400_BAD_REQUEST)
Пример #2
0
    def post(self, request):

        paymentID = request.data["paymentID"]
        success, transaction_details = create_transaction(
            paymentID=paymentID, borrower=request.user)

        if success:
            return Response(data={"success": transaction_details},
                            status=status.HTTP_201_CREATED)
        else:
            return Response({"error": transaction_details},
                            status=status.HTTP_400_BAD_REQUEST)
Пример #3
0
 def get(self, request, format=None):
     queryset = self.get_queryset()
     serializer = ItemStubSerializer(queryset,
                                     many=True,
                                     context={'user': self.request.user})
     logger.error(serializer)
     return Response(serializer.data)
Пример #4
0
    def get(self, request):
        print('request')
        print(request.GET)

        serializer = self.serializer_class(data=request.GET,
                                           context={'request': request})
        serializer.is_valid(raise_exception=True)
        serializer.save()
        data = serializer.validated_data

        paginator = Paginator(list(data['results']),
                              25)  # Show 25 contacts per page

        page = request.GET.get('page', '')

        try:
            data = paginator.page(page)
        except PageNotAnInteger:
            data = paginator.page(1)
        except EmptyPage:
            data = paginator.page(paginator.num_pages)

        json_data = {
            "num_pages": data.paginator.num_pages,
            "current_page": data.number,
            "results": [result for result in data]
        }

        return Response({'search': json_data})
Пример #5
0
    def get(self, request):
        if 'item' in self.request.query_params:
            try:
                item = Item.objects.get(pk=self.request.query_params['item'])
                user = self.request.user

                if not (user == item.user):
                    return Response('User not owner of this item',
                                    status=status.HTTP_400_BAD_REQUEST)

                return Response({
                    'item_id': item.id,
                    'item_title': item.title,
                    'lockouts': item.lockout_dates,
                })
            except:
                return Response('Item not found')
        else:
            return Response('Provide item id as a query parameter',
                            status=status.HTTP_400_BAD_REQUEST)
Пример #6
0
    def post(self, request, format=None):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        item = Item.objects.get(id=serializer.data['item'])

        if not request.user == item.user:
            raise PermissionDenied(
                "You do not have permission to modify that Item")

        lockout = serializer.save()
        return Response({"success": "created lockout_date"})
Пример #7
0
    def put(self, request):
        profile = self.request.user.profile

        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)

        if 'profile' in serializer.validated_data:
            profile = update_profile(profile,
                                     serializer.validated_data['profile'])
            profile.save()

        return Response(serializer.validated_data)
Пример #8
0
    def put(self, request, format=None):
        print('request.data')
        print(request.data)
        try:
            serializer = self.serializer_class(data=request.data)
        except:
            serializer = self.serializer_class(data=request.data.qqfile)

        serializer.is_valid(raise_exception=True)

        if not 'item' in self.request.data:
            return Response({"error": 'Must include attribute `item`.'},
                            status=status.HTTP_400_BAD_REQUEST)

        item = Item.objects.get(id=serializer.data['item'])
        if not request.user == item.user:
            raise PermissionDenied(
                "You do not have permission to modify that Item")
        image = serializer.save()
        return Response(
            {"success": "created image successfully: " + image.avatar.url},
            status=status.HTTP_201_CREATED)
Пример #9
0
    def post(self, request):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        try:
            user = serializer.save()
        except:
            return JsonResponse({
                'non_field_errors':
                'Problem with request, user not logged in'
            })

        Token.objects.filter(user=user).delete()
        token, created = Token.objects.get_or_create(user=user)
        return Response({'token': token.key})
Пример #10
0
    def update(self, request, *args, **kwargs):
        print('inside update')
        instance = self.queryset.get(pk=kwargs.get('pk'))
        serializer = self.serializer_class(instance,
                                           data=request.data,
                                           context={'request': request})
        serializer.is_valid(raise_exception=True)

        if 'tags' in self.request.data:
            tags = self.request.data.get('tags')
            tags = tags.replace(" ", "")
            tags = tags.split(',')
            Tag.objects.update_tags(instance, " ".join(tags))

        serializer.save()
        return Response(serializer.data)
Пример #11
0
    def post(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)

        user = serializer.save()

        Token.objects.filter(user=user).delete()
        token, created = Token.objects.get_or_create(user=user)

        data = {"id": user.id, "success": True, "token": token.key}

        profile = Profile(user=user)
        profile = update_profile(profile, serializer.validated_data)
        profile.save()

        return Response(data, status=status.HTTP_201_CREATED)
Пример #12
0
    def post(self, request):
        try:
            user = User.objects.get(pk=request.user.id)
        except User.DoesNotExist:
            return Response({"error": "User not found"},
                            status=status.HTTP_400_BAD_REQUEST)

        if 'borrow_request_slug' in request.data:
            try:
                borrow_request = BorrowRequest.objects.get(
                    slug=request.data['borrow_request_slug'])
            except BorrowRequest.DoesNotExist:
                return Response({"error": "BorrowRequest Slug not found."},
                                status=status.HTTP_400_BAD_REQUEST)
        else:
            return Response({"error": "Must supply BorrowRequest slug."},
                            status=status.HTTP_400_BAD_REQUEST)

        if user != borrow_request.lender:
            return Response({"error": "User not lender of this item."},
                            status=status.HTTP_400_BAD_REQUEST)

        if borrow_request.canceled == True:
            return Response(
                {"error": "Cannot accept BorrowRequest with expired status."},
                status=status.HTTP_400_BAD_REQUEST)

        item = borrow_request.item
        start_date = borrow_request.date_used_start
        end_date = borrow_request.date_used_end

        ### CHECK LOCKOUTS ###
        success, message = item.test_lockout_range(start_date, end_date)
        if not success:
            return Response({
                "error": message,
                "dateConflict": True
            },
                            status=status.HTTP_400_BAD_REQUEST)

        borrow_request.lender_accepted = True
        borrow_request.save()

        # once item is accepted, create lockouts.
        # Prevents users from requesting same days and also prevents OWNER from accepting conflicting requests.
        lockout = ItemLockout(item=item,
                              accepted_request=borrow_request,
                              start_date=start_date,
                              end_date=end_date)
        lockout.save()

        send_fcm_message(recipient=borrow_request.borrower,
                         title="Borrow Request Accepted!",
                         body="%s has accepted to lend %s" %
                         (borrow_request.lender.username, item.title),
                         tag="REQUEST UPDATE")
        send_request_accepted_email(recipient=borrow_request.borrower,
                                    sender=borrow_request.lender,
                                    item_name=item.title)

        serializer = BorrowRequestSerializer(borrow_request)
        return Response({"success": serializer.data},
                        status=status.HTTP_202_ACCEPTED)
Пример #13
0
 def get(self, request, format=None):
     data = {"success": True}
     headers = self.get_success_headers(data)
     results = Item.objects.get_trending_tags()
     data = {"tags": results, "success": True}
     return Response(data, status=status.HTTP_200_OK, headers=headers)
Пример #14
0
    def post(self, request):

        paymentID = request.data['paymentID']
        payerID = request.data['payerID']

        payment = Payment.find(paymentID)

        if not payment['payer']['status'] == 'VERIFIED':
            return Response(data={
                "success": False,
                "error": "The paypal account is not verified.",
                "not_verified": True,
            },
                            status=status.HTTP_400_BAD_REQUEST)

        custom = payment['transactions'][0]['custom']
        item_id = payment['transactions'][0]['item_list']['items'][0]['sku']
        email = payment['payer']['payer_info']['email']
        user_id, start_date, end_date, request_slug = custom.split(',')
        start_date = parse_datetime(start_date)
        end_date = parse_datetime(end_date)

        try:
            item = Item.objects.get(pk=item_id)
        except:
            return Response({"error": "item in custom field not found"},
                            status=status.HTTP_400_BAD_REQUEST)

        # success, message = item.test_lockout_range(start_date, end_date);
        # if not success:
        #     return Response({"error": message}, status=status.HTTP_400_BAD_REQUEST)

        try:
            user = User.objects.get(pk=user_id)
        except:
            return Response({"error": "user not found"},
                            status=status.HTTP_400_BAD_REQUEST)

        if payment.execute({"payer_id": payerID}):
            # save paypal account in user profile
            user.profile.paypal_email = email
            user.profile.is_verified = True
            user.profile.save()

            # TODO: Maybe? save history of all paypal accounts a user has used. Helps prevent fraud
            # in case someone uses a stolen account we have a history of it.

            success, transaction_details = create_transaction(
                paymentID=paymentID,
                borrower=request.user,
                borrowRequestSlug=request_slug)

            if success:
                return Response(data={
                    "success": True,
                    "transaction": transaction_details
                },
                                status=status.HTTP_201_CREATED)
            else:
                return Response(data={
                    "success":
                    True,
                    "error":
                    transaction_details,
                    "message":
                    "Payment executed but error in creating Transaction Model",
                    "details for create_transaction":
                    transaction_details
                },
                                status=status.HTTP_400_BAD_REQUEST)
            # return Response({"success": True, "paymentID": payment.id})
        else:
            return Response(data={
                "success": False,
                "error": "PayPal payment execute failed."
            },
                            status=status.HTTP_400_BAD_REQUEST)
            logger.error(payment.error)  # Error Hash
Пример #15
0
 def get(self, request):
     return Response('testing yo')
Пример #16
0
    def post(self, request):
        # logger.error("request")
        # logger.error(request.META)
        logger.error("data")
        logger.error(request.data)

        if not 'borrow_request_slug' in request.data:
            return Response({"error": "Must supply BorrowRequest slug"},
                            status=status.HTTP_400_BAD_REQUEST)

        borrow_request = BorrowRequest.objects.get(
            slug=request.data['borrow_request_slug'])

        if request.user != borrow_request.borrower:
            return Response({"error": "User is not the borrower"},
                            status=status.HTTP_400_BAD_REQUEST)

        if borrow_request.lender_accepted != True:
            return Response(
                {
                    "error":
                    "Cannot Pay for request that lender has not accepted"
                },
                status=status.HTTP_400_BAD_REQUEST)

        item = borrow_request.item
        transaction_price = borrow_request.total_price
        start_date = str(borrow_request.date_used_start).replace(' ', 'T')
        end_date = str(borrow_request.date_used_end).replace(' ', 'T')
        days = borrow_request.duration

        start_date = start_date[:start_date.index('+')] + 'Z'
        end_date = end_date[:end_date.index('+')] + 'Z'

        today = timezone.now().date()
        _pickup = parse_datetime(start_date)
        print(today)
        print(_pickup.date())

        if _pickup.date() < today:
            return Response({"error": "Pick Up date has already passed"},
                            status=status.HTTP_400_BAD_REQUEST)

        payment = Payment({
            "intent":
            "sale",
            "payer": {
                "payment_method": "paypal"
            },
            "redirect_urls": {
                "return_url": "http://borrowonce.com",
                "cancel_url": "http://borrowonce.com"
            },
            "transactions": [{
                "item_list": {
                    "items": [{
                        "name": item.title,
                        "sku": item.id,
                        "price": str(item.price_per_day),
                        "currency": "USD",
                        "quantity": days
                    }]
                },
                "amount": {
                    "total": str(transaction_price),
                    "currency": "USD"
                },
                "description":
                "Borrowing this item for %s days" % (days),
                # used for validating that Transaction creation in DB
                "custom":
                str(request.user.id) + ',' + start_date + ',' + end_date +
                ',' + str(borrow_request.slug)
            }]
        })

        if payment.create():
            print(payment.id)
            return Response({"paymentID": payment.id})
        else:
            logger.error("Payment creation failed")
            logger.error(payment.error)
            return Response("An error has occurred.")
Пример #17
0
 def get(self, request):
     items = Item.objects.filter(user=request.user)
     serializer = ItemSerializer(items, many=True)
     return Response({'items': serializer.data})
Пример #18
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)
Пример #19
0
 def get(self, request, format=None):
     user = request.user
     serializer = UserSerializer(user)
     return Response(serializer.data)