From 1a1d8b8377db029ae33c38cc00c6dd5f070d4dd4 Mon Sep 17 00:00:00 2001 From: aaron <> Date: Mon, 27 Jan 2025 14:13:34 +0800 Subject: [PATCH] =?UTF-8?q?=E5=A2=9E=E5=8A=A0=E7=A7=AF=E5=88=86=E7=AE=A1?= =?UTF-8?q?=E7=90=86=E5=99=A8=E3=80=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/api/endpoints/wechat.py | 12 +++- app/core/config.py | 3 + app/core/point_manager.py | 135 ++++++++++++++++++++++++++++++++++++ 3 files changed, 149 insertions(+), 1 deletion(-) create mode 100644 app/core/point_manager.py diff --git a/app/api/endpoints/wechat.py b/app/api/endpoints/wechat.py index acf185d..cafad69 100644 --- a/app/api/endpoints/wechat.py +++ b/app/api/endpoints/wechat.py @@ -17,7 +17,7 @@ import string from app.models.merchant_order import MerchantOrderDB, MerchantOrderStatus from app.models.merchant_pay_order import MerchantPayOrderDB, MerchantPayOrderStatus import enum - +from app.core.point_manager import PointManager router = APIRouter() class PhoneNumberRequest(BaseModel): @@ -235,6 +235,11 @@ async def payment_notify( order.transaction_id = transaction_id order.pay_time = datetime.fromisoformat(success_time.replace('Z', '+00:00')) + # 添加积分 + points = order.pay_amount * 10 + point_manager = PointManager(db) + point_manager.add_points(order.userid, points, f"订单完成,获得 {points} {settings.POINT_ALIAS}") + elif out_trade_no.startswith("P"): # 商家在线买单 order = db.query(MerchantPayOrderDB).filter( MerchantPayOrderDB.order_id == out_trade_no @@ -249,6 +254,11 @@ async def payment_notify( order.status = MerchantPayOrderStatus.PAID order.transaction_id = transaction_id order.pay_time = datetime.fromisoformat(success_time.replace('Z', '+00:00')) + + # 添加积分 + points = order.amount * 10 + point_manager = PointManager(db) + point_manager.add_points(order.userid, points, f"订单完成,获得 {points} {settings.POINT_ALIAS}") else: return error_response(code=400, message="未知的订单类型") diff --git a/app/core/config.py b/app/core/config.py index af77817..19660fc 100644 --- a/app/core/config.py +++ b/app/core/config.py @@ -8,6 +8,9 @@ class Settings(BaseSettings): API_BASE_URL: str = "https://api-dev.beefast.co" + # 积分别名 + POINT_ALIAS: str = "蜂蜜" + # 订单价格配置 ORDER_BASE_PRICE: float = 3.0 # 基础费用 ORDER_EXTRA_PACKAGE_PRICE: float = 0.5 # 额外包裹费用 diff --git a/app/core/point_manager.py b/app/core/point_manager.py new file mode 100644 index 0000000..d70cce6 --- /dev/null +++ b/app/core/point_manager.py @@ -0,0 +1,135 @@ +from sqlalchemy.orm import Session +from app.models.user import UserDB +from app.models.point import PointRecordDB, PointRecordType +from app.models.message import MessageDB, MessageType +from typing import Optional +from datetime import datetime + +class PointManager: + """积分管理器""" + + def __init__(self, db: Session): + self.db = db + + def _create_point_message( + self, + user_id: int, + points: int, + description: str + ): + """创建积分变动消息""" + message = MessageDB( + user_id=user_id, + content=description + ) + self.db.add(message) + + def add_points( + self, + user_id: int, + points: int, + type: PointRecordType, + description: str, + order_id: Optional[str] = None + ) -> bool: + """ + 添加积分 + + Args: + user_id: 用户ID + points: 积分数量(正数) + type: 积分变动类型 + description: 变动说明 + order_id: 关联订单号(可选) + + Returns: + bool: 是否添加成功 + """ + try: + if points <= 0: + raise ValueError("积分必须为正数") + + # 查询用户 + user = self.db.query(UserDB).filter(UserDB.userid == user_id).first() + if not user: + raise ValueError("用户不存在") + + # 添加积分记录 + point_record = PointRecordDB( + user_id=user_id, + points=points, + type=type, + description=description, + order_id=order_id + ) + self.db.add(point_record) + + # 更新用户积分 + user.points += points + + # 创建消息通知 + self._create_point_message(user_id, points, description) + + self.db.commit() + return True + + except Exception as e: + self.db.rollback() + raise Exception(f"添加积分失败: {str(e)}") + + def deduct_points( + self, + user_id: int, + points: int, + type: PointRecordType, + description: str, + order_id: Optional[str] = None + ) -> bool: + """ + 扣减积分 + + Args: + user_id: 用户ID + points: 扣减积分数量(正数) + type: 积分变动类型 + description: 变动说明 + order_id: 关联订单号(可选) + + Returns: + bool: 是否扣减成功 + """ + try: + if points <= 0: + raise ValueError("扣减积分必须为正数") + + # 查询用户 + user = self.db.query(UserDB).filter(UserDB.userid == user_id).first() + if not user: + raise ValueError("用户不存在") + + # 检查积分是否足够 + if user.points < points: + raise ValueError("用户积分不足") + + # 添加积分记录(负数表示扣减) + point_record = PointRecordDB( + user_id=user_id, + points=-points, # 负数表示扣减 + type=type, + description=description, + order_id=order_id + ) + self.db.add(point_record) + + # 更新用户积分 + user.points -= points + + # 创建消息通知 + self._create_point_message(user_id, -points, description) + + self.db.commit() + return True + + except Exception as e: + self.db.rollback() + raise Exception(f"扣减积分失败: {str(e)}") \ No newline at end of file