69 lines
2.3 KiB
Python
69 lines
2.3 KiB
Python
from fastapi import APIRouter, Depends
|
|
from sqlalchemy.orm import Session
|
|
from app.models.database import get_db
|
|
from app.api.deps import get_current_user
|
|
from app.models.user import UserDB
|
|
from app.core.response import success_response, error_response, ResponseModel
|
|
from app.models.subscribe import SubscribeDB, SubscribeCreate, SubscribeInfo
|
|
from sqlalchemy import and_, func
|
|
|
|
router = APIRouter()
|
|
|
|
@router.post("", response_model=ResponseModel)
|
|
async def subscribe_template(
|
|
subscribe: SubscribeCreate,
|
|
db: Session = Depends(get_db),
|
|
current_user: UserDB = Depends(get_current_user)
|
|
):
|
|
"""订阅消息模板"""
|
|
results = []
|
|
|
|
try:
|
|
for template_info in subscribe.template_infos:
|
|
# 检查是否已存在订阅记录
|
|
exists = db.query(SubscribeDB).filter(
|
|
and_(
|
|
SubscribeDB.user_id == current_user.userid,
|
|
SubscribeDB.template_id == template_info.template_id
|
|
)
|
|
).first()
|
|
|
|
if exists:
|
|
# 更新动作
|
|
exists.action = template_info.action
|
|
exists.update_time = func.now()
|
|
results.append(exists)
|
|
else:
|
|
# 创建新的订阅记录
|
|
db_subscribe = SubscribeDB(
|
|
user_id=current_user.userid,
|
|
template_id=template_info.template_id,
|
|
action=template_info.action
|
|
)
|
|
db.add(db_subscribe)
|
|
results.append(db_subscribe)
|
|
|
|
db.commit()
|
|
for r in results:
|
|
db.refresh(r)
|
|
|
|
return success_response(data=[
|
|
SubscribeInfo.model_validate(r) for r in results
|
|
])
|
|
except Exception as e:
|
|
db.rollback()
|
|
return error_response(code=500, message=f"处理订阅失败: {str(e)}")
|
|
|
|
@router.get("", response_model=ResponseModel)
|
|
async def get_subscribes(
|
|
db: Session = Depends(get_db),
|
|
current_user: UserDB = Depends(get_current_user)
|
|
):
|
|
"""获取用户的订阅列表"""
|
|
subscribes = db.query(SubscribeDB).filter(
|
|
SubscribeDB.user_id == current_user.userid
|
|
).all()
|
|
|
|
return success_response(data=[
|
|
SubscribeInfo.model_validate(s) for s in subscribes
|
|
]) |