models_db.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  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. )
  19. from sqlalchemy.orm import declarative_base
  20. from sqlalchemy.sql import func
  21. PKBigInt = BigInteger().with_variant(Integer, "sqlite")
  22. Base = declarative_base()
  23. class User(Base):
  24. """用户表模型"""
  25. __tablename__ = "users"
  26. id = Column(PKBigInt, primary_key=True, autoincrement=True)
  27. user_id = Column(String(64), unique=True, nullable=False, index=True, comment="用户唯一标识(UUID)")
  28. # 基本信息
  29. username = Column(String(100), nullable=False, comment="用户名/昵称")
  30. user_type = Column(Enum("guest", "registered", name="user_type"), default="guest", comment="用户类型")
  31. bot_name = Column(String(100), nullable=True, comment="用户给机器人取的名字")
  32. # 注册信息(可选)
  33. phone = Column(String(20), unique=True, nullable=True, index=True, comment="手机号")
  34. email = Column(String(200), unique=True, nullable=True, index=True, comment="邮箱")
  35. wechat_openid = Column(String(100), unique=True, nullable=True, index=True, comment="微信OpenID")
  36. qq_openid = Column(String(100), unique=True, nullable=True, index=True, comment="QQ OpenID")
  37. qq_unionid = Column(String(128), unique=True, nullable=True, index=True, comment="QQ UnionID")
  38. google_email = Column(String(200), unique=True, nullable=True, index=True, comment="Google邮箱")
  39. # 认证信息
  40. is_verified = Column(Boolean, default=False, comment="是否已认证")
  41. registered_at = Column(TIMESTAMP, nullable=True, comment="注册时间")
  42. # 统计信息
  43. total_messages = Column(Integer, default=0, comment="总消息数")
  44. total_rounds = Column(Integer, default=0, comment="总对话轮次")
  45. total_speech_duration_ms = Column(BigInteger, default=0, comment="累积说话时长(毫秒)")
  46. user_level = Column(Integer, default=0, nullable=False, comment="用户等级(0-5)")
  47. last_active_at = Column(TIMESTAMP, nullable=True, comment="最后活跃时间")
  48. created_at = Column(TIMESTAMP, server_default=func.current_timestamp(), comment="创建时间")
  49. updated_at = Column(TIMESTAMP, server_default=func.current_timestamp(), onupdate=func.current_timestamp(), comment="更新时间")
  50. def to_dict(self) -> dict:
  51. """转换为字典"""
  52. return {
  53. "user_id": self.user_id,
  54. "username": self.username,
  55. "user_type": self.user_type,
  56. "bot_name": self.bot_name,
  57. "phone": self.phone,
  58. "email": self.email,
  59. "wechat_openid": self.wechat_openid,
  60. "qq_openid": self.qq_openid,
  61. "qq_unionid": self.qq_unionid,
  62. "google_email": self.google_email,
  63. "is_verified": self.is_verified,
  64. "registered_at": self.registered_at.isoformat() if self.registered_at else None,
  65. "total_messages": self.total_messages,
  66. "total_rounds": self.total_rounds,
  67. "total_speech_duration_ms": self.total_speech_duration_ms,
  68. "user_level": self.user_level,
  69. "last_active_at": self.last_active_at.isoformat() if self.last_active_at else None,
  70. "created_at": self.created_at.isoformat() if self.created_at else None,
  71. }
  72. class Message(Base):
  73. """消息表模型"""
  74. __tablename__ = "messages"
  75. id = Column(PKBigInt, primary_key=True, autoincrement=True)
  76. message_id = Column(String(64), unique=True, nullable=False, comment="消息ID")
  77. user_id = Column(String(64), nullable=False, index=True, comment="用户ID")
  78. # 消息内容
  79. role = Column(Enum("user", "assistant", "system", name="role"), nullable=False, comment="角色")
  80. content = Column(Text, nullable=False, comment="消息内容")
  81. # 轮次信息
  82. round_number = Column(Integer, nullable=False, comment="对话轮次(从1开始)")
  83. # 扩展信息
  84. emotion = Column(String(50), nullable=True, comment="情感标签")
  85. message_metadata = Column(JSON, nullable=True, comment="扩展信息(音频路径、识别耗时等)")
  86. token_count = Column(Integer, nullable=True, comment="Token数量")
  87. created_at = Column(TIMESTAMP, server_default=func.current_timestamp(), index=True, comment="创建时间")
  88. # 复合索引
  89. __table_args__ = (
  90. Index("idx_user_round", "user_id", "round_number"),
  91. )
  92. def to_dict(self) -> dict:
  93. """转换为字典"""
  94. return {
  95. "message_id": self.message_id,
  96. "user_id": self.user_id,
  97. "role": self.role,
  98. "content": self.content,
  99. "round_number": self.round_number,
  100. "emotion": self.emotion,
  101. "metadata": self.message_metadata, # 对外保持 metadata 字段名
  102. "token_count": self.token_count,
  103. "created_at": self.created_at.isoformat() if self.created_at else None,
  104. }
  105. class ConversationSummary(Base):
  106. """对话总结表模型"""
  107. __tablename__ = "conversation_summaries"
  108. id = Column(PKBigInt, primary_key=True, autoincrement=True)
  109. summary_id = Column(String(64), unique=True, nullable=False, comment="总结ID")
  110. user_id = Column(String(64), nullable=False, index=True, comment="用户ID")
  111. # 总结范围
  112. start_round = Column(Integer, nullable=False, comment="起始轮次")
  113. end_round = Column(Integer, nullable=False, comment="结束轮次")
  114. # 总结内容
  115. summary_text = Column(Text, nullable=False, comment="总结内容")
  116. summary_type = Column(Enum("auto", "manual", name="summary_type"), default="auto", comment="总结类型")
  117. # 统计信息
  118. message_count = Column(Integer, nullable=True, comment="总结的消息数量")
  119. token_count = Column(Integer, nullable=True, comment="总结文本Token数")
  120. created_at = Column(TIMESTAMP, server_default=func.current_timestamp(), comment="创建时间")
  121. # 复合索引和唯一约束
  122. __table_args__ = (
  123. Index("idx_user_end_round", "user_id", "end_round"),
  124. UniqueConstraint("user_id", "start_round", "end_round", name="uk_user_round_range"),
  125. )
  126. def to_dict(self) -> dict:
  127. """转换为字典"""
  128. return {
  129. "summary_id": self.summary_id,
  130. "user_id": self.user_id,
  131. "start_round": self.start_round,
  132. "end_round": self.end_round,
  133. "summary_text": self.summary_text,
  134. "summary_type": self.summary_type,
  135. "message_count": self.message_count,
  136. "token_count": self.token_count,
  137. "created_at": self.created_at.isoformat() if self.created_at else None,
  138. }
  139. class MissionType(Base):
  140. """任务类型配置"""
  141. __tablename__ = "mission_types"
  142. id = Column(PKBigInt, primary_key=True, autoincrement=True)
  143. type_key = Column(String(64), unique=True, nullable=False, index=True, comment="任务类型唯一标识")
  144. display_name = Column(String(100), nullable=False, comment="任务显示名称")
  145. description = Column(String(255), nullable=True, comment="类型描述")
  146. is_repeatable = Column(Boolean, default=False, comment="是否允许重复触发")
  147. is_active = Column(Boolean, default=True, comment="是否启用")
  148. metadata_json = Column("metadata", JSON, nullable=True, comment="扩展配置")
  149. created_at = Column(TIMESTAMP, server_default=func.current_timestamp(), comment="创建时间")
  150. updated_at = Column(
  151. TIMESTAMP,
  152. server_default=func.current_timestamp(),
  153. onupdate=func.current_timestamp(),
  154. comment="更新时间"
  155. )
  156. __table_args__ = (
  157. Index("idx_mission_type_active", "is_active"),
  158. )
  159. class MissionEnergyStone(Base):
  160. """任务能量石(首次对话奖励)"""
  161. __tablename__ = "mission_energy_stones"
  162. id = Column(PKBigInt, primary_key=True, autoincrement=True)
  163. stone_id = Column(String(64), unique=True, nullable=False, index=True, comment="能量石ID")
  164. user_id = Column(String(64), nullable=False, index=True, comment="用户ID")
  165. request_id = Column(String(64), nullable=True, comment="触发的请求ID")
  166. appear_reason = Column(String(64), nullable=False, default="first_dialog", comment="触发原因")
  167. mission_type = Column(String(64), nullable=False, default="first_dialog", comment="任务类型")
  168. appear_at = Column(TIMESTAMP, server_default=func.current_timestamp(), comment="出现时间")
  169. clicked_at = Column(TIMESTAMP, nullable=True, comment="点击时间")
  170. auto_removed = Column(Boolean, default=False, comment="是否由系统自动消失")
  171. metadata_json = Column("metadata", JSON, nullable=True, comment="扩展信息")
  172. created_at = Column(TIMESTAMP, server_default=func.current_timestamp(), comment="创建时间")
  173. updated_at = Column(
  174. TIMESTAMP,
  175. server_default=func.current_timestamp(),
  176. onupdate=func.current_timestamp(),
  177. comment="更新时间"
  178. )
  179. __table_args__ = (
  180. Index("idx_mission_stone_user", "user_id", "appear_at"),
  181. Index("idx_mission_type_user", "mission_type", "user_id"),
  182. )
  183. class ConversationEnergyStone(Base):
  184. """对话能量石(按时长发放)"""
  185. __tablename__ = "conversation_energy_stones"
  186. id = Column(PKBigInt, primary_key=True, autoincrement=True)
  187. stone_id = Column(String(64), unique=True, nullable=False, index=True, comment="能量石ID")
  188. user_id = Column(String(64), nullable=False, index=True, comment="用户ID")
  189. request_id = Column(String(64), nullable=True, comment="触发的请求ID")
  190. threshold_index = Column(Integer, nullable=False, comment="达到的阈值序号(30秒一档)")
  191. total_duration_ms = Column(BigInteger, nullable=False, comment="达到阈值后的累计说话时长")
  192. duration_increment_ms = Column(Integer, nullable=False, comment="本次增加的说话时长")
  193. appear_at = Column(TIMESTAMP, server_default=func.current_timestamp(), comment="出现时间")
  194. clicked_at = Column(TIMESTAMP, nullable=True, comment="点击时间")
  195. auto_removed = Column(Boolean, default=False, comment="是否由系统自动消失")
  196. metadata_json = Column("metadata", JSON, nullable=True, comment="扩展信息")
  197. created_at = Column(TIMESTAMP, server_default=func.current_timestamp(), comment="创建时间")
  198. updated_at = Column(
  199. TIMESTAMP,
  200. server_default=func.current_timestamp(),
  201. onupdate=func.current_timestamp(),
  202. comment="更新时间"
  203. )
  204. __table_args__ = (
  205. UniqueConstraint("user_id", "threshold_index", name="uk_conversation_stone_threshold"),
  206. Index("idx_conversation_stone_user_threshold", "user_id", "threshold_index"),
  207. )
  208. class UserUIState(Base):
  209. """用户前端可视化状态表(页面与提示状态)"""
  210. __tablename__ = "user_ui_states"
  211. id = Column(PKBigInt, primary_key=True, autoincrement=True)
  212. user_id = Column(String(64), unique=True, nullable=False, index=True, comment="用户ID(关联 users.user_id)")
  213. # 页面与路由状态
  214. current_page = Column(String(64), nullable=True, comment="当前业务流程页面标识")
  215. visited_routes = Column(JSON, nullable=True, comment="已访问路由列表")
  216. # 新手引导与提示状态
  217. has_shown_tap_to_chat = Column(Boolean, default=False, nullable=False, comment="是否已展示过 TapToChat 提示")
  218. has_shown_cancel_tooltip = Column(Boolean, default=False, nullable=False, comment="是否已展示过取消按钮提示")
  219. has_shown_send_tooltip = Column(Boolean, default=False, nullable=False, comment="是否已展示过发送按钮提示")
  220. has_shown_progress_bar_tooltip = Column(Boolean, default=False, nullable=False, comment="是否已展示过进度条提示")
  221. has_shown_mission_stone_modal = Column(Boolean, default=False, nullable=False, comment="是否已展示过任务能量石弹窗")
  222. has_shown_conversation_stone_modal = Column(Boolean, default=False, nullable=False, comment="是否已展示过对话能量石弹窗")
  223. # Avatar-C 解锁状态
  224. avatar_c_unlocked = Column(Boolean, default=False, nullable=False, comment="是否已解锁 Avatar-C")
  225. created_at = Column(TIMESTAMP, server_default=func.current_timestamp(), comment="创建时间")
  226. updated_at = Column(
  227. TIMESTAMP,
  228. server_default=func.current_timestamp(),
  229. onupdate=func.current_timestamp(),
  230. comment="更新时间",
  231. )
  232. def to_dict(self) -> dict:
  233. return {
  234. "user_id": self.user_id,
  235. "current_page": self.current_page,
  236. "visited_routes": self.visited_routes or [],
  237. "has_shown_tap_to_chat": self.has_shown_tap_to_chat,
  238. "has_shown_cancel_tooltip": self.has_shown_cancel_tooltip,
  239. "has_shown_send_tooltip": self.has_shown_send_tooltip,
  240. "has_shown_progress_bar_tooltip": self.has_shown_progress_bar_tooltip,
  241. "has_shown_mission_stone_modal": self.has_shown_mission_stone_modal,
  242. "has_shown_conversation_stone_modal": self.has_shown_conversation_stone_modal,
  243. "avatar_c_unlocked": self.avatar_c_unlocked,
  244. "created_at": self.created_at.isoformat() if self.created_at else None,
  245. "updated_at": self.updated_at.isoformat() if self.updated_at else None,
  246. }
  247. def _attach_metadata_alias(model_cls):
  248. """Allow using `metadata` keyword/attribute while storing in metadata_json."""
  249. original_init = model_cls.__init__
  250. def __init__(self, *args, **kwargs):
  251. metadata_value = kwargs.pop("metadata", None)
  252. original_init(self, *args, **kwargs)
  253. if metadata_value is not None:
  254. setattr(self, "metadata_json", metadata_value)
  255. model_cls.__init__ = __init__
  256. def getter(self):
  257. return getattr(self, "metadata_json")
  258. def setter(self, value):
  259. setattr(self, "metadata_json", value)
  260. model_cls.metadata = property(getter, setter)
  261. for _model in (MissionType, MissionEnergyStone, ConversationEnergyStone):
  262. _attach_metadata_alias(_model)