Skip to content

Commit

Permalink
Merge pull request #156 from jonatasoli/staging
Browse files Browse the repository at this point in the history
Staging
  • Loading branch information
Jônatas Oliveira authored Nov 26, 2020
2 parents 47f34d1 + db7cb28 commit 482837f
Show file tree
Hide file tree
Showing 21 changed files with 379 additions and 32 deletions.
9 changes: 9 additions & 0 deletions app/constants.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,3 +19,12 @@ class StepsOrder(enum.Enum):
GENERATE_INVOICE = 'GENERATE_INVOICE'
IN_TRANSIT = 'IN_TRANSIT'
DELIVERED_ORDER = 'DELIVERED_ORDER'

class OrderStatus(enum.Enum):
PAYMENT_PENDING = 'PAYMENT_PENDING'
PAYMENT_PAID = 'PAYMENT_PAID'
PAYMENT_CANCELLED = 'PAYMENT_CANCELLED'
PREPARING_ORDER = 'PREPARING_ORDER'
SHIPPING_ORDER = 'SHIPPING_ORDER'
GENERATE_INVOICE = 'GENERATE_INVOICE'
SHIPPING_COMPLETE = 'SHIPPING_COMPLETE'
33 changes: 33 additions & 0 deletions app/domains/domain_order.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,11 @@
from schemas.order_schema import ProductSchema, OrderSchema, OrderFullResponse, ProductInDB, ListProducts

from models.order import Product, Order, OrderItems
from models.transaction import Payment
from models.users import User
from loguru import logger
import requests
import json

def get_product(db : Session, uri):
return db.query(Product).filter(Product.uri == uri).first()
Expand All @@ -29,6 +33,35 @@ def get_showcase(db:Session):
return { "products": []}


def get_installments(db: Session, cart):
_cart = cart.dict()
_product_id = _cart['cart'][0]['product_id']
_product_config = db.query(Product).filter_by(id=int(_product_id)).first()
_total_amount = 0
_installments = []

for item in _cart['cart']:
_total_amount += (item['amount'] * item['qty'])

for n in range(1,13):
_installment = (_total_amount/n)/100
_installments.append({"name": f"{n} x R${_installment}", "value": f"{n}"})


return _installments
# _config_installments = db.query(CreditCardFeeConfig)\
# .filter_by(id=_product_config.installments_config)\
# .first()
# if _installments > 12:
# raise Exception("O número máximo de parcelas é 12")
# elif _installments >= _config_installments.min_installment_with_fee:
# _total_amount = _total_amount * ((1+_config_installments.fee) ** _installments)


def get_product_by_id(db: Session, id):
product = db.query(Product).filter_by(id=id).first()
return ProductInDB.from_orm(product)


def get_order(db: Session, id):
users = db.query(User).join(Order, Order.customer_id == User.id).filter(Order.id == id)
Expand Down
27 changes: 23 additions & 4 deletions app/domains/domain_payment.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@

import requests
import json

Expand Down Expand Up @@ -48,7 +49,8 @@ def credit_card_payment(db: Session, payment: CreditCardPayment):
"user": "usuario",
"token": r.get("acquirer_id"),
"status": r.get('status'),
"authorization_code": r.get("authorization_code"),
"authorization_code": r.get('authorization_code'),
"gateway_id": r.get("id"),
"payment_method": "credit-card",
"errors": r.get("errors")}
except Exception as e:
Expand Down Expand Up @@ -90,6 +92,7 @@ def process_checkout(db: Session, checkout_data: CheckoutSchema, affiliate=None,
db=db,
shopping_cart=checkout_data.get('shopping_cart')[0].get("itens"),
user=_user)
logger.info(_order)
_payment = process_payment(
db=db,
checkout_data=checkout_data,
Expand All @@ -99,6 +102,8 @@ def process_checkout(db: Session, checkout_data: CheckoutSchema, affiliate=None,
payment_address=_payment_address,
affiliate=affiliate,
cupom=cupom)
if "pending" or "paid" in _payment.values():
update_gateway_id(db=db, payment_data=_payment, order=_order)
if "paid" in _payment.values():
update_payment_status(db=db, payment_data=_payment, order=_order)
if "credit-card" in _payment.values():
Expand Down Expand Up @@ -136,6 +141,7 @@ def check_user(db: Session, checkout_data: CheckoutSchema):
_document = checkout_data.get('document')
_phone = checkout_data.get('phone')
logger.info(f"DOCUMENT -----------------{_document}")


_user = check_existent_user(db=db, email=_user_email, document=_document, password=_password)
logger.info("----------------USER----------------")
Expand Down Expand Up @@ -183,8 +189,9 @@ def process_order(db: Session, shopping_cart, user):
try:
db_order = Order(
customer_id=user.id,
order_date=datetime.now()
)
order_date=datetime.now(),
order_status = 'pending',
payment_id = 1)
db.add(db_order)
for cart in shopping_cart:
db_item = OrderItems(
Expand Down Expand Up @@ -355,6 +362,17 @@ def postback_payment(db: Session, payment_data, order):
except Exception as e:
raise e

def update_gateway_id(db:Session, payment_data, order):
try:
db_transaction = db.query(Transaction).filter_by(order_id=order.id).first()
db_payment = db.query(Payment).filter_by(id=db_transaction.payment_id).first()

db_payment.gateway_id=payment_data.get("gateway_id")
db.add(db_payment)
db.commit()

except Exception as e:
raise e

def update_payment_status(db:Session, payment_data, order):
try:
Expand All @@ -366,6 +384,7 @@ def update_payment_status(db:Session, payment_data, order):
db_payment.processed_at=datetime.now()
db_payment.token=payment_data.get("token")
db_payment.authorization=payment_data.get("authorization_code")
db_payment.gateway_id=payment_data.get("gateway_id")
db_payment.status='paid'
db.add(db_transaction)
db.add(db_payment)
Expand All @@ -374,4 +393,4 @@ def update_payment_status(db:Session, payment_data, order):
# send_payment_mail(db=db, user=_user, payment=_payment)

except Exception as e:
raise e
raise e
31 changes: 16 additions & 15 deletions app/domains/domain_shipping.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,20 +3,21 @@
from dynaconf import settings

def shipping_zip_code(shipping: Shipping):
try:
shipping = CalculateShipping(
zip_code_source=settings.ZIP_CODE_SOURCE,
zip_code_target=shipping.zip_code_target,
weigth=shipping.weigth,
length=shipping.length,
heigth=shipping.heigth,
width=shipping.width,
diameter=shipping.diameter
)
shipping = shipping.calculate_shipping()
return shipping
except Exception as e:
raise e
return { "shipping": 1000}
# try:
# shipping = CalculateShipping(
# zip_code_source=settings.ZIP_CODE_SOURCE,
# zip_code_target=shipping.zip_code_target,
# weigth=shipping.weigth,
# length=shipping.length,
# heigth=shipping.heigth,
# width=shipping.width,
# diameter=shipping.diameter
# )
# shipping = shipping.calculate_shipping()
# return shipping
# except Exception as e:
# raise e

def adress_zip_code(shipping: Shipping, status_code=200):
try:
Expand All @@ -27,4 +28,4 @@ def adress_zip_code(shipping: Shipping, status_code=200):
raise e




53 changes: 53 additions & 0 deletions app/endpoints/v1/order.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,16 @@
from fastapi import Header, APIRouter, Depends
from domains import domain_order
from schemas.order_schema import OrderSchema, OrderFullResponse
from models.order import Order
from models.transaction import Payment
from endpoints.deps import get_db
from constants import OrderStatus
from gateway.payment_gateway import return_transaction
from loguru import logger
from job_service.service import get_session

import requests
import json

order = APIRouter()

Expand Down Expand Up @@ -45,3 +54,47 @@ async def create_order(
):
return domain_order.create_order(db=db, order_data=order_data)


@order.post('/update-payment-and-order-status', status_code=200)
def order_status():
db = get_session()
orders = db.query(Order).filter(Order.id.isnot(None))
for order in orders:
return {
"order_id": order.id,
"payment_id": order.payment_id,
"order_status": order.order_status}


def check_status_pedding():
data = order_status()
logger.debug(data)
if data.get('order_status') == 'pending':
return 'pending'


def status_pending():
data = order_status()
logger.debug(data)
db = get_session()
payment = db.query(Payment).filter_by(id= data.get('payment_id')).first()
return return_transaction(payment.gateway_id)


def status_paid():
gateway = status_pending()
data = order_status()
logger.debug(gateway.get('status'))
if gateway.get('status') == 'paid' and data.get('order_status') == 'pending':
logger.debug(data)
data['order_status'] = OrderStatus.PAYMENT_PAID.value
logger.debug(data)
return data


def alternate_status(status):
order_status = {
'pending' : status_pending,
'paid': status_paid
}
return order_status[status]
2 changes: 2 additions & 0 deletions app/endpoints/v1/payment.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@
from domains import domain_payment
from endpoints import deps

from loguru import logger

payment = APIRouter()


Expand Down
30 changes: 28 additions & 2 deletions app/endpoints/v1/product.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
from sqlalchemy.orm import Session
from fastapi import Header, APIRouter, Depends
from domains import domain_order
from schemas.order_schema import OrderSchema, OrderFullResponse, ProductSchema
from schemas.order_schema import OrderSchema, OrderFullResponse,\
ProductSchema, InstallmentSchema
from endpoints.deps import get_db
from loguru import logger

product = APIRouter()


@product.get('/product/showcase/all', status_code=200)
@product.get('/showcase/all', status_code=200)
async def get_showcase(
*,
db: Session = Depends(get_db)
Expand All @@ -18,3 +19,28 @@ async def get_showcase(
except Exception as e:
logger.error(f"Erro em obter os produtos - { e }")
raise e


@product.get('/{id}', status_code=200)
async def get_product_id(
*,
db: Session = Depends(get_db),
id
):
try:
return domain_order.get_product_by_id(db, id)
except Exception as e:
logger.error(f"Erro em obter os produto - { e }")
raise e

@product.post('/cart/installments', status_code=200)
async def get_installments(
*,
db: Session = Depends(get_db),
cart: InstallmentSchema
):
try:
return domain_order.get_installments(db, cart=cart)
except Exception as e:
logger.error(f"Erro ao coletar o parcelamento - {e}")
raise e
10 changes: 8 additions & 2 deletions app/endpoints/v1/shipping.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from fastapi import Header, APIRouter, Depends
from sqlalchemy.orm import Session
from schemas.shipping_schema import Shipping
from schemas.shipping_schema import Shipping, ShippingCalc
from domains import domain_shipping
from endpoints.deps import get_db

Expand All @@ -14,4 +14,10 @@ def zip_code_shipping(shipping_data: Shipping):
@shipping.post('/zip_code/adress', status_code=200)
def zip_code_adress(shipping_data: Shipping):
adress = domain_shipping.adress_zip_code(shipping=shipping_data)
return adress
return adress

@shipping.post('/zip_code/shipping/calc', status_code=200)
def zip_code_shipping(shipping_data: ShippingCalc):
from loguru import logger
logger.debug(shipping_data)
return { "shipping": 1000}
2 changes: 1 addition & 1 deletion app/endpoints/v1/tests/test_mail.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,6 @@ def test_send_mail(t_client):
data=mail_data.json()
)

assert resp.status_code == 201
assert resp.status_code == 200
logger.debug(f"JSON --- {resp.json()}")
assert resp.json().get("message") == "Mail Sended"
Loading

0 comments on commit 482837f

Please sign in to comment.