""" backend/app/models/user.py 用途:用户账户、首页偏好、登录审计相关模型。 依赖:models.base(Base、user_agent_permissions)。 逻辑:User 与 Agent 多对多经 user_agent_permissions;admin/user API 主要读写本模块。 """ from __future__ import annotations from datetime import datetime from typing import List, Optional from sqlalchemy import DateTime, ForeignKey, JSON, String from sqlalchemy.orm import Mapped, mapped_column, relationship from werkzeug.security import check_password_hash, generate_password_hash from app.models.base import Base, user_agent_permissions 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={}) updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow) class UserFavoriteAgent(Base): """用户收藏的 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(最多 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) created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow) class User(Base): """系统用户:认证、RBAC、企微绑定、个人资料。""" __tablename__ = 'users' 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)) role: Mapped[str] = mapped_column(String(20), default='user') status: Mapped[str] = mapped_column(String(20), default='active') feature_permissions: Mapped[dict] = mapped_column(JSON, default=dict, nullable=False) password_hash: Mapped[Optional[str]] = mapped_column(String(255)) language: Mapped[str] = mapped_column(String(10), default='zh-CN') 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) default_agent_id: Mapped[Optional[int]] = mapped_column(ForeignKey('agents.id')) agents: Mapped[List['Agent']] = relationship( secondary=user_agent_permissions, back_populates='users', ) reset_token: Mapped[Optional[str]] = mapped_column(String(100), nullable=True) reset_token_expiry: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) training_records: Mapped[List['TrainingRecord']] = relationship( 'TrainingRecord', back_populates='user', ) def _role_default_feature_permissions(self) -> dict[str, bool]: """返回当前角色自带的功能权限默认值。""" return { 'training_hr_manage': self.role in {'admin', 'hr'}, # 发货通知强制新建重复单据:admin 默认开;其他角色默认关,可显式授予 'shipping_notice_force_create': self.role == 'admin', # 货代审计敏感快照/前后 Diff 读取:admin 默认开;不新建角色,可显式关闭或授予 'shipping_notice.audit_sensitive_read': self.role == 'admin', # XFA 字段拆分:编辑 / 预览 / 发布审核;admin 默认开,可显式收紧 'shipping_notice.xfa_split_rule_edit': self.role == 'admin', 'shipping_notice.xfa_split_rule_preview': self.role == 'admin', 'shipping_notice.xfa_split_rule_publish': self.role == 'admin', } def get_feature_permissions(self) -> dict[str, bool]: """ 返回当前用户的有效功能权限。 用途:统一为前端展示、登录态注入与后端业务校验提供同一份权限结果。 核心逻辑:先按角色生成默认权限,再用用户显式配置覆盖,避免把培训类业务权限硬编码在多个模块。 输出约束:仅返回布尔型权限键,缺失项自动回退到角色默认值。 """ defaults = self._role_default_feature_permissions() raw = self.feature_permissions if isinstance(self.feature_permissions, dict) else {} result: dict[str, bool] = {} for key, default_value in defaults.items(): if key in raw: result[key] = bool(raw.get(key)) else: result[key] = bool(default_value) return result def set_feature_permissions(self, permissions: dict | None) -> None: """ 保存用户显式配置的功能权限覆盖项。 用途:给管理后台用户编辑表单落库权限配置。 核心逻辑:只持久化与角色默认值不同的权限,既保留“admin/hr 角色默认可见”的现有语义,也支持前端手动关闭或给普通用户单独授予。 参数约束:permissions 必须为 dict 或 None;未知键会被忽略。 """ defaults = self._role_default_feature_permissions() raw = permissions if isinstance(permissions, dict) else {} overrides: dict[str, bool] = {} for key, default_value in defaults.items(): if key not in raw: continue normalized = bool(raw.get(key)) if normalized != bool(default_value): overrides[key] = normalized self.feature_permissions = overrides def has_feature_permission(self, permission_key: str) -> bool: """判断当前用户是否具备指定功能权限。""" return bool(self.get_feature_permissions().get(permission_key)) def can_manage_training(self) -> bool: """判断当前用户是否可使用培训 HR 管理面板与接口。""" return self.has_feature_permission('training_hr_manage') def set_password(self, password: str) -> None: """设置密码哈希。""" self.password_hash = generate_password_hash(password) def check_password(self, password: str) -> bool: """校验明文密码是否匹配。""" if not self.password_hash: return False return check_password_hash(self.password_hash, password) 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') status: Mapped[str] = mapped_column(String(20), default='success') 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)