Files
syops/backend/app/models.py
T
2026-04-20 09:08:58 +08:00

345 lines
15 KiB
Python

from datetime import datetime
from typing import Optional, List
from sqlalchemy import String, Text, Integer, ForeignKey, JSON, DateTime, Index
from sqlalchemy.orm import Mapped, mapped_column, relationship
from app import db
from werkzeug.security import generate_password_hash, check_password_hash
class Base(db.Model):
"""
基础模型类,设置为抽象基类
"""
__abstract__ = True
# RBAC 关联表:用户与 Agent 的多对多关系
# 用于存储用户拥有哪些 Agent 的访问权限
user_agent_permissions = db.Table(
'user_agent_permissions',
db.Column('user_id', ForeignKey('users.id'), primary_key=True),
db.Column('agent_id', ForeignKey('agents.id'), primary_key=True)
)
class ZlLanguage(Base):
"""
多语言配置表
用途:存储系统支持的语言列表
"""
__tablename__ = 'zl_languages'
id: Mapped[int] = mapped_column(primary_key=True)
code: Mapped[str] = mapped_column(String(10), unique=True) # en, zh-CN, zh-TW, th
name: Mapped[str] = mapped_column(String(50)) # English, 简体中文, ...
is_active: Mapped[bool] = mapped_column(default=True)
class Department(Base):
"""
部门表
用途:存储公司部门列表
"""
__tablename__ = 'departments'
id: Mapped[int] = mapped_column(primary_key=True)
name: Mapped[str] = mapped_column(String(100), unique=True)
code: Mapped[Optional[str]] = mapped_column(String(50), unique=True) # 部门编号
company: Mapped[Optional[str]] = mapped_column(String(100)) # 所属公司
description: Mapped[Optional[str]] = mapped_column(Text)
class UserHomepageConfig(Base):
"""
用户首页配置表
用途:存储用户自定义的首页布局与配置
"""
__tablename__ = 'user_homepage_configs'
user_id: Mapped[int] = mapped_column(ForeignKey('users.id'), primary_key=True)
layout: Mapped[dict] = mapped_column(JSON, default={}) # 存储模块布局配置
# 示例: { "modules": [{"id": "favorites", "x": 0, "y": 0}, {"id": "agents", "x": 0, "y": 1}] }
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
class UserFavoriteAgent(Base):
"""
用户收藏 Agent 表
用途:存储用户收藏的 Agent
"""
__tablename__ = 'user_favorite_agents'
user_id: Mapped[int] = mapped_column(ForeignKey('users.id'), primary_key=True)
agent_id: Mapped[int] = mapped_column(ForeignKey('agents.id'), primary_key=True)
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow)
class UserDefaultAgent(Base):
"""
用户默认 Agent 表 (嵌入首页)
用途:存储用户设置的默认嵌入 Agent (最多2个)
"""
__tablename__ = 'user_default_agents'
id: Mapped[int] = mapped_column(primary_key=True)
user_id: Mapped[int] = mapped_column(ForeignKey('users.id'))
agent_id: Mapped[int] = mapped_column(ForeignKey('agents.id'))
sort_order: Mapped[int] = mapped_column(default=0) # 排序,0为第一个,1为第二个
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow)
class User(Base):
"""
用户表
用途:存储系统用户信息
核心逻辑:包含部门、角色等字段,关联 Agent 权限
"""
__tablename__ = 'users'
# 主键 ID
id: Mapped[int] = mapped_column(primary_key=True)
# 用户名,唯一且带索引
username: Mapped[str] = mapped_column(String(50), unique=True, index=True)
# 邮箱,唯一
email: Mapped[str] = mapped_column(String(100), unique=True)
# 部门信息
department: Mapped[Optional[str]] = mapped_column(String(100))
# 角色:admin 或 user
role: Mapped[str] = mapped_column(String(20), default='user')
# 账号状态:active (正常), pending (待审批), disabled (禁用)
status: Mapped[str] = mapped_column(String(20), default='active')
# 密码哈希
password_hash: Mapped[Optional[str]] = mapped_column(String(255))
# 首选语言
language: Mapped[str] = mapped_column(String(10), default='zh-CN')
# 主题偏好: light / dark / system
theme_preference: Mapped[str] = mapped_column(String(10), default='system')
# 企业微信关联字段
wecom_userid: Mapped[Optional[str]] = mapped_column(String(128), unique=True, nullable=True)
wecom_unionid: Mapped[Optional[str]] = mapped_column(String(128), unique=True, nullable=True)
# 真实姓名
real_name: Mapped[Optional[str]] = mapped_column(String(50))
# 公司工号,唯一
employee_id: Mapped[Optional[str]] = mapped_column(String(50), unique=True)
# 手机号,唯一
phone_number: Mapped[Optional[str]] = mapped_column(String(20), unique=True)
# 默认嵌入的 Agent ID (忽略权限检查)
default_agent_id: Mapped[Optional[int]] = mapped_column(ForeignKey('agents.id'))
# 关系:用户拥有的 Agent 权限 (多对多)
agents: Mapped[List["Agent"]] = relationship(
secondary=user_agent_permissions,
back_populates="users"
)
# 密码重置 Token
reset_token: Mapped[Optional[str]] = mapped_column(String(100), nullable=True)
reset_token_expiry: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
def set_password(self, password):
self.password_hash = generate_password_hash(password)
def check_password(self, password):
if not self.password_hash:
return False
return check_password_hash(self.password_hash, password)
class Agent(Base):
"""
AI 应用配置表
用途:存储接入的 Dify Agent 配置信息
核心逻辑:存储 Dify App ID 和 API Key,控制应用开关
"""
__tablename__ = 'agents'
id: Mapped[int] = mapped_column(primary_key=True)
# 应用名称
name: Mapped[str] = mapped_column(String(100))
# 应用描述
description: Mapped[Optional[str]] = mapped_column(Text)
# 图标 URL
icon_url: Mapped[Optional[str]] = mapped_column(String(255))
# Dify 配置:App ID (唯一,对于 iframe 模式可选)
dify_app_id: Mapped[Optional[str]] = mapped_column(String(100), unique=True, nullable=True)
# Dify 配置:API Key (实际生产应加密存储,对于 iframe 模式可选)
dify_api_key: Mapped[Optional[str]] = mapped_column(String(100), nullable=True)
# 类型:api (默认) 或 iframe
type: Mapped[str] = mapped_column(String(20), default='api')
# 自定义 API Base URL (覆盖全局配置)
api_base_url: Mapped[Optional[str]] = mapped_column(String(255))
# 额外配置 (JSON),用于存储 iframe_url 等
extra_config: Mapped[Optional[dict]] = mapped_column(JSON)
# 是否激活
is_active: Mapped[bool] = mapped_column(default=True)
# 创建时间
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow)
# 关系:拥有该应用权限的用户 (多对多)
users: Mapped[List["User"]] = relationship(
secondary=user_agent_permissions,
back_populates="agents"
)
class ChatLog(Base):
"""
对话日志表
用途:存储用户与 Agent 的对话记录
"""
__tablename__ = 'chat_logs'
id: Mapped[int] = mapped_column(primary_key=True)
user_id: Mapped[int] = mapped_column(ForeignKey('users.id'))
agent_id: Mapped[int] = mapped_column(ForeignKey('agents.id'))
query: Mapped[str] = mapped_column(Text)
answer: Mapped[str] = mapped_column(Text)
latency: Mapped[int] = mapped_column(default=0)
conversation_id: Mapped[Optional[str]] = mapped_column(String(100))
tokens_used: Mapped[int] = mapped_column(default=0)
# Persist citation/source metadata so history messages can still show sources.
retriever_resources: Mapped[Optional[list]] = mapped_column(JSON)
attribution_parts: Mapped[Optional[list]] = mapped_column(JSON)
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow)
# 关联 Feedback
feedback: Mapped[Optional["Feedback"]] = relationship(back_populates="chat_log", uselist=False)
class Feedback(Base):
"""
反馈表
用途:存储用户对回答的评分与评价
"""
__tablename__ = 'feedbacks'
id: Mapped[int] = mapped_column(primary_key=True)
chat_log_id: Mapped[int] = mapped_column(ForeignKey('chat_logs.id'), unique=True)
score: Mapped[int] = mapped_column(Integer) # 1-5
comment: Mapped[Optional[str]] = mapped_column(Text)
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow)
chat_log: Mapped["ChatLog"] = relationship(back_populates="feedback")
class PermissionRequest(Base):
"""
权限申请表
用途:存储用户的权限申请记录
"""
__tablename__ = 'permission_requests'
id: Mapped[int] = mapped_column(primary_key=True)
user_id: Mapped[int] = mapped_column(ForeignKey('users.id'))
agent_id: Mapped[int] = mapped_column(ForeignKey('agents.id'))
reason: Mapped[str] = mapped_column(Text)
status: Mapped[str] = mapped_column(String(20), default='pending') # pending, approved, rejected
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow)
reviewed_at: Mapped[Optional[datetime]] = mapped_column(DateTime)
class QuickQuestion(Base):
"""
常用问题表
用途:存储用户自定义的常用问题
"""
__tablename__ = 'quick_questions'
id: Mapped[int] = mapped_column(primary_key=True)
user_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
agent_id: Mapped[int] = mapped_column(ForeignKey('agents.id'))
title: Mapped[str] = mapped_column(String(100))
question: Mapped[str] = mapped_column(Text)
sort_order: Mapped[int] = mapped_column(default=0)
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow)
class Announcement(Base):
"""
公告表
用途:存储系统公告
"""
__tablename__ = 'announcements'
id: Mapped[int] = mapped_column(primary_key=True)
title: Mapped[str] = mapped_column(String(200))
content: Mapped[str] = mapped_column(Text)
is_active: Mapped[bool] = mapped_column(default=True)
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow)
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
class LoginAudit(Base):
"""
登录审计表
用途:记录密码登录与企业微信登录结果,便于排障与审计
"""
__tablename__ = 'login_audits'
id: Mapped[int] = mapped_column(primary_key=True)
user_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
username: Mapped[Optional[str]] = mapped_column(String(50), nullable=True)
source: Mapped[str] = mapped_column(String(20), default='password') # password / wecom
status: Mapped[str] = mapped_column(String(20), default='success') # success / failed
reason: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
error_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
match_rules: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
match_operator: Mapped[Optional[str]] = mapped_column(String(8), nullable=True)
match_result: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
wecom_userid: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
ip: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
user_agent: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
class WecomNotifyAudit(Base):
"""
企业微信触达审计表
用途:记录企微消息发送结果与回流点击数据
"""
__tablename__ = 'wecom_notify_audits'
id: Mapped[int] = mapped_column(primary_key=True)
event_type: Mapped[str] = mapped_column(String(64), index=True)
status: Mapped[str] = mapped_column(String(20), default='sent', index=True) # sent / failed
trace_id: Mapped[str] = mapped_column(String(64), unique=True, index=True)
user_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True, index=True)
username: Mapped[Optional[str]] = mapped_column(String(50), nullable=True)
wecom_userid: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
title: Mapped[Optional[str]] = mapped_column(String(120), nullable=True)
content: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
jump_url: Mapped[Optional[str]] = mapped_column(String(512), nullable=True)
error_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
error_message: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
opened_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True, index=True)
class AppSetting(Base):
"""
应用运行时配置表(Key/Value)
用途:将企业微信等管理员可编辑的配置长效保存到数据库,
避免容器/部署重建后写入 backend/.env 的修改丢失。
"""
__tablename__ = 'app_settings'
key: Mapped[str] = mapped_column(String(128), primary_key=True)
value: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
updated_at: Mapped[datetime] = mapped_column(
DateTime, default=datetime.utcnow, onupdate=datetime.utcnow
)
class WecomCallbackAudit(Base):
"""
企业微信回调审计表
用途:记录消息与事件回调(安全模式解密后的内容摘要)
"""
__tablename__ = 'wecom_callback_audits'
id: Mapped[int] = mapped_column(primary_key=True)
msg_signature: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
timestamp: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
nonce: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
encrypt_raw: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
decrypted_xml: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
msg_type: Mapped[Optional[str]] = mapped_column(String(32), nullable=True, index=True)
event: Mapped[Optional[str]] = mapped_column(String(64), nullable=True, index=True)
from_user: Mapped[Optional[str]] = mapped_column(String(128), nullable=True, index=True)
agent_id: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
msg_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True, index=True)
error_message: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)