fourcal-pms/backend/app/models/org.py

393 lines
20 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

"""组织架构与系统账号。
口径与 unisoa 的「账户、组织同步与统一身份验证」保持一致,这样同一套 Hub 导出接口
两个系统都能吃:
* ``OrgUnit.hub_org_id`` / ``Account.hub_user_id`` 是"这条记录是不是统一身份的、
是其中哪一个"的唯一依据,本地自建的一律为 NULL;
* ``Account.source`` 区分本地账号与同步账号,**同步永远不碰本地账号**,避免夜间同步
把管理员改掉;
* 部门负责人存人员主键而不是名字或 DN:组织同步会改名、挪部门,而"谁是这个部门的
负责人"要跟着人走,解析审批人时再换成对方当前身份。
"""
from __future__ import annotations
from datetime import datetime
from sqlalchemy import ForeignKey, Index, Integer, String, Text, UniqueConstraint, text
from sqlalchemy.orm import Mapped, mapped_column, relationship
from .base import Base, SoftDeleteMixin, TimestampMixin, timestamp_col, u_bigint, u_tinyint
class Status:
"""组织与账号共用的状态口径,和 Hub 导出的 status 同一套数字。
``1`` 是启用,其余值(停用/待审核/已拒绝)本地一律按不可用处理,读代码时不用换算。
"""
DISABLED = 0
ACTIVE = 1
PENDING = 2
REJECTED = 3
LABELS = {DISABLED: "已停用", ACTIVE: "正常", PENDING: "待审核", REJECTED: "已拒绝"}
@classmethod
def label(cls, value: object) -> str:
return cls.LABELS.get(int(value or 0), "未知")
@classmethod
def is_active(cls, value: object) -> bool:
return int(value or 0) == cls.ACTIVE
@classmethod
def normalize(cls, value: object) -> int:
"""外部(Hub)状态折成本地取值:只认 1=启用,其余一律停用。"""
return cls.ACTIVE if int(value or 0) == cls.ACTIVE else cls.DISABLED
class AccountSource:
"""``accounts.source``:账号是谁建的,决定同步能不能动它。"""
LOCAL = "local"
HUB = "hub"
LABELS = {LOCAL: "本地", HUB: "统一身份"}
@classmethod
def label(cls, value: str) -> str:
return cls.LABELS.get(value or cls.LOCAL, value or cls.LOCAL)
class OrgUnit(Base, TimestampMixin, SoftDeleteMixin):
"""组织/部门树。
``path`` 存的是 ``/1/5/23/`` 这样的祖先链,数据权限里"本部门及下级"就靠它做前缀
匹配,比递归查询快得多;``level`` 与 ``order_number`` 供左树右表的排序与缩进用。
"""
__tablename__ = "org_unit"
__table_args__ = (
# 一个 Hub 组织只能落地成本地一个部门:撞两个就等于组织树裂开,必须唯一。
# NULL 不参与唯一性,所以本地自建部门不受影响。
Index("uq_org_unit_hub_org_id", "hub_org_id", unique=True),
Index("idx_org_unit_parent", "parent_id"),
# path 是 VARCHAR(1024),utf8mb4 下全列索引会超过 3072 字节上限,取前 255 字符
Index("idx_org_unit_path", "path", mysql_length=255),
{"mysql_charset": "utf8mb4", "mysql_collate": "utf8mb4_unicode_ci"},
)
id: Mapped[int] = mapped_column(u_bigint(), primary_key=True, autoincrement=True)
name: Mapped[str] = mapped_column(String(255), nullable=False, comment="部门名称")
code: Mapped[str] = mapped_column(
String(190), default="", server_default="", nullable=False, index=True,
comment="组织编码(Hub 的 code),本地自建可留空",
)
short_name: Mapped[str] = mapped_column(String(255), default="", nullable=False)
parent_id: Mapped[int | None] = mapped_column(
u_bigint(), ForeignKey("org_unit.id", ondelete="SET NULL"), nullable=True
)
# 祖先链,形如 /1/5/;根节点为 /。同步与数据权限都读它。
path: Mapped[str] = mapped_column(String(1024), default="/", nullable=False)
level: Mapped[int] = mapped_column(Integer, default=1, server_default="1", nullable=False)
order_number: Mapped[int] = mapped_column(Integer, default=0, server_default="0", nullable=False)
status: Mapped[int] = mapped_column(
u_tinyint(), default=Status.ACTIVE, server_default="1", nullable=False,
comment="1=正常 0=停用 2=待审核 3=已拒绝",
)
hub_org_id: Mapped[int | None] = mapped_column(
u_bigint(), nullable=True, comment="Hub 组织主键;非空时 Hub 侧接管名称/编码/状态/上级"
)
# 部门负责人:存人员主键而不是 DN,理由见模块 docstring。不加外键,避免
# accounts.org_unit_id 与它形成双向外键环,让建表脚本绕圈子。
manager_id: Mapped[int | None] = mapped_column(
u_bigint(), nullable=True, index=True, comment="部门负责人的 accounts.id"
)
# 同步接管范围:Hub 侧只接管这几个键,其余(负责人、排序、说明)永远归本地。
synced_at: Mapped[datetime | None] = mapped_column(timestamp_col(), nullable=True)
remark: Mapped[str] = mapped_column(String(500), default="", nullable=False)
parent: Mapped["OrgUnit | None"] = relationship(
"OrgUnit", remote_side=[id], back_populates="children", foreign_keys=[parent_id]
)
children: Mapped[list["OrgUnit"]] = relationship(
"OrgUnit", back_populates="parent", foreign_keys=[parent_id]
)
@property
def is_active(self) -> bool:
return Status.is_active(self.status)
@property
def is_hub(self) -> bool:
return self.hub_org_id is not None
class Position(Base, TimestampMixin, SoftDeleteMixin):
"""职位/岗位。
老系统用 ``sys_role.level``(1 执行董事、2 财务总监…)同时兼职级和审批人来源,
一个字段两套语义;这里把岗位拆出来,审批人解析可以用「按岗位找人」。
"""
__tablename__ = "org_position"
__table_args__ = (
UniqueConstraint("code", name="uk_org_position_code"),
{"mysql_charset": "utf8mb4", "mysql_collate": "utf8mb4_unicode_ci"},
)
id: Mapped[int] = mapped_column(u_bigint(), primary_key=True, autoincrement=True)
code: Mapped[str] = mapped_column(String(64), nullable=False, comment="岗位编码,流程按它解析审批人")
name: Mapped[str] = mapped_column(String(128), nullable=False, comment="岗位名称")
rank: Mapped[int] = mapped_column(Integer, default=100, server_default="100", nullable=False,
comment="岗位级别,数字越小级别越高,用于『升级到上级审批』")
order_number: Mapped[int] = mapped_column(Integer, default=0, server_default="0", nullable=False)
enabled: Mapped[bool] = mapped_column(u_tinyint(), default=True, server_default="1", nullable=False)
remark: Mapped[str] = mapped_column(String(500), default="", nullable=False)
class Account(Base, SoftDeleteMixin):
"""系统账号(登录人)。
一个自然人只有一条 ``accounts``;他挂在哪个部门、以什么身份审批,走
``AccountIdentity``,因为现实中存在"一个人同时在两个部门审批"的情况。
"""
__tablename__ = "accounts"
__table_args__ = (
UniqueConstraint("account", name="uk_accounts_account"),
Index("idx_accounts_email", "email"),
Index("idx_accounts_status", "status"),
Index("idx_accounts_org", "org_unit_id"),
# Hub 的 user_id 是同步账号的唯一身份:账号能被别人注册走、姓名会改,
# 只有它从头到尾指向同一个人。
Index("uq_accounts_hub_user_id", "hub_user_id", unique=True),
{"mysql_charset": "utf8mb4", "mysql_collate": "utf8mb4_unicode_ci"},
)
id: Mapped[int] = mapped_column(u_bigint(), primary_key=True, autoincrement=True)
account: Mapped[str] = mapped_column(String(190), nullable=False, comment="登录账号")
password_hash: Mapped[str] = mapped_column(String(255), nullable=False, default="")
display_name: Mapped[str] = mapped_column(String(100), default="", server_default="", nullable=False,
comment="姓名")
emp_code: Mapped[str] = mapped_column(String(64), default="", server_default="", nullable=False,
index=True, comment="工号")
telephone: Mapped[str] = mapped_column(String(30), default="", server_default="", nullable=False)
email: Mapped[str] = mapped_column(String(190), default="", server_default="", nullable=False)
avatar_url: Mapped[str] = mapped_column(String(500), default="", server_default="", nullable=False)
org_unit_id: Mapped[int | None] = mapped_column(
u_bigint(), ForeignKey("org_unit.id", ondelete="SET NULL"), nullable=True
)
position_id: Mapped[int | None] = mapped_column(
u_bigint(), ForeignKey("org_position.id", ondelete="SET NULL"), nullable=True, index=True
)
# 直属上级:「发起人上级审批」最常用的口径;没设置时解析退回所在部门负责人。
leader_id: Mapped[int | None] = mapped_column(
u_bigint(), ForeignKey("accounts.id", ondelete="SET NULL"), nullable=True, index=True
)
# 是否系统管理员:只决定"能不能进系统管理",业务权限一律走角色,不用它开后门。
is_system_admin: Mapped[bool] = mapped_column(
u_tinyint(), default=False, server_default="0", nullable=False
)
status: Mapped[int] = mapped_column(
u_tinyint(), default=Status.ACTIVE, server_default="1", nullable=False,
comment="1=正常 0=停用 2=待审核 3=已拒绝",
)
# --- 统一身份(Hub)镜像字段:来源、Hub 主键、最后一次同步时间 -------------
source: Mapped[str] = mapped_column(
String(16), default=AccountSource.LOCAL, server_default=AccountSource.LOCAL, nullable=False,
comment="local=本地建号 hub=统一身份同步",
)
hub_user_id: Mapped[int | None] = mapped_column(u_bigint(), nullable=True)
hub_synced_at: Mapped[datetime | None] = mapped_column(timestamp_col(), nullable=True)
# 登录安全:连续失败锁号,替代老系统的 login_error_count/locked/locked_date 三兄弟
login_failed_count: Mapped[int] = mapped_column(Integer, default=0, server_default="0", nullable=False)
locked_until: Mapped[datetime | None] = mapped_column(timestamp_col(), nullable=True)
last_login_at: Mapped[datetime | None] = mapped_column(timestamp_col(), nullable=True)
last_login_ip: Mapped[str] = mapped_column(String(64), default="", nullable=False)
password_updated_at: Mapped[datetime | None] = mapped_column(timestamp_col(), nullable=True)
work_location: Mapped[str] = mapped_column(String(255), default="", nullable=False)
remark: Mapped[str] = mapped_column(String(500), default="", nullable=False, comment="账号说明")
created_at: Mapped[datetime] = mapped_column(
timestamp_col(), default=datetime.now,
server_default=text("CURRENT_TIMESTAMP(3)"), nullable=False,
)
updated_at: Mapped[datetime] = mapped_column(
timestamp_col(), default=datetime.now, onupdate=datetime.now,
server_default=text("CURRENT_TIMESTAMP(3) ON UPDATE CURRENT_TIMESTAMP(3)"), nullable=False,
)
org_unit: Mapped["OrgUnit | None"] = relationship("OrgUnit", foreign_keys=[org_unit_id])
position: Mapped["Position | None"] = relationship("Position", foreign_keys=[position_id])
leader: Mapped["Account | None"] = relationship(
"Account", remote_side=[id], foreign_keys=[leader_id]
)
identities: Mapped[list["AccountIdentity"]] = relationship(
"AccountIdentity", back_populates="account", cascade="all, delete-orphan"
)
@property
def can_login(self) -> bool:
return Status.is_active(self.status)
@property
def is_hub(self) -> bool:
return self.source == AccountSource.HUB
@property
def org_unit_name(self) -> str:
return self.org_unit.name if self.org_unit else ""
class AccountIdentity(Base, TimestampMixin):
"""一个人在系统里的"身份":某人以某部门成员的身份参与业务与审批。
兼岗、跨部门审批、借调都靠它表达。``is_default`` 的那个人是默认身份,用于
列表上"所属部门"这一列以及数据权限的默认口径。
"""
__tablename__ = "account_identity"
__table_args__ = (
UniqueConstraint("account_id", "org_unit_id", name="uk_account_identity"),
Index("idx_account_identity_unit", "org_unit_id"),
{"mysql_charset": "utf8mb4", "mysql_collate": "utf8mb4_unicode_ci"},
)
id: Mapped[int] = mapped_column(u_bigint(), primary_key=True, autoincrement=True)
account_id: Mapped[int] = mapped_column(
u_bigint(), ForeignKey("accounts.id", ondelete="CASCADE"), nullable=False, index=True
)
org_unit_id: Mapped[int] = mapped_column(
u_bigint(), ForeignKey("org_unit.id", ondelete="CASCADE"), nullable=False
)
position_id: Mapped[int | None] = mapped_column(
u_bigint(), ForeignKey("org_position.id", ondelete="SET NULL"), nullable=True
)
is_default: Mapped[bool] = mapped_column(
u_tinyint(), default=False, server_default="0", nullable=False, comment="是否默认身份"
)
# 主岗/兼岗:数据权限里"本人及下属部门"要区分这两者,兼岗一般不给下级数据。
kind: Mapped[str] = mapped_column(
String(16), default="primary", server_default="primary", nullable=False,
comment="primary=主岗 concurrent=兼岗",
)
account: Mapped["Account"] = relationship("Account", back_populates="identities")
org_unit: Mapped["OrgUnit"] = relationship("OrgUnit")
class HubSyncRun(Base):
"""一次统一身份同步的流水,界面上的"同步历史"读这张表。"""
__tablename__ = "hub_sync_run"
__table_args__ = (
Index("idx_hub_sync_run_started", "started_at"),
{"mysql_charset": "utf8mb4", "mysql_collate": "utf8mb4_unicode_ci"},
)
id: Mapped[int] = mapped_column(u_bigint(), primary_key=True, autoincrement=True)
trigger: Mapped[str] = mapped_column(String(16), default="manual", nullable=False,
comment="manual=手动 scheduled=定时")
status: Mapped[str] = mapped_column(String(16), default="running", nullable=False,
comment="running/success/partial/failed")
started_at: Mapped[datetime] = mapped_column(timestamp_col(), nullable=False)
finished_at: Mapped[datetime | None] = mapped_column(timestamp_col(), nullable=True)
org_total: Mapped[int] = mapped_column(Integer, default=0, server_default="0", nullable=False)
org_created: Mapped[int] = mapped_column(Integer, default=0, server_default="0", nullable=False)
org_updated: Mapped[int] = mapped_column(Integer, default=0, server_default="0", nullable=False)
org_disabled: Mapped[int] = mapped_column(Integer, default=0, server_default="0", nullable=False)
account_total: Mapped[int] = mapped_column(Integer, default=0, server_default="0", nullable=False)
account_created: Mapped[int] = mapped_column(Integer, default=0, server_default="0", nullable=False)
account_updated: Mapped[int] = mapped_column(Integer, default=0, server_default="0", nullable=False)
account_disabled: Mapped[int] = mapped_column(Integer, default=0, server_default="0", nullable=False)
skipped_local: Mapped[int] = mapped_column(Integer, default=0, server_default="0", nullable=False,
comment="因为是本地账号而没动的条数")
# 增量同步后的目录游标。全量那次记的是"拉完再取一次 changes 的 newest_seq",
# 之后每次增量只在整批成功时才往前推,中途失败保持原游标重来。
cursor_after: Mapped[int] = mapped_column(Integer, default=0, server_default="0", nullable=False,
comment="本次同步后的目录游标;0=不是增量批次")
# 逐步落盘,失败时能看出停在哪一步
steps_json: Mapped[str] = mapped_column(Text, default="[]", nullable=False)
error: Mapped[str] = mapped_column(Text, default="", nullable=False)
class LoginLog(Base):
"""登录审计。"""
__tablename__ = "login_log"
__table_args__ = (
Index("idx_login_log_account", "account", "created_at"),
{"mysql_charset": "utf8mb4", "mysql_collate": "utf8mb4_unicode_ci"},
)
id: Mapped[int] = mapped_column(u_bigint(), primary_key=True, autoincrement=True)
account: Mapped[str] = mapped_column(String(190), default="", nullable=False)
account_id: Mapped[int | None] = mapped_column(u_bigint(), nullable=True)
success: Mapped[bool] = mapped_column(u_tinyint(), default=False, nullable=False)
reason: Mapped[str] = mapped_column(String(255), default="", nullable=False)
ip: Mapped[str] = mapped_column(String(64), default="", nullable=False)
user_agent: Mapped[str] = mapped_column(String(500), default="", nullable=False)
mode: Mapped[str] = mapped_column(String(16), default="password", nullable=False,
comment="password=口令 hub=统一身份 sso=免登")
created_at: Mapped[datetime] = mapped_column(
timestamp_col(), default=datetime.now, server_default=text("CURRENT_TIMESTAMP(3)"), nullable=False
)
class OperationLog(Base):
"""写操作审计:谁在什么时候改了哪个对象的哪个字段。"""
__tablename__ = "operation_log"
__table_args__ = (
Index("idx_operation_log_object", "object_type", "object_id"),
Index("idx_operation_log_created", "created_at"),
{"mysql_charset": "utf8mb4", "mysql_collate": "utf8mb4_unicode_ci"},
)
id: Mapped[int] = mapped_column(u_bigint(), primary_key=True, autoincrement=True)
account_id: Mapped[int | None] = mapped_column(u_bigint(), nullable=True, index=True)
account_name: Mapped[str] = mapped_column(String(100), default="", nullable=False)
action: Mapped[str] = mapped_column(String(64), nullable=False, comment="create/update/delete/approve…")
object_type: Mapped[str] = mapped_column(String(64), default="", nullable=False)
object_id: Mapped[str] = mapped_column(String(64), default="", nullable=False)
object_name: Mapped[str] = mapped_column(String(255), default="", nullable=False)
detail_json: Mapped[str] = mapped_column(Text, default="", nullable=False, comment="字段级变更前后值")
ip: Mapped[str] = mapped_column(String(64), default="", nullable=False)
created_at: Mapped[datetime] = mapped_column(
timestamp_col(), default=datetime.now, server_default=text("CURRENT_TIMESTAMP(3)"), nullable=False
)
class SsoHandoff(Base):
"""后端免登回调发给浏览器的一次性短码。
回调(``GET /api/v1/auth/sso/callback``)验完票不能直接把本地令牌拼在 302 的地址上
——那等于把会话钥匙写进浏览历史、代理日志和 Referer。于是中间垫一条短码:库里只存
它的哈希与"兑换串"的哈希,60 秒失效、只能用一次,兑换还必须配着回调当场下发的
HttpOnly Cookie,两半都在别人手里就兑不出会话。口径与 unisoa 的 ``oa_sso_handoff`` 一致。
"""
__tablename__ = "sso_handoff"
__table_args__ = (
Index("idx_sso_handoff_expires", "expires_at"),
{"mysql_charset": "utf8mb4", "mysql_collate": "utf8mb4_unicode_ci"},
)
id: Mapped[int] = mapped_column(u_bigint(), primary_key=True, autoincrement=True)
code_hash: Mapped[str] = mapped_column(
String(64), nullable=False, unique=True, comment="短码 SHA-256,明文只在 302 的片段里出现过一次"
)
bind_hash: Mapped[str] = mapped_column(
String(64), nullable=False, comment="HttpOnly 兑换串的 SHA-256,缺它这条短码就是废纸"
)
account_id: Mapped[int] = mapped_column(u_bigint(), nullable=False, comment="验票认出来的本地账号")
redirect: Mapped[str] = mapped_column(String(255), default="", nullable=False, comment="免登进去要落到哪一页")
detail: Mapped[str] = mapped_column(String(255), default="", nullable=False, comment="写进登录日志的说明")
expires_at: Mapped[datetime] = mapped_column(timestamp_col(), nullable=False)
used_at: Mapped[datetime | None] = mapped_column(timestamp_col(), nullable=True)
created_at: Mapped[datetime] = mapped_column(
timestamp_col(), default=datetime.now, server_default=text("CURRENT_TIMESTAMP(3)"), nullable=False
)