Files
X25020501_card_book/core/routers/pay/actions.py
2025-05-12 12:01:44 +08:00

113 lines
3.6 KiB
Python

# -*- coding = utf-8 -*-
# @Time : 2025/2/27 上午12:15
# @File : actions.py
# @Software : PyCharm
# @Author : xingc
# @Desc :
import logging
from datetime import timedelta, datetime
from sqlalchemy.ext.asyncio import AsyncSession
from core.base.schema import ProductCategory, ProductAction, OrderStatusType
from core.db.crud import CRUD
from core.db.models import User, Order, Product, PointsTransaction
logger = logging.getLogger(__name__)
async def actions_after_payment(
notify_params: dict,
db_session: AsyncSession
) -> None:
try:
db_crud = CRUD(db_session, Order)
order_id = notify_params['out_trade_no']
order: Order = await db_crud.get(filters={'order_id': order_id})
if not order:
logger.error(f'Order not found -> {order_id}')
return
if order.status != OrderStatusType.WAIT_PAYMENT:
logger.error(f'Order not wait_payment -> {order_id}')
return
product: Product = await db_crud.get(model=Product, filters={'id': order.product_id})
if not product:
logger.warning(f'Product not found -> {order.product_id}')
return
user: User = await db_crud.get(model=User, filters={'user_id': order.user_id})
if not user:
logger.warning(f'User not found -> {order.order_id}')
return
await actions_handler(db_crud, product, user)
if product.gift_id:
gift_product = await db_crud.get(
model=Product, filters={
'id': product.gift_id,
'category': ProductCategory.GIFT
}
)
await actions_handler(db_crud, gift_product, user)
record = {
'order_id': notify_params['out_trade_no'],
'transaction_id': notify_params['transaction_id'],
'status': OrderStatusType.OK,
}
await db_crud.update(data=record, filters={'order_id': record['order_id']})
except Exception as e:
logger.error(f'Payment Actions Exception occurred -> {e}')
logger.exception(e)
async def actions_handler(db_crud: CRUD, product: Product, user: User):
if product.action == ProductAction.VIP_RENEWAL:
old_vip_expire_date = user.vip_expire_date or datetime.now().date()
if old_vip_expire_date < datetime.now().date():
old_vip_expire_date = datetime.now().date()
vip_expire_date = old_vip_expire_date + timedelta(days=product.number)
await db_crud.update(
model=User,
data={
'vip_expire_date': vip_expire_date
},
filters={'user_id': user.user_id}
)
elif product.action == ProductAction.RECHARGE_POINTS:
points = (
user.points or 0
) + product.number
await db_crud.update(
model=User,
data={
'points': points
},
filters={'user_id': user.user_id}
)
if product.category.value == 'gift':
transaction_type = 3
else:
transaction_type = 1
await db_crud.create(
model=PointsTransaction,
data={
'user_id': user.user_id,
'transaction_type': transaction_type,
'points': product.number,
'product_id': product.id,
'balance': points,
'description': f'{product.name} {product.number}'
},
filters={'id': -1}
)
else:
logger.error(f'Unknown action -> {product.action}')