114 lines
3.3 KiB
Python
114 lines
3.3 KiB
Python
from sqlalchemy.orm import Session
|
|
from app.models.user import UserDB
|
|
from app.models.point import PointRecordDB, PointRecordType
|
|
from app.models.message import MessageDB
|
|
from typing import Optional
|
|
from datetime import datetime
|
|
|
|
class PointManager:
|
|
"""积分管理器"""
|
|
|
|
def __init__(self, db: Session):
|
|
self.db = db
|
|
|
|
def add_points(
|
|
self,
|
|
user_id: int,
|
|
points: int,
|
|
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=PointRecordType.CONSUME_RETURN,
|
|
description=description,
|
|
order_id=order_id
|
|
)
|
|
self.db.add(point_record)
|
|
|
|
# 更新用户积分
|
|
user.points += points
|
|
|
|
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,
|
|
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=PointRecordType.CONSUME_DEDUCT,
|
|
description=description,
|
|
order_id=order_id
|
|
)
|
|
self.db.add(point_record)
|
|
|
|
# 更新用户积分
|
|
user.points -= points
|
|
|
|
self.db.commit()
|
|
return True
|
|
|
|
except Exception as e:
|
|
self.db.rollback()
|
|
raise Exception(f"扣减积分失败: {str(e)}") |