52 lines
1.3 KiB
Python
52 lines
1.3 KiB
Python
from sqlalchemy.orm import Session
|
|
from app.models.coupon import CouponDB, UserCouponDB
|
|
from app.models.user import UserDB
|
|
from datetime import datetime
|
|
from typing import Optional, List
|
|
|
|
class CouponManager:
|
|
def __init__(self, coupon: CouponDB = None):
|
|
self.coupon = coupon
|
|
|
|
# 发放优惠券
|
|
def add_coupon(
|
|
self,
|
|
user_id: int,
|
|
coupon_id: int,
|
|
count: int = 1,
|
|
expire_time: datetime = None
|
|
) -> UserCouponDB:
|
|
"""
|
|
为用户发放优惠券
|
|
|
|
Args:
|
|
user_id: 用户ID
|
|
coupon_id: 优惠券ID
|
|
count: 发放数量
|
|
expire_time: 过期时间
|
|
|
|
Returns:
|
|
UserCouponDB: 创建的用户优惠券对象
|
|
|
|
Raises:
|
|
ValueError: 当优惠券对象不存在时抛出
|
|
"""
|
|
# 检查优惠券对象是否存在
|
|
if not self.coupon:
|
|
raise ValueError("优惠券对象不存在")
|
|
|
|
# 发放优惠券
|
|
user_coupon = UserCouponDB(
|
|
user_id=user_id,
|
|
coupon_id=coupon_id,
|
|
coupon_name=self.coupon.name,
|
|
coupon_amount=self.coupon.amount,
|
|
coupon_type=self.coupon.coupon_type,
|
|
expire_time=expire_time,
|
|
)
|
|
|
|
return user_coupon
|
|
|
|
|
|
|