Пример #1
0
async def coinbase_checkout(body: CoinbaseCheckoutBody, identity: Optional[str] = Depends(get_jwt_identity_optional)):
	try:
		order = Order.objects.get(id=body.orderID, orderer=identity)
		amount = price_service.calculate_order_total(order)
		charge_info = {
			'name': CoinbaseCommerceSettings.CHARGE_NAME,
			'description': CoinbaseCommerceSettings.CHARGE_DESCRIPTION,
			'local_price': {
				'amount': amount,
				'currency': ShopSettings.CURRENCY_CODE.upper()
			},
			'pricing_type': 'fixed_price',
			'redirect_url': body['location'] + '/store/checkout/placed?clear=1?id=' + str(order.id),
			'cancel_url': body['location'] + '/store/checkout',
			'metadata': {
				'order': str(order.id)
			}
		}
		charge = ccClient.charge.create(**charge_info)

		return {
			'expires_at': charge['expires_at'],
			'hosted_url': charge['hosted_url'],
			'logo_url': charge['logo_url']
		}
	except DoesNotExist:
		raise NotFoundError().http_exception
	except Exception as e:
		raise e
Пример #2
0
async def get_post(post: str,
                   id: str,
                   withSchema: Optional[bool] = False,
                   identity: str = Depends(get_jwt_identity)):
    try:
        get_admin_user(identity)
    except (DoesNotExist, UnauthorizedError):
        raise UnauthorizedError('User is not admin')
    try:
        try:
            postType = class_name_to_class(__name__, post)
            if not is_post(postType):
                raise InvalidPostTypeError
        except Exception:
            raise InvalidPostTypeError
        obj = postType.objects.get(id=id)
        out = {'obj': obj.serialize()}
        if withSchema:
            out['schema'] = postType.schema()
        return out
    except DoesNotExist:
        raise NotFoundError()
    except InvalidPostTypeError:
        raise InvalidPostTypeError()
    except Exception as e:
        raise e
Пример #3
0
async def set_metadata(id: str, metadata_body: MetadataForm, identity: str = Depends(get_jwt_identity)):
	try:
		Media.objects.get(id=id, owner=identity).update(metadata=metadata_body.metadata)
		return True
	except DoesNotExist:
		raise NotFoundError().http_exception
	except Exception as e:
		raise e
Пример #4
0
async def get_tax_rate(zip: str):
	try:
		tax_jurisdiction = UsTaxJurisdiction.objects.get(zip=zip)
		return tax_jurisdiction.serialize()
	except DoesNotExist:
		raise NotFoundError().http_exception
	except Exception as e:
		raise e
Пример #5
0
async def modify_order(
    id: str,
    order_body: OrderModel,
    identity: Optional[str] = Depends(get_jwt_identity_optional)):
    try:
        order = Order.objects.get(id=id, orderer=identity)
        if order_body.addresses:
            if 'billing' in order_body.addresses:
                taxJurisdiction = UsTaxJurisdiction.objects.get(
                    zip=order_body.addresses['billing']['zip'])
            else:
                taxJurisdiction = UsTaxJurisdiction.objects.get(
                    zip=order_body.addresses['shipping']['zip'])
            shippingZone = None
            try:
                shippingZone = UsShippingZone.objects.get(
                    applicableStates=order_body.addresses['shipping']
                    ['region'])
            except DoesNotExist:
                shippingZone = UsShippingZone.objects.get(default=True)
            rateCandidates = []
            price = price_service.calculate_order_discount(order)
            for rate in shippingZone.rates:
                if ((rate.minCutoff != None and rate.minCutoff < price)
                        or rate.minCutoff == None) and (
                            (rate.maxCutoff != None and rate.maxCutoff > price)
                            or rate.maxCutoff == None):
                    rateCandidates.append(rate)
            match = None
            for candidate in rateCandidates:
                if match == None:
                    match = candidate
                elif match.minCutoff == None and candidate.minCutoff != None:
                    match = candidate
                elif match.maxCutoff == None and candidate.maxCutoff != None:
                    match = candidate
                elif match.maxCutoff - match.minCutoff > candidate.maxCutoff - candidate.minCutoff:
                    match = candidate
            order.update(addressses=order_body.addresses,
                         taxRate=taxJurisdiction.estimatedCombinedRate,
                         shippingType=match.type,
                         shippingRate=match.rate)
        if order_body.coupons:
            coupons = list(
                map(lambda c: Coupon.objects.get(id=c), order_body.coupons))
            order.update(coupons=coupons)
        if order_body.items:
            products = []
            for p in order_body.items:
                product: Product = Product.objects.get(id=p.id)
                products.append(
                    CartItem(product=product, qty=p.qty, price=product.price))
            order.update(products=products)
        return 'ok'
    except DoesNotExist:
        raise NotFoundError().http_exception
    except Exception as e:
        raise e
Пример #6
0
    def update(self, cpf: str, json: dict):
        reseller = Reseller.objects(cpf=cpf).first()
        if reseller is None:
            raise NotFoundError(f"Reseller cpf: {cpf} not found")
        for key, value in json.items():
            reseller[key] = value
        reseller.save()

        return reseller
Пример #7
0
    def register_purchase(self, cpf: str, json: dict):
        reseller = self.resellerService.get_by_cpf(cpf)
        if reseller is None:
            raise NotFoundError()

        json["created_by"] = cpf
        json["created_at"] = datetime.now()
        json["status_code"] = 1 if "manager" in reseller.roles else 0
        json["status_description"] = "Aprovado" if "manager" in reseller.roles else "Em validação"
        json["cashback"] = self.get_cashback_by_value(json["value"])

        self.resellerRepository.add_purchase(reseller, json)
Пример #8
0
async def delete_order(id: str, identity: str = Depends(get_jwt_identity)):
    try:
        get_admin_user(identity)
    except (DoesNotExist, UnauthorizedError):
        raise UnauthorizedError('User is not admin')
    try:
        models.Order.objects.get(id=id).delete()
        return 'ok'
    except DoesNotExist:
        raise NotFoundError()
    except Exception as e:
        raise e
Пример #9
0
async def get_us_shipping_rate(state: str):
	try:
		shipping_zone = UsShippingZone.objects.get(applicableStates=state)
		return shipping_zone.serialize()
	except DoesNotExist:
		try:
			shipping_zone = UsShippingZone.objects.get(default=True)
			return shipping_zone.serialize()
		except DoesNotExist:
			raise NotFoundError().http_exception
	except Exception as e:
		raise e
Пример #10
0
async def get_order(
    id: str, identity: Optional[str] = Depends(get_jwt_identity_optional)):
    try:
        order = Order.objects.get(id=id, orderer=identity)
        if identity:
            return order.serialize()
        else:
            return {'orderStatus': order.orderStatus}
    except (DoesNotExist, ValidationError):
        raise NotFoundError().http_exception
    except Exception as e:
        raise e
Пример #11
0
async def get_us_shipping_zone(id: str,
                               identity: str = Depends(get_jwt_identity)):
    try:
        get_admin_user(identity)
    except (DoesNotExist, UnauthorizedError):
        raise UnauthorizedError('User is not admin')
    try:
        zone = models.UsShippingZone.objects.get(id=id)
        return zone.serialize()
    except DoesNotExist:
        raise NotFoundError()
    except Exception as e:
        raise e
Пример #12
0
async def get_user(id: str, identity: str = Depends(get_jwt_identity)):
    try:
        get_admin_user(identity)
    except (DoesNotExist, UnauthorizedError):
        raise UnauthorizedError('User is not admin')
    except Exception as e:
        raise e
    try:
        user = models.User.objects.get(id=id)
        return user.serialize()
    except DoesNotExist:
        raise NotFoundError(detail='User with id ' + id + ' does not exist')
    except Exception as e:
        raise e
Пример #13
0
async def delete_media(folder: str, filename: Optional[str] = None, identity: str = Depends(get_jwt_identity)):
	try:
		media = Media.objects.get(owner=identity, folder=folder, filename=filename)
		for subMedia in media.associatedMedia:
			try:
				subMedia = subMedia.fetch()
				if subMedia.private:
					subMedia.delete()
			except DoesNotExist:
				pass # media doesn't exist
		media.delete()
	except DoesNotExist:
		raise NotFoundError().http_exception
	except Exception as e:
		raise e
Пример #14
0
async def update_us_shipping_zone(id: str,
                                  shippingZone: models.UsShippingZoneModel,
                                  identity: str = Depends(get_jwt_identity)):
    try:
        get_admin_user(identity)
    except (DoesNotExist, UnauthorizedError):
        raise UnauthorizedError('User is not admin')
    try:
        toUpdate = models.UsShippingZone.objects.get(id=id)
        toUpdate.update(**base_model_to_clean_dict(shippingZone))
        return 'ok'
    except DoesNotExist:
        raise NotFoundError()
    except Exception as e:
        raise e
Пример #15
0
async def update_user(id: str,
                      user: models.UserModel,
                      identity: str = Depends(get_jwt_identity)):
    try:
        get_admin_user(identity)
    except (DoesNotExist, UnauthorizedError):
        raise UnauthorizedError('User is not admin')
    except Exception as e:
        raise e
    try:
        models.User.objects.get(id=id).update(**base_model_to_clean_dict(user))
        return 'ok'
    except DoesNotExist:
        raise NotFoundError(detail='User with id ' + id + ' does not exist')
    except Exception as e:
        raise e
Пример #16
0
async def get_post_from_slug(post: str, slug: str):
    try:
        try:
            postType = class_name_to_class(__name__, post)
        except Exception:
            raise InvalidPostTypeError
        if not is_post(postType):
            raise InvalidPostTypeError
        post = postType.objects.get(slug=slug)
        return post.serialize()
    except DoesNotExist:
        raise NotFoundError().http_exception
    except InvalidPostTypeError:
        raise InvalidPostTypeError().http_exception
    except Exception as e:
        raise e
Пример #17
0
async def edit_order(id: str,
                     order: models.OrderModel,
                     identity: str = Depends(get_jwt_identity)):
    try:
        get_admin_user(identity)
    except (DoesNotExist, UnauthorizedError):
        raise UnauthorizedError('User is not admin')
    try:
        toUpdate = models.Order.objects.get(id=id)
        toUpdate.update(**base_model_to_clean_dict(order))
        toUpdate.reload()
        toUpdate.modified = datetime.now
        toUpdate.save()
        return 'ok'
    except DoesNotExist:
        raise NotFoundError()
    except Exception as e:
        raise e
Пример #18
0
def stream(filename: Optional[str] = '', folder: Optional[str] = '', id: Optional[str] = None, range: str = Header('bytes=0-')):
	try:
		def iterfile(file, chunk_size, start, size):
			bytes_read = 0
			file.seek(start)
			while bytes_read < size:
				bytes_to_read = min(chunk_size, size - bytes_read)
				yield file.read(bytes_to_read)
				bytes_read += bytes_to_read
		if id:
			media = Media.objects.get(id=id)
		else:
			media = Media.objects.get(folder=folder, filename=filename)
		if not media.file:
			raise DoesNotExist
		start_byte = int(range.split('=')[-1].split('-')[0])
		chunk_size = FileSettings.MAX_STREAM_CHUNK_SIZE
		size = media.file.length
		if start_byte + chunk_size  > size:
			chunk_size = size - 1 - start_byte
		return StreamingResponse(
			content=iterfile(
				#media.file.read(),
				media.file,
				chunk_size,
				start_byte,
				size
			),
			status_code=206,
			headers={
				'Accept-Ranges': 'bytes',
        		'Content-Range': f'bytes {start_byte}-{start_byte+chunk_size}/{size - 1}',
        		'Content-Type': media.file.content_type,
				'Content-Disposition': f'inline; filename="{media.filename.rsplit(".", 1)[0]}"'
			},
			media_type=media.file.content_type
		)
	except DoesNotExist:
		raise NotFoundError().http_exception
	except SchemaValidationError:
		raise SchemaValidationError().http_exception
	except Exception as e:
		raise e
Пример #19
0
async def webhook(payload: dict = Body(...),
                  Stripe_Signature: str = Header(...)):
    try:
        event = None

        try:
            if StripeSettings.USE_SIGNING_SECRET and StripeSettings.SIGNING_SECRET:
                event = stripe.Webhook.construct_event(
                    payload, Stripe_Signature, StripeSettings.SIGNING_SECRET)
            else:
                event = stripe.Event.construct_from(payload, stripe.api_key)
        except ValueError:
            return '', 400

        payment_intent = event.data.object  # contains a stripe.PaymentIntent
        order = Order.objects.get(
            id=payment_intent['metadata']['Order object'])
        if event.type == 'payment_intent.succeeded':
            order.orderStatus = 'paid'
        elif event.type == 'payment_intent.failed':
            order.orderStatus = 'failed'
            if order.stockRemoved:
                price_service.add_stock(order)
                order.stockRemoved = False
        elif event.type == 'invoice.paid':
            # TODO: create order with details
            pass
        elif event.type == 'invoice.payment_failed':
            # TODO: create order with details
            pass
        else:
            print('Unhandled Strip webhook event type {}'.format(event.type))
            return 'ok', 200

        order.save()
        return 'ok', 200
    except DoesNotExist:
        raise NotFoundError().http_exception
    except Exception as e:
        raise e
Пример #20
0
async def update_post(id: str,
                      post_body: PostForm,
                      identity: str = Depends(get_jwt_identity)):
    try:
        get_admin_user(identity)
    except (DoesNotExist, UnauthorizedError):
        raise UnauthorizedError('User is not admin')
    try:
        try:
            postType = class_name_to_class(__name__, post_body.post)
            if not is_post(postType):
                raise InvalidPostTypeError
        except Exception:
            raise InvalidPostTypeError
        toUpdate = postType.objects.get(id=id)

        postTypeName = postType.__name__
        if postTypeName == 'Coupon':
            if post_body.obj['applicableProducts']:
                post_body.obj['applicableProducts'] = list(
                    map(lambda p: models.Product.objects.get(id=p),
                        post_body.obj['applicableProducts']))

        toUpdate.update(**post_body.obj)
        toUpdate.reload()
        toUpdate.modified = datetime.now
        toUpdate.generateNgrams()
        toUpdate.save()
        return 'ok'
    except DoesNotExist:
        raise NotFoundError()
    except InvalidPostTypeError:
        raise InvalidPostTypeError()
    except (FieldDoesNotExist, ValidationError, SchemaValidationError):
        raise SchemaValidationError()
    except Exception as e:
        raise e
Пример #21
0
 def delete(self, cpf: str):
     reseller = Reseller.objects(cpf=cpf).first()
     if reseller is None:
         raise NotFoundError(f"Reseller cpf: {cpf} not found")
     else:
         reseller.delete()
Пример #22
0
async def stripe_checkout(
    checkout_body: CheckoutModel,
    identity: Optional[str] = Depends(get_jwt_identity_optional)):
    try:
        order = Order.objects.get(id=checkout_body.orderID, orderer=identity)
        order.addresses = checkout_body.addresses

        if not price_service.remove_stock(order):
            raise OutOfStockError

        order.stockRemoved = True
        order.save()

        shipping = checkout_body.addresses['shipping']
        shipping = {
            'address': {
                'line1': shipping['street1'],
                'city': shipping['city'],
                'country': shipping['country'],
                'line2': shipping['street2'],
                'postal_code': shipping['zip'],
                'state': shipping['region']
            },
            'name': shipping['name'],
            'phone': shipping['phoneNumber']
        }
        amount = price_service.calculate_order_total(order)
        amount = round(amount * 100)  # Convert for stripe
        intent = None
        if identity:
            user = User.objects.get(id=identity)
            cust = None
            if user.stripeCustomerID:
                cust = stripe.Customer.retrieve(user.stripeCustomerID)
            else:
                cust = stripe.Customer.create(
                    email=checkout_body.email,
                    shipping=shipping,
                    phone=order.addresses['billing']['phoneNumber'],
                    name=order.addresses['billing']['name'])
                user.stripeCustomerID = cust['id']
                user.save()
            intent = stripe.PaymentIntent.create(
                amount=amount,
                currency='usd',
                customer=cust['id'],
                confirm=True,
                payment_method=checkout_body.paymentMethodID,
                shipping=shipping,
                metadata={order: str(order.pk)})
        else:
            intent = stripe.PaymentIntent.create(
                amount=amount,
                currency='usd',
                confirm=True,
                payment_method=checkout_body.paymentMethodID,
                shipping=shipping,
                metadata={order: str(order.pk)})
        order.paymentIntentID = intent['id']
        order.orderStatus = 'placed'
        order.save()

        return str(order.id)
    except DoesNotExist:
        raise NotFoundError().http_exception
    except OutOfStockError:
        raise OutOfStockError().http_exception
    except Exception as e:
        raise e
Пример #23
0
async def create_transaction(
    transaction_body: CreateTransactionModel,
    identity: Optional[str] = Depends(get_jwt_identity_optional)):
    try:
        order = Order.objects.get(id=transaction_body.orderID,
                                  orderer=identity)
        shipping = order.addresses['shipping']
        shipping = {
            "method":
            "United States Postal Service",  # TODO: make this dynamic
            "address": {
                "name": {
                    "full_name": shipping['name']
                },
                "address_line_1": shipping['street1'],
                "address_line_2": shipping['street2'],
                "admin_area_2": shipping['city'],
                "admin_area_1": shipping['region'],
                "postal_code": shipping['zip'],
                "country_code": shipping['country']
            }
        }
        base_amount = price_service.calculate_order_subtotal(order)
        tax = price_service.calculate_order_tax(order)
        amount = base_amount + tax
        shippingAmt = price_service.calculate_order_shipping(order)
        total = amount + shippingAmt
        discount = price_service.calculate_order_discount(order)

        requestBody = {
            "intent":
            "CAPTURE",
            "application_context": {
                "brand_name":
                PayPalSettings.BRAND_NAME,
                "landing_page":
                'BILLING',
                "shipping_preference":
                "SET_PROVIDED_ADDRESS",
                "user_action":
                "PAY_NOW",
                "return_url":
                transaction_body.location + "/checkout/placed?id=" +
                str(order.id),
                "cancel_url":
                transaction_body.location + "/checkout",
            },
            "purchase_units": [{
                #					"reference_id": "",
                #					"description": "",
                "custom_id": str(order.id),
                #					"soft_descriptor": "",
                "amount": {
                    "currency_code": "USD",
                    "value": '{:.2f}'.format(round(amount, 2)),
                    "breakdown": {
                        "item_total": {
                            "currency_code": "USD",
                            "value": '{:.2f}'.format(round(total, 2))
                        },
                        "shipping": {
                            "currency_code": "USD",
                            "value": '{:.2f}'.format(round(shippingAmt, 2))
                        },
                        "tax_total": {
                            "currency_code": "USD",
                            "value": '{:.2f}'.format(round(tax, 2))
                        },
                        "discount": {
                            "currency_code": "USD",
                            "value": '{:.2f}'.format(round(discount, 2))
                        }
                    }
                },
                "items": [],
                "shipping": shipping
            }]
        }
        for item in order.products:
            requestBody['purchase_units'][0]['items'].append({
                "name":
                item.product.title,
                "unit_amount": {
                    "currency_code": "USD",
                    "value": '{:.2f}'.format(float(item.product.price))
                },
                "tax": {
                    "currency_code":
                    "USD",
                    "value":
                    '{:.2f}'.format(float(item.product.price) * order.taxRate)
                },
                "quantity":
                str(item.qty),
                "description":
                item.product.excerpt,
                "sku":
                item.product.sku,
                "category":
                "DIGITAL_GOODS" if item.product.digital else "PHYSICAL_GOODS"
            })
        requestArgs = OrdersCreateRequest()
        requestArgs.prefer('return=representation')
        requestArgs.request_body(requestBody)
        response = paypal_client.client.execute(requestArgs)
        return response.result.id
    except DoesNotExist:
        raise NotFoundError().http_exception
    except Exception as e:
        raise e
Пример #24
0
    def get_purchases(self, cpf: str):
        reseller = self.resellerService.get_by_cpf(cpf)
        if reseller is None:
            raise NotFoundError()

        return reseller.purchases