models_db.py 13 KB

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