remove subscribedb
This commit is contained in:
parent
86c148816e
commit
7d205a6086
@ -1,69 +0,0 @@
|
|||||||
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
|
|
||||||
])
|
|
||||||
@ -23,8 +23,6 @@ from app.models.user_auth import UserAuthDB, UserAuthCreate, UserAuthInfo
|
|||||||
from app.core.qcloud import qcloud_manager
|
from app.core.qcloud import qcloud_manager
|
||||||
from app.models.merchant import MerchantDB
|
from app.models.merchant import MerchantDB
|
||||||
from app.models.address import AddressDB, AddressInfo
|
from app.models.address import AddressDB, AddressInfo
|
||||||
from app.models.subscribe import SubscribeDB
|
|
||||||
|
|
||||||
|
|
||||||
router = APIRouter()
|
router = APIRouter()
|
||||||
|
|
||||||
@ -163,13 +161,6 @@ async def get_user_info(
|
|||||||
UserCouponDB.status == CouponStatus.UNUSED
|
UserCouponDB.status == CouponStatus.UNUSED
|
||||||
).count()
|
).count()
|
||||||
user_data['coupon_count'] = coupon_count
|
user_data['coupon_count'] = coupon_count
|
||||||
|
|
||||||
# 查询当前用户是否订阅的模板
|
|
||||||
subscribe_count = db.query(SubscribeDB).filter(
|
|
||||||
SubscribeDB.user_id == current_user.userid
|
|
||||||
).count()
|
|
||||||
|
|
||||||
user_data['is_subscribe'] = subscribe_count > 0
|
|
||||||
|
|
||||||
return success_response(data=user_data)
|
return success_response(data=user_data)
|
||||||
|
|
||||||
|
|||||||
@ -16,13 +16,11 @@ import uuid
|
|||||||
from typing import Dict, Any
|
from typing import Dict, Any
|
||||||
from sqlalchemy.orm import Session
|
from sqlalchemy.orm import Session
|
||||||
from sqlalchemy import and_
|
from sqlalchemy import and_
|
||||||
from app.models.subscribe import SubscribeDB
|
|
||||||
|
|
||||||
def generate_random_string(length=32):
|
def generate_random_string(length=32):
|
||||||
"""生成指定长度的随机字符串"""
|
"""生成指定长度的随机字符串"""
|
||||||
return ''.join(random.choices(string.ascii_letters + string.digits, k=length))
|
return ''.join(random.choices(string.ascii_letters + string.digits, k=length))
|
||||||
|
|
||||||
|
|
||||||
class WeChatClient:
|
class WeChatClient:
|
||||||
"""微信客户端"""
|
"""微信客户端"""
|
||||||
|
|
||||||
@ -447,71 +445,3 @@ class WeChatClient:
|
|||||||
except Exception as e:
|
except Exception as e:
|
||||||
print(f"申请退款异常: {str(e)}")
|
print(f"申请退款异常: {str(e)}")
|
||||||
raise Exception(f"申请退款失败: {str(e)}")
|
raise Exception(f"申请退款失败: {str(e)}")
|
||||||
|
|
||||||
async def send_subscribe_message(
|
|
||||||
self,
|
|
||||||
openid: str,
|
|
||||||
template_id: str,
|
|
||||||
data: Dict[str, Any],
|
|
||||||
db: Session = None,
|
|
||||||
user_id: int = None,
|
|
||||||
page: str = None
|
|
||||||
) -> bool:
|
|
||||||
"""
|
|
||||||
发送订阅消息
|
|
||||||
:param openid: 用户openid
|
|
||||||
:param template_id: 模板ID
|
|
||||||
:param data: 模板数据
|
|
||||||
:param db: 数据库会话(可选)
|
|
||||||
:param user_id: 用户ID(可选,用于检查订阅状态)
|
|
||||||
:param page: 点击模板卡片后的跳转页面(可选)
|
|
||||||
:return: 发送是否成功
|
|
||||||
"""
|
|
||||||
try:
|
|
||||||
# 如果提供了数据库会话和用户ID,检查订阅状态
|
|
||||||
if db and user_id:
|
|
||||||
subscribe = db.query(SubscribeDB).filter(
|
|
||||||
and_(
|
|
||||||
SubscribeDB.user_id == user_id,
|
|
||||||
SubscribeDB.template_id == template_id
|
|
||||||
)
|
|
||||||
).first()
|
|
||||||
|
|
||||||
# 如果用户没有订阅或拒绝了订阅,则不发送
|
|
||||||
if not subscribe or subscribe.action == "reject":
|
|
||||||
return False
|
|
||||||
|
|
||||||
# 构建消息数据
|
|
||||||
message_data = {
|
|
||||||
"touser": openid,
|
|
||||||
"template_id": template_id,
|
|
||||||
"data": {
|
|
||||||
key: {
|
|
||||||
"value": value
|
|
||||||
} for key, value in data.items()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
# 如果提供了跳转页面
|
|
||||||
if page:
|
|
||||||
message_data["page"] = page
|
|
||||||
|
|
||||||
# 发送订阅消息
|
|
||||||
access_token = await self.get_access_token()
|
|
||||||
url = f"https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token={access_token}"
|
|
||||||
|
|
||||||
async with aiohttp.ClientSession() as session:
|
|
||||||
async with session.post(url, json=message_data) as response:
|
|
||||||
result = await response.json()
|
|
||||||
|
|
||||||
if result.get("errcode") == 0:
|
|
||||||
return True
|
|
||||||
|
|
||||||
print(f"发送订阅消息失败: {result}")
|
|
||||||
return False
|
|
||||||
|
|
||||||
except Exception as e:
|
|
||||||
print(f"发送订阅消息异常: {str(e)}")
|
|
||||||
return False
|
|
||||||
|
|
||||||
|
|
||||||
@ -1,38 +0,0 @@
|
|||||||
from sqlalchemy import Column, Integer, String, DateTime, ForeignKey, Boolean
|
|
||||||
from sqlalchemy.sql import func
|
|
||||||
from pydantic import BaseModel, Field
|
|
||||||
from typing import Optional, List
|
|
||||||
from datetime import datetime
|
|
||||||
from .database import Base
|
|
||||||
|
|
||||||
class SubscribeDB(Base):
|
|
||||||
__tablename__ = "user_subscribes"
|
|
||||||
|
|
||||||
id = Column(Integer, primary_key=True, autoincrement=True)
|
|
||||||
user_id = Column(Integer, ForeignKey("users.userid"), nullable=False)
|
|
||||||
template_id = Column(String(64), nullable=False) # 模板ID
|
|
||||||
action = Column(String(10), nullable=False) # accept 或 reject
|
|
||||||
create_time = Column(DateTime(timezone=True), server_default=func.now())
|
|
||||||
update_time = Column(DateTime(timezone=True), onupdate=func.now())
|
|
||||||
|
|
||||||
class Config:
|
|
||||||
from_attributes = True
|
|
||||||
|
|
||||||
|
|
||||||
class TemplateInfo(BaseModel):
|
|
||||||
template_id: str
|
|
||||||
action: str = Field(..., pattern="^(accept|reject)$") # 只允许 accept 或 reject
|
|
||||||
|
|
||||||
class SubscribeCreate(BaseModel):
|
|
||||||
template_infos: List[TemplateInfo] = Field(..., min_items=1) # 至少一个模板ID
|
|
||||||
|
|
||||||
class SubscribeInfo(BaseModel):
|
|
||||||
id: int
|
|
||||||
user_id: int
|
|
||||||
template_id: str
|
|
||||||
action: str
|
|
||||||
create_time: datetime
|
|
||||||
update_time: Optional[datetime]
|
|
||||||
|
|
||||||
class Config:
|
|
||||||
from_attributes = True
|
|
||||||
Loading…
Reference in New Issue
Block a user