models_db.py 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939
  1. """
  2. SQLAlchemy 数据库模型定义
  3. """
  4. from datetime import datetime
  5. from typing import Optional
  6. from sqlalchemy import (
  7. Column,
  8. String,
  9. Integer,
  10. BigInteger,
  11. Text,
  12. Enum,
  13. Boolean,
  14. JSON,
  15. TIMESTAMP,
  16. Index,
  17. UniqueConstraint,
  18. ForeignKey,
  19. )
  20. from sqlalchemy.orm import declarative_base
  21. from sqlalchemy.sql import func
  22. PKBigInt = BigInteger().with_variant(Integer, "sqlite")
  23. Base = declarative_base()
  24. class User(Base):
  25. """用户表模型"""
  26. __tablename__ = "users"
  27. id = Column(PKBigInt, primary_key=True, autoincrement=True)
  28. user_id = Column(String(64), unique=True, nullable=False, index=True, comment="用户唯一标识(UUID)")
  29. # 基本信息
  30. username = Column(String(100), nullable=False, comment="用户名/昵称")
  31. user_type = Column(Enum("guest", "registered", name="user_type"), default="guest", comment="用户类型")
  32. user_segment = Column(String(32), nullable=False, default="individual", comment="用户/场景分群:individual/school/internal等")
  33. org_id = Column(String(64), nullable=True, comment="组织ID(关联 organizations.org_id)")
  34. is_test_user = Column(Boolean, nullable=False, default=False, comment="是否测试账号")
  35. region = Column(String(32), nullable=True, comment="国家/地区(如 CN、US)")
  36. bot_name = Column(String(100), nullable=True, comment="用户给机器人取的名字")
  37. # 注册信息(可选)
  38. area_code = Column(String(10), nullable=True, comment="手机区号(如 +86)")
  39. phone = Column(String(20), unique=True, nullable=True, index=True, comment="手机号")
  40. email = Column(String(200), unique=True, nullable=True, index=True, comment="邮箱")
  41. wechat_openid = Column(String(100), unique=True, nullable=True, index=True, comment="微信OpenID")
  42. qq_openid = Column(String(100), unique=True, nullable=True, index=True, comment="QQ OpenID")
  43. qq_unionid = Column(String(128), unique=True, nullable=True, index=True, comment="QQ UnionID")
  44. google_email = Column(String(200), unique=True, nullable=True, index=True, comment="Google邮箱")
  45. # 认证信息
  46. is_verified = Column(Boolean, default=False, comment="是否已认证")
  47. registered_at = Column(TIMESTAMP, nullable=True, comment="注册时间")
  48. # 统计信息
  49. total_messages = Column(Integer, default=0, comment="总消息数")
  50. total_rounds = Column(Integer, default=0, comment="总对话轮次")
  51. total_speech_duration_ms = Column(BigInteger, default=0, comment="累积说话时长(毫秒)")
  52. user_level = Column(Integer, default=0, nullable=False, comment="用户等级(0-5)")
  53. preferred_language = Column(String(8), nullable=True, comment="首选语言(zh/en)")
  54. last_active_at = Column(TIMESTAMP, nullable=True, comment="最后活跃时间")
  55. # 背景图片
  56. current_background_image_id = Column(String(64), nullable=True, comment="当前使用的背景图片ID")
  57. created_at = Column(TIMESTAMP, server_default=func.current_timestamp(), comment="创建时间")
  58. updated_at = Column(TIMESTAMP, server_default=func.current_timestamp(), onupdate=func.current_timestamp(), comment="更新时间")
  59. def to_dict(self) -> dict:
  60. """转换为字典"""
  61. return {
  62. "user_id": self.user_id,
  63. "username": self.username,
  64. "user_type": self.user_type,
  65. "user_segment": self.user_segment,
  66. "org_id": self.org_id,
  67. "is_test_user": self.is_test_user,
  68. "region": self.region,
  69. "bot_name": self.bot_name,
  70. "area_code": self.area_code,
  71. "phone": self.phone,
  72. "email": self.email,
  73. "wechat_openid": self.wechat_openid,
  74. "qq_openid": self.qq_openid,
  75. "qq_unionid": self.qq_unionid,
  76. "google_email": self.google_email,
  77. "is_verified": self.is_verified,
  78. "registered_at": self.registered_at.isoformat() if self.registered_at else None,
  79. "total_messages": self.total_messages,
  80. "total_rounds": self.total_rounds,
  81. "total_speech_duration_ms": self.total_speech_duration_ms,
  82. "user_level": self.user_level,
  83. "preferred_language": self.preferred_language,
  84. "last_active_at": self.last_active_at.isoformat() if self.last_active_at else None,
  85. "current_background_image_id": self.current_background_image_id,
  86. "created_at": self.created_at.isoformat() if self.created_at else None,
  87. }
  88. class Organization(Base):
  89. """组织表模型"""
  90. __tablename__ = "organizations"
  91. id = Column(PKBigInt, primary_key=True, autoincrement=True, comment="主键")
  92. org_id = Column(String(64), nullable=False, unique=True, index=True, comment="组织唯一标识")
  93. org_name = Column(String(200), nullable=False, comment="组织名称")
  94. org_type = Column(String(32), nullable=True, index=True, comment="组织类型:school/institution/internal等")
  95. region = Column(String(32), nullable=True, index=True, comment="组织所在地区")
  96. metadata_json = Column(JSON, nullable=True, comment="扩展信息")
  97. created_at = Column(TIMESTAMP, server_default=func.current_timestamp(), nullable=False, comment="创建时间")
  98. updated_at = Column(
  99. TIMESTAMP,
  100. server_default=func.current_timestamp(),
  101. onupdate=func.current_timestamp(),
  102. nullable=False,
  103. comment="更新时间",
  104. )
  105. def to_dict(self) -> dict:
  106. return {
  107. "org_id": self.org_id,
  108. "org_name": self.org_name,
  109. "org_type": self.org_type,
  110. "region": self.region,
  111. "metadata": self.metadata_json,
  112. "created_at": self.created_at.isoformat() if self.created_at else None,
  113. "updated_at": self.updated_at.isoformat() if self.updated_at else None,
  114. }
  115. class Message(Base):
  116. """消息表模型"""
  117. __tablename__ = "messages"
  118. id = Column(PKBigInt, primary_key=True, autoincrement=True)
  119. message_id = Column(String(64), unique=True, nullable=False, comment="消息ID")
  120. user_id = Column(String(64), nullable=False, index=True, comment="用户ID")
  121. # 消息内容
  122. role = Column(Enum("user", "assistant", "system", name="role"), nullable=False, comment="角色")
  123. content = Column(Text, nullable=False, comment="消息内容")
  124. # 轮次信息
  125. round_number = Column(Integer, nullable=False, comment="对话轮次(从1开始)")
  126. # 扩展信息
  127. emotion = Column(String(50), nullable=True, comment="情感标签")
  128. message_metadata = Column(JSON, nullable=True, comment="扩展信息(音频路径、识别耗时等)")
  129. token_count = Column(Integer, nullable=True, comment="Token数量")
  130. created_at = Column(TIMESTAMP, server_default=func.current_timestamp(), index=True, comment="创建时间")
  131. # 复合索引
  132. __table_args__ = (
  133. Index("idx_user_round", "user_id", "round_number"),
  134. )
  135. def to_dict(self) -> dict:
  136. """转换为字典"""
  137. return {
  138. "message_id": self.message_id,
  139. "user_id": self.user_id,
  140. "role": self.role,
  141. "content": self.content,
  142. "round_number": self.round_number,
  143. "emotion": self.emotion,
  144. "metadata": self.message_metadata, # 对外保持 metadata 字段名
  145. "token_count": self.token_count,
  146. "created_at": self.created_at.isoformat() if self.created_at else None,
  147. }
  148. class LLMPrompt(Base):
  149. """LLM提示词记录表模型"""
  150. __tablename__ = "llm_prompts"
  151. id = Column(PKBigInt, primary_key=True, autoincrement=True)
  152. prompt_id = Column(String(64), unique=True, nullable=False, index=True, comment="提示词记录ID")
  153. # 关联消息表(外键关联到messages.id)
  154. message_id = Column(PKBigInt, ForeignKey("messages.id", ondelete="CASCADE"), nullable=False, index=True, comment="关联的消息ID")
  155. # 用户信息
  156. user_id = Column(String(64), nullable=False, index=True, comment="用户ID")
  157. round_number = Column(Integer, nullable=False, comment="对话轮次")
  158. # 提示词内容
  159. system_prompt = Column(Text, nullable=False, comment="系统提示词(完整内容)")
  160. runtime_context = Column(Text, nullable=True, comment="运行时上下文")
  161. messages_json = Column(JSON, nullable=False, comment="完整的messages数组(JSON格式)")
  162. # LLM调用参数
  163. model_name = Column(String(100), nullable=False, comment="模型名称")
  164. temperature = Column(String(20), nullable=True, comment="温度参数")
  165. max_tokens = Column(Integer, nullable=True, comment="最大Token数")
  166. stream = Column(Boolean, default=True, comment="是否流式输出")
  167. # 统计信息
  168. prompt_token_count = Column(Integer, nullable=True, comment="提示词Token数")
  169. total_token_count = Column(Integer, nullable=True, comment="总Token数(包含响应)")
  170. # 扩展信息
  171. metadata_json = Column(JSON, nullable=True, comment="扩展信息(调用耗时、错误信息等)")
  172. created_at = Column(TIMESTAMP, server_default=func.current_timestamp(), index=True, comment="创建时间")
  173. # 索引
  174. __table_args__ = (
  175. Index("idx_llm_prompt_message", "message_id"),
  176. Index("idx_llm_prompt_user_round", "user_id", "round_number"),
  177. Index("idx_llm_prompt_created", "created_at"),
  178. )
  179. def to_dict(self) -> dict:
  180. """转换为字典"""
  181. return {
  182. "prompt_id": self.prompt_id,
  183. "message_id": self.message_id,
  184. "user_id": self.user_id,
  185. "round_number": self.round_number,
  186. "system_prompt": self.system_prompt,
  187. "runtime_context": self.runtime_context,
  188. "messages": self.messages_json, # 对外保持 messages 字段名
  189. "model_name": self.model_name,
  190. "temperature": self.temperature,
  191. "max_tokens": self.max_tokens,
  192. "stream": self.stream,
  193. "prompt_token_count": self.prompt_token_count,
  194. "total_token_count": self.total_token_count,
  195. "metadata": self.metadata_json, # 对外保持 metadata 字段名
  196. "created_at": self.created_at.isoformat() if self.created_at else None,
  197. }
  198. class ConversationSummary(Base):
  199. """对话总结表模型"""
  200. __tablename__ = "conversation_summaries"
  201. id = Column(PKBigInt, primary_key=True, autoincrement=True)
  202. summary_id = Column(String(64), unique=True, nullable=False, comment="总结ID")
  203. user_id = Column(String(64), nullable=False, index=True, comment="用户ID")
  204. # 总结范围
  205. start_round = Column(Integer, nullable=False, comment="起始轮次")
  206. end_round = Column(Integer, nullable=False, comment="结束轮次")
  207. # 总结内容
  208. summary_text = Column(Text, nullable=False, comment="总结内容")
  209. summary_type = Column(Enum("auto", "manual", name="summary_type"), default="auto", comment="总结类型")
  210. # 统计信息
  211. message_count = Column(Integer, nullable=True, comment="总结的消息数量")
  212. token_count = Column(Integer, nullable=True, comment="总结文本Token数")
  213. created_at = Column(TIMESTAMP, server_default=func.current_timestamp(), comment="创建时间")
  214. # 复合索引和唯一约束
  215. __table_args__ = (
  216. Index("idx_user_end_round", "user_id", "end_round"),
  217. UniqueConstraint("user_id", "start_round", "end_round", name="uk_user_round_range"),
  218. )
  219. def to_dict(self) -> dict:
  220. """转换为字典"""
  221. return {
  222. "summary_id": self.summary_id,
  223. "user_id": self.user_id,
  224. "start_round": self.start_round,
  225. "end_round": self.end_round,
  226. "summary_text": self.summary_text,
  227. "summary_type": self.summary_type,
  228. "message_count": self.message_count,
  229. "token_count": self.token_count,
  230. "created_at": self.created_at.isoformat() if self.created_at else None,
  231. }
  232. class MissionType(Base):
  233. """任务类型配置"""
  234. __tablename__ = "mission_types"
  235. id = Column(PKBigInt, primary_key=True, autoincrement=True)
  236. type_key = Column(String(64), unique=True, nullable=False, index=True, comment="任务类型唯一标识")
  237. display_name = Column(String(100), nullable=False, comment="任务显示名称")
  238. description = Column(String(255), nullable=True, comment="类型描述")
  239. is_repeatable = Column(Boolean, default=False, comment="是否允许重复触发")
  240. is_active = Column(Boolean, default=True, comment="是否启用")
  241. metadata_json = Column("metadata", JSON, nullable=True, comment="扩展配置")
  242. created_at = Column(TIMESTAMP, server_default=func.current_timestamp(), comment="创建时间")
  243. updated_at = Column(
  244. TIMESTAMP,
  245. server_default=func.current_timestamp(),
  246. onupdate=func.current_timestamp(),
  247. comment="更新时间"
  248. )
  249. __table_args__ = (
  250. Index("idx_mission_type_active", "is_active"),
  251. )
  252. class MissionEnergyStone(Base):
  253. """任务能量石(首次对话奖励)"""
  254. __tablename__ = "mission_energy_stones"
  255. id = Column(PKBigInt, primary_key=True, autoincrement=True)
  256. stone_id = Column(String(64), unique=True, nullable=False, index=True, comment="能量石ID")
  257. user_id = Column(String(64), nullable=False, index=True, comment="用户ID")
  258. request_id = Column(String(64), nullable=True, comment="触发的请求ID")
  259. appear_reason = Column(String(64), nullable=False, default="first_dialog", comment="触发原因")
  260. mission_type = Column(String(64), nullable=False, default="first_dialog", comment="任务类型")
  261. appear_at = Column(TIMESTAMP, server_default=func.current_timestamp(), comment="出现时间")
  262. clicked_at = Column(TIMESTAMP, nullable=True, comment="点击时间")
  263. auto_removed = Column(Boolean, default=False, comment="是否由系统自动消失")
  264. metadata_json = Column("metadata", JSON, nullable=True, comment="扩展信息")
  265. created_at = Column(TIMESTAMP, server_default=func.current_timestamp(), comment="创建时间")
  266. updated_at = Column(
  267. TIMESTAMP,
  268. server_default=func.current_timestamp(),
  269. onupdate=func.current_timestamp(),
  270. comment="更新时间"
  271. )
  272. __table_args__ = (
  273. Index("idx_mission_stone_user", "user_id", "appear_at"),
  274. Index("idx_mission_type_user", "mission_type", "user_id"),
  275. )
  276. class ConversationEnergyStone(Base):
  277. """对话能量石(按时长发放)"""
  278. __tablename__ = "conversation_energy_stones"
  279. id = Column(PKBigInt, primary_key=True, autoincrement=True)
  280. stone_id = Column(String(64), unique=True, nullable=False, index=True, comment="能量石ID")
  281. user_id = Column(String(64), nullable=False, index=True, comment="用户ID")
  282. request_id = Column(String(64), nullable=True, comment="触发的请求ID")
  283. threshold_index = Column(Integer, nullable=False, comment="达到的阈值序号(30秒一档)")
  284. total_duration_ms = Column(BigInteger, nullable=False, comment="达到阈值后的累计说话时长")
  285. duration_increment_ms = Column(Integer, nullable=False, comment="本次增加的说话时长")
  286. appear_at = Column(TIMESTAMP, server_default=func.current_timestamp(), comment="出现时间")
  287. clicked_at = Column(TIMESTAMP, nullable=True, comment="点击时间")
  288. auto_removed = Column(Boolean, default=False, comment="是否由系统自动消失")
  289. metadata_json = Column("metadata", JSON, nullable=True, comment="扩展信息")
  290. created_at = Column(TIMESTAMP, server_default=func.current_timestamp(), comment="创建时间")
  291. updated_at = Column(
  292. TIMESTAMP,
  293. server_default=func.current_timestamp(),
  294. onupdate=func.current_timestamp(),
  295. comment="更新时间"
  296. )
  297. __table_args__ = (
  298. UniqueConstraint("user_id", "threshold_index", name="uk_conversation_stone_threshold"),
  299. Index("idx_conversation_stone_user_threshold", "user_id", "threshold_index"),
  300. )
  301. class UserBonusEnergyStone(Base):
  302. """用户赠送的对话能量石数量(活动/回馈等,与 conversation_energy_stones 分开统计,展示时相加)"""
  303. __tablename__ = "user_bonus_energy_stones"
  304. user_id = Column(String(64), primary_key=True, nullable=False, comment="用户ID(关联 users.user_id)")
  305. bonus_conversation_count = Column(Integer, default=0, nullable=False, comment="赠送的对话能量石个数")
  306. updated_at = Column(
  307. TIMESTAMP,
  308. server_default=func.current_timestamp(),
  309. onupdate=func.current_timestamp(),
  310. comment="更新时间",
  311. )
  312. class UserUIState(Base):
  313. """用户前端可视化状态表(页面与提示状态)"""
  314. __tablename__ = "user_ui_states"
  315. id = Column(PKBigInt, primary_key=True, autoincrement=True)
  316. user_id = Column(String(64), unique=True, nullable=False, index=True, comment="用户ID(关联 users.user_id)")
  317. # 页面与路由状态
  318. current_page = Column(String(64), nullable=True, comment="当前业务流程页面标识")
  319. visited_routes = Column(JSON, nullable=True, comment="已访问路由列表")
  320. # 新手引导与提示状态
  321. has_shown_tap_to_chat = Column(Boolean, default=False, nullable=False, comment="是否已展示过 TapToChat 提示")
  322. has_shown_cancel_tooltip = Column(Boolean, default=False, nullable=False, comment="是否已展示过取消按钮提示")
  323. has_shown_send_tooltip = Column(Boolean, default=False, nullable=False, comment="是否已展示过发送按钮提示")
  324. has_shown_progress_bar_tooltip = Column(Boolean, default=False, nullable=False, comment="是否已展示过进度条提示")
  325. # 字幕显示偏好
  326. subtitle_on = Column(Boolean, default=False, nullable=False, comment="是否开启字幕显示")
  327. has_shown_mission_stone_modal = Column(Boolean, default=False, nullable=False, comment="是否已展示过任务能量石弹窗")
  328. has_shown_conversation_stone_modal = Column(Boolean, default=False, nullable=False, comment="是否已展示过对话能量石弹窗")
  329. has_clicked_mission_stone = Column(Boolean, default=False, nullable=False, comment="是否已点击过任务能量石(控制光晕显示)")
  330. has_clicked_conversation_stone = Column(Boolean, default=False, nullable=False, comment="是否已点击过对话能量石(控制光晕显示)")
  331. # Avatar-C 解锁状态
  332. avatar_c_unlocked = Column(Boolean, default=False, nullable=False, comment="是否已解锁 Avatar-C")
  333. has_shared_avatar = Column(Boolean, default=False, nullable=False, comment="是否已分享头像奖励")
  334. # 当前选中的形象
  335. current_avatar_id = Column(String(64), nullable=True, comment="当前使用的形象ID(关联 avatars.avatar_id)")
  336. created_at = Column(TIMESTAMP, server_default=func.current_timestamp(), comment="创建时间")
  337. updated_at = Column(
  338. TIMESTAMP,
  339. server_default=func.current_timestamp(),
  340. onupdate=func.current_timestamp(),
  341. comment="更新时间",
  342. )
  343. def to_dict(self) -> dict:
  344. return {
  345. "user_id": self.user_id,
  346. "current_page": self.current_page,
  347. "visited_routes": self.visited_routes or [],
  348. "has_shown_tap_to_chat": self.has_shown_tap_to_chat,
  349. "has_shown_cancel_tooltip": self.has_shown_cancel_tooltip,
  350. "has_shown_send_tooltip": self.has_shown_send_tooltip,
  351. "has_shown_progress_bar_tooltip": self.has_shown_progress_bar_tooltip,
  352. "has_shown_mission_stone_modal": self.has_shown_mission_stone_modal,
  353. "has_shown_conversation_stone_modal": self.has_shown_conversation_stone_modal,
  354. "has_clicked_mission_stone": self.has_clicked_mission_stone,
  355. "has_clicked_conversation_stone": self.has_clicked_conversation_stone,
  356. "subtitle_on": self.subtitle_on,
  357. "avatar_c_unlocked": self.avatar_c_unlocked,
  358. "has_shared_avatar": self.has_shared_avatar,
  359. "current_avatar_id": self.current_avatar_id,
  360. "created_at": self.created_at.isoformat() if self.created_at else None,
  361. "updated_at": self.updated_at.isoformat() if self.updated_at else None,
  362. }
  363. class PageVisitLog(Base):
  364. """页面访问日志表(每次打开任意界面记录一条)"""
  365. __tablename__ = "page_visit_logs"
  366. id = Column(PKBigInt, primary_key=True, autoincrement=True)
  367. user_id = Column(String(64), nullable=True, index=True, comment="用户ID(未登录则为空)")
  368. path = Column(String(512), nullable=False, index=True, comment="访问路径(如 /chatbot)")
  369. visited_at = Column(TIMESTAMP, server_default=func.current_timestamp(), nullable=False, index=True, comment="访问时间")
  370. __table_args__ = (Index("idx_page_visit_visited_at", "visited_at"),)
  371. def to_dict(self) -> dict:
  372. return {
  373. "id": self.id,
  374. "user_id": self.user_id,
  375. "path": self.path,
  376. "visited_at": self.visited_at.isoformat() if self.visited_at else None,
  377. }
  378. class UserEvent(Base):
  379. """用户事件表(前端埋点:页面/按钮/操作等)"""
  380. __tablename__ = "user_events"
  381. id = Column(PKBigInt, primary_key=True, autoincrement=True, comment="主键")
  382. event_id = Column(String(64), nullable=False, unique=True, index=True, comment="事件ID(客户端或服务端生成,唯一)")
  383. user_id = Column(String(64), nullable=False, index=True, comment="用户ID(关联 users.user_id)")
  384. event_name = Column(String(64), nullable=False, index=True, comment="事件代码,如 page.chatbot__enter(遵循埋点命名规范)")
  385. event_label = Column(String(128), nullable=True, comment="事件中文名称/描述(如“进入聊天页”、“欢迎页开始按钮点击”)")
  386. event_time = Column(TIMESTAMP, nullable=False, comment="事件发生时间(UTC)")
  387. session_id = Column(String(64), nullable=True, index=True, comment="会话ID,同一次前台停留共享")
  388. platform = Column(String(16), nullable=False, comment="平台:ios/android/web")
  389. app_version = Column(String(32), nullable=True, comment="应用版本号,如 v0.1.x")
  390. timezone_offset_minutes = Column(Integer, nullable=True, comment="用户本地相对UTC的分钟偏移量(分钟)")
  391. properties = Column(JSON, nullable=True, comment="扩展属性(page、entry、button_id、duration_seconds 等)")
  392. created_at = Column(TIMESTAMP, server_default=func.current_timestamp(), nullable=False, comment="记录创建时间")
  393. __table_args__ = (
  394. Index("idx_user_event_time", "user_id", "event_time"),
  395. Index("idx_event_time_name", "event_time", "event_name"),
  396. )
  397. def to_dict(self) -> dict:
  398. return {
  399. "event_id": self.event_id,
  400. "user_id": self.user_id,
  401. "event_name": self.event_name,
  402. "event_label": self.event_label,
  403. "event_time": self.event_time.isoformat() if self.event_time else None,
  404. "session_id": self.session_id,
  405. "platform": self.platform,
  406. "app_version": self.app_version,
  407. "timezone_offset_minutes": self.timezone_offset_minutes,
  408. "properties": self.properties,
  409. "created_at": self.created_at.isoformat() if self.created_at else None,
  410. }
  411. class UserSpecialScenarioTopicLog(Base):
  412. """用户情景话题对话记录(情景对话模式:用于概率排除与不再触发)"""
  413. __tablename__ = "user_special_scenario_topic_logs"
  414. id = Column(PKBigInt, primary_key=True, autoincrement=True, comment="主键")
  415. user_id = Column(String(64), nullable=False, index=True, comment="用户ID(关联 users.user_id)")
  416. scenario_key = Column(String(32), nullable=False, index=True, comment="场景: window|reading|eating")
  417. topic_key = Column(String(32), nullable=False, index=True, comment="话题键")
  418. conversed_at = Column(TIMESTAMP, nullable=False, server_default=func.current_timestamp(), comment="该场景该话题下首次对话时间")
  419. created_at = Column(TIMESTAMP, server_default=func.current_timestamp(), comment="记录创建时间")
  420. __table_args__ = (
  421. UniqueConstraint("user_id", "scenario_key", "topic_key", name="uk_user_scenario_topic"),
  422. Index("idx_user_scenario", "user_id", "scenario_key"),
  423. )
  424. def to_dict(self) -> dict:
  425. return {
  426. "id": self.id,
  427. "user_id": self.user_id,
  428. "scenario_key": self.scenario_key,
  429. "topic_key": self.topic_key,
  430. "conversed_at": self.conversed_at.isoformat() if self.conversed_at else None,
  431. "created_at": self.created_at.isoformat() if self.created_at else None,
  432. }
  433. class UserIntimacy(Base):
  434. """用户亲密度表(三颗心,0-3)"""
  435. __tablename__ = "user_intimacy"
  436. id = Column(PKBigInt, primary_key=True, autoincrement=True)
  437. user_id = Column(String(64), unique=True, nullable=False, index=True, comment="用户ID(关联 users.user_id)")
  438. heart_count = Column(Integer, default=3, nullable=False, comment="当前亲密度心数 0-3")
  439. last_visit_date_at_deduction = Column(String(10), nullable=True, comment="上次扣心时所依据的最后访问日期 YYYY-MM-DD,避免重复扣")
  440. last_light_up_date = Column(String(10), nullable=True, comment="上次手动点亮日期 YYYY-MM-DD,控制每天仅点亮一次")
  441. updated_at = Column(TIMESTAMP, server_default=func.current_timestamp(), onupdate=func.current_timestamp(), nullable=False, comment="更新时间")
  442. def to_dict(self) -> dict:
  443. return {
  444. "user_id": self.user_id,
  445. "heart_count": self.heart_count,
  446. "last_visit_date_at_deduction": self.last_visit_date_at_deduction,
  447. "last_light_up_date": self.last_light_up_date,
  448. "updated_at": self.updated_at.isoformat() if self.updated_at else None,
  449. }
  450. class Avatar(Base):
  451. """形象配置表"""
  452. __tablename__ = "avatars"
  453. id = Column(PKBigInt, primary_key=True, autoincrement=True)
  454. avatar_id = Column(String(64), unique=True, nullable=False, index=True, comment="形象唯一标识")
  455. # 基本信息
  456. avatar_name = Column(String(100), nullable=False, comment="形象名称")
  457. description = Column(String(255), nullable=True, comment="形象描述")
  458. is_active = Column(Boolean, default=True, nullable=False, comment="是否启用")
  459. # 扩展信息
  460. metadata_json = Column("metadata", JSON, nullable=True, comment="扩展配置")
  461. created_at = Column(TIMESTAMP, server_default=func.current_timestamp(), comment="创建时间")
  462. updated_at = Column(
  463. TIMESTAMP,
  464. server_default=func.current_timestamp(),
  465. onupdate=func.current_timestamp(),
  466. comment="更新时间",
  467. )
  468. __table_args__ = (
  469. Index("idx_avatar_is_active", "is_active"),
  470. )
  471. def to_dict(self) -> dict:
  472. return {
  473. "avatar_id": self.avatar_id,
  474. "avatar_name": self.avatar_name,
  475. "description": self.description,
  476. "is_active": self.is_active,
  477. "metadata": self.metadata_json,
  478. "created_at": self.created_at.isoformat() if self.created_at else None,
  479. "updated_at": self.updated_at.isoformat() if self.updated_at else None,
  480. }
  481. class AvatarAsset(Base):
  482. """形象动作/情绪资源表"""
  483. __tablename__ = "avatar_assets"
  484. id = Column(PKBigInt, primary_key=True, autoincrement=True)
  485. avatar_id = Column(String(64), nullable=False, index=True, comment="形象ID")
  486. state = Column(
  487. Enum(
  488. "default",
  489. "positive",
  490. "negative",
  491. "talking",
  492. "idle",
  493. "sleep",
  494. name="avatar_state",
  495. ),
  496. nullable=False,
  497. default="default",
  498. comment="动作/情绪状态",
  499. )
  500. image_url = Column(String(500), nullable=False, comment="GIF 资源 URL")
  501. thumbnail_url = Column(String(500), nullable=True, comment="缩略图URL")
  502. metadata_json = Column("metadata", JSON, nullable=True, comment="扩展配置")
  503. created_at = Column(TIMESTAMP, server_default=func.current_timestamp(), comment="创建时间")
  504. updated_at = Column(
  505. TIMESTAMP,
  506. server_default=func.current_timestamp(),
  507. onupdate=func.current_timestamp(),
  508. comment="更新时间",
  509. )
  510. __table_args__ = (
  511. UniqueConstraint("avatar_id", "state", name="uk_avatar_asset_state"),
  512. Index("idx_avatar_asset_avatar_id", "avatar_id"),
  513. )
  514. def to_dict(self) -> dict:
  515. return {
  516. "id": self.id,
  517. "avatar_id": self.avatar_id,
  518. "state": self.state,
  519. "image_url": self.image_url,
  520. "thumbnail_url": self.thumbnail_url,
  521. "metadata": self.metadata_json,
  522. "created_at": self.created_at.isoformat() if self.created_at else None,
  523. "updated_at": self.updated_at.isoformat() if self.updated_at else None,
  524. }
  525. class UserAvatar(Base):
  526. """用户已拥有的形象"""
  527. __tablename__ = "user_avatars"
  528. id = Column(PKBigInt, primary_key=True, autoincrement=True)
  529. user_id = Column(String(64), nullable=False, index=True, comment="用户ID")
  530. avatar_id = Column(String(64), nullable=False, index=True, comment="形象ID")
  531. obtained_at = Column(TIMESTAMP, server_default=func.current_timestamp(), comment="获得时间")
  532. obtained_type = Column(
  533. Enum("default", "register", "level_up", "mission", "purchase", "gift", "event", name="avatar_obtained_type"),
  534. default="default",
  535. comment="获得方式",
  536. )
  537. obtained_source = Column(String(64), nullable=True, comment="获得来源(等级/任务/订单等)")
  538. metadata_json = Column("metadata", JSON, nullable=True, comment="扩展信息")
  539. created_at = Column(TIMESTAMP, server_default=func.current_timestamp(), comment="创建时间")
  540. __table_args__ = (
  541. UniqueConstraint("user_id", "avatar_id", name="uk_user_avatar"),
  542. Index("idx_user_avatar_user_obtained", "user_id", "obtained_at"),
  543. )
  544. def to_dict(self) -> dict:
  545. return {
  546. "id": self.id,
  547. "user_id": self.user_id,
  548. "avatar_id": self.avatar_id,
  549. "obtained_at": self.obtained_at.isoformat() if self.obtained_at else None,
  550. "obtained_type": self.obtained_type,
  551. "obtained_source": self.obtained_source,
  552. "metadata": self.metadata_json,
  553. "created_at": self.created_at.isoformat() if self.created_at else None,
  554. }
  555. class Feedback(Base):
  556. """用户反馈表模型"""
  557. __tablename__ = "feedbacks"
  558. id = Column(PKBigInt, primary_key=True, autoincrement=True)
  559. feedback_id = Column(String(64), unique=True, nullable=False, index=True, comment="反馈ID")
  560. user_id = Column(String(64), nullable=False, index=True, comment="用户ID")
  561. # 反馈内容
  562. content = Column(Text, nullable=False, comment="反馈内容")
  563. # 状态信息
  564. status = Column(
  565. Enum("pending", "reviewed", "resolved", "closed", name="feedback_status"),
  566. default="pending",
  567. nullable=False,
  568. comment="反馈状态"
  569. )
  570. # 扩展信息
  571. metadata_json = Column("metadata", JSON, nullable=True, comment="扩展信息")
  572. created_at = Column(TIMESTAMP, server_default=func.current_timestamp(), index=True, comment="创建时间")
  573. updated_at = Column(
  574. TIMESTAMP,
  575. server_default=func.current_timestamp(),
  576. onupdate=func.current_timestamp(),
  577. comment="更新时间",
  578. )
  579. __table_args__ = (
  580. Index("idx_feedback_user_created", "user_id", "created_at"),
  581. )
  582. def to_dict(self) -> dict:
  583. """转换为字典"""
  584. return {
  585. "feedback_id": self.feedback_id,
  586. "user_id": self.user_id,
  587. "content": self.content,
  588. "status": self.status,
  589. "metadata": self.metadata_json,
  590. "created_at": self.created_at.isoformat() if self.created_at else None,
  591. "updated_at": self.updated_at.isoformat() if self.updated_at else None,
  592. }
  593. def _attach_metadata_alias(model_cls):
  594. """Allow using `metadata` keyword/attribute while storing in metadata_json."""
  595. original_init = model_cls.__init__
  596. def __init__(self, *args, **kwargs):
  597. metadata_value = kwargs.pop("metadata", None)
  598. original_init(self, *args, **kwargs)
  599. if metadata_value is not None:
  600. setattr(self, "metadata_json", metadata_value)
  601. model_cls.__init__ = __init__
  602. def getter(self):
  603. return getattr(self, "metadata_json")
  604. def setter(self, value):
  605. setattr(self, "metadata_json", value)
  606. model_cls.metadata = property(getter, setter)
  607. class BackgroundImage(Base):
  608. """背景图片配置表"""
  609. __tablename__ = "background_images"
  610. id = Column(PKBigInt, primary_key=True, autoincrement=True)
  611. image_id = Column(String(64), unique=True, nullable=False, index=True, comment="背景图片唯一标识")
  612. # 基本信息
  613. image_name = Column(String(100), nullable=False, comment="背景图片名称")
  614. image_url = Column(String(500), nullable=False, comment="背景图片URL")
  615. thumbnail_url = Column(String(500), nullable=True, comment="缩略图URL")
  616. # 解锁条件
  617. unlock_type = Column(Enum("default", "level", "purchase", "mission", name="unlock_type"),
  618. default="default", comment="解锁类型")
  619. unlock_level = Column(Integer, nullable=True, comment="解锁所需等级(unlock_type=level时)")
  620. unlock_mission_type = Column(String(64), nullable=True, comment="解锁所需任务类型(unlock_type=mission时)")
  621. # 显示信息
  622. display_order = Column(Integer, default=0, comment="显示顺序")
  623. is_active = Column(Boolean, default=True, comment="是否启用")
  624. description = Column(String(255), nullable=True, comment="背景图片描述")
  625. # 扩展信息
  626. metadata_json = Column("metadata", JSON, nullable=True, comment="扩展配置")
  627. created_at = Column(TIMESTAMP, server_default=func.current_timestamp(), comment="创建时间")
  628. updated_at = Column(TIMESTAMP, server_default=func.current_timestamp(),
  629. onupdate=func.current_timestamp(), comment="更新时间")
  630. __table_args__ = (
  631. Index("idx_unlock_type", "unlock_type"),
  632. Index("idx_display_order", "display_order"),
  633. )
  634. def to_dict(self) -> dict:
  635. """转换为字典"""
  636. return {
  637. "image_id": self.image_id,
  638. "image_name": self.image_name,
  639. "image_url": self.image_url,
  640. "thumbnail_url": self.thumbnail_url,
  641. "unlock_type": self.unlock_type,
  642. "unlock_level": self.unlock_level,
  643. "unlock_mission_type": self.unlock_mission_type,
  644. "display_order": self.display_order,
  645. "is_active": self.is_active,
  646. "description": self.description,
  647. "metadata": self.metadata_json,
  648. "created_at": self.created_at.isoformat() if self.created_at else None,
  649. "updated_at": self.updated_at.isoformat() if self.updated_at else None,
  650. }
  651. class UserBackgroundImage(Base):
  652. """用户背景图片关联表(记录用户已获得的背景图片)"""
  653. __tablename__ = "user_background_images"
  654. id = Column(PKBigInt, primary_key=True, autoincrement=True)
  655. user_id = Column(String(64), nullable=False, index=True, comment="用户ID")
  656. image_id = Column(String(64), nullable=False, index=True, comment="背景图片ID")
  657. # 获得信息
  658. obtained_at = Column(TIMESTAMP, server_default=func.current_timestamp(), comment="获得时间")
  659. obtained_type = Column(Enum("default", "level_up", "purchase", "mission", "gift", name="obtained_type"),
  660. default="default", comment="获得方式")
  661. obtained_source = Column(String(64), nullable=True, comment="获得来源(任务类型、等级等)")
  662. # 扩展信息
  663. metadata_json = Column("metadata", JSON, nullable=True, comment="扩展信息")
  664. created_at = Column(TIMESTAMP, server_default=func.current_timestamp(), comment="创建时间")
  665. __table_args__ = (
  666. UniqueConstraint("user_id", "image_id", name="uk_user_background_image"),
  667. Index("idx_user_obtained", "user_id", "obtained_at"),
  668. )
  669. def to_dict(self) -> dict:
  670. """转换为字典"""
  671. return {
  672. "id": self.id,
  673. "user_id": self.user_id,
  674. "image_id": self.image_id,
  675. "obtained_at": self.obtained_at.isoformat() if self.obtained_at else None,
  676. "obtained_type": self.obtained_type,
  677. "obtained_source": self.obtained_source,
  678. "metadata": self.metadata_json,
  679. "created_at": self.created_at.isoformat() if self.created_at else None,
  680. }
  681. class VerificationCode(Base):
  682. """验证码表模型"""
  683. __tablename__ = "verification_codes"
  684. id = Column(PKBigInt, primary_key=True, autoincrement=True)
  685. code_id = Column(String(64), unique=True, nullable=False, index=True, comment="验证码ID")
  686. # 接收方信息(手机号或邮箱,根据发送类型二选一)
  687. area_code = Column(String(10), nullable=True, comment="手机区号(如 +86)")
  688. phone = Column(String(20), nullable=True, index=True, comment="手机号")
  689. email = Column(String(200), nullable=True, index=True, comment="邮箱")
  690. # 验证码信息
  691. code = Column(String(10), nullable=False, comment="验证码")
  692. send_type = Column(
  693. Enum("domestic_sms", "international_sms", "email", name="send_type"),
  694. nullable=False,
  695. comment="发送类型:国内短信、国外短信、邮箱"
  696. )
  697. # 状态信息
  698. is_sent = Column(Boolean, default=False, nullable=False, comment="是否已发送")
  699. is_valid = Column(Boolean, default=True, nullable=False, comment="是否有效")
  700. # 时间信息
  701. created_at = Column(TIMESTAMP, server_default=func.current_timestamp(), index=True, comment="创建时间")
  702. sent_at = Column(TIMESTAMP, nullable=True, comment="发送时间")
  703. # 扩展信息
  704. metadata_json = Column("metadata", JSON, nullable=True, comment="扩展信息(发送结果、错误信息等)")
  705. __table_args__ = (
  706. Index("idx_verification_code_phone", "phone", "is_valid", "created_at"),
  707. Index("idx_verification_code_email", "email", "is_valid", "created_at"),
  708. Index("idx_verification_code_send_type", "send_type", "is_sent", "is_valid"),
  709. )
  710. def to_dict(self) -> dict:
  711. """转换为字典"""
  712. return {
  713. "code_id": self.code_id,
  714. "area_code": self.area_code,
  715. "phone": self.phone,
  716. "email": self.email,
  717. "code": self.code,
  718. "send_type": self.send_type,
  719. "is_sent": self.is_sent,
  720. "is_valid": self.is_valid,
  721. "created_at": self.created_at.isoformat() if self.created_at else None,
  722. "sent_at": self.sent_at.isoformat() if self.sent_at else None,
  723. "metadata": self.metadata_json,
  724. }
  725. class UserCommunityChoice(Base):
  726. """用户是否退出早期共创社区(V2.0)"""
  727. __tablename__ = "user_community_choice"
  728. id = Column(PKBigInt, primary_key=True, autoincrement=True)
  729. user_id = Column(String(64), unique=True, nullable=False, index=True, comment="用户ID")
  730. opted_out = Column(Boolean, default=False, nullable=False, comment="是否选择退出早期共创社区")
  731. updated_at = Column(TIMESTAMP, server_default=func.current_timestamp(), onupdate=func.current_timestamp())
  732. def to_dict(self) -> dict:
  733. return {
  734. "user_id": self.user_id,
  735. "opted_out": self.opted_out,
  736. "updated_at": self.updated_at.isoformat() if self.updated_at else None,
  737. }
  738. class UserEarlyCommunity(Base):
  739. """用户早期共创社区(手机号新用户留邮箱,V2.0)"""
  740. __tablename__ = "user_early_community"
  741. id = Column(PKBigInt, primary_key=True, autoincrement=True)
  742. user_id = Column(String(64), unique=True, nullable=False, index=True, comment="用户ID")
  743. email = Column(String(200), nullable=True, comment="加入早期共创时留的邮箱")
  744. popup_shown = Column(Boolean, default=False, nullable=False, comment="是否已展示过弹窗")
  745. joined_at = Column(TIMESTAMP, nullable=True, comment="加入时间(留邮箱时)")
  746. created_at = Column(TIMESTAMP, server_default=func.current_timestamp())
  747. updated_at = Column(TIMESTAMP, server_default=func.current_timestamp(), onupdate=func.current_timestamp())
  748. def to_dict(self) -> dict:
  749. return {
  750. "user_id": self.user_id,
  751. "email": self.email,
  752. "popup_shown": self.popup_shown,
  753. "joined_at": self.joined_at.isoformat() if self.joined_at else None,
  754. "created_at": self.created_at.isoformat() if self.created_at else None,
  755. }
  756. for _model in (
  757. MissionType,
  758. MissionEnergyStone,
  759. ConversationEnergyStone,
  760. UserBonusEnergyStone,
  761. BackgroundImage,
  762. UserBackgroundImage,
  763. Avatar,
  764. AvatarAsset,
  765. UserAvatar,
  766. ):
  767. _attach_metadata_alias(_model)