unis-oa/backend/app/models.py

3216 lines
205 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.

"""Database models for the UnisOA approval platform.
The schema is a faithful python/relational translation of the O2OA
process-platform module (``x_processplatform_core_entity``):
* design time -> ``oa_category`` / ``oa_form`` / ``oa_process`` /
``oa_activity`` / ``oa_route``
* run time -> ``oa_work`` / ``oa_task`` / ``oa_task_completed`` /
``oa_work_log`` / ``oa_work_completed`` / ``oa_read`` /
``oa_read_completed`` / ``oa_attachment`` / ``oa_draft``
* organization -> ``users`` / ``oa_unit`` / ``oa_role`` / ``oa_group`` /
``oa_agent`` / ``oa_handover``
``users`` and ``oa_unit`` are keyed by ``BIGINT UNSIGNED AUTO_INCREMENT``; the
O2OA-derived tables keep their 32-char hex ids and store user ids as strings in
their ``person`` columns, so use :func:`as_id` before a primary-key lookup.
"""
from __future__ import annotations
import logging
import re
import uuid
from datetime import datetime, timezone
from sqlalchemy import (
JSON,
BigInteger,
Boolean,
DateTime,
Float,
ForeignKey,
Index,
Integer,
SmallInteger,
String,
Text,
UniqueConstraint,
text,
)
from sqlalchemy.dialects import mysql
from sqlalchemy.ext.mutable import MutableDict, MutableList
from sqlalchemy.orm import Mapped, mapped_column, relationship
from .db import Base
# JSON columns are mutated in place by the engine (gateway joins, tokens,
# form data), so they need the mutable wrappers to be tracked for flush.
#: 已经纠正过的「列名 -> 提醒过没有」,同一个列只提醒一次,别把日志刷满
_COERCION_WARNED: set[str] = set()
def _note_coercion(key: object, value: object, target: str) -> None:
name = str(key)
if name in _COERCION_WARNED:
return
_COERCION_WARNED.add(name)
logging.getLogger("unisoa.models").warning(
"字段 %s 存到了 %s 类型的 JSON,已按%s读出来;启动自检会顺手修历史数据",
name,
type(value).__name__,
target,
)
class _MutableJsonList(MutableList):
"""JSON 数组列:把读到的空对象读成空清单,而不是让整条查询抛错。
这几列早期的默认值写成了 ``{}``(``oa_task_completed.attachments`` 里存量上千条),
而 MutableList 遇到 dict 是直接抛 ``ValueError`` 的,后果是「点开任一已办详情就
500」。值本身没有歧义:空对象就是空清单,单个对象就是长度为 1 的清单,
所以在这里纠正比抛给调用方诚实。真正搞不懂的类型仍然照抛。
"""
@classmethod
def coerce(cls, key, value): # type: ignore[override]
if value is None:
value = []
elif isinstance(value, dict):
_note_coercion(key, value, "空清单")
value = [value] if value else []
return super().coerce(key, value)
class _MutableJsonDict(MutableDict):
"""JSON 对象列:只把空数组读成空对象,装满了东西又不匹配就照旧抛错。"""
@classmethod
def coerce(cls, key, value): # type: ignore[override]
if value is None:
value = {}
elif isinstance(value, list) and not value:
_note_coercion(key, value, "空对象")
value = {}
return super().coerce(key, value)
JsonDict = _MutableJsonDict.as_mutable(JSON)
JsonList = _MutableJsonList.as_mutable(JSON)
def new_id() -> str:
return uuid.uuid4().hex
def new_time_id() -> str:
"""时间在前、随机在后的 32 位主键:**按 id 排序就是按创建先后排序**。
给"读的时候必须按发生顺序取"的表用(发件箱)。那种表的读取方写的是
``ORDER BY job, id`` 来保证同一张单严格有序,而 ``new_id()`` 是随机 uuid,
拿它当这种保证等于没写——冲销的报文可能排在原报文前面,上游就会先收到
"作废"再收到"建单"。长度与 ``new_id()`` 一致,主键列不用改。
"""
return datetime.now().strftime("%Y%m%d%H%M%S%f") + uuid.uuid4().hex[:12]
def u_bigint() -> BigInteger:
"""``BIGINT UNSIGNED`` on MySQL, plain BIGINT on other dialects."""
return BigInteger().with_variant(mysql.BIGINT(unsigned=True), "mysql")
def u_tinyint() -> SmallInteger:
"""``TINYINT UNSIGNED`` on MySQL, SMALLINT elsewhere."""
return SmallInteger().with_variant(mysql.TINYINT(unsigned=True), "mysql")
def timestamp3() -> DateTime:
"""``DATETIME(3)`` on MySQL, plain DATETIME elsewhere."""
return DateTime().with_variant(mysql.DATETIME(fsp=3), "mysql")
def as_id(value: object) -> int | None:
"""Coerce a wire/legacy value into a ``users`` / ``oa_unit`` primary key.
Person and unit ids travel as strings in JWTs, query strings and in the
O2OA-style ``person`` columns of the workflow tables, so every lookup has to
normalise before hitting a BIGINT primary key.
"""
try:
return int(str(value).strip())
except (TypeError, ValueError):
return None
def clip(value: object, limit: int) -> str:
"""Trim a wire value to a column width before writing it.
``users.account`` 是 190、``display_name`` 是 100、``oa_unit.code`` 是 190、
``name`` 是 255;统一身份那边长一点就会让整批同步(或一次 JIT 建号)撞上
MySQL 的截断错误,所以读进来就先裁到列宽。
"""
return str(value or "")[:limit]
#: 全角数字与全角加号转半角:从表格和企微通讯录里粘过来的号码常是全角的
_MOBILE_WIDTH = str.maketrans(
"\uff10\uff11\uff12\uff13\uff14\uff15\uff16\uff17\uff18\uff19\uff0b", "0123456789+"
)
#: 手机号里常见的分隔符,规范化时一律去掉(含全角括号、全/半角破折号、全角空格与不换行空格)
_MOBILE_NOISE = str.maketrans(
"", "", " \t-().\u2013\u2014/\uff08\uff09\uff0d\u3000\u00a0"
)
#: 「可选的 + 加 5~15 位数字」:上限是 E.164 的 15 位,下限 5 位给国际短号留余地
_MOBILE_SHAPE = re.compile(r"^\+?\d{5,15}$")
def normalize_mobile(value: object) -> str:
"""把进来的手机号洗成入库的样子,洗不出一个像样的号码就回空串。
这一列是拿来联系人和"按号码找人"的,脏值比空值更害人:一个带空格的全角号码
谁都匹配不上,看上去却像有数据。所以一次做三件事——全角数字转半角、去掉
``-``/``()``/空格这类分隔符、再要求剩下的是可选 ``+`` 加 5~15 位数字。
回空串的三类:``无``/``待补充`` 这种占位、位数不对的残缺号码、``010-62345678``
这种去掉分隔符后剩下一串数字的座机——国内手机号不以 0 开头,带 0 的是区号,
混进来会让按号码查人查到错的人;国际号写全 ``+852…`` 照样收。
上游确实给了东西但没洗出来时别默默丢掉,调用方数出来报掉(同步侧是
``SyncStats.mobile_invalid``)。
"""
raw = str(value or "").strip().translate(_MOBILE_WIDTH).translate(_MOBILE_NOISE)
if raw.startswith("0"):
return ""
return raw if _MOBILE_SHAPE.match(raw) else ""
#: 企业微信 UserID 的写法:企微自己规定「字母、数字与 ``.``/``-``/``_``/``@``,
#: 不超过 64 字节」。通讯录里那个号是人在企微后台填的,比这野的一律当脏数据。
#: 下限取 2:单个 ``0`` 是上下游最爱写的"没有",把它当成真号存下来,
#: 后果是发消息时按一个不存在的收件人找了一圈人
_WECOM_USER_ID_SHAPE = re.compile(r"^[A-Za-z0-9._@\-]{2,64}$")
def normalize_wecom_user_id(value: object) -> str:
"""把进来的企业微信 UserID 洗成入库的样子,洗不出一个像样的号就回空串。
这一列是拿去找人的**收件地址**(企微 ``message/send`` 的 ``touser``),写错的后果
不是查不到人,是把张三的待办推到李四手机上,所以宁缺毋滥:只认企微那套字符集,
去掉首尾空白(含全角空格与不换行空格),中间带空格、带中文、超长的都回空串。
上游确实给了东西却没洗出来时别默默丢掉,调用方数出来报掉(同步侧是
``SyncStats.wecom_invalid``)。手机号那套「去掉分隔符」的洗法在这里**不适用**:
``.``/``-``/``_`` 在企微 UserID 里是合法字符,去掉就变成了另一个人。
少于两位的(``0``、``-`` 这类"没有"的写法)也一律算没给。
"""
raw = str(value or "").strip()
return raw if _WECOM_USER_ID_SHAPE.match(raw) else ""
#: 收款账号里常见的分隔符:从回单、表格里粘过来常常带空格与各种横杠
_BANK_ACCOUNT_NOISE = str.maketrans("", "", " \t\u3000\u00a0-\u2010\u2011\u2012\u2013\u2014-")
#: 全角数字转半角:和手机号同一套毛病
_BANK_ACCOUNT_WIDTH = str.maketrans("0123456789", "0123456789")
#: 洗完之后"得像个账号":6~34 位的数字与大写字母(上限是 IBAN 的长度)
_BANK_ACCOUNT_SHAPE = re.compile(r"^[0-9A-Z]{6,34}$")
#: 开户行名称里的连续空白,压成单个空格
_BANK_NAME_SPACE = re.compile(r"\s+")
def normalize_bank_account(value: object) -> str:
"""把进来的收款账号洗成入库的样子,洗不出一个像样的账号就回空串。
这一列是拿来打款的,写错一位就是钱打错地方,所以宁可拒收:全角数字转半角、
去掉空格与横杠这类分隔符、字母转大写,剩下的必须是 6~34 位的数字/大写字母,
并且**至少 6 位是数字**——``AAAAAAAA`` 这种一看就不是账号。
国内对公账号长到二三十位、银行卡 16~19 位、境外 IBAN 带字母,都收得下;
"无"「同上」这类占位和位数不对的残缺号一律回空串,由调用方决定报错还是计数。
"""
raw = (
str(value or "")
.strip()
.translate(_BANK_ACCOUNT_WIDTH)
.translate(_BANK_ACCOUNT_NOISE)
.upper()
)
if not _BANK_ACCOUNT_SHAPE.fullmatch(raw):
return ""
return raw if sum(ch.isdigit() for ch in raw) >= 6 else ""
def normalize_bank_name(value: object) -> str:
"""开户行名称:只把换行与连续空白压成单个空格,其余照原样留。
支行网点名里本来就有空格(``中国工商银行北京中关村支行``),不敢删;
但从回单上粘过来常带换行和全角空格,不压就会存进一列看不出区别的脏名字,
下个人照着历史值改时又是新的脏法。长度上限交给调用方(列宽 190)。
"""
return _BANK_NAME_SPACE.sub(" ", str(value or "").strip())
def localnow_second() -> datetime:
"""整秒的本机时间:给"要和 ``datetime.now()`` 比大小"的列当默认值。
DATETIME 存的是秒(不带小数位),带毫秒的时刻会被 MySQL 四舍五入——``.7`` 秒会被抬
到下一秒。发件箱的 ``next_attempt_at`` 就吃过这个亏:配的是"现在就能发",落库变成
"一秒后才能发",刚入队的那一条在自己那一秒里永远取不到,白等一轮投递。
"""
return localnow().replace(microsecond=0)
def localnow() -> datetime:
"""Naive local timestamp.
The workflow engine compares and writes naive local datetimes everywhere
(``start_time``, ``expire_time``, serial numbers...), so ORM defaults have to
use the same clock or every default-filled column lands 8 hours off.
"""
return datetime.now()
# Historical alias kept for the original O2OA-style column definitions.
utcnow = localnow
class TimestampMixin:
create_time: Mapped[datetime] = mapped_column(DateTime, default=localnow, nullable=False)
update_time: Mapped[datetime] = mapped_column(
DateTime, default=localnow, onupdate=localnow, nullable=False
)
# ---------------------------------------------------------------------------
# Organization (O2OA: x_organization_core_entity)
# ---------------------------------------------------------------------------
class UnitStatus:
"""``oa_unit.status`` 取值。
与 Hub 导出的组织 ``status`` 同一口径:``1`` 是启用,其余值(停用/待审核)本地
一律按不可用处理;``users.status`` 用同一套数字,两边读代码时不用换算。
"""
DISABLED = 0
ACTIVE = 1
PENDING = 2
REJECTED = 3
LABELS = {DISABLED: "已停用", ACTIVE: "正常", PENDING: "待审核", REJECTED: "已拒绝"}
@classmethod
def is_known(cls, value: object) -> bool:
return value in cls.LABELS
@classmethod
def label(cls, value: int) -> str:
return cls.LABELS.get(int(value), "未知")
@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 Unit(Base, TimestampMixin):
"""组织/部门;列名对齐 Hub 导出的组织节点(``code`` / ``status`` / ``organization_id``)。"""
__tablename__ = "oa_unit"
__table_args__ = (
# 一个 Hub 组织只能落地成一个本地部门。同步按这一列认人,撞两个就等于组织树裂开,
# 所以必须是唯一索引(NULL 不参与唯一性,本地自建部门不受影响)。
Index("uq_oa_unit_hub_org_id", "hub_org_id", unique=True),
)
id: Mapped[int] = mapped_column(u_bigint(), primary_key=True, autoincrement=True)
name: Mapped[str] = mapped_column(String(255), nullable=False)
alias: Mapped[str] = mapped_column(String(255), default="", nullable=False)
description: Mapped[str] = mapped_column(Text, default="", nullable=False)
parent_id: Mapped[int | None] = mapped_column(
u_bigint(), ForeignKey("oa_unit.id", ondelete="SET NULL"), nullable=True, index=True
)
parent_name: Mapped[str] = mapped_column(String(255), default="", nullable=False)
path: Mapped[str] = mapped_column(String(512), default="", nullable=False, index=True)
distinguished_name: Mapped[str] = mapped_column(String(512), default="", nullable=False, index=True)
short_name: Mapped[str] = mapped_column(String(255), default="", nullable=False)
order_number: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
# 组织编码:Hub 导出的 ``code``(root/rd/hr...),本地自建部门可以留空或自取。
code: Mapped[str] = mapped_column(String(190), default="", server_default="", nullable=False, index=True)
# 与 users.status 同一套口径,也对齐 Hub 导出的 ``status``:1=启用,其余为停用/待审核。
status: Mapped[int] = mapped_column(
u_tinyint(),
default=UnitStatus.ACTIVE,
server_default="1",
nullable=False,
comment="1=active, 0=disabled, 2=pending, 3=rejected",
)
# Hub 组织主表 id(导出里的 ``organization_id``):这一列就是"这个部门是不是 Hub 的、
# 是 Hub 里哪一个"的唯一依据,同步靠它保住组织架构,本地自建部门为 NULL。
# 非空时 Hub 侧接管 name / code / status / parent_id,本地只留 alias、description、
# order_number、manager_person_id 和挂在下面的自建部门;要摆脱接管就解绑(见 api/org.py)。
hub_org_id: Mapped[int | None] = mapped_column(u_bigint(), nullable=True)
# Hub 导出里该组织的直属人数只用于校验规模,本地按 organization_id 现算,不落库。
# 部门负责人:存人员主键而不是身份 DN。组织同步会改名、挪部门,届时 DN 会变,
# 而「谁是这个部门的负责人」要跟着人走;解析审批人时按人现取他当前所在部门。
# 不加外键:users.organization_id 已经指向 oa_unit,再加一条反向外键会让
# ``create_all`` 在两张表之间绕环。
manager_person_id: Mapped[int | None] = mapped_column(
u_bigint(), nullable=True, index=True, comment="部门负责人的 users.id"
)
@property
def is_active(self) -> bool:
return UnitStatus.is_active(self.status)
parent: Mapped["Unit | None"] = relationship(
"Unit", remote_side=[id], back_populates="children", foreign_keys=[parent_id]
)
children: Mapped[list["Unit"]] = relationship(
"Unit", back_populates="parent", foreign_keys=[parent_id]
)
ROLE_ADMIN = "admin"
ROLE_MEMBER = "member"
class AccountSource:
"""``users.source``:账号是谁建的,决定同步能不能动它。
只有 ``hub`` 账号会被夜间同步改姓名/换部门/停用,``local`` 账号(含初始
``admin`` 和手工新建的人)同步永远不碰。
"""
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 UserStatus:
"""``users.status`` 取值,与列注释 ``1=active, 0=disabled, 2=pending, 3=rejected`` 一致."""
DISABLED = 0
ACTIVE = 1
PENDING = 2
REJECTED = 3
LABELS = {DISABLED: "已停用", ACTIVE: "正常", PENDING: "待审核", REJECTED: "已拒绝"}
LOGIN_ALLOWED = (ACTIVE,)
@classmethod
def is_known(cls, value: object) -> bool:
return value in cls.LABELS
@classmethod
def label(cls, value: int) -> str:
return cls.LABELS.get(int(value), "未知")
@classmethod
def can_login(cls, value: int) -> bool:
return int(value) in cls.LOGIN_ALLOWED
class User(Base):
"""平台用户(登录账号).
列名/类型与 ``sql/schema.sql`` 里的 ``users`` 表逐字对齐:``display_name`` 是
姓名,``avatar_url`` 是头像,``organization_id`` 指向 ``oa_unit``,``status``
取代了原来的 ``enabled`` 开关。
"""
__tablename__ = "users"
__table_args__ = (
UniqueConstraint("account", name="uk_users_account"),
Index("idx_users_email", "email"),
Index("idx_users_status", "status"),
# 按手机号查人(HR 找回本人、企业微信按 mobile 认userid)走等值匹配,靠这一条。
Index("idx_users_mobile", "mobile"),
# 按姓名查人(``org._expand`` 那条 ``account = ? OR display_name = ?``、批量版的
# ``display_name IN (...)``)靠这一条。少了它 MySQL 用不上 account 那个唯一索引:
# OR 两边只要有一边没索引就只能整表扫。5 万行替身表实测 35.6ms -> 7.8ms
# (index_merge 把两边并起来),而这一问是全站最热的——每个请求认人、每条审批人
# 配置、每次按姓名找人都在问它。姓名会重,所以不建唯一索引,只做加速。
Index("idx_users_display_name", "display_name"),
# 企业微信 UserID(wecom_user_id)**不建索引**:这一列的用途是"由人取号"发消息,
# 库里唯一的反向查询是"这个号绑在谁身上",只在同步写之前判一次重,而全量同步
# 本来就整表读进内存了。等真出现按企微号搜人的接口再加。
# Hub 的 user_id 是同步账号的唯一身份:账号能被别人注册走、姓名会改、
# 账号也会在 Hub 侧改名,只有这个 id 从头到尾指向同一个人。
# 唯一索引(NULL 不参与唯一性):本地自建账号照样可以没有它。
Index("uq_users_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)
email: Mapped[str] = mapped_column(String(190), default="", server_default="", nullable=False)
# 手机号:Hub / 企业微信是权威源,本地只管展示、检索与按号找人。空串 = 没有;
# 写法只有一种(可选 + 开头的纯数字),落库前一律过 :func:`normalize_mobile`。
mobile: Mapped[str] = mapped_column(String(32), default="", server_default="", nullable=False)
password_hash: Mapped[str] = mapped_column(String(255), nullable=False)
display_name: Mapped[str] = mapped_column(
String(100), default="", server_default="", nullable=False
)
avatar_url: Mapped[str] = mapped_column(
String(500), default="", server_default="", nullable=False
)
organization_id: Mapped[int | None] = mapped_column(
u_bigint(), ForeignKey("oa_unit.id", ondelete="SET NULL"), nullable=True
)
# 直属上级:「发起人上级审批」最常用的口径。没设置时解析会退回所在部门负责人,
# 见 ``service/org.py::leader_person``。
leader_id: Mapped[int | None] = mapped_column(
u_bigint(), ForeignKey("users.id", ondelete="SET NULL"), nullable=True, index=True
)
role: Mapped[str] = mapped_column(
String(32), default=ROLE_MEMBER, server_default=ROLE_MEMBER, nullable=False
)
status: Mapped[int] = mapped_column(
u_tinyint(),
default=UserStatus.ACTIVE,
server_default="1",
nullable=False,
comment="1=active, 0=disabled, 2=pending, 3=rejected",
)
# --- 统一身份(Hub)镜像字段:来源、Hub 主键、最后一次同步时间 -----------
source: Mapped[str] = mapped_column(
String(16), default=AccountSource.LOCAL, server_default=AccountSource.LOCAL, nullable=False
)
hub_user_id: Mapped[int | None] = mapped_column(u_bigint(), nullable=True)
hub_synced_at: Mapped[datetime | None] = mapped_column(timestamp3(), nullable=True)
# 企业微信 UserID(企微通讯录里那个 userid):Hub 把自己那份企微映射结果一起下发时
# 跟着人员同步写过来,本地只读镜像。空串 = 没有(Hub 没下发过,或这人在企微没号)。
# 它不是登录凭据、也不参与任何身份判定,只作"给这个人发企微消息"的收件地址,
# 见 docs/wecom-app-notification-plan.md。
wecom_user_id: Mapped[str] = mapped_column(
String(190), default="", server_default="", nullable=False
)
last_login_at: Mapped[datetime | None] = mapped_column(timestamp3(), nullable=True)
#: 本人的界面偏好:深色档、字号这类"我习惯怎么看"的东西。
#: 存库而不是只存本地那一份:换一台设备、清一次缓存、从企业微信换个入口进来,
#: 都不该回到默认样子。登录返回体带着它,本地那一份就此降级成缓存——首屏那段
#: 防闪烁脚本只能读本地(那时还没登录),登录后由前端拿库里这一份对齐。
#: 只存放展示层的东西:权限、数据范围、审批口径一律不进这一格。
#: 取值与清洗见 :func:`app.api.auth.clean_preferences`。
preferences: Mapped[JsonDict] = mapped_column(
JsonDict, default=dict, server_default="{}", nullable=False
)
created_at: Mapped[datetime] = mapped_column(
timestamp3(), default=localnow, server_default=text("CURRENT_TIMESTAMP(3)"), nullable=False
)
updated_at: Mapped[datetime] = mapped_column(
timestamp3(),
default=localnow,
onupdate=localnow,
server_default=text("CURRENT_TIMESTAMP(3) ON UPDATE CURRENT_TIMESTAMP(3)"),
nullable=False,
)
unit: Mapped["Unit | None"] = relationship("Unit", foreign_keys=[organization_id])
leader: Mapped["User | None"] = relationship(
"User", remote_side=[id], foreign_keys=[leader_id]
)
#: 这个人身上的**权限角色**(只认启用的,顺序 ``sort, name``)。
#: 它存在的唯一理由是让"认人"这一趟只排一次队:每个请求都要先知道这是谁、在哪个部门、
#: 能干什么,原来是人员一条、权限角色一条,串在请求开头就是两趟往返。
#: ``viewonly`` —— 授权写的是 ``oa_person_auth_role`` 那张关联表本身(见
#: ``api/authrole.py``),不从这边刷;``lazy="raise"`` —— 谁没带 ``joinedload`` 就
#: 偷偷读它,让它当场炸,而不是在某个接口里悄悄长成 N+1。
#: 取角色的口径与 :func:`app.permissions.roles_of` 一字不差,两份都改了才有保证,
#: 由 ``scripts/check_current_user.py`` 拿库里每一个人当场对一遍。
auth_roles: Mapped[list["AuthRole"]] = relationship(
"AuthRole",
secondary="oa_person_auth_role",
primaryjoin="User.id == PersonAuthRole.person_id",
secondaryjoin="and_(AuthRole.id == PersonAuthRole.role_id, AuthRole.enabled.is_(True))",
order_by="AuthRole.sort, AuthRole.name",
viewonly=True,
lazy="raise",
)
# --- 派生字段:来自 oa_unit / status,不落库 ----------------------------
@property
def can_login(self) -> bool:
return UserStatus.can_login(self.status)
@property
def organization_name(self) -> str:
return self.unit.name if self.unit else ""
@property
def organization_path(self) -> str:
if self.unit is None:
return ""
return (self.unit.path or self.unit.name).rstrip("\\")
@property
def is_admin(self) -> bool:
return self.role == ROLE_ADMIN
class BankAccount(Base, TimestampMixin):
"""个人收款账户(开户行名称 + 收款账号),人在「个人资料」里自己填。
费用报销那一类单据的「收款账号 / 开户行名称」以后就取这一行,不必每次手敲。
**按 ``users.account`` 挂,不按 ``users.id``**:登录账号是财务与 HR 对外认人的口径,
``users.account`` 上有唯一键,一人一行;表单和导出的模板上也都是账号,挂账号少一次换算。
代价是统一身份同步会跟着 Hub 改账号(``hub_sync._plan_account_renames``),
所以这类"按账号存的东西"必须在改名时一起搬走 —— 已经挂在
:func:`app.service.hub_refs.rewrite` 的 ``accounts`` 映射上,漏不掉。
**为什么不建外键**:``users`` 行是真删得掉的(``api/org.py::delete_person`` 带
``force``),而同步改名动的恰恰就是 ``account`` 这一列本身。写上
``REFERENCES users(account)``,同步每改一次账号就会被外键顶回去,整趟人员同步失败。
为了绝不干扰同步,这一列和 ``oa_unit.hub_org_id`` 一样只做
逻辑关联,删人时由 ``delete_person`` 顺手清掉这一行(不然账号被下一个人认领时,
他会凭空继承上一个人的银行卡)。
**``person_id`` 是这一行的稳定键,``account`` 是对外口径**。挂账号的好处是真的:财务与 HR
认人、导出模板、上游系统的员工编码,写的都是账号,挂账号少一次换算(``{account:form.x}``
那个取值写法就是替 SQL 与报文做这次换算的)。但账号是 Hub 会改的一列,只认它的一行数据
就得跟着搬——搬不干净(有歧义、目标账号上压着别人的行)时,这个人打开个人资料是空的,
报销单带出的还是上辈子的号。所以这里两个键并存:**读**先按 ``person_id``(人没变就不该找不到),
**写**两个一起落,账号在启动种子(``seed._realign_bank_accounts``)与保存时各自对一次口径。
刻意不加外键、也不给 ``person_id`` 上唯一键:删人删得掉、老库里可能压着同一人的两行
(早期删人留下的孤儿行),唯一索引会把补列这步顶死;重复行由读路径按"账号对得上的那行"挑。
**同步永远不碰这张表**:Hub 只下发姓名/部门/状态/手机号,收款账户是本地数据;
这张表也不在 ``users`` 上留任何列,所以既不会被夜间同步覆盖,也不会让同步多一行写入。
"""
__tablename__ = "oa_bank_account"
__table_args__ = (
# 一人一行;同步改名时要按这一列等值找人,唯一性也靠它挡住重复保存。
UniqueConstraint("account", name="uq_oa_bank_account_account"),
# 排序规则跟着 ``users`` 走(库里只有它是 utf8mb4_unicode_ci,其余表吃库默认 0900_ai_ci):
# 这一列生来就是要和 ``users.account`` 比对的,两边不一致时 JOIN 直接报
# ``(1267, "Illegal mix of collations ...")``——按参数等值查看不出错,一旦有人写
# ``JOIN users ON users.account = ...``(财务导出、报销自动带出都会这么写)就炸。
{"mysql_charset": "utf8mb4", "mysql_collate": "utf8mb4_unicode_ci"},
)
id: Mapped[int] = mapped_column(u_bigint(), primary_key=True, autoincrement=True)
#: 关联 ``users.account``(登录账号,唯一键);对外口径与上游系统认的那一列。
account: Mapped[str] = mapped_column(String(190), nullable=False)
#: 关联 ``users.id``:账号被 Hub 改掉之后仍然认得人的那一列。老行可能为空,
#: 启动种子按账号回补一次;读路径按它优先、按账号兜底。
person_id: Mapped[int | None] = mapped_column(u_bigint(), nullable=True, index=True)
#: 开户行名称,写全到支行网点:``中国工商银行股份有限公司北京中关村支行``
bank_name: Mapped[str] = mapped_column(String(190), default="", server_default="", nullable=False)
#: 收款账号(银行卡号 / 对公账号),已过 :func:`normalize_bank_account`
pay_account: Mapped[str] = mapped_column(String(34), default="", server_default="", nullable=False)
class Role(Base, TimestampMixin):
__tablename__ = "oa_role"
id: Mapped[str] = mapped_column(String(32), primary_key=True, default=new_id)
name: Mapped[str] = mapped_column(String(255), unique=True, nullable=False)
description: Mapped[str] = mapped_column(Text, default="", nullable=False)
list_auth: Mapped[JsonList] = mapped_column(JsonList, default=list, nullable=False)
unit: Mapped[str] = mapped_column(String(512), default="", nullable=False)
class AuthRole(Base, TimestampMixin):
"""权限角色 -- 菜单/功能权限 + 数据范围,与审批岗位角色 ``oa_role`` 无关."""
__tablename__ = "oa_auth_role"
id: Mapped[str] = mapped_column(String(32), primary_key=True, default=new_id)
name: Mapped[str] = mapped_column(String(255), unique=True, nullable=False)
description: Mapped[str] = mapped_column(Text, default="", nullable=False)
permissions: Mapped[JsonList] = mapped_column(JsonList, default=list, nullable=False)
data_scope: Mapped[str] = mapped_column(String(32), default="self", nullable=False)
# 自定义口径(data_scope=custom)的三个配置项,其余口径下保持默认值不用。
data_unit_ids: Mapped[JsonList] = mapped_column(
JsonList, default=list, nullable=False, comment="data_scope=custom 时勾选的部门 id"
)
data_unit_children: Mapped[bool] = mapped_column(Boolean, default=True, nullable=False)
data_include_self: Mapped[bool] = mapped_column(Boolean, default=True, nullable=False)
enabled: Mapped[bool] = mapped_column(Boolean, default=True, nullable=False)
builtin: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
sort: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
class PersonAuthRole(Base):
"""人员与权限角色的关联."""
__tablename__ = "oa_person_auth_role"
person_id: Mapped[int] = mapped_column(
u_bigint(), ForeignKey("users.id", ondelete="CASCADE"), primary_key=True
)
role_id: Mapped[str] = mapped_column(
String(32), ForeignKey("oa_auth_role.id", ondelete="CASCADE"), primary_key=True, index=True
)
class Group(Base, TimestampMixin):
__tablename__ = "oa_group"
id: Mapped[str] = mapped_column(String(32), primary_key=True, default=new_id)
name: Mapped[str] = mapped_column(String(255), unique=True, nullable=False)
description: Mapped[str] = mapped_column(Text, default="", nullable=False)
list_identity: Mapped[JsonList] = mapped_column(JsonList, default=list, nullable=False)
list_person: Mapped[JsonList] = mapped_column(JsonList, default=list, nullable=False)
unit: Mapped[str] = mapped_column(String(512), default="", nullable=False)
class Agent(Base, TimestampMixin):
"""流程代理 -- delegate todo handling to another identity."""
__tablename__ = "oa_agent"
id: Mapped[str] = mapped_column(String(32), primary_key=True, default=new_id)
person_id: Mapped[str] = mapped_column(String(32), nullable=False, index=True)
person_name: Mapped[str] = mapped_column(String(255), default="", nullable=False)
identity: Mapped[str] = mapped_column(String(512), nullable=False)
from_identity: Mapped[str] = mapped_column(String(512), nullable=False)
from_person: Mapped[str] = mapped_column(String(255), default="", nullable=False)
process: Mapped[str] = mapped_column(String(32), default="", nullable=False)
process_name: Mapped[str] = mapped_column(String(255), default="", nullable=False)
enable_time: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
expire_time: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
enabled: Mapped[bool] = mapped_column(Boolean, default=True, nullable=False)
comment: Mapped[str] = mapped_column(Text, default="", nullable=False)
class Handover(Base, TimestampMixin):
"""流程交接 -- batch transfer of pending work."""
__tablename__ = "oa_handover"
id: Mapped[str] = mapped_column(String(32), primary_key=True, default=new_id)
title: Mapped[str] = mapped_column(String(255), default="", nullable=False)
from_person: Mapped[str] = mapped_column(String(32), nullable=False, index=True)
from_person_name: Mapped[str] = mapped_column(String(255), default="", nullable=False)
from_identity: Mapped[str] = mapped_column(String(512), default="", nullable=False)
to_person: Mapped[str] = mapped_column(String(32), nullable=False)
to_person_name: Mapped[str] = mapped_column(String(255), default="", nullable=False)
to_identity: Mapped[str] = mapped_column(String(512), nullable=False)
scheme: Mapped[str] = mapped_column(String(32), default="task", nullable=False)
status: Mapped[str] = mapped_column(String(32), default="pending", nullable=False)
task_count: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
work_count: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
execute_time: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
person: Mapped[str] = mapped_column(String(32), default="", nullable=False)
# ---------------------------------------------------------------------------
# Design time (O2OA: x_processplatform_assemble_designer)
# ---------------------------------------------------------------------------
class Category(Base, TimestampMixin):
__tablename__ = "oa_category"
id: Mapped[str] = mapped_column(String(32), primary_key=True, default=new_id)
name: Mapped[str] = mapped_column(String(255), nullable=False)
description: Mapped[str] = mapped_column(Text, default="", nullable=False)
order_number: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
enabled: Mapped[bool] = mapped_column(Boolean, default=True, nullable=False)
person: Mapped[str] = mapped_column(String(32), default="", nullable=False)
class FormElement(Base, TimestampMixin):
"""表单 -- the visual form definition bound to a process."""
__tablename__ = "oa_form"
id: Mapped[str] = mapped_column(String(32), primary_key=True, default=new_id)
name: Mapped[str] = mapped_column(String(255), nullable=False)
alias: Mapped[str] = mapped_column(String(255), default="", nullable=False)
description: Mapped[str] = mapped_column(Text, default="", nullable=False)
process: Mapped[str] = mapped_column(String(32), default="", nullable=False, index=True)
version: Mapped[int] = mapped_column(Integer, default=1, nullable=False)
content: Mapped[JsonDict] = mapped_column(JsonDict, default=dict, nullable=False)
editable: Mapped[str] = mapped_column(String(32), default="edit", nullable=False)
order_number: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
person: Mapped[str] = mapped_column(String(32), default="", nullable=False)
class DictType(Base, TimestampMixin):
"""数据字典分类 -- 一张可复用的选项来源(费用类别、物料、省市…)。
表单字段按 ``code`` 引用,字典项集中维护,改一处所有表单都跟着变。
``tree`` 表示层级字典(省→市→区),配合字段的 ``cascadeFrom`` 做级联下拉。
``source`` 决定选项从哪来:``manual`` 是人在页面上维护;``data_source`` 是
从一张列表型外部数据源**同步**下来(见 ``service/dicts.sync``)。选同步而不是
"渲染表单时现调上游",为的是下游一行代码都不用改——级联、字典项附加值带出、
提交时的选项校验、导出与标题翻译读的都是 ``oa_dict_item``,而且上游挂了
表单照样打得开,选项停在最后一次同步那份。
外部来源也**允许人补项**(上游漏了一项时不至于等 IT 改源):谁写的这一行记在
``DictItem.source`` 上,同步只动它自己那份,判据见 ``service/dicts.item_is_manual``。
"""
__tablename__ = "oa_dict_type"
#: 选项来源:手工维护 / 从外部数据源同步
SOURCE_MANUAL = "manual"
SOURCE_REMOTE = "data_source"
SOURCES = (SOURCE_MANUAL, SOURCE_REMOTE)
id: Mapped[str] = mapped_column(String(32), primary_key=True, default=new_id)
code: Mapped[str] = mapped_column(String(64), nullable=False, unique=True)
name: Mapped[str] = mapped_column(String(255), nullable=False)
description: Mapped[str] = mapped_column(Text, default="", nullable=False)
tree: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
enabled: Mapped[bool] = mapped_column(Boolean, default=True, nullable=False)
order_number: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
source: Mapped[str] = mapped_column(String(16), default=SOURCE_MANUAL, nullable=False)
#: source=data_source 时引用的数据源编码(得是列表型,方向不能是只往外写)
source_code: Mapped[str] = mapped_column(String(64), default="", nullable=False)
#: 同步时的固定入参,写法同数据源请求体模板(如 {"year": "{auto:today:YYYY}"})
source_args: Mapped[JsonDict] = mapped_column(JsonDict, default=dict, nullable=False)
#: 上次同步时间(**不论成败**都更新:失败了也要有个间隔再去试,不能每开一张单打一次上游)
synced_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
#: 上次同步成功时的条数与说明;失败时 synced_count 保持上一次那份,只有 message 换
synced_count: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
sync_status: Mapped[str] = mapped_column(String(16), default="", nullable=False)
sync_message: Mapped[str] = mapped_column(String(512), default="", nullable=False)
creator: Mapped[str] = mapped_column(String(32), default="", nullable=False)
creator_name: Mapped[str] = mapped_column(String(255), default="", nullable=False)
class DictItem(Base, TimestampMixin):
"""字典项 -- ``extra`` 是联动带出的附加值(单价、负责人、库存…)。
一本选项来自外部数据源的字典里,每一项都可能有两个主人:上游同步下来的那一份,
以及 OA 里手工补的那一份(上游缺了一项、又要马上开单,只能人先补上)。``source``
记的就是"这一行归谁写",同步只动上游那份,手工那份同步一律不碰——判据见
``service/dicts.item_is_manual``。
"""
__tablename__ = "oa_dict_item"
#: 这一行由谁写:OA 里手工加的 / 外部数据源同步下来的 / 空 = 分家之前就有
SOURCE_MANUAL = "manual"
SOURCE_REMOTE = "data_source"
id: Mapped[str] = mapped_column(String(32), primary_key=True, default=new_id)
type: Mapped[str] = mapped_column(String(64), default="", nullable=False, index=True)
source: Mapped[str] = mapped_column(
String(16),
default="",
nullable=False,
comment="这一行的主人:manual=OA 手工加, data_source=外部同步, 空=分家之前的老行",
)
value: Mapped[str] = mapped_column(String(255), default="", nullable=False)
label: Mapped[str] = mapped_column(String(255), default="", nullable=False)
parent: Mapped[str] = mapped_column(String(255), default="", nullable=False)
extra: Mapped[JsonDict] = mapped_column(JsonDict, default=dict, nullable=False)
color: Mapped[str] = mapped_column(String(32), default="", nullable=False)
enabled: Mapped[bool] = mapped_column(Boolean, default=True, nullable=False)
order_number: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
class QuotaDef(Base, TimestampMixin):
"""额度定义 -- 一种额度长什么样(部门预算、备用金冲销、差旅专项…)。
额度不是「一个数」,而是「一组维度上的一把钱 + 谁能扣 + 扣超了怎么办」:
``dims`` 定维度键(预算是科目 + 年度,备用金是那笔借款本身),``basis`` 定扣减
口径,``over`` 定超支的默认策略。方案出处见 ``docs/quota-control-design.md``。
"""
__tablename__ = "oa_quota_def"
#: 总额从哪来:外部同步/导入、由某条流程办结时生成(备用金借款),
#: 或按「取数配置」从别的历史单据聚合出来(项目预算 = 立项单的预算金额)
SOURCE_EXTERNAL = "external"
SOURCE_WORK = "work"
SOURCE_FLOW = "flow"
#: 扣减口径:本地全记,或「上游已用 + 本地在途」(此时本地 settled 不再重复扣)
BASIS_LOCAL = "local_all"
BASIS_UPSTREAM = "upstream_used"
#: 超支策略:硬挡提交、软提示、不控
OVER_HARD = "hard"
OVER_SOFT = "soft"
OVER_OFF = "off"
id: Mapped[str] = mapped_column(String(32), primary_key=True, default=new_id)
code: Mapped[str] = mapped_column(String(64), nullable=False, unique=True)
name: Mapped[str] = mapped_column(String(255), nullable=False)
description: Mapped[str] = mapped_column(Text, default="", nullable=False)
#: 额度下拉里怎么念这一笔,写法见 :func:`app.service.quota.quota_label`。
#: 留空 = 沿用来源单据标题(``备用金申请流程(部门)-张三-2026-10-16`` 那一长串):
#: 单据标题天生长,塞进明细表那一格会把人淹了,所以给一层可配的显示。
label_template: Mapped[str] = mapped_column(String(512), default="", nullable=False)
enabled: Mapped[bool] = mapped_column(Boolean, default=True, nullable=False)
source: Mapped[str] = mapped_column(String(16), default=SOURCE_EXTERNAL, nullable=False)
#: 维度键名,有序(["budget","year"]);一笔额度 = 定义 + 一组维度取值
dims: Mapped[JsonList] = mapped_column(JsonList, default=list, nullable=False)
#: source=work:办结时按这三个配置自动生成额度(备用金申请单 -> 一笔应冲销额度)
issue_process: Mapped[str] = mapped_column(String(32), default="", nullable=False)
issue_amount: Mapped[str] = mapped_column(String(191), default="", nullable=False)
issue_dims: Mapped[JsonDict] = mapped_column(JsonDict, default=dict, nullable=False)
#: source=flow:总额来源的取数配置 {process,amount,dims,match,states},见 service/quota_source.py
total_source: Mapped[JsonDict] = mapped_column(JsonDict, default=dict, nullable=False)
#: 消耗来源(可多条):哪些流程的单据算这笔额度的消耗,用于判断、试算与重建台账
consume_sources: Mapped[JsonList] = mapped_column(JsonList, default=list, nullable=False)
#: 按取数配置重算的频率(分钟):0=每次提交都重算,>0=增量记账 + 到点纠偏
sync_minutes: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
#: 提交时额度行不存在就按来源单据自动落一笔(流程聚合的额度不需要人工建台账)
auto_provision: Mapped[bool] = mapped_column(Boolean, default=True, nullable=False)
basis: Mapped[str] = mapped_column(String(24), default=BASIS_LOCAL, nullable=False)
over: Mapped[str] = mapped_column(String(8), default=OVER_HARD, nullable=False)
#: 软控时是否强制填写说明(落 quotaOver 后由表单的 requiredWhen 把关)
need_note: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
#: self=只认本人名下(备用金);global=不限人(预算)
scope: Mapped[str] = mapped_column(String(16), default="self", nullable=False)
#: 超期未核销提醒天数,0=不提醒
remind_days: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
#: 名下还有未核销余额时不许再发起(备用金挡借用)
block_new_when_open: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
creator: Mapped[str] = mapped_column(String(32), default="", nullable=False)
creator_name: Mapped[str] = mapped_column(String(255), default="", nullable=False)
class Quota(Base, TimestampMixin):
"""一笔额度 -- 按 (定义, 维度) 唯一。
这一行就是**加锁的那一行**:占用、释放、核销都先 ``SELECT ... FOR UPDATE`` 锁住它
再动计数,形状与 :func:`app.engine.engine.next_serial` 的流水号计数器一致,只是把
流水号换成了金额。金额一律存「分」:``work.data`` 里的金额是 float 元,浮点做累计
迟早漂几分,而台账差一分都对不上账。
"""
__tablename__ = "oa_quota"
__table_args__ = (
UniqueConstraint("quota_def", "dim_hash", name="uk_quota_def_dim"),
Index("idx_quota_def_status", "quota_def", "status"),
Index("idx_quota_person", "person", "status"),
)
STATUS_OPEN = "open"
STATUS_CLOSED = "closed"
id: Mapped[str] = mapped_column(String(32), primary_key=True, default=new_id)
quota_def: Mapped[str] = mapped_column(String(64), default="", nullable=False)
#: 规范化维度(键排序、值转字符串)的 sha1,用来做唯一键与检索
dim_hash: Mapped[str] = mapped_column(String(40), default="", nullable=False)
dims: Mapped[JsonDict] = mapped_column(JsonDict, default=dict, nullable=False)
title: Mapped[str] = mapped_column(String(512), default="", nullable=False)
#: 归属人:备用金这类按发起人判,待办交接不转移额度归属
person: Mapped[str] = mapped_column(String(32), default="", nullable=False)
person_name: Mapped[str] = mapped_column(String(255), default="", nullable=False)
unit: Mapped[str] = mapped_column(String(32), default="", nullable=False)
total_cents: Mapped[int] = mapped_column(BigInteger, default=0, nullable=False)
settled_cents: Mapped[int] = mapped_column(BigInteger, default=0, nullable=False)
occupied_cents: Mapped[int] = mapped_column(BigInteger, default=0, nullable=False)
upstream_used_cents: Mapped[int] = mapped_column(BigInteger, default=0, nullable=False)
upstream_synced_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
#: source=flow:总额上次按来源单据刷新的时间(sync_minutes 的计时起点)
total_synced_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
#: source=work 时的来源单据(备用金申请单)
source_work: Mapped[str] = mapped_column(String(32), default="", nullable=False)
source_job: Mapped[str] = mapped_column(String(32), default="", nullable=False)
status: Mapped[str] = mapped_column(String(8), default=STATUS_OPEN, nullable=False)
remark: Mapped[str] = mapped_column(String(512), default="", nullable=False)
class QuotaLedger(Base):
"""额度流水 -- 每次占用 / 释放 / 核销 / 调整都留一条,用来回答「这笔钱去哪了」。
``balance_after_cents`` 记下动完之后的可用额度:三个月后有人问「当时为什么不让我
提交」,凭这一列能直接答出来,不用重算历史。
"""
__tablename__ = "oa_quota_ledger"
__table_args__ = (
UniqueConstraint("quota", "kind", "work", "revision", name="uk_quota_ledger_idem"),
Index("idx_quota_ledger_quota", "quota", "created_at"),
Index("idx_quota_ledger_job", "job"),
# 状态钩子按单号问"这张单在各笔额度上还占着多少在途"(``service/quota.py::
# _work_quotas``,办结、作废、来源单据改额度都要问一次),是 ``WHERE work = ?``
# 一条单独的条件:原先这一列只出现在 ``uk_quota_ledger_idem`` 的第三位,用不上。
# 另一处 ``(work = ? OR job = ?)``(``quota.options``)也顺带被救活——index_merge
# 要每一支都有索引可用才凑得齐,原先 ``work`` 那一边没有,整条退化成整表扫。
Index("idx_quota_ledger_work", "work"),
)
KIND_ISSUE = "issue"
KIND_OCCUPY = "occupy"
KIND_RELEASE = "release"
KIND_SETTLE = "settle"
KIND_UNSETTLE = "unsettle"
KIND_ADJUST = "adjust"
#: 总额按取数配置从来源单据刷新(source=flow),与人工 adjust 区分开
KIND_SYNC = "sync"
id: Mapped[str] = mapped_column(String(32), primary_key=True, default=new_id)
quota: Mapped[str] = mapped_column(String(32), default="", nullable=False)
quota_def: Mapped[str] = mapped_column(String(64), default="", nullable=False)
kind: Mapped[str] = mapped_column(String(16), default=KIND_OCCUPY, nullable=False)
amount_cents: Mapped[int] = mapped_column(BigInteger, default=0, nullable=False)
balance_after_cents: Mapped[int] = mapped_column(BigInteger, default=0, nullable=False)
work: Mapped[str] = mapped_column(String(32), default="", nullable=False)
job: Mapped[str] = mapped_column(String(32), default="", nullable=False)
#: 退回补正后重新提交会 +1,配合唯一键挡住同一版本重复占用
revision: Mapped[int] = mapped_column(Integer, default=1, nullable=False)
activity: Mapped[str] = mapped_column(String(32), default="", nullable=False)
activity_name: Mapped[str] = mapped_column(String(255), default="", nullable=False)
person: Mapped[str] = mapped_column(String(32), default="", nullable=False)
person_name: Mapped[str] = mapped_column(String(255), default="", nullable=False)
reason: Mapped[str] = mapped_column(String(512), default="", nullable=False)
created_at: Mapped[datetime] = mapped_column(DateTime, default=localnow, nullable=False)
class DataSource(Base, TimestampMixin):
"""外部业务系统的数据源注册表 -- 表单字段只管点名要哪个源,怎么调归这一层管。
为什么要这张表:密钥、超时、重试、缓存、限流、熔断、审计这七件事,写在每个
表单字段的配置里迟早会漏一个,写在代码里每接一个系统就要改一次。注册成一条记录,
管理员在页面上配完就能「测试连通」看结果,业务侧只引用 ``code``。
``auth_secret`` **只进不出**:接口从不回显明文,只回 ``secret_set``,
与 Hub 目录密钥、MinIO SecretKey、大模型 api_key 是同一套约定。
"""
__tablename__ = "oa_data_source"
__table_args__ = (
UniqueConstraint("code", name="uq_data_source_code"),
Index("idx_data_source_enabled", "enabled", "kind"),
)
#: fetch = 查一个值(选成本中心带出余额);search = 查一个列表(大列表里挑一条)
KIND_FETCH = "fetch"
KIND_SEARCH = "search"
#: 鉴权方式:none / api_key(塞进指定请求头)/ basic / bearer
AUTH_NONE = "none"
AUTH_API_KEY = "api_key"
AUTH_BASIC = "basic"
AUTH_BEARER = "bearer"
AUTH_TYPES = (AUTH_NONE, AUTH_API_KEY, AUTH_BASIC, AUTH_BEARER)
#: 取数通道:http 真调上游接口;mock 直接回一份样例响应;
#: process 取**本平台另一个流程**的单据数据(不是外部系统,见 service/processdata.py);
#: sql 跑一条管理员配好的只读 SELECT(见 service/sqlsource.py);
#: embed 是**页面**不是接口——表单上那一格嵌的就是它(见 service/embed.py)。
#: 为什么复用这张表而不是另开一张:密钥只进不出、启停、``min_permission``、
#: 「测试连通」那四列结果、调用留痕、按环境搬运,这六件事嵌页面一件都少不了,
#: 而这张表看起来与嵌页面无关的那多半列(method / pick / map_* / success_path…)
#: 今天已经在被 sql 与 process 两条通道整片忽略。
PROVIDER_HTTP = "http"
PROVIDER_MOCK = "mock"
PROVIDER_PROCESS = "process"
PROVIDER_SQL = "sql"
PROVIDER_EMBED = "embed"
PROVIDERS = (PROVIDER_HTTP, PROVIDER_MOCK, PROVIDER_PROCESS, PROVIDER_SQL, PROVIDER_EMBED)
id: Mapped[str] = mapped_column(String(32), primary_key=True, default=new_id)
code: Mapped[str] = mapped_column(String(64), nullable=False)
name: Mapped[str] = mapped_column(String(255), nullable=False)
#: 属于哪个系统(ERP / HR / MES / 主数据…),只是界面上的归类与筛选
system: Mapped[str] = mapped_column(String(64), default="", nullable=False)
kind: Mapped[str] = mapped_column(String(16), default=KIND_FETCH, nullable=False)
enabled: Mapped[bool] = mapped_column(Boolean, default=True, nullable=False)
#: 上游还没开发时选 mock:解析规则、字段绑定、额度阈值全都照常配,
#: 等接口就绪只把这里改成 http 并填地址,表单上一格都不用动
provider: Mapped[str] = mapped_column(String(16), default=PROVIDER_HTTP, nullable=False)
#: provider=mock 时的样例响应,里面的 ``{arg.x}`` 照样会被替换,等于一个自己家的假接口
mock_payload: Mapped[JsonDict] = mapped_column(JsonDict, default=dict, nullable=False)
#: provider=sql 时跑的那条只读查询。入参一律写 ``:name`` 绑定(值绝不拼进 SQL),
#: 能不能执行、最多取多少行、超时多久,判据全在 service/sqlsource.py
sql_text: Mapped[str] = mapped_column(Text, default="", nullable=False)
#: provider=embed 专用:这个页面怎么带登录态进去(``none`` / ``hub`` / ``ticket``),
#: 判据与渲染全在 service/embed.py。地址模板仍用上面那列 ``url``,参数位写 ``{arg.x}``
page_mode: Mapped[str] = mapped_column(String(16), default="none", nullable=False)
#: provider=embed 专用:对方系统的应用编码。``ticket`` 模式下它同时是验票时的 audience
#: (防 A 系统拿着自己和 OA 的密钥去换 B 系统的用户),``hub`` 模式下它是 Hub 的应用编码
app_code: Mapped[str] = mapped_column(String(64), default="", nullable=False)
#: provider=embed 专用:那一页的地址**从哪来**。``template`` = 就用上面那列 ``url`` 拼;
#: ``api`` = 先打一个接口(地址、方法、请求头、请求体、密钥都走下面那几列现成的),
#: 从它回的信里取出要嵌的那条链接。为什么要有这一档:对方那一页是**按这张单现生成**的
#: (每次调用给一条带签名的临时地址,同样的参数下次就是另一个链接),OA 这边拼不出来,
#: 只能问它要。判据、取值、来源白名单全在 service/embed.py
url_mode: Mapped[str] = mapped_column(String(16), default="template", nullable=False)
#: provider=embed 且 ``url_mode=api`` 时用:链接在响应里的点路径(如 ``data.url``),
#: 写法与下面那列 ``pick`` 同一种(取值函数就是 :func:`service.fetch.pick_path`)
url_path: Mapped[str] = mapped_column(String(128), default="", nullable=False)
#: provider=embed 且 ``url_mode=api`` 时用:**查看页那条链接**在同一次响应里的点路径
#: (如 ``data.viewUrl``)。为什么强调"同一次":那个接口是**建页面**的,多打一次对面
#: 就多一张页,于是两条链接必须一次调用一起取回(``service/embed.py:_finish_link``)。
#: 留空 = 这个接口只给一条链接,行为与没有这一列时一模一样
view_url_path: Mapped[str] = mapped_column(String(128), default="", nullable=False)
#: provider=embed 且 ``url_mode=template`` 时的**第二条地址模板**(查看页那一屏)。
#: 参数位同样写 ``{arg.x}``。留空 = 没有查看页这一说,谁都拿上面那条 ``url``
view_url: Mapped[str] = mapped_column(String(512), default="", nullable=False)
#: provider=embed 专用:**对方还回了哪几条链接**。对方一次回三条以上(编辑页、查看页、
#: 打印页、票据页…)时逐条登记在这里,表单上那一格「给哪一条地址」因此点得到名字。
#: 每一条 ``{"key": "print", "name": "打印页", "path": "data.print_url",
#: "template": ""}``:「先调接口取链接」那一档填 ``path``(响应里的位置),
#: 「照地址模板拼」那一档填 ``template``(地址模板,参数位照写 ``{arg.x}``)。
#: 为什么不让它接管上面那两列:``edit`` / ``view`` 两个键名归那两列管,
#: 存量配置(含生产上那条费用报销)一条都不动就照原样跑,一处配置只有一个真相来源。
#: 取回仍只打**一次**接口,全部链接从同一份响应里一起摊出来(``service/embed.py:link_defs``)
url_links: Mapped[JsonList] = mapped_column(JsonList, default=list, nullable=False)
#: provider=embed 且 ``url_mode=api`` 时用:**同一次响应里顺手带回的那几个值**
#: (``{"对方单号": "data.flow_number"}``,键名给人看、值是响应里的点路径)。
#: 那一页的地址是这条源存在库里的原因,但同一个响应里常常还挂着审核状态、对方单号
#: 这些**只看一眼**的东西,今天全被扔掉,要看得再登记一条取数源、多打一次对面的接口。
#: 这一列只把它们摊到那一框下面当灰字看:**不写单据数据**,一次接口也不多打
url_meta: Mapped[JsonDict] = mapped_column(JsonDict, default=dict, nullable=False)
#: provider=embed 专用:**这一页被放弃时**(人没保存就返回)通知对方的那条地址。
#: 空 = 这一格就算开了那一档也发不出去(设计期会点名)。写完整地址,也可以只写路径
#: (如 ``/api/reimbursements/oa/by-flow-number``)——只写路径时挂到上面 ``url`` 那台主机上,
#: 于是"同一套接口、换个路径"这种最常见的情形只要填几个字符。判据见 service/embed.py:abandon_plan
abandon_url: Mapped[str] = mapped_column(String(512), default="", nullable=False)
#: provider=embed 专用:**这一句通知走哪条写回通道**(那条记录上的 URL、鉴权、
#: 成功判定、超时全跟它走)。"按 OA 单号删草稿"这类接口常常本来就登记过一条写回通道,
#: 选一下比再抄一遍网址省事,也不会留下两条会各自漂开的地址。填了 ``abandon_url``
#: 时以地址为准,鉴权与判定仍照这条通道。判据见 service/embed.py:abandon_plan
abandon_source: Mapped[str] = mapped_column(String(64), default="", nullable=False)
#: provider=embed 专用:那一句通知用什么方法发。默认 ``DELETE``("删掉那张草稿"这一类)
abandon_method: Mapped[str] = mapped_column(String(8), default="DELETE", nullable=False)
#: provider=embed 专用:对方按哪个字段收那个值(如 ``oa_flow_number``)。
#: 请求体就一份、就这一个键;值取哪儿见下面那列 ``abandon_expr``(留空 = 预留单号)
abandon_field: Mapped[str] = mapped_column(String(64), default="", nullable=False)
#: provider=embed 专用:那一句删除里**值**的取值写法(留空 = 这一趟预留的正式单号,
#: 没有正式号就退回预受理号)。要按别的键去对面删(比如自己的流程编号那一格),
#: 在这里写取值写法:``{auto:serial}``、``{form.流程编号}``、``{arg.x}`` 或一个写死的值。
#: 打开这一刻解析、记进会话快照,放弃那一刻照快照发——与「要不要发」同一份理由。
abandon_expr: Mapped[str] = mapped_column(String(256), default="", nullable=False)
#: provider=embed 专用:那一句删除的**多键请求体**。键 = 对方那个字段名,值 = 取值写法
#: (与 ``abandon_expr`` 同一种写法,在打开那一刻逐个算死)。配了就整份照它发,
#: 盖过上面"单键"那一档(``abandon_field`` / ``abandon_expr``);留空就退回单键。
#: 要按好几个字段去对面删(单号 + 项目号那种)就配在这里。
abandon_body: Mapped[JsonDict] = mapped_column(JsonDict, default=dict, nullable=False)
#: provider=embed 且 ``url_mode=api`` 时用:那个接口回给你的链接**允许是哪几个来源**。
#: 空 = 只认接口自己那一台主机(``https://erp/api/genLink`` 回 ``https://erp/page/1`` 那种)。
#: 这一列既是取回链接后唯一那道闸,也是 CSP ``frame-src`` 那份白名单的来源之一——
#: 少了它,"设计者碰不到完整网址"这套设计就被"接口回什么就嵌什么"顶穿了
url_origins: Mapped[JsonList] = mapped_column(JsonList, default=list, nullable=False)
method: Mapped[str] = mapped_column(String(8), default="POST", nullable=False)
url: Mapped[str] = mapped_column(String(512), default="", nullable=False)
headers: Mapped[JsonDict] = mapped_column(JsonDict, default=dict, nullable=False)
#: 请求体模板,值里的 ``{form.x}`` / ``{auto:today:YYYY}`` 在调用时替换(口径同 quota)
body_template: Mapped[JsonDict] = mapped_column(JsonDict, default=dict, nullable=False)
#: 参数表格比上面三份对象多出来的信息:每个键的备注、被停用的行(含它的取值)。
#: **只有配置界面看得懂它**——执行器照旧只读 headers / body_template / map_extra,
#: 停用的行根本不往那三份里写,所以取数逻辑一处都不用改。
param_meta: Mapped[JsonDict] = mapped_column(JsonDict, default=dict, nullable=False)
auth_type: Mapped[str] = mapped_column(String(16), default=AUTH_NONE, nullable=False)
#: api_key 时这里写头名(如 X-API-Key),basic / bearer 时这里是用户名
auth_username: Mapped[str] = mapped_column(String(255), default="", nullable=False)
auth_secret: Mapped[str] = mapped_column(String(512), default="", nullable=False)
#: 列表在响应里的点路径(search 用),如 ``data.rows``
items_path: Mapped[str] = mapped_column(String(128), default="", nullable=False)
#: 单值在响应里的点路径(fetch 用),如 ``data.balance``
pick: Mapped[str] = mapped_column(String(128), default="", nullable=False)
map_value: Mapped[str] = mapped_column(String(64), default="value", nullable=False)
map_label: Mapped[str] = mapped_column(String(64), default="label", nullable=False)
#: 可带出的其它键:{给表单看的键名: 响应里的点路径}
map_extra: Mapped[JsonDict] = mapped_column(JsonDict, default=dict, nullable=False)
#: provider=process 专用:取哪个流程(``oa_process.id``)的单据。
#: 单独一列是为了「这个流程被删/被停用时要提醒谁」能查得到,配置本体在 src_match。
src_process: Mapped[str] = mapped_column(String(32), default="", nullable=False)
#: provider=process 专用:取哪一单。
#: ``{scope, person, status, filters: [{field, op, value}], order, days, limit}``,
#: 口径与校验都在 service/processdata.py
src_match: Mapped[JsonDict] = mapped_column(JsonDict, default=dict, nullable=False)
timeout_seconds: Mapped[int] = mapped_column(Integer, default=5, nullable=False)
retries: Mapped[int] = mapped_column(Integer, default=1, nullable=False)
#: 0 = 不缓存。按数据变化速度自己定,余额类几秒就够,主数据类可以几分钟
cache_seconds: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
#: 0 = 不限。防的是「审批页一个防抖没做好,把 ERP 打爆」
rate_limit_qpm: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
#: 连续失败之后的静默期:这段时间内不再打外部,直接按失败策略走
cooldown_seconds: Mapped[int] = mapped_column(Integer, default=60, nullable=False)
#: 空 = 登录即可;否则要求这个人有这个权限码才能调
min_permission: Mapped[str] = mapped_column(String(64), default="", nullable=False)
#: 方向:in = 只往里取(表单带出);out = 只往外写(审批结果反写);both = 同一系统两边都用
direction: Mapped[str] = mapped_column(String(8), default="in", nullable=False)
#: 出站成功判定:响应里这个点路径等于 success_value 才算发成功(如 code == 0)。
#: 判不了就只能看 HTTP 状态码,而业务失败上游常常照样回 200
success_path: Mapped[str] = mapped_column(String(128), default="", nullable=False)
success_value: Mapped[str] = mapped_column(String(64), default="", nullable=False)
#: 上游那句人话错误在哪(失败时要原样留在发件箱里,别只留个 500)
message_path: Mapped[str] = mapped_column(String(128), default="", nullable=False)
#: 上游凭证号在哪:提出来存进发件箱的 external_ref,单据上就能显示「已写入 ERP:Voucher 0001」
ref_path: Mapped[str] = mapped_column(String(128), default="", nullable=False)
#: 影子模式:报文照常渲染、照常落发件箱与历史,就是不打出去。
#: 上游常常没有测试环境,这条让模板在生产数据上也能验(见 outbound-integration-design.md §17)
shadow: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
#: 熔断状态(不写日志表,省得每次调用先查一遍流水)
fail_count: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
open_until: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
#: 最近一次「测试连通」的结果,界面上直接显示,省得翻日志
last_test_status: Mapped[str] = mapped_column(String(16), default="", nullable=False)
last_test_message: Mapped[str] = mapped_column(Text, default="", nullable=False)
last_test_ms: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
last_test_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
last_test_by: Mapped[str] = mapped_column(String(255), default="", nullable=False)
#: 方向可选值
DIRECTION_IN = "in"
DIRECTION_OUT = "out"
DIRECTION_BOTH = "both"
DIRECTIONS = (DIRECTION_IN, DIRECTION_OUT, DIRECTION_BOTH)
description: Mapped[str] = mapped_column(Text, default="", nullable=False)
creator: Mapped[str] = mapped_column(String(32), default="", nullable=False)
creator_name: Mapped[str] = mapped_column(String(255), default="", nullable=False)
class Integration(Base, TimestampMixin):
"""写回模板(L2)-- 一张单要发哪些字段、怎么取值、成功怎么判。
三层配置里的中间那层(``docs/outbound-integration-design.md`` §2):L1 ``oa_data_source``
管协议与密钥(IT 配一次),L2 管业务映射(业务顾问配),L3 挂在流程环节上(流程设计者配)。
**"再加一个写回接口不用改代码"全靠这张表**:映射存 JSON,改口径是改一条记录,不是发一次版。
映射也刻意不做成明细表而是一整份 JSON:和本仓库 ``oa_form.content`` /
``oa_activity.config`` 同一做派——整体保存、随流程导出一起搬环境、配一份
``integration_problems`` 式的设计期校验。
"""
__tablename__ = "oa_integration"
__table_args__ = (
UniqueConstraint("code", name="uq_integration_code"),
Index("idx_integration_form", "biz_form", "enabled"),
)
#: 触发事件:办结 / 终止 / 作废 / 到达某环节 / 手工
EVENT_COMPLETED = "completed"
EVENT_TERMINATED = "terminated"
EVENT_CANCELED = "canceled"
EVENT_ACTIVITY = "activity"
EVENT_MANUAL = "manual"
EVENTS = (EVENT_COMPLETED, EVENT_TERMINATED, EVENT_CANCELED, EVENT_ACTIVITY, EVENT_MANUAL)
#: 终态事件:单据进这三态那一刻入队
TERMINAL_EVENTS = (EVENT_COMPLETED, EVENT_TERMINATED, EVENT_CANCELED)
#: 失败怎么办:继续走 / 挡住处理人 / 走一条人工补救路线
FAILURE_CONTINUE = "continue"
FAILURE_BLOCK = "block"
FAILURE_BRANCH = "branch"
FAILURE_POLICIES = (FAILURE_CONTINUE, FAILURE_BLOCK, FAILURE_BRANCH)
id: Mapped[str] = mapped_column(String(32), primary_key=True, default=new_id)
code: Mapped[str] = mapped_column(String(64), nullable=False)
name: Mapped[str] = mapped_column(String(255), nullable=False)
enabled: Mapped[bool] = mapped_column(Boolean, default=True, nullable=False)
#: L1 的 ``oa_data_source.code``(方向得是 out / both)
source: Mapped[str] = mapped_column(String(64), default="", nullable=False)
#: 绑定表单:设计器按表单筛模板,设计期也按它校验字段引用存不存在
biz_form: Mapped[str] = mapped_column(String(32), default="", nullable=False)
#: 「什么时候发」里属于终态的那几条:办结 / 终止 / 作废,可以多选,也可以一条都不勾。
#: 为什么做成清单而不是一个标量:一条模板只能认一条终态,「办结和终止都要通知上游」
#: 就只能把模板复制一份,两份映射从此各改各的。读法只有一处(``mapping.terminal_events_of``),
#: 空清单回落到下面那个标量,口径与 ``mapping.mount_blocks``「一条时平铺、多条才换形状」一样。
#: 一条都不勾 = 这张模板自己不自动发:要么在流程设计器里挂到某个环节上(那一刻才谈得上时机),
#: 要么只在集成页人工重推。
trigger_events: Mapped[JsonList] = mapped_column(JsonList, default=list, nullable=False)
#: 存量那一格标量:新配置写进来的是上面清单的第一条(老读法照旧能用),
#: 只有 ``activity``(旧写法「到达某环节」,见下行)与 ``manual``(不自动发)会停在这儿。
trigger_event: Mapped[str] = mapped_column(String(24), default=EVENT_COMPLETED, nullable=False)
#: 旧写法留下的环节 id:``trigger_event=activity`` 时指某条流程里的某个环节。
#: 环节时机如今统一在 L3 环节挂载上配(``oa_activity.config.writeback``):配模板的时候
#: 还没决定它挂在哪个环节上,而环节 id 是每条流程自己的主键——复制流程、导到别的环境
#: 都会换 id,绑在模板上迟早静默失效。这里留着只为让存量配置继续发,界面不再给新配置选。
event_key: Mapped[str] = mapped_column(String(32), default="", nullable=False)
#: 重复到达同一环节(撤回重提 / 退回重走)且上一份已经成功时,再发一条(修订版 +1)。
#: 对面「按单号更新」这类幂等写回该开;开凭证那类别开,维持「每张单每个环节只发一次」的老口径。
refire_revisit: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
#: 哪些单才发这一条:结构化条件,与表单条件显隐、路由条件、写回挂载的 when 同一份数据结构。
#: 绑定表单管的是「这条写回认哪张单」,这一格管的是「同一张单里哪几笔要发」——
#: 一张报销单按「结算方式」发给资金系统或 ERP,就是靠它分流,不用改代码也不用改流程。
#: 空 = 这张单每一笔都发(存量配置的口径不变)。
send_condition: Mapped[JsonDict] = mapped_column(JsonDict, default=dict, nullable=False)
#: 报文映射(method / path / fields),渲染结果就是发件箱里那份 payload
payload: Mapped[JsonDict] = mapped_column(JsonDict, default=dict, nullable=False)
#: 幂等键模板,默认 {source}:{code}:{job}:{event}:{event_key}:{revision};随 X-Idempotency-Key 发出
# 键里带 code 与 event_key:同一张单可以挂多个模板(凭证创建 + 归档通知),同一个模板也可以
# 挂在两个环节上(先建凭证、后面再传附件)。少了哪一段,后入队的那条都会被 uk_ob_idem
# 当成重复而**静默吃掉**——上游少一张凭证,而发件箱里干干净净,最难查。
idem_rule: Mapped[str] = mapped_column(
String(191), default="{source}:{code}:{job}:{event}:{event_key}:{revision}", nullable=False
)
#: 响应回写单据:[{pick: 响应里的点路径, to: 表单字段}]
result_write: Mapped[JsonList] = mapped_column(JsonList, default=list, nullable=False)
on_failure: Mapped[str] = mapped_column(String(8), default=FAILURE_CONTINUE, nullable=False)
fail_route: Mapped[str] = mapped_column(String(64), default="", nullable=False)
retries: Mapped[int] = mapped_column(Integer, default=5, nullable=False)
#: 超过这个时长就不再自动补发:三个月前的凭证今天补发出去多半是事故。0 = 不限
max_age_hours: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
#: 冲销模板:终止 / 作废时按它自动生成一条反向消息;没配就只报待处理,不猜该怎么做
reversal_code: Mapped[str] = mapped_column(String(64), default="", nullable=False)
#: 对账模板(查询类)
recon_code: Mapped[str] = mapped_column(String(64), default="", nullable=False)
#: 最近一次试跑的报文与响应,同行照着抄
sample: Mapped[JsonDict] = mapped_column(JsonDict, default=dict, nullable=False)
remark: Mapped[str] = mapped_column(Text, default="", nullable=False)
creator: Mapped[str] = mapped_column(String(32), default="", nullable=False)
creator_name: Mapped[str] = mapped_column(String(255), default="", nullable=False)
class OutboundMessage(Base, TimestampMixin):
"""发件箱 -- 写回这件事只有落在本地表里才谈得上重试、顺序、对账和人工兜底。
为什么不在流转请求里同步调外部:那一调用失败,审批人要么白等一次超时、要么单据
停在半路。发件箱把"业务已经定了"和"上游什么时候收到"分开——状态变更与入队同一事务,
绝不允许"单过去了消息丢了",也不允许"单没过凭证先发"。
``payload`` 是**入队那一刻渲染好的报文快照**:办结后 ``oa_work`` 那行会被搬进
``oa_work_completed`` 再删掉,发送时回查原表会查不到东西;改模板也不该改动已经在路上的报文。
"""
__tablename__ = "oa_outbound_message"
__table_args__ = (
#: 重复入队的唯一防线:同一张单同一事件同一修订版只可能有一条
UniqueConstraint("idem", name="uk_ob_idem"),
Index("idx_ob_due", "status", "next_attempt_at"),
Index("idx_ob_job", "job", "id"),
Index("idx_ob_work_event", "work", "event"),
# 模板页的「报文历史」按 integration 取最近 50 条(``api/integrations.py::
# template_messages``),是一条**必带** integration 的过滤 + 排序,原先这一列没有
# 任何索引:2 万行替身表实测「整表扫 + filesort」中位 59.9ms → 走索引 16.7ms。
# 发件箱每发一次外部写回长一行、只长不删,所以把 ORDER BY 那一列一起放进来免排序。
Index("idx_ob_integration_time", "integration", "create_time"),
)
STATUS_PENDING = "pending"
#: 已经打出去了但结果没落库(进程可能死在中间)——重启后不许直接重发
STATUS_SENDING = "sending"
STATUS_SUCCESS = "success"
#: 失败但还会按退避再试
STATUS_FAILED = "failed"
#: 重试次数用满,等人处理
STATUS_DEAD = "dead"
#: 结果未知:发过、没拿到可判定的答复,且没有查询接口能确认
STATUS_UNKNOWN = "unknown"
#: 这条被冲销消息顶掉了(原消息进这个态,避免对账时把作废的单当成有效凭证)
STATUS_REVERSED = "reversed"
STATUSES = (
STATUS_PENDING, STATUS_SENDING, STATUS_SUCCESS, STATUS_FAILED,
STATUS_DEAD, STATUS_UNKNOWN, STATUS_REVERSED,
)
#: 还需要投递的状态
STATUS_OPEN = (STATUS_PENDING, STATUS_FAILED)
# 主键用 new_time_id:投递按 (job, id) 取队首,id 必须等于入队先后(见其注释)
id: Mapped[str] = mapped_column(String(32), primary_key=True, default=new_time_id)
source: Mapped[str] = mapped_column(String(64), default="", nullable=False)
integration: Mapped[str] = mapped_column(String(64), default="", nullable=False)
event: Mapped[str] = mapped_column(String(24), default="", nullable=False)
event_key: Mapped[str] = mapped_column(String(32), default="", nullable=False)
#: 单据标识只作展示与排查,**不做外键**:归档表与原表是两张,绑哪个都会丢
work: Mapped[str] = mapped_column(String(32), default="", nullable=False)
job: Mapped[str] = mapped_column(String(32), default="", nullable=False)
serial: Mapped[str] = mapped_column(String(64), default="", nullable=False)
title: Mapped[str] = mapped_column(String(512), default="", nullable=False)
revision: Mapped[int] = mapped_column(Integer, default=1, nullable=False)
#: 幂等键(唯一键)
idem: Mapped[str] = mapped_column(String(191), nullable=False)
method: Mapped[str] = mapped_column(String(8), default="POST", nullable=False)
url: Mapped[str] = mapped_column(String(512), default="", nullable=False)
payload: Mapped[JsonDict] = mapped_column(JsonDict, default=dict, nullable=False)
#: 入队那一刻环节挂载上勾的「要发的字段」(映射目标,逗号分隔);空 = 整份模板。
#: 重推是拿模板重新渲染的,不存下这一份范围,重推会把人明明没勾的字段悄悄发回去。
field_scope: Mapped[str] = mapped_column(String(512), default="", nullable=False)
#: 触发这条报文的**时刻**(``arrive`` / ``leave`` / ``goBack`` / ``recall``,见
#: ``service.mapping.TRIGGERS``);三条终态与集成页手工送审那一路留空。
#: 幂等键里那一小截时刻段只给「退回」「撤回」补,而这一格把四个时刻都写明白:
#: 发件箱要答得出"这条是同意触发的还是退回触发的",人工重推也要照原时刻回放。
phase: Mapped[str] = mapped_column(String(16), default="", nullable=False)
#: 那一刻那颗按钮的上下文快照(时刻 / 按钮名 / 这条线的决定语义 / 人填的意见),
#: 只喂 ``{action.x}``。值刷新与人工重推都照这一份重渲染——单据后来走到哪儿、
#: 这一环又改没改按钮,都不该改写"当初那一次是谁按的、填了什么"。
action_data: Mapped[JsonDict] = mapped_column(JsonDict, default=dict, nullable=False)
status: Mapped[str] = mapped_column(String(16), default=STATUS_PENDING, nullable=False)
attempts: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
next_attempt_at: Mapped[datetime] = mapped_column(DateTime, default=localnow_second, nullable=False)
#: 本轮开始发送的时刻:停在 sending 超过发送超时的,重启后先当"结果未知"处理
attempt_started_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
sent_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
last_error: Mapped[str] = mapped_column(Text, default="", nullable=False)
#: 响应摘要(截断存,排错用;不含密钥)
response: Mapped[JsonDict] = mapped_column(JsonDict, default=dict, nullable=False)
ms: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
#: 上游凭证号(按 L1 的 ref_path 提出来)
external_ref: Mapped[str] = mapped_column(String(191), default="", nullable=False)
#: 冲销链:这条消息冲销的是哪一条
cancels: Mapped[str] = mapped_column(String(32), default="", nullable=False)
#: 需要冲销但没配冲销模板:不猜该怎么做,只在集成页挂一条待人工处理(§6)
needs_reversal: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
#: 影子模式发的(没真打出去),界面上要看得出来,别当成已写入
shadowed: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
#: 失败策略:继续 / 挡住 / 走补救路线(入队时从模板或环节配置上抄下来)
on_failure: Mapped[str] = mapped_column(String(8), default="continue", nullable=False)
#: 谁触发的入队(办结人 / 手动作废人),出问题能找到人
actor: Mapped[str] = mapped_column(String(32), default="", nullable=False)
actor_name: Mapped[str] = mapped_column(String(255), default="", nullable=False)
class DataSourceLog(Base):
"""外部取数的调用留痕 -- 谁在哪张单上调了哪个源、多久、成没成。
「外部系统只能提供值,不能决定流转」这句话要能被查证:审批人一句「当时页面显示
有余额」,凭这张表能答出来那次调用什么时候发生、返回了什么、是不是命中了缓存。
"""
__tablename__ = "oa_data_source_log"
__table_args__ = (
Index("idx_ds_log_source_time", "source", "created_at"),
Index("idx_ds_log_work", "work"),
)
STATUS_OK = "ok"
STATUS_ERROR = "error"
#: 被限流 / 熔断 / 权限挡住:一次都没打出去,所以不算失败次数
STATUS_BLOCKED = "blocked"
id: Mapped[str] = mapped_column(String(32), primary_key=True, default=new_id)
source: Mapped[str] = mapped_column(String(64), default="", nullable=False)
kind: Mapped[str] = mapped_column(String(16), default="", nullable=False)
work: Mapped[str] = mapped_column(String(32), default="", nullable=False)
job: Mapped[str] = mapped_column(String(32), default="", nullable=False)
activity: Mapped[str] = mapped_column(String(32), default="", nullable=False)
actor: Mapped[str] = mapped_column(String(32), default="", nullable=False)
actor_name: Mapped[str] = mapped_column(String(255), default="", nullable=False)
#: 入参留痕(密钥不参与——密钥在 header 上,本来就不进这一列)
args: Mapped[JsonDict] = mapped_column(JsonDict, default=dict, nullable=False)
status: Mapped[str] = mapped_column(String(16), default=STATUS_OK, nullable=False)
http_status: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
ms: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
cached: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
message: Mapped[str] = mapped_column(String(512), default="", nullable=False)
created_at: Mapped[datetime] = mapped_column(DateTime, default=localnow, nullable=False)
class ExternalCheck(Base, TimestampMixin):
"""外部核验台账 -- 「外部系统把这件事办了没有」在 OA 这一侧的真相。
系统里没有任何内置的核验场景,每一种都由用户在设计器里配出来。比如报销单的票据初审
(用户给场景起的名字,附件送进外部系统、
那边人工作业、结论回传落这张表,OA 在提交那一刻读它决定放不放行。
**为什么不塞进 ``work.data``**:逐票结论是多行、状态要能建索引按状态筛、幂等要靠唯一
约束,而且单据办结后 ``oa_work`` 那行会被搬进归档表再删掉(:class:`OutboundMessage`
的注释里那条坑),台账必须活得比 work 久。``work.data`` 里只放**最新一版摘要快照**,
供待办列表、打印、导出与条件分支读——它们永不现取外部数据。
**为什么不复用发件箱**:发件箱管「我发出去的东西成没成」,这张表管「外部那件事现在是
什么状态」,生命周期、幂等主体、清理策略都不一样。但送审那一次投递确实走发件箱
(白拿退避重试、死信、一键重推、影子模式),这里只留它的 ``message_id`` 做回溯。
``job`` / ``serial`` / ``work`` 全部自带、**不做外键**:绑哪个都会在归档那一刻丢掉一半。
方案出处:``docs/invoice-review-integration-design.md`` §4。
"""
__tablename__ = "oa_external_check"
__table_args__ = (
#: 重复送审与重复回调的唯一防线:同一批次同一修订版只可能有一条
UniqueConstraint("provider", "biz_key", "revision", name="uk_check_batch"),
#: 对账兜底按这一对扫(照 oa_outbound_message.idx_ob_due 的样子抄)
Index("idx_check_due", "status", "next_poll_at"),
Index("idx_check_job", "job", "id"),
Index("idx_check_serial", "serial"),
Index("idx_check_work_scene", "work", "scene", "id"),
)
#: 已入队送审,对方还没回执
STATUS_SUBMITTING = "submitting"
#: 对方已受理,正在人工初审
STATUS_CHECKING = "checking"
STATUS_PASSED = "passed"
#: 部分通过:放行与否是业务决定,不在这里替人拍板
STATUS_PARTIAL = "partial"
STATUS_REJECTED = "rejected"
#: 查不到这个批次 / 连续查不到:结果未知,**永远不等于通过**
STATUS_UNKNOWN = "unknown"
#: 结论超过闸门配的时长上限,按过期处置
STATUS_EXPIRED = "expired"
#: 附件清单变了,这一版作废,另起 revision
STATUS_STALE = "stale"
#: 单据退回 / 作废,已通知对方撤回
STATUS_WITHDRAWN = "withdrawn"
STATUSES = (
STATUS_SUBMITTING, STATUS_CHECKING, STATUS_PASSED, STATUS_PARTIAL, STATUS_REJECTED,
STATUS_UNKNOWN, STATUS_EXPIRED, STATUS_STALE, STATUS_WITHDRAWN,
)
#: 还在等结果的:定时对账只扫这两档
STATUS_OPEN = (STATUS_SUBMITTING, STATUS_CHECKING)
#: 终态:状态机不许从这些状态倒退回去(迟到回执一律当噪声丢掉)
STATUS_FINAL = (STATUS_PASSED, STATUS_PARTIAL, STATUS_REJECTED, STATUS_STALE, STATUS_WITHDRAWN)
#: 结论从哪来的:回传 / 对账查到 / 提交时现场回源 / 人工放行
ORIGIN_CALLBACK = "callback"
ORIGIN_POLL = "poll"
ORIGIN_SUBMIT = "submit"
ORIGIN_MANUAL = "manual"
ORIGINS = (ORIGIN_CALLBACK, ORIGIN_POLL, ORIGIN_SUBMIT, ORIGIN_MANUAL)
id: Mapped[str] = mapped_column(String(32), primary_key=True, default=new_id)
#: L1 数据源 ``oa_data_source.code``:一张单可能同时对接票据系统与预算系统,台账分得开
provider: Mapped[str] = mapped_column(String(64), default="", nullable=False)
#: 核验场景(``invoice_check``…):回传接口与闸门按场景找规则,不写死"发票"
scene: Mapped[str] = mapped_column(String(64), default="", nullable=False)
#: 送审批次号。**由 OA 出**(同 integration-contract §0 第 2 条):回执、对账、人工排查都靠它
biz_key: Mapped[str] = mapped_column(String(127), default="", nullable=False)
#: 第几版:附件清单一变就是一版,旧版置 stale
revision: Mapped[int] = mapped_column(Integer, default=1, nullable=False)
#: 附件清单指纹(排序后的 id + 大小 + 名字摘要)——判"附件变了没"
files_hash: Mapped[str] = mapped_column(String(64), default="", nullable=False)
# 单据标识:全部自带、不做外键(见类注释)
work: Mapped[str] = mapped_column(String(32), default="", nullable=False)
job: Mapped[str] = mapped_column(String(32), default="", nullable=False)
serial: Mapped[str] = mapped_column(String(64), default="", nullable=False)
title: Mapped[str] = mapped_column(String(512), default="", nullable=False)
#: 送审时单据停在哪个环节(回传时要不要自动办单按它判)
activity: Mapped[str] = mapped_column(String(32), default="", nullable=False)
activity_name: Mapped[str] = mapped_column(String(255), default="", nullable=False)
status: Mapped[str] = mapped_column(String(16), default=STATUS_SUBMITTING, nullable=False)
#: 上游原话的结论值(没归一化前那份):对账时"我们判的"与"他们说的"要能各看一眼
verdict: Mapped[str] = mapped_column(String(32), default="", nullable=False)
#: 给人看的那一句话。驳回时必须说清**是哪一张票、为什么**,只回"审核未通过"会被财务骂
verdict_reason: Mapped[str] = mapped_column(Text, default="", nullable=False)
#: 逐票结论快照 [{attachmentId, invoiceNo, status, reason}]
items: Mapped[JsonList] = mapped_column(JsonList, default=list, nullable=False)
#: 谁审的:只作署名展示,**不参与判定**(判定只看 status)
checker: Mapped[str] = mapped_column(String(64), default="", nullable=False)
checker_name: Mapped[str] = mapped_column(String(255), default="", nullable=False)
checked_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
origin: Mapped[str] = mapped_column(String(16), default="", nullable=False)
#: 送审报文快照 / 回执 / 对方批次号 / 发件箱消息 id:出问题时不重放也能还原当时发了什么
request_snapshot: Mapped[JsonDict] = mapped_column(JsonDict, default=dict, nullable=False)
response_snapshot: Mapped[JsonDict] = mapped_column(JsonDict, default=dict, nullable=False)
external_ref: Mapped[str] = mapped_column(String(191), default="", nullable=False)
message_id: Mapped[str] = mapped_column(String(32), default="", nullable=False)
#: 对账排期:照 oa_outbound_message.next_attempt_at 的样子
next_poll_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
poll_attempts: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
last_poll_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
#: 应急放行:闸门唯一能让路的口子,落在这条批次上,随单据永久可见
override_by: Mapped[str] = mapped_column(String(32), default="", nullable=False)
override_name: Mapped[str] = mapped_column(String(255), default="", nullable=False)
override_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
override_reason: Mapped[str] = mapped_column(Text, default="", nullable=False)
#: 谁点的送审
actor: Mapped[str] = mapped_column(String(32), default="", nullable=False)
actor_name: Mapped[str] = mapped_column(String(255), default="", nullable=False)
class Process(Base, TimestampMixin):
"""流程定义."""
__tablename__ = "oa_process"
id: Mapped[str] = mapped_column(String(32), primary_key=True, default=new_id)
name: Mapped[str] = mapped_column(String(255), nullable=False)
alias: Mapped[str] = mapped_column(String(255), default="", nullable=False)
description: Mapped[str] = mapped_column(Text, default="", nullable=False)
category: Mapped[str] = mapped_column(String(32), default="", nullable=False, index=True)
category_name: Mapped[str] = mapped_column(String(255), default="", nullable=False)
enabled: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
published: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
version: Mapped[int] = mapped_column(Integer, default=1, nullable=False)
latest_form: Mapped[str] = mapped_column(String(32), default="", nullable=False)
latest_form_name: Mapped[str] = mapped_column(String(255), default="", nullable=False)
# O2OA 保留列,本平台未使用:表单绑定只看 latest_form 与 activity.form。
main_routing: Mapped[str] = mapped_column(String(32), default="", nullable=False)
quick_forms: Mapped[JsonList] = mapped_column(JsonList, default=list, nullable=False)
query_fields: Mapped[JsonList] = mapped_column(JsonList, default=list, nullable=False)
start_identity_list: Mapped[JsonList] = mapped_column(JsonList, default=list, nullable=False)
manageable_identity_list: Mapped[JsonList] = mapped_column(JsonList, default=list, nullable=False)
visible_identity_list: Mapped[JsonList] = mapped_column(JsonList, default=list, nullable=False)
data_template: Mapped[JsonDict] = mapped_column(JsonDict, default=dict, nullable=False)
#: 画布偏好(连线画法、拐角半径等),跟着流程走,换个人打开还是同一个样子。
canvas: Mapped[JsonDict] = mapped_column(JsonDict, default=dict, nullable=False)
#: 审批规则(流程级默认):``skipStarter`` 发起人自己不重复审批、
#: ``dedup`` 同一审批人前面批过就自动通过(none / all)、
#: ``dedupAhead`` 同一审批人后面还要批时跳过前面这一环(none / all / any,
#: 口径见 engine/lookahead.py)、``dedupAheadKeepOne`` 整环都被前瞻免掉时留一人。
#: 环节上的 skipStarter / skipApproved / skipAhead 显式配置时优先于这里。
approval_config: Mapped[JsonDict] = mapped_column(JsonDict, default=dict, nullable=False)
#: 标题生成规则(``mode`` / ``template`` / ``expression`` / ``maxLength`` /
#: ``emptyText`` / ``editable`` / ``refresh``),取值口径见 service/titles.py。
#: 空 dict = 没配过,标题走老口径(表单里的 title/subject/name,否则「某某的XX流程」)。
title_config: Mapped[JsonDict] = mapped_column(JsonDict, default=dict, nullable=False)
#: 编号(``oa_work.serial``)什么时候排出来:``at`` = ``start`` 发起时(出厂口径)/
#: ``draft`` 存草稿就占号 / ``activity`` 走到指定环节时 / ``none`` 不自动生成;
#: ``activity`` 指环节 id,``when`` 只在 ``activity`` 下生效(``enter`` 到达时 /
#: ``leave`` 本环节通过后)。口径见 service/numbering.py 的 timing 一节。
#: 空 dict = 没配过 = ``start``,老流程行为一字不差。
serial_config: Mapped[JsonDict] = mapped_column(JsonDict, default=dict, nullable=False)
#: 环节外部审批接口的**流程级默认档**:环节上 ``config.openApprove`` 显式配置的键
#: 优先于这里(口径与 ``approval_config`` 一致)。空 dict = 没配过,任何环节都关着。
#: 见 service/node_approve.py 与 docs/node-open-approve-design.md。
open_approve: Mapped[JsonDict] = mapped_column(JsonDict, default=dict, nullable=False)
#: 「终止」这一动作的流程级配置。空 dict = 没配过 = 老行为(发起人随时能终止、
#: 终止那一刻不再额外发写回)。每一格的读法只在 :mod:`app.service.terminate` 一处:
#: ``allowStarter`` 发起人还能不能终止(关掉:界面上不出现那颗钮,引擎也挡),
#: ``until`` / ``untilActivity`` / ``untilHours`` 说的是**什么时候之后**不再允许他终止,
#: ``writeback`` 是终止那一刻要调用的回写模板挂载(形状同环节挂载,时刻固定 terminate)。
#: 管理员不受这套约束:他手上的终止是流程监控里的干预手段,不是发起人在收拾自己的单。
terminate_config: Mapped[JsonDict] = mapped_column(JsonDict, default=dict, nullable=False)
open_create: Mapped[bool] = mapped_column(Boolean, default=True, nullable=False)
order_number: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
icon: Mapped[str] = mapped_column(String(255), default="", nullable=False)
color: Mapped[str] = mapped_column(String(32), default="", nullable=False)
creator: Mapped[str] = mapped_column(String(32), default="", nullable=False)
creator_name: Mapped[str] = mapped_column(String(255), default="", nullable=False)
activities: Mapped[list["Activity"]] = relationship(
"Activity", back_populates="process_ref", cascade="all, delete-orphan"
)
routes: Mapped[list["Route"]] = relationship(
"Route", back_populates="process_ref", cascade="all, delete-orphan"
)
class Activity(Base, TimestampMixin):
"""流程环节 (begin/manual/choice/parallel/merge/split/script/invoke/embed/end/cancel)."""
__tablename__ = "oa_activity"
id: Mapped[str] = mapped_column(String(32), primary_key=True, default=new_id)
process: Mapped[str] = mapped_column(
String(32), ForeignKey("oa_process.id", ondelete="CASCADE"), nullable=False, index=True
)
type: Mapped[str] = mapped_column(String(32), nullable=False)
name: Mapped[str] = mapped_column(String(255), nullable=False)
alias: Mapped[str] = mapped_column(String(255), default="", nullable=False)
description: Mapped[str] = mapped_column(Text, default="", nullable=False)
x: Mapped[float] = mapped_column(Float, default=0, nullable=False)
y: Mapped[float] = mapped_column(Float, default=0, nullable=False)
order_number: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
form: Mapped[str] = mapped_column(String(32), default="", nullable=False)
config: Mapped[JsonDict] = mapped_column(JsonDict, default=dict, nullable=False)
process_ref: Mapped["Process"] = relationship("Process", back_populates="activities")
class Route(Base, TimestampMixin):
"""流程路由 (activity -> activity)."""
__tablename__ = "oa_route"
id: Mapped[str] = mapped_column(String(32), primary_key=True, default=new_id)
process: Mapped[str] = mapped_column(
String(32), ForeignKey("oa_process.id", ondelete="CASCADE"), nullable=False, index=True
)
name: Mapped[str] = mapped_column(String(255), nullable=False)
alias: Mapped[str] = mapped_column(String(255), default="", nullable=False)
from_activity: Mapped[str] = mapped_column(String(32), nullable=False, index=True)
to_activity: Mapped[str] = mapped_column(String(32), nullable=False, index=True)
decision: Mapped[str] = mapped_column(String(255), default="", nullable=False)
expression: Mapped[str] = mapped_column(Text, default="", nullable=False)
order_number: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
process_ref: Mapped["Process"] = relationship("Process", back_populates="routes")
class ProcessVersion(Base, TimestampMixin):
"""流程发布快照."""
__tablename__ = "oa_process_version"
id: Mapped[str] = mapped_column(String(32), primary_key=True, default=new_id)
process: Mapped[str] = mapped_column(String(32), nullable=False, index=True)
process_name: Mapped[str] = mapped_column(String(255), default="", nullable=False)
version: Mapped[int] = mapped_column(Integer, default=1, nullable=False)
snapshot: Mapped[JsonDict] = mapped_column(JsonDict, default=dict, nullable=False)
comment: Mapped[str] = mapped_column(Text, default="", nullable=False)
creator: Mapped[str] = mapped_column(String(32), default="", nullable=False)
creator_name: Mapped[str] = mapped_column(String(255), default="", nullable=False)
class ProcessSnapshot(Base, TimestampMixin):
"""单据发起那一刻冻结下来的流程设计(流程 / 环节 / 路由 + 那几张表单的内容)。
与 :class:`ProcessVersion` 的分工:那张表是**发布历史**,给人看、给人回滚,
一次发布一行;这一张是**在途单据脚下那块地**,一张在途单指向一行,写完就不再改。
所以它按内容寻址——同一份设计全库只存一行,一百张同时在途的单共用它,
``fingerprint`` 就是查重用的那把尺。
为什么要它:设计器是自动保存到 ``oa_activity`` / ``oa_route`` 的,改一笔就等于改了
线上正在跑的那张图;没有这一层,中途改流程或表单会当场改变已经在走的单子。
"""
__tablename__ = "oa_process_snapshot"
id: Mapped[str] = mapped_column(String(32), primary_key=True, default=new_id)
process: Mapped[str] = mapped_column(String(32), nullable=False, index=True)
#: 拍下这一张时 ``oa_process.version`` 是多少:只给单据详情页显示"按第几版设计在走",
#: 认领快照靠的是 ``fingerprint``,不是这个号(草稿没发布过也有号)。
version: Mapped[int] = mapped_column(Integer, default=1, nullable=False)
#: 设计内容的指纹(sha256,规范化 JSON 之后):同指纹必同内容,发起单据时先问有没有
#: 现成的这一行,有就直接复用,不给每张单存一份设计。
fingerprint: Mapped[str] = mapped_column(String(64), default="", nullable=False, index=True)
#: ``definition._to_payload`` 那三份原始行 + ``forms``(form_id -> 表单 content)。
#: 形状与 :mod:`app.designcache` 存进 Redis 的那份一字不差,重建走同一个 ``build``。
definition: Mapped[JsonDict] = mapped_column(JsonDict, default=dict, nullable=False)
class ScriptElement(Base, TimestampMixin):
"""流程脚本 (beforeArrive/afterArrive/task/read...)."""
__tablename__ = "oa_script"
id: Mapped[str] = mapped_column(String(32), primary_key=True, default=new_id)
name: Mapped[str] = mapped_column(String(255), nullable=False)
type: Mapped[str] = mapped_column(String(32), default="python", nullable=False)
description: Mapped[str] = mapped_column(Text, default="", nullable=False)
process: Mapped[str] = mapped_column(String(32), default="", nullable=False, index=True)
activity: Mapped[str] = mapped_column(String(32), default="", nullable=False)
script: Mapped[str] = mapped_column(Text, default="", nullable=False)
# ---------------------------------------------------------------------------
# Run time (O2OA: x_processplatform_assemble_surface / service_processing)
# ---------------------------------------------------------------------------
class Work(Base, TimestampMixin):
"""工作 -- 运行中的流程实例."""
__tablename__ = "oa_work"
__table_args__ = (
Index("idx_oa_work_process_start", "process", "start_time"),
Index("idx_oa_work_creator", "creator_identity", "status"),
)
id: Mapped[str] = mapped_column(String(32), primary_key=True, default=new_id)
job: Mapped[str] = mapped_column(String(32), nullable=False, index=True)
#: 单号上有索引:开放平台那三条(定位 / 表态 / 查单)都是按这个号等值找单,
#: 报文里带的就是它;表会随单据一直长大,没索引时每一次回写都是一趟全表扫
serial: Mapped[str] = mapped_column(String(64), default="", nullable=False, index=True)
title: Mapped[str] = mapped_column(String(512), default="", nullable=False)
status: Mapped[str] = mapped_column(String(32), default="running", nullable=False)
application: Mapped[str] = mapped_column(String(64), default="processplatform", nullable=False)
process: Mapped[str] = mapped_column(String(32), nullable=False, index=True)
process_name: Mapped[str] = mapped_column(String(255), default="", nullable=False)
process_alias: Mapped[str] = mapped_column(String(255), default="", nullable=False)
category: Mapped[str] = mapped_column(String(32), default="", nullable=False, index=True)
category_name: Mapped[str] = mapped_column(String(255), default="", nullable=False)
form: Mapped[str] = mapped_column(String(32), default="", nullable=False)
#: 本单发起那一刻冻结的设计(``oa_process_snapshot.id``)。空 = 这张单是在"按当前设计
#: 走"这套机制之前发起的老单,照旧现读设计——所以升级不迁数据,老单行为一字不变。
#: 口径见 :func:`app.engine.definition.for_work`。
design_snapshot: Mapped[str] = mapped_column(String(32), default="", nullable=False)
data: Mapped[JsonDict] = mapped_column(JsonDict, default=dict, nullable=False)
creator: Mapped[str] = mapped_column(String(32), default="", nullable=False, index=True)
creator_person: Mapped[str] = mapped_column(String(255), default="", nullable=False)
creator_identity: Mapped[str] = mapped_column(String(512), default="", nullable=False, index=True)
creator_identity_name: Mapped[str] = mapped_column(String(255), default="", nullable=False)
creator_unit: Mapped[str] = mapped_column(String(512), default="", nullable=False)
creator_unit_name: Mapped[str] = mapped_column(String(255), default="", nullable=False)
activity: Mapped[str] = mapped_column(String(32), default="", nullable=False)
activity_name: Mapped[str] = mapped_column(String(255), default="", nullable=False)
activity_type: Mapped[str] = mapped_column(String(32), default="", nullable=False)
activity_token: Mapped[str] = mapped_column(String(512), default="", nullable=False)
activity_arrived_time: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
current_activity_names: Mapped[str] = mapped_column(String(512), default="", nullable=False)
tokens: Mapped[JsonList] = mapped_column(JsonList, default=list, nullable=False)
joins: Mapped[JsonDict] = mapped_column(JsonDict, default=dict, nullable=False)
variables: Mapped[JsonDict] = mapped_column(JsonDict, default=dict, nullable=False)
tickets: Mapped[JsonList] = mapped_column(JsonList, default=list, nullable=False)
split_state: Mapped[JsonDict] = mapped_column(JsonDict, default=dict, nullable=False)
go_back_store: Mapped[JsonDict] = mapped_column(JsonDict, default=dict, nullable=False)
manual_identity_text: Mapped[str] = mapped_column(String(512), default="", nullable=False)
manual_identity_list: Mapped[JsonList] = mapped_column(JsonList, default=list, nullable=False)
#: 流程干预:挂起是「运行中但暂时冻结」,故意不动 ``status``——恢复之后单据
#: 还停在原来那一环继续走,归档与统计也不必多认一个状态。挂起期间待办办不动、
#: 超时不计时,``pause_reason`` 是操作人填的原因,要能在单据上直接看见。
paused: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
pause_reason: Mapped[str] = mapped_column(Text, default="", nullable=False)
pause_actor: Mapped[str] = mapped_column(String(255), default="", nullable=False)
pause_time: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
work_create_type: Mapped[str] = mapped_column(String(32), default="surface", nullable=False)
parent_work: Mapped[str] = mapped_column(String(32), default="", nullable=False)
parent_job: Mapped[str] = mapped_column(String(32), default="", nullable=False)
embed_activity: Mapped[str] = mapped_column(String(32), default="", nullable=False)
embed_target_job: Mapped[str] = mapped_column(String(32), default="", nullable=False)
embed_completed: Mapped[str] = mapped_column(String(32), default="", nullable=False)
start_time: Mapped[datetime] = mapped_column(DateTime, default=localnow, nullable=False, index=True)
start_time_month: Mapped[str] = mapped_column(String(16), default="", nullable=False)
finish_time: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
expire_time: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
read: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
deleted: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
deleted_time: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
deleted_person: Mapped[str] = mapped_column(String(32), default="", nullable=False)
class WorkCompleted(Base, TimestampMixin):
"""办结工作 (归档)."""
__tablename__ = "oa_work_completed"
__table_args__ = (
Index("idx_oa_work_completed_creator", "creator_identity", "finish_time"),
# 集成模板页的「预览候选单据」按 form 取最近 15 张已办结的单
# (``api/integrations.py::template_samples``)。这一列原先没有任何索引,MySQL 就
# 拿 finish_time 那个索引倒着扫再筛 form:被查的 form 行多时差不多(2 万行替身表
# 实测中位 10.7ms → 9.9ms),一旦这个 form 很稀或很旧——新建的写回模板压根还没
# 办结过单是最狠的一种——倒扫要翻完整表才凑不满 LIMIT:65.1ms → 17.7ms,且不带
# 索引那版随表变大线性变差,带索引这版只按命中的行数花钱。归档表只长不删。
# 代价量过:批量搬档 2000 行 489ms → 524ms(约 +7%)。
Index("idx_oa_work_completed_form", "form", "finish_time"),
)
id: Mapped[str] = mapped_column(String(32), primary_key=True, default=new_id)
job: Mapped[str] = mapped_column(String(32), nullable=False, index=True)
#: 归档表的单号也要索引:关联那一格的「存值列」可以改成单号(`optionMap.valueKey: serial`),
#: 于是回显那一趟 `GET /work/summaries` 手上只有单号,按 job 查不到的那半数的单**九成套在归档表里**
#: ——已经挂上的关联单据当然都是走完的。没索引时那一句是每次开单倒扫整张归档表,而这张表只长不删。
serial: Mapped[str] = mapped_column(String(64), default="", nullable=False, index=True)
title: Mapped[str] = mapped_column(String(512), default="", nullable=False)
status: Mapped[str] = mapped_column(String(32), default="completed", nullable=False)
process: Mapped[str] = mapped_column(String(32), nullable=False, index=True)
process_name: Mapped[str] = mapped_column(String(255), default="", nullable=False)
process_alias: Mapped[str] = mapped_column(String(255), default="", nullable=False)
category: Mapped[str] = mapped_column(String(32), default="", nullable=False)
category_name: Mapped[str] = mapped_column(String(255), default="", nullable=False)
form: Mapped[str] = mapped_column(String(32), default="", nullable=False)
#: 抄自所属单据的 ``oa_work.design_snapshot``(办结归档那一刻一起搬过来)。
#: 没有这一列,一张单**办结之前**改流程改表单都影响不到它、**办结之后**回头打开
#: 归档详情却跟着新设计跑——同一条"发起即冻结"的口径在归档这道坎上断掉:环节改名、
#: 表单换字段、甚至流程被删,都会改写这张已经落定的单在界面上呈现的那一版图。
#: 空 = 这一单归档时还没这套机制(老归档单),照旧现读当前设计,升级不迁数据。
#: 口径见 :func:`app.engine.definition.for_work`。
design_snapshot: Mapped[str] = mapped_column(String(32), default="", nullable=False)
data: Mapped[JsonDict] = mapped_column(JsonDict, default=dict, nullable=False)
creator: Mapped[str] = mapped_column(String(32), default="", nullable=False)
creator_person: Mapped[str] = mapped_column(String(255), default="", nullable=False)
creator_identity: Mapped[str] = mapped_column(String(512), default="", nullable=False, index=True)
creator_identity_name: Mapped[str] = mapped_column(String(255), default="", nullable=False)
creator_unit: Mapped[str] = mapped_column(String(512), default="", nullable=False)
creator_unit_name: Mapped[str] = mapped_column(String(255), default="", nullable=False)
result: Mapped[str] = mapped_column(String(32), default="agree", nullable=False)
result_opinion: Mapped[str] = mapped_column(Text, default="", nullable=False)
current_activity_names: Mapped[str] = mapped_column(String(512), default="", nullable=False)
start_time: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
finish_time: Mapped[datetime] = mapped_column(DateTime, default=localnow, nullable=False, index=True)
expire_time: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
read: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
work_create_type: Mapped[str] = mapped_column(String(32), default="surface", nullable=False)
parent_work: Mapped[str] = mapped_column(String(32), default="", nullable=False)
parent_job: Mapped[str] = mapped_column(String(32), default="", nullable=False)
deleted: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
deleted_time: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
deleted_person: Mapped[str] = mapped_column(String(32), default="", nullable=False)
class Task(Base, TimestampMixin):
"""待办."""
__tablename__ = "oa_task"
__table_args__ = (
Index("idx_oa_task_identity_status", "identity", "status"),
Index("idx_oa_task_work", "work"),
Index("idx_oa_task_job_activity", "job", "activity"),
)
id: Mapped[str] = mapped_column(String(32), primary_key=True, default=new_id)
job: Mapped[str] = mapped_column(String(32), nullable=False)
work: Mapped[str] = mapped_column(String(32), nullable=False)
title: Mapped[str] = mapped_column(String(512), default="", nullable=False)
status: Mapped[str] = mapped_column(String(32), default="pending", nullable=False)
process: Mapped[str] = mapped_column(String(32), nullable=False, index=True)
process_name: Mapped[str] = mapped_column(String(255), default="", nullable=False)
category: Mapped[str] = mapped_column(String(32), default="", nullable=False)
category_name: Mapped[str] = mapped_column(String(255), default="", nullable=False)
serial: Mapped[str] = mapped_column(String(64), default="", nullable=False)
activity: Mapped[str] = mapped_column(String(32), nullable=False)
activity_name: Mapped[str] = mapped_column(String(255), default="", nullable=False)
activity_type: Mapped[str] = mapped_column(String(32), default="manual", nullable=False)
activity_token: Mapped[str] = mapped_column(String(512), default="", nullable=False)
activity_description: Mapped[str] = mapped_column(Text, default="", nullable=False)
person: Mapped[str] = mapped_column(String(32), default="", nullable=False)
identity: Mapped[str] = mapped_column(String(512), nullable=False)
identity_name: Mapped[str] = mapped_column(String(255), default="", nullable=False)
unit: Mapped[str] = mapped_column(String(512), default="", nullable=False)
unit_name: Mapped[str] = mapped_column(String(255), default="", nullable=False)
empower_from_identity: Mapped[str] = mapped_column(String(512), default="", nullable=False)
agent_from_identity: Mapped[str] = mapped_column(String(512), default="", nullable=False)
creator: Mapped[str] = mapped_column(String(32), default="", nullable=False)
creator_person: Mapped[str] = mapped_column(String(255), default="", nullable=False)
creator_identity: Mapped[str] = mapped_column(String(512), default="", nullable=False)
creator_unit: Mapped[str] = mapped_column(String(512), default="", nullable=False)
#: 抄自所属单据的 ``oa_work.creator_unit_name``:发起人发起那一刻所在部门的名字。
#: 待办自己的 ``unit_name`` 存的是**本环节处理人**的部门(建待办时从处理人的 org ref
#: 抄来),两者不是一回事——待办列表在「发起人」那一列下面要显示部门,只能认这一列。
creator_unit_name: Mapped[str] = mapped_column(String(255), default="", nullable=False)
prev_task_identity: Mapped[str] = mapped_column(String(512), default="", nullable=False)
prev_task_identity_list: Mapped[JsonList] = mapped_column(JsonList, default=list, nullable=False)
route_name: Mapped[str] = mapped_column(String(255), default="", nullable=False)
route_list: Mapped[JsonList] = mapped_column(JsonList, default=list, nullable=False)
route_name_list: Mapped[JsonList] = mapped_column(JsonList, default=list, nullable=False)
route_opinion_list: Mapped[JsonList] = mapped_column(JsonList, default=list, nullable=False)
route_name_disable: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
opinion: Mapped[str] = mapped_column(Text, default="", nullable=False)
media_opinion: Mapped[str] = mapped_column(Text, default="", nullable=False)
form: Mapped[str] = mapped_column(String(32), default="", nullable=False)
#: 抄自所属单据的 ``oa_work.design_snapshot``:待办是审批与超时扫到的最细一层,
#: 带上这一份就不必每条待办都按 ``work`` 再回查一趟单据(口径见 definition.for_work)。
design_snapshot: Mapped[str] = mapped_column(String(32), default="", nullable=False)
data_patch: Mapped[JsonDict] = mapped_column(JsonDict, default=dict, nullable=False)
first: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
act: Mapped[str] = mapped_column(String(32), default="create", nullable=False)
act_person: Mapped[str] = mapped_column(String(255), default="", nullable=False)
label: Mapped[str] = mapped_column(String(255), default="", nullable=False)
order_number: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
start_time: Mapped[datetime] = mapped_column(DateTime, default=localnow, nullable=False, index=True)
start_time_month: Mapped[str] = mapped_column(String(16), default="", nullable=False)
view_time: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
expire_time: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
expired: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
urge_time: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
urged: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
press_count: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
press_time: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
press_activity_token: Mapped[str] = mapped_column(String(512), default="", nullable=False)
pause: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
allow_rapid: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
add_task_from: Mapped[str] = mapped_column(String(32), default="", nullable=False)
class TaskCompleted(Base, TimestampMixin):
"""已办."""
__tablename__ = "oa_task_completed"
__table_args__ = (Index("idx_oa_task_completed_identity", "identity", "completed_time"),)
id: Mapped[str] = mapped_column(String(32), primary_key=True, default=new_id)
task: Mapped[str] = mapped_column(String(32), default="", nullable=False, index=True)
job: Mapped[str] = mapped_column(String(32), nullable=False, index=True)
work: Mapped[str] = mapped_column(String(32), nullable=False, index=True)
work_completed: Mapped[str] = mapped_column(String(32), default="", nullable=False)
title: Mapped[str] = mapped_column(String(512), default="", nullable=False)
completed: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
process: Mapped[str] = mapped_column(String(32), nullable=False, index=True)
process_name: Mapped[str] = mapped_column(String(255), default="", nullable=False)
category: Mapped[str] = mapped_column(String(32), default="", nullable=False)
category_name: Mapped[str] = mapped_column(String(255), default="", nullable=False)
serial: Mapped[str] = mapped_column(String(64), default="", nullable=False)
activity: Mapped[str] = mapped_column(String(32), nullable=False)
activity_name: Mapped[str] = mapped_column(String(255), default="", nullable=False)
activity_type: Mapped[str] = mapped_column(String(32), default="manual", nullable=False)
activity_token: Mapped[str] = mapped_column(String(512), default="", nullable=False)
current_activity_name: Mapped[str] = mapped_column(String(512), default="", nullable=False)
person: Mapped[str] = mapped_column(String(32), default="", nullable=False)
identity: Mapped[str] = mapped_column(String(512), nullable=False)
identity_name: Mapped[str] = mapped_column(String(255), default="", nullable=False)
unit: Mapped[str] = mapped_column(String(512), default="", nullable=False)
unit_name: Mapped[str] = mapped_column(String(255), default="", nullable=False)
empower_from_identity: Mapped[str] = mapped_column(String(512), default="", nullable=False)
empower_to_identity: Mapped[str] = mapped_column(String(512), default="", nullable=False)
creator: Mapped[str] = mapped_column(String(32), default="", nullable=False)
creator_person: Mapped[str] = mapped_column(String(255), default="", nullable=False)
creator_identity: Mapped[str] = mapped_column(String(512), default="", nullable=False)
creator_unit: Mapped[str] = mapped_column(String(512), default="", nullable=False)
prev_task_identity: Mapped[str] = mapped_column(String(512), default="", nullable=False)
prev_task_identity_list: Mapped[JsonList] = mapped_column(JsonList, default=list, nullable=False)
next_task_identity_list: Mapped[JsonList] = mapped_column(JsonList, default=list, nullable=False)
route_name: Mapped[str] = mapped_column(String(255), default="", nullable=False)
route_alias: Mapped[str] = mapped_column(String(255), default="", nullable=False)
opinion: Mapped[str] = mapped_column(Text, default="", nullable=False)
media_opinion: Mapped[str] = mapped_column(Text, default="", nullable=False)
# 审批意见随附的图片与文件,结构与批注一致(引用快照,字节在 MinIO)
attachments: Mapped[JsonList] = mapped_column(JsonList, default=list, nullable=False)
form: Mapped[str] = mapped_column(String(32), default="", nullable=False)
#: 抄自待办 / 单据的冻结设计:已办清单上「这一步还能不能撤回」要按**这张单当时那一版**
#: 环节配置判,否则中途改了流程,界面上给的按钮和引擎的答复会各说一套。
design_snapshot: Mapped[str] = mapped_column(String(32), default="", nullable=False)
#: 办这一步时改动过的表单字段:[{label, before, after}]。
#: 环节没配字段权限时表单默认可编辑,审批人改经办人填的内容是允许的,
#: 但改完必须看得见是谁改的、原来是什么,否则单据被人改过都查不出来。
form_changes: Mapped[JsonList] = mapped_column(JsonList, default=list, nullable=False)
start_time: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
completed_time: Mapped[datetime] = mapped_column(
DateTime, default=localnow, nullable=False, index=True
)
processing_type: Mapped[str] = mapped_column(String(32), default="normal", nullable=False)
act: Mapped[str] = mapped_column(String(32), default="create", nullable=False)
label: Mapped[str] = mapped_column(String(255), default="", nullable=False)
#: 替这一步收尾的人:只在**不是本人表态**的那些记录上有值(目前只有终止——引擎把当时
#: 还挂着的待办强行结掉,``identity`` 仍是那位没来得及表态的处理人,不写清楚就成了
#: 「部门主管自己终止了这张单」)。空 = 本人办的,界面上不多嘴。见 engine.terminate。
operator: Mapped[str] = mapped_column(String(512), default="", nullable=False)
operator_name: Mapped[str] = mapped_column(String(255), default="", nullable=False)
latest: Mapped[bool] = mapped_column(Boolean, default=True, nullable=False)
retract_time: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
press_count: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
press_time: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
view_time: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
expired: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
class WorkLog(Base, TimestampMixin):
"""流转日志 (工作从环节 A 通过路由 R 到达环节 B)."""
__tablename__ = "oa_work_log"
__table_args__ = (Index("idx_oa_work_log_work", "work", "arrived_time"),)
id: Mapped[str] = mapped_column(String(32), primary_key=True, default=new_id)
job: Mapped[str] = mapped_column(String(32), nullable=False, index=True)
work: Mapped[str] = mapped_column(String(32), nullable=False)
work_completed: Mapped[str] = mapped_column(String(32), default="", nullable=False)
completed: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
process: Mapped[str] = mapped_column(String(32), default="", nullable=False)
process_name: Mapped[str] = mapped_column(String(255), default="", nullable=False)
application: Mapped[str] = mapped_column(String(64), default="processplatform", nullable=False)
from_activity: Mapped[str] = mapped_column(String(32), default="", nullable=False)
from_activity_name: Mapped[str] = mapped_column(String(255), default="", nullable=False)
from_activity_type: Mapped[str] = mapped_column(String(32), default="", nullable=False)
from_activity_token: Mapped[str] = mapped_column(String(512), default="", nullable=False)
from_identity: Mapped[str] = mapped_column(String(512), default="", nullable=False)
from_identity_name: Mapped[str] = mapped_column(String(255), default="", nullable=False)
from_person_name: Mapped[str] = mapped_column(String(255), default="", nullable=False)
from_opinion: Mapped[str] = mapped_column(Text, default="", nullable=False)
from_time: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
arrived_activity: Mapped[str] = mapped_column(String(32), default="", nullable=False)
arrived_activity_name: Mapped[str] = mapped_column(String(255), default="", nullable=False)
arrived_activity_type: Mapped[str] = mapped_column(String(32), default="", nullable=False)
arrived_activity_token: Mapped[str] = mapped_column(String(512), default="", nullable=False)
arrived_time: Mapped[datetime] = mapped_column(DateTime, default=localnow, nullable=False)
route: Mapped[str] = mapped_column(String(32), default="", nullable=False)
route_name: Mapped[str] = mapped_column(String(255), default="", nullable=False)
type: Mapped[str] = mapped_column(String(32), default="normal", nullable=False)
connected: Mapped[bool] = mapped_column(Boolean, default=True, nullable=False)
go_back_from_activity: Mapped[str] = mapped_column(String(32), default="", nullable=False)
go_back_from_activity_name: Mapped[str] = mapped_column(String(255), default="", nullable=False)
go_back_from_activity_token: Mapped[str] = mapped_column(String(512), default="", nullable=False)
split_token: Mapped[str] = mapped_column(String(512), default="", nullable=False)
split_value: Mapped[str] = mapped_column(String(255), default="", nullable=False)
tickets: Mapped[JsonList] = mapped_column(JsonList, default=list, nullable=False)
class Read(Base, TimestampMixin):
"""待阅."""
__tablename__ = "oa_read"
__table_args__ = (
Index("idx_oa_read_identity", "identity", "view_time"),
# 同一人同一单同类型只留一条待阅,每次抄送都要按 work 捞一遍已有的那几条
# (``engine.create_reads``);办结搬档也按 work 整批取(``_finish_work``)。
# 没这一条就是每次抄送一次整表扫——``oa_read`` 和 ``oa_task`` 一样随使用长。
Index("idx_oa_read_work", "work"),
)
id: Mapped[str] = mapped_column(String(32), primary_key=True, default=new_id)
job: Mapped[str] = mapped_column(String(32), nullable=False, index=True)
work: Mapped[str] = mapped_column(String(32), nullable=False)
work_completed: Mapped[str] = mapped_column(String(32), default="", nullable=False)
completed: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
title: Mapped[str] = mapped_column(String(512), default="", nullable=False)
process: Mapped[str] = mapped_column(String(32), nullable=False, index=True)
process_name: Mapped[str] = mapped_column(String(255), default="", nullable=False)
category: Mapped[str] = mapped_column(String(32), default="", nullable=False)
serial: Mapped[str] = mapped_column(String(64), default="", nullable=False)
activity: Mapped[str] = mapped_column(String(32), default="", nullable=False)
activity_name: Mapped[str] = mapped_column(String(255), default="", nullable=False)
activity_token: Mapped[str] = mapped_column(String(512), default="", nullable=False)
current_activity_name: Mapped[str] = mapped_column(String(512), default="", nullable=False)
person: Mapped[str] = mapped_column(String(32), default="", nullable=False)
identity: Mapped[str] = mapped_column(String(512), nullable=False)
identity_name: Mapped[str] = mapped_column(String(255), default="", nullable=False)
unit: Mapped[str] = mapped_column(String(512), default="", nullable=False)
sender: Mapped[str] = mapped_column(String(512), default="", nullable=False)
creator_identity: Mapped[str] = mapped_column(String(512), default="", nullable=False)
#: 这张单的**发起人**是谁、他发起那一刻在哪个部门,建待阅时抄自所属单据
#: (口径同 ``oa_task.creator_person`` / ``oa_task.creator_unit_name``)。
#: 为什么不拿 ``sender`` 顶:``sender`` 说的是「谁把这一条递到我手上」,而环节上配的
#: 自动抄送规则把它写成**触发这次抄送的那位经手人**——最后一环批完、归档抄送当场发出,
#: 「发起人」那一列于是画成了最后一个审批人(2026-11-17 线上截图即此)。
creator_person: Mapped[str] = mapped_column(String(255), default="", nullable=False)
creator_unit_name: Mapped[str] = mapped_column(String(255), default="", nullable=False)
opinion: Mapped[str] = mapped_column(Text, default="", nullable=False)
start_time: Mapped[datetime] = mapped_column(DateTime, default=localnow, nullable=False)
# 待阅来源:cc 抄送 / share 分享 / comment 批注提醒
read_type: Mapped[str] = mapped_column(String(32), default="cc", nullable=False)
# 抄送需处理:收件人要填写处理意见并确认,只点开看不算处理完
requires_action: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
# 处理意见随附的图片与文件:只存引用快照,字节在 oa_attachment.storage 指向的对象里。
# 与批注同一套存法(见 ``engine.claim_attachments``),区别只在 type 那一格写的是 read。
attachments: Mapped[JsonList] = mapped_column(JsonList, default=list, nullable=False)
source_identity: Mapped[str] = mapped_column(String(512), default="", nullable=False)
handle_time: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
view_time: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
#: 本人**点开过**这一条(红点就此熄灭),但它还没登记已阅 / 没处理。
#: 待阅并入待办之后(2026-11),抄送/转发那一行也要有"读过没读过"那一枚红点,
#: 而 ``view_time`` 在这张表上是**已阅时刻**(``oa_read_completed.view_time`` NOT NULL、
#: 轨迹图上那句"已阅于…"、办结搬档都认它),不能拿来当"扫过一眼"用。两件事分两列:
#: 打开单据页给所有名下这一单的行盖上 ``seen_time``,其中不要求处理的那几条
#: 照旧当场登记已阅(搬进已阅档),要求处理的那几条留着等本人写处理意见。
seen_time: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
#: 这一条是不是「办结之后的转发」落出来的(``engine.forward_completed``)。
#: 来源那一格照旧写 ``read_type="cc"``——待阅列表、导出、筛选认的是 cc / share /
#: comment 那三种,转发与抄送在待阅里本就是同一种东西。这一列只补一个布尔:
#: 流程步骤要能分辨「环节配出来的抄送」与「发起人事后手工递过来的转发」,
#: 否则轨迹图上会把一次转发念成一次抄送。再抄/再转命中同一条时取并集
#: (见 ``engine._refresh_read``)——被抄过又被转发过的人,两种都算。
#: 老数据全是 False,等于「没转发过」,正是它从前应有的样子,不迁数据。
forwarded: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
class ReadCompleted(Base, TimestampMixin):
"""已阅."""
__tablename__ = "oa_read_completed"
__table_args__ = (Index("idx_oa_read_completed_identity", "identity", "view_time"),)
id: Mapped[str] = mapped_column(String(32), primary_key=True, default=new_id)
read: Mapped[str] = mapped_column(String(32), default="", nullable=False)
job: Mapped[str] = mapped_column(String(32), nullable=False, index=True)
work: Mapped[str] = mapped_column(String(32), nullable=False)
work_completed: Mapped[str] = mapped_column(String(32), default="", nullable=False)
completed: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
title: Mapped[str] = mapped_column(String(512), default="", nullable=False)
process: Mapped[str] = mapped_column(String(32), nullable=False, index=True)
process_name: Mapped[str] = mapped_column(String(255), default="", nullable=False)
category: Mapped[str] = mapped_column(String(32), default="", nullable=False)
serial: Mapped[str] = mapped_column(String(64), default="", nullable=False)
activity: Mapped[str] = mapped_column(String(32), default="", nullable=False)
activity_name: Mapped[str] = mapped_column(String(255), default="", nullable=False)
person: Mapped[str] = mapped_column(String(32), default="", nullable=False)
identity: Mapped[str] = mapped_column(String(512), nullable=False)
identity_name: Mapped[str] = mapped_column(String(255), default="", nullable=False)
unit: Mapped[str] = mapped_column(String(512), default="", nullable=False)
sender: Mapped[str] = mapped_column(String(512), default="", nullable=False)
creator_identity: Mapped[str] = mapped_column(String(512), default="", nullable=False)
#: 与 ``oa_read`` 同名的两格:登记已阅 / 办结搬档时整行带过来,
#: 已阅列表与导出里的「发起人」从此也有得读。
creator_person: Mapped[str] = mapped_column(String(255), default="", nullable=False)
creator_unit_name: Mapped[str] = mapped_column(String(255), default="", nullable=False)
opinion: Mapped[str] = mapped_column(Text, default="", nullable=False)
start_time: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
# 已阅侧同步保留抄送来源与是否需要处理,归档后还看得出是哪种待阅
read_type: Mapped[str] = mapped_column(String(32), default="cc", nullable=False)
requires_action: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
# 处理意见随附的图片与文件跟着这条已阅记录显示(待阅那一条登记已阅时整行搬过来)
attachments: Mapped[JsonList] = mapped_column(JsonList, default=list, nullable=False)
source_identity: Mapped[str] = mapped_column(String(512), default="", nullable=False)
handle_time: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
view_time: Mapped[datetime] = mapped_column(DateTime, default=localnow, nullable=False)
#: 与 ``oa_read.forwarded`` 同一件事:登记已阅时整行搬过来(见 ``engine.mark_read``),
#: 办结搬档那一条也一样带过来。归档之后回看「这单被转发给过谁」全靠它。
forwarded: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
class WorkComment(Base, TimestampMixin):
"""批注:不走流转的补充说明,可 @ 相关人(被 @ 的人收到待阅提醒)."""
__tablename__ = "oa_work_comment"
__table_args__ = (Index("idx_oa_work_comment_work", "work", "create_time"),)
id: Mapped[str] = mapped_column(String(32), primary_key=True, default=new_id)
job: Mapped[str] = mapped_column(String(32), default="", nullable=False, index=True)
work: Mapped[str] = mapped_column(String(32), nullable=False, index=True)
work_completed: Mapped[str] = mapped_column(String(32), default="", nullable=False)
completed: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
process: Mapped[str] = mapped_column(String(32), default="", nullable=False, index=True)
process_name: Mapped[str] = mapped_column(String(255), default="", nullable=False)
title: Mapped[str] = mapped_column(String(512), default="", nullable=False)
activity: Mapped[str] = mapped_column(String(32), default="", nullable=False)
activity_name: Mapped[str] = mapped_column(String(255), default="", nullable=False)
person: Mapped[str] = mapped_column(String(32), default="", nullable=False)
identity: Mapped[str] = mapped_column(String(512), default="", nullable=False)
identity_name: Mapped[str] = mapped_column(String(255), default="", nullable=False)
unit: Mapped[str] = mapped_column(String(512), default="", nullable=False)
content: Mapped[str] = mapped_column(Text, default="", nullable=False)
# 被 @ 的人:身份串 + 显示名,抄送提醒用
mentions: Mapped[JsonList] = mapped_column(JsonList, default=list, nullable=False)
mention_names: Mapped[JsonList] = mapped_column(JsonList, default=list, nullable=False)
# @ 的人是否需要处理(抄送需处理 / 无需处理同一个开关)
mention_action: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
order_number: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
# 批注随附的图片与文件:只存引用快照 [{id,name,extension,length,is_image}],
# 字节在 oa_attachment.storage 指向的 MinIO 对象里。
attachments: Mapped[JsonList] = mapped_column(JsonList, default=list, nullable=False)
class Attachment(Base, TimestampMixin):
__tablename__ = "oa_attachment"
# 每张单据办结时都要按 work 把它那几条附件标成已归档(``_finish_work`` 里的
# UPDATE),界面上按单列附件也按 work 筛(``api.support.list_attachments``)。
# process / job / business_id 三列都建了索引,偏偏真正拿来定位这一单附件的
# work 没有,那条 UPDATE 于是每办结一张单整表扫一次。
__table_args__ = (Index("idx_oa_attachment_work", "work"),)
#: ``type`` 里"跟着某条批注/审批意见/处理意见一起发出去"的几种取值。这类附件不进单据的
#: 附件清单,而是跟着那条记录一起显示(见 api.support.list_attachments)。
KIND_COMMENT = "comment"
KIND_OPINION = "opinion"
KIND_READ = "read"
KIND_LINKED = (KIND_COMMENT, KIND_OPINION, KIND_READ)
id: Mapped[str] = mapped_column(String(32), primary_key=True, default=new_id)
name: Mapped[str] = mapped_column(String(512), nullable=False)
extension: Mapped[str] = mapped_column(String(32), default="", nullable=False)
storage: Mapped[str] = mapped_column(String(512), default="", nullable=False)
length: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
type: Mapped[str] = mapped_column(String(32), default="attachment", nullable=False)
text: Mapped[str] = mapped_column(Text, default="", nullable=False)
application: Mapped[str] = mapped_column(String(64), default="processplatform", nullable=False)
process: Mapped[str] = mapped_column(String(32), default="", nullable=False, index=True)
job: Mapped[str] = mapped_column(String(32), default="", nullable=False, index=True)
work: Mapped[str] = mapped_column(String(32), default="", nullable=False)
activity: Mapped[str] = mapped_column(String(32), default="", nullable=False)
activity_name: Mapped[str] = mapped_column(String(255), default="", nullable=False)
activity_token: Mapped[str] = mapped_column(String(512), default="", nullable=False)
person: Mapped[str] = mapped_column(String(32), default="", nullable=False)
person_name: Mapped[str] = mapped_column(String(255), default="", nullable=False)
completed: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
work_completed: Mapped[str] = mapped_column(String(32), default="", nullable=False)
order_number: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
# 认领这条附件的业务记录 id(批注 id / 已办 id),顺带当"已被认领"的标记用
business_id: Mapped[str] = mapped_column(String(64), default="", nullable=False, index=True)
class Draft(Base, TimestampMixin):
__tablename__ = "oa_draft"
id: Mapped[str] = mapped_column(String(32), primary_key=True, default=new_id)
title: Mapped[str] = mapped_column(String(512), default="", nullable=False)
process: Mapped[str] = mapped_column(String(32), nullable=False, index=True)
process_name: Mapped[str] = mapped_column(String(255), default="", nullable=False)
category: Mapped[str] = mapped_column(String(32), default="", nullable=False)
category_name: Mapped[str] = mapped_column(String(255), default="", nullable=False)
form: Mapped[str] = mapped_column(String(32), default="", nullable=False)
data: Mapped[JsonDict] = mapped_column(JsonDict, default=dict, nullable=False)
#: 草稿阶段就占下的单号(只在流程配了「存草稿就生成编号」时非空)。
#: 存着它是为了同一张草稿反复保存只占一个号,发起时引擎照原样接过去。
#: 同 oa_work.serial:占号与认领那几步按号等值查,草稿表也只会一直长
serial: Mapped[str] = mapped_column(String(64), default="", nullable=False, index=True)
person: Mapped[str] = mapped_column(String(32), nullable=False, index=True)
person_name: Mapped[str] = mapped_column(String(255), default="", nullable=False)
identity: Mapped[str] = mapped_column(String(512), default="", nullable=False)
unit: Mapped[str] = mapped_column(String(512), default="", nullable=False)
class Notification(Base, TimestampMixin):
__tablename__ = "oa_notification"
id: Mapped[str] = mapped_column(String(32), primary_key=True, default=new_id)
type: Mapped[str] = mapped_column(String(32), default="task", nullable=False)
title: Mapped[str] = mapped_column(String(512), default="", nullable=False)
body: Mapped[str] = mapped_column(Text, default="", nullable=False)
job: Mapped[str] = mapped_column(String(32), default="", nullable=False)
work: Mapped[str] = mapped_column(String(32), default="", nullable=False)
task: Mapped[str] = mapped_column(String(32), default="", nullable=False)
process: Mapped[str] = mapped_column(String(32), default="", nullable=False)
identity: Mapped[str] = mapped_column(String(512), nullable=False, index=True)
person: Mapped[str] = mapped_column(String(32), default="", nullable=False)
sender: Mapped[str] = mapped_column(String(255), default="", nullable=False)
read: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
read_time: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
class SerialNumber(Base, TimestampMixin):
"""流程编号计数器."""
__tablename__ = "oa_serial_number"
__table_args__ = (UniqueConstraint("process", "period", name="uq_oa_serial_process_period"),)
id: Mapped[str] = mapped_column(String(32), primary_key=True, default=new_id)
process: Mapped[str] = mapped_column(String(32), nullable=False)
period: Mapped[str] = mapped_column(String(16), nullable=False)
prefix: Mapped[str] = mapped_column(String(64), default="", nullable=False)
value: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
length: Mapped[int] = mapped_column(Integer, default=6, nullable=False)
class OperationLog(Base, TimestampMixin):
"""谁在什么时候动了哪条数据。只增不改,也没有保留期,所以只会一直长。
两个索引都是给「操作日志」那一页准备的:它每次打开都按人筛一遍、按时间倒序翻一页,
还要拿同样的条件再 COUNT 一次。这张表过去一个二级索引都没有,那些查询全是全表扫
加 filesort,日志攒到几万条就是肉眼可见的卡。
"""
__tablename__ = "oa_operation_log"
__table_args__ = (
# 带数据范围的人(只看得见自己或本部门那几个人)走这条:先按人定位再按时间倒序读
Index("idx_oa_operation_log_person_time", "person", "create_time"),
# 管理员不带人的条件时只有时间这一条可用,别让「倒序翻一页」去扫全表
Index("idx_oa_operation_log_time", "create_time"),
)
id: Mapped[str] = mapped_column(String(32), primary_key=True, default=new_id)
action: Mapped[str] = mapped_column(String(64), nullable=False)
target: Mapped[str] = mapped_column(String(255), default="", nullable=False)
detail: Mapped[str] = mapped_column(Text, default="", nullable=False)
person: Mapped[str] = mapped_column(String(32), default="", nullable=False)
person_name: Mapped[str] = mapped_column(String(255), default="", nullable=False)
identity: Mapped[str] = mapped_column(String(512), default="", nullable=False)
ip: Mapped[str] = mapped_column(String(64), default="", nullable=False)
class HubSyncRun(Base):
"""一次「同步 Hub 组织人员」的执行记录。
既给页面上的「上次同步结果 / 同步历史」用,也给定时任务当幂等凭据:凌晨那趟
只认 ``trigger='schedule'`` 的当天记录,避免重启后又补跑一次;增量轮询(``changes``)
每次拉流水也记一条,历史上能看出"哪几分钟没拉到"。
"""
__tablename__ = "oa_hub_sync_run"
__table_args__ = (
# 这张表按同步频率一直长:增量轮询(``changes``)每拉一次就记一行,开发环境十几天
# 就攒了四百多行,正式环境一年就是上万行。而读它的每一处都是「按 trigger 挑出
# 定时/手动/增量这几类,再按开始时间倒序取最近一条」——定时任务的幂等判断每次都
# 要问一次。过去只有 trigger 与 status 两个单列索引,按时间取最近一条永远是全表扫
# 加 filesort,扫的行数跟着同步次数一起涨。
Index("idx_oa_hub_sync_run_trigger_time", "trigger", "started_at"),
# 同步历史页问「最近一趟跑过没有」时不带 trigger,那只能靠时间这一条
Index("idx_oa_hub_sync_run_time", "started_at"),
)
TRIGGER_SCHEDULE = "schedule"
TRIGGER_MANUAL = "manual"
#: 增量轮询(GET /api/v1/auth/directory/changes)跑的一趟
TRIGGER_CHANGES = "changes"
STATUS_SUCCESS = "success"
STATUS_PARTIAL = "partial"
STATUS_SKIPPED = "skipped"
STATUS_FAILED = "failed"
#: 这一趟正在跑。进程被 ``kill -9`` / 容器重启会把它永远留在库里,
#: 界面上就是一直转圈的"进行中",收尾交给 ``hub_sync.reap_stale_runs``。
STATUS_RUNNING = "running"
#: 没跑完就结束:管理员手动终止,或后端重启 / 崩溃后被判成残留
STATUS_CANCELLED = "cancelled"
id: Mapped[str] = mapped_column(String(32), primary_key=True, default=new_id)
trigger: Mapped[str] = mapped_column(String(16), default=TRIGGER_SCHEDULE, nullable=False)
status: Mapped[str] = mapped_column(String(16), default=STATUS_SUCCESS, nullable=False, index=True)
started_at: Mapped[datetime] = mapped_column(timestamp3(), default=localnow, nullable=False)
finished_at: Mapped[datetime | None] = mapped_column(timestamp3(), nullable=True)
duration_ms: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
total_users: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
returned_users: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
created: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
updated: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
offboarded: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
units_created: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
units_updated: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
units_offboarded: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
permission_version: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
member_limit: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
# 人员清单是否被 member_limit 截断(截断时只写不撤)。
truncated: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
# 本次拉全量用的是哪种凭证:directory_key / token / account / anonymous。
credential: Mapped[str] = mapped_column(String(16), default="", nullable=False)
operator: Mapped[str] = mapped_column(String(64), default="", nullable=False)
operator_name: Mapped[str] = mapped_column(String(255), default="", nullable=False)
# 增量轮询专用:本批处理完之后停在哪个游标、这趟一共落了变更条数
cursor_seq: Mapped[int] = mapped_column(u_bigint(), default=0, nullable=False)
changes_applied: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
message: Mapped[str] = mapped_column(Text, default="", nullable=False)
# 下面三项以前只出现在 message 的文本里,而 message 只留 2000 字:改名、僵尸账号让位
# 这类「必须有人去核对」的动作一旦排在提示末尾就被截掉,同步历史里只剩一个笼统的
# 「更新 N 人」,看完不知道该核对什么。计数单独成列,明细另存一份有界 JSON。
#: 这一趟真正换掉登录名的人数(Hub 改了账号名,见 ``_plan_account_renames``)
renamed: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
#: 已停用、且这一趟完整清单里查无此人的同步账号让出登录名的个数(``_retire_lost_accounts``)
reclaimed: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
#: Hub 换了 ``organization_id`` 之后按「编码 + 名称」认回原部门的个数(``_sync_units``)
units_rebound: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
#: 有界明细:改名前后对照、让位的账号、认回的部门、熔断与号码计数、提示原文(见 ``run_details``)
details: Mapped[JsonDict] = mapped_column(JsonDict, default=dict, nullable=False)
class RefreshToken(Base, TimestampMixin):
__tablename__ = "oa_refresh_token"
id: Mapped[str] = mapped_column(String(32), primary_key=True, default=new_id)
person: Mapped[str] = mapped_column(String(32), nullable=False, index=True)
token_hash: Mapped[str] = mapped_column(String(128), unique=True, nullable=False)
expires_at: Mapped[datetime] = mapped_column(DateTime, nullable=False)
revoked: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
# 最近一次活动时间(登录 / 续期 / 心跳都算):空闲超时看它,不看创建时间,
# 否则活跃用户也会被刷新令牌的总有效期提前踢下线
last_used_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
class SsoHandoff(Base, TimestampMixin):
"""统一门户免登回调发出的一次性短码(``code``)。
后端回调 ``GET /api/v1/auth/sso/callback`` 验完 Hub 票据,不把令牌拼进地址栏,
而是发一条短码 302 回前端;前端拿它调 ``POST /api/v1/auth/sso/exchange`` 换本地会话。
一条短码只许兑一次、60 秒即失效,而且必须配着回调当场下发的 HttpOnly Cookie
(``oa_sso_handoff``)一起交回来 —— 兑换串只存哈希,地址栏那条短码被人翻出来
也换不走会话,因为它不在别人的浏览器里。
"""
__tablename__ = "oa_sso_handoff"
id: Mapped[str] = mapped_column(String(32), primary_key=True, default=new_id)
#: 短码本身的 SHA-256,明文只在回调那一次 302 里出现
code_hash: Mapped[str] = mapped_column(String(128), unique=True, nullable=False)
person: Mapped[str] = mapped_column(String(32), nullable=False, index=True)
#: 配套 Cookie 值的哈希:兑换时必须一并带上,把这条短码钉死在发起跳转的浏览器上
bind_hash: Mapped[str] = mapped_column(String(128), default="", nullable=False)
#: 免登进去要落到哪个站内路径(空 = 由前端决定兜底页)
redirect: Mapped[str] = mapped_column(String(255), default="", nullable=False)
#: 登录日志的说明文字,回调时算好,真正兑换到会话那一刻才落库
detail: Mapped[str] = mapped_column(String(255), default="", nullable=False)
expires_at: Mapped[datetime] = mapped_column(DateTime, nullable=False, index=True)
used_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
class EmbedTicket(Base, TimestampMixin):
"""嵌页面免登发出的一次性短码(``service/embed.py``,设计见 docs/embed-page-field-design.md §3.1)。
方向与 :class:`SsoHandoff` 相反:那边是门户发票、本系统兑换;这边是本系统发票、
被嵌进来的那个系统拿短码调 ``POST /api/v1/embed/tickets/verify`` 换身份。
抄的是同一套分寸——库里只存哈希、几十秒即废、用一次就烧、绑死在一个人和一个源上。
地址上那条短码放在 ``#`` 之后,所以它不进服务端访问日志、也不跟着 Referer 出站。
"""
__tablename__ = "oa_embed_ticket"
id: Mapped[str] = mapped_column(String(32), primary_key=True, default=new_id)
#: 短码明文的 SHA-256;明文只在返回给浏览器的那一次里出现
code_hash: Mapped[str] = mapped_column(String(128), unique=True, nullable=False)
#: 换出去的是谁:当前**看单的人**,不是发起人。对方系统的日志与权限都按这个人算
person: Mapped[str] = mapped_column(String(32), nullable=False, index=True)
#: 哪一条注册记录(``oa_data_source.code``)发的,验票时按它取密钥
source: Mapped[str] = mapped_column(String(64), default="", nullable=False, index=True)
#: 发出去时给的那份参数指纹:验票时一并回给调用方,用来对"要打开的那一单"有没有被换过
args_digest: Mapped[str] = mapped_column(String(128), default="", nullable=False)
#: 从哪张单打开的,只作留痕与排查,不参与判定
work: Mapped[str] = mapped_column(String(32), default="", nullable=False)
expires_at: Mapped[datetime] = mapped_column(DateTime, nullable=False, index=True)
used_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
class EmbedSession(Base, TimestampMixin):
"""一趟"嵌进来的第三方页面"与这张单之间的**可对答凭据**(``service/embed_session.py``)。
设计见 ``docs/embed-action-design.md``。为什么短码不够用:``oa_embed_ticket`` 是 60 秒、
用一次即烧的一次性凭据,它回答的只有"现在站在屏幕前的是谁"这一个问题。而真正要能对上话
的三件事都发生在**验票之后**:
* 发起页还没保存就退出去了——第三方那边按哪一号开的草稿,第二天回来还认不认;
* 第三方那一页操作完了——它怎么知道自己看的是 OA 上哪一格、哪一次打开;
* 第三方自己审完了——它凭什么说"张三那一步通过了",OA 凭什么信。
这三件都要一个**跨调用稳定**的东西指代"那一趟打开",而短码在第一步就被烧掉了。
这一张表就是那个东西:发一次、活几小时、绑死在 (哪条源, 哪个人, 哪张单/哪份草稿,
哪个环节, 哪条待办) 上,能做哪几件事写在 :attr:`scopes` 里,**不在清单里的一件事也做不了**。
与短码同样的分寸:库里只存令牌哈希、明文只在返回那一次出现、到期即废、可提前作废。
差别只在存活期与用途——短码证明"是谁",这一条证明"是哪一趟"。
"""
__tablename__ = "oa_embed_session"
#: 用 :func:`new_time_id` 而不是 :func:`new_id`:下面 :func:`find_open` 与
#: :func:`latest_open` 都是按 id 倒序取"最近在开着的那一趟",主键是随机 uuid 时
#: 那句倒序只是随机挑一条——一个人开着两趟(比如两张单上同一格)时,回写会落到
#: 任意那一趟上,而两边日志都写着成功。长度与 ``new_id()`` 一样,主键列不用改。
id: Mapped[str] = mapped_column(String(32), primary_key=True, default=new_time_id)
#: 会话令牌明文的 SHA-256;明文只出现在发它那一次(回给浏览器 / 回给验票方)
token_hash: Mapped[str] = mapped_column(String(128), unique=True, nullable=False)
#: **预受理号**:给第三方当自己那边草稿的主键用。为什么要单独一列而不是直接用令牌——
#: 令牌是凭据(泄露了要能作废),预受理号是**话题**(要能印在对方工单上、能打电话念出来)。
#: 未保存的发起页上这是双方唯一共有的标识:那时 OA 还没有单据号可给
prekey: Mapped[str] = mapped_column(String(32), unique=True, nullable=False, index=True)
#: 哪一条注册记录(``oa_data_source.code``)发的;回写时按它取密钥,也防 A 系统兑 B 系统的会话
source: Mapped[str] = mapped_column(String(64), default="", nullable=False, index=True)
#: 这一趟是谁打开的。**回写就以这个人的身份办**,所以它必须是发起打开的那个人本人
person: Mapped[str] = mapped_column(String(32), default="", nullable=False, index=True)
#: 是哪一格(表单上那个 ``embed`` 字段的 key)发的。回写要按它把**回填白名单**再算一遍:
#: 白名单是配在格子上的,会话不带格子名就等于第三方交什么后端都只能先收下、
#: 等前端去筛——筛在那一头不是闸
field: Mapped[str] = mapped_column(String(64), default="", nullable=False)
#: 从哪张单打开(发起页还没保存时为空)
work: Mapped[str] = mapped_column(String(32), default="", nullable=False, index=True)
job: Mapped[str] = mapped_column(String(32), default="", nullable=False)
#: 打开时看的是哪个环节;``decide`` 那一档要靠它把"该办哪一条待办"定位到唯一一条
activity: Mapped[str] = mapped_column(String(64), default="", nullable=False)
#: 那个人在这个环节上的待办号;待办被办掉之后这一条就是"已处理"的对答凭据
task: Mapped[str] = mapped_column(String(32), default="", nullable=False)
#: 打开时挂的那份草稿号。发起页上"没保存就返回"最常见的一条路就是草稿还没落库,
#: 所以它也可能是空——那时唯一能把两次打开认成同一趟的,只有 :attr:`prekey`
draft: Mapped[str] = mapped_column(String(32), default="", nullable=False, index=True)
#: 发起页上顺手占住的那个单据号(``serial_config.at=create`` 那档预留的)。
#: 带着它,第三方那边的草稿能直接按 OA 的**正式单号**建档,不用二次对号
serial: Mapped[str] = mapped_column(String(64), default="", nullable=False)
#: 这一趟能做哪几件事。取值见 ``service/embed_session.SCOPES``,
#: 由**后端**按"注册表那条源配了什么 + 这一格配了什么 + 当前这个人这个环节动得动哪几格"算出来,
#: 前端与第三方都只是被告知,谁都不许自己申报
scopes: Mapped[JsonList] = mapped_column(JsonList, default=list, nullable=False)
#: 打开那一刻的参数指纹。第三方回写时把它算过的值一并交回来,指纹不一致就说明
#: 它拿着 A 单的结果去写了 B 单(对接期真出过这种事:页面复用、忘了重新拿短码)
args_digest: Mapped[str] = mapped_column(String(128), default="", nullable=False)
#: ``decide`` / ``prefill`` 最近一次落地的内容,只作留痕与对答,不再参与判定
result: Mapped[JsonDict] = mapped_column(JsonDict, default=dict, nullable=False)
#: 这一趟**已经从对面拿到的那条编辑页地址**(没挂免登短码的那一份)。
#: 存这一列的理由只有一句话:对面那个接口是"每调一次建一张页"的。同一趟第二次打开时
#: 若还去问一次,第三方那边就多出一张没人认领的草稿,屏幕上看见的就是"每开一次是新页"
#: ——用户在生产上撞到的正是这个。有这一列在,"对面已经建过页了"第一次变成 OA 自己
#: 答得出的问题(:func:`service.embed_session.held_links`)。
#: 存**没挂短码**那一份:短码 60 秒就废、用一次即烧,每次打开都要现发一条再挂上去
url_edit: Mapped[str] = mapped_column(String(2048), default="", nullable=False)
#: 同一趟的**查看页地址**(对面一次回两条时才有)。留空 = 这一趟只有一条地址
#: 两列都跟着这一趟活:参数换了(:attr:`args_digest` 变了)就作废重来,会话过期或
#: 被放弃也一起翻篇,下一趟该问新的(判据见 ``service/embed_session.py:stamp_links``)
url_view: Mapped[str] = mapped_column(String(2048), default="", nullable=False)
#: 同一趟从**同一次**响应里拿到的其它那几条链接(``{"print": "https://..."}``)。
#: 编辑页与查看页仍各占一列:那两列是排查"对面到底建了几张页"时最先看的两眼,
#: 得能被眼睛直接看见;后面登记的那些数量不定,摊成一列。作废口径与上面两条同一条
url_extra: Mapped[JsonDict] = mapped_column(JsonDict, default=dict, nullable=False)
#: 同一趟顺手带回的那几个只读值(``{"对方单号": "RE-20261027-004"}``)。
#: 存这一列的理由与上面那几列一模一样:**沿用而不是再问一次**——不然第二个人打开时
#: 一次接口都不打,链接有得沿用、那行灰字却是空的,屏幕上就是一句撒谎的话
link_meta: Mapped[JsonDict] = mapped_column(JsonDict, default=dict, nullable=False)
#: 这一趟最终有没有真的变成一张单:第三方从自己那边发起时回填,OA 发起页据此说
#: "ERP 那边已经发起了(单号 X)"而不是再建一张重复的
claim_job: Mapped[str] = mapped_column(String(32), default="", nullable=False)
claim_serial: Mapped[str] = mapped_column(String(64), default="", nullable=False)
claim_time: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
#: 最近一次回写落地的时间:配合 ``[embed] callback_dedupe`` 那段静默期压重复提交
last_callback: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
status: Mapped[str] = mapped_column(String(16), default="open", nullable=False)
expires_at: Mapped[datetime] = mapped_column(DateTime, nullable=False, index=True)
closed_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
STATUS_OPEN = "open"
STATUS_CLOSED = "closed"
STATUS_EXPIRED = "expired"
STATUS_CLAIMED = "claimed"
class EmbedPage(Base, TimestampMixin):
"""**这张单**在第三方系统里那一页的账(``oa_embed_page``)。
设计见 ``docs/embed-action-design.md`` §2.1.1。它存在的全部理由是一句被生产验证过两次的话:
**对面那一页属于这张单,不属于哪个人的一趟**。
:class:`EmbedSession` 把 ``url_edit`` / ``url_view`` 记在会话上,而会话按
``(哪条源, 哪个人, 哪张单)`` 认——发起人在发起页点开那一格时建了第一页,走到审批环节
换了一个人,``find_open`` 按 ``person`` 查不到,于是又打一次那个"每调一次建一张页"的
接口,第三方系统里就此多出第二张、第三张草稿,每一张都没人认领、也没人删得掉
(``abandon`` 那三条腿只认发起页占下的那个号)。用户那句
「后面的节点难道不应该看的就是第一次返回的那个查看页面么」问的就是这个。
所以这一张表把"那一页"从会话里搬出来,记在它真正的主人身上:
* **一行 = 一张单上的一个格子对应的那一页**,按 ``(source, field, work)`` 唯一;
* **活得和这张单一样长**:没有 ``expires_at``,单删了跟着删(见
``engine._WORK_TRACE_MODELS``)。会话两小时就过期,而一张单要走上几天、经过好几个环节,
拿会话的存活期当"对面那一页还在不在"的尺子,本身就拿错了;
* **参数指纹只作留痕,不作作废的理由**:对面那一页是按这张单建的,而
``{auto:…}`` 那类取值(当前看单的人)本来每次都不同;值变了就重新建页,等于
把这一档在每个环节都作废一次;
* **它不是凭据**:令牌、``scopes``、该办哪条待办仍然全在会话上,每人一趟各判各的。
这一行只回答"对面那一页是哪几条地址、是谁第一次建出来的"。
谁都能沿用,谁都不许改写:``service/embed_session.stamp_links`` 只补空着的那几格,
与会话上那两条同一条分寸——同一张单上这一格指的必须始终是同一张页。
"""
__tablename__ = "oa_embed_page"
__table_args__ = (
#: 一张单、一条源、一个格子 = 对面只有一页。这条唯一约束就是"只有一页"这件事本身
UniqueConstraint("source", "field", "work", name="uq_embed_page_anchor"),
Index("idx_embed_page_work", "work"),
)
#: 用 :func:`new_time_id`:排查"这张单上先后建出过几页"时要能按创建顺序读出先后
id: Mapped[str] = mapped_column(String(32), primary_key=True, default=new_time_id)
#: 哪一条注册记录(``oa_data_source.code``)建的这一页
source: Mapped[str] = mapped_column(String(64), default="", nullable=False, index=True)
#: 表单上哪一格(``type=embed`` 字段的 key)建的。同一张单上两个格子嵌的是两个系统里
#: 两个不同的页面,各记一行,谁也不许沿用谁的那条地址
field: Mapped[str] = mapped_column(String(64), default="", nullable=False)
#: **这张单**(``oa_work.id``)。发起页上还没单的那一刻没有这一行——那时双方唯一共有的
#: 标识还是会话上的预受理号,等这张单真的建出来、那一趟认到单据之后,地址才落到这一行上
work: Mapped[str] = mapped_column(String(32), default="", nullable=False)
#: 给人看的单号,只为排查时一眼认得出是哪张单(判据一律看 :attr:`work`)
job: Mapped[str] = mapped_column(String(32), default="", nullable=False)
#: 这张单的流程编号(``serial_config.at=create`` 那一档占下的那个号)。第三方那边按号
#: 记东西的居多,而这一行第一次落库时那张单可能还没排上号(发起页上就建了页),
#: 所以它和 :attr:`prekey` 一样是"认到单据之后补上"的那一列
serial: Mapped[str] = mapped_column(String(64), default="", nullable=False)
#: 第一次建这一页那一趟的预受理号。第三方那边那张草稿是按它建的,后续节点上的人拿到的是
#: 自己的号,凭这一列才答得出"这一屏其实是 PRE-第一次那个号在对面建的那一页"
prekey: Mapped[str] = mapped_column(String(32), default="", nullable=False)
#: 是谁、在哪个环节第一次让对面建出这一页的。界面上那句"这一屏不是刚新建的"要念的就是它
person: Mapped[str] = mapped_column(String(32), default="", nullable=False)
person_name: Mapped[str] = mapped_column(String(100), default="", nullable=False)
activity: Mapped[str] = mapped_column(String(64), default="", nullable=False)
#: 那一刻所在环节的名字。界面上那句灰字念的是"由谁在哪个环节建出来",环节名比 id 有用
activity_name: Mapped[str] = mapped_column(String(255), default="", nullable=False)
#: 与会话上那四列同形状:**没挂免登短码**的那几条地址(短码 60 秒就废,每次打开现发)
url_edit: Mapped[str] = mapped_column(String(2048), default="", nullable=False)
url_view: Mapped[str] = mapped_column(String(2048), default="", nullable=False)
url_extra: Mapped[JsonDict] = mapped_column(JsonDict, default=dict, nullable=False)
link_meta: Mapped[JsonDict] = mapped_column(JsonDict, default=dict, nullable=False)
#: 建这一页那一刻的参数指纹。**只作留痕**(见类文档第三条约法):值变了不重新建页,
#: 但"这一页当初是按哪一组值建出来的"得说得出,那是联调期第一个要问的问题
args_digest: Mapped[str] = mapped_column(String(128), default="", nullable=False)
#: 这一页被沿用过几次、最近一次是什么时候。对面那张草稿到底有没有人在看,
#: 靠这两列答,不必再去猜第三方那边的日志
opens: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
last_open: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
class NodeDecision(Base, TimestampMixin):
"""第三方服务端对某个环节的一次「表态」(``service/node_approve.py``)。
设计见 ``docs/node-open-approve-design.md``。它是环节审批对外接口
(``POST /open/nodes/{流程编号}[/{activity}]/decide``——环节那一段可省,OA 自己认)
的落账处,两种确认模式共用这一行:
* ``confirm`` 模式(默认):第三方把话说好,行停在 ``staged``——审批页上亮一条横幅,
处理人点头才走引擎;驳了就 ``rejected``,到期没人理就 ``expired``。
* ``auto`` 模式:当场办掉,行直接落 ``handled``,``response`` 里存着那次调用的响应
快照——同一个 ``bizKey`` 再来一次,原样回第一份,重试不会变成重复表态。
幂等记在 ``(app, work, activity, biz_key)`` 上:同一趟的两次表态只认一次,
与嵌入会话「没发成的一分钟内不重发」是同一条分寸,只是这里的账跨调用。
"""
__tablename__ = "oa_node_decision"
__table_args__ = (
UniqueConstraint("app", "work", "activity", "biz_key", name="uq_node_decision_biz"),
Index("idx_node_decision_task", "task"),
Index("idx_node_decision_work", "work", "status"),
Index("idx_node_decision_status", "status", "expires_at"),
)
STATUS_STAGED = "staged"
STATUS_HANDLED = "handled"
STATUS_REJECTED = "rejected"
STATUS_EXPIRED = "expired"
id: Mapped[str] = mapped_column(String(32), primary_key=True, default=new_id)
#: 哪个应用调的(应用编码,不是密钥):出事先认钥匙再认人
app: Mapped[str] = mapped_column(String(64), default="", nullable=False)
app_name: Mapped[str] = mapped_column(String(255), default="", nullable=False)
#: 表态挂在 (哪张单, 哪个环节, 当时那条待办) 上。待办号记下来是因为转办 / 加签之后
#: 手上那条可能换过,横幅与留痕要能指出当时说的是哪一条
work: Mapped[str] = mapped_column(String(32), default="", nullable=False)
job: Mapped[str] = mapped_column(String(32), default="", nullable=False)
serial: Mapped[str] = mapped_column(String(64), default="", nullable=False)
process: Mapped[str] = mapped_column(String(32), default="", nullable=False)
process_name: Mapped[str] = mapped_column(String(255), default="", nullable=False)
activity: Mapped[str] = mapped_column(String(32), default="", nullable=False)
activity_name: Mapped[str] = mapped_column(String(255), default="", nullable=False)
task: Mapped[str] = mapped_column(String(32), default="", nullable=False)
task_identity: Mapped[str] = mapped_column(String(64), default="", nullable=False)
task_identity_name: Mapped[str] = mapped_column(String(255), default="", nullable=False)
#: 对方原话的结论词(没归一化前那份)与翻出来的结论(agree / refuse / submit):
#: 「他们说的」与「我们办的」要能各看一眼,翻错了才查得出来
decision: Mapped[str] = mapped_column(String(191), default="", nullable=False)
kind: Mapped[str] = mapped_column(String(16), default="", nullable=False)
#: 表态那一刻匹到的这条出口。确认模式下人点头时再验一次它还存不存在——
#: 图改了的单不该按旧图走
route: Mapped[str] = mapped_column(String(255), default="", nullable=False)
opinion: Mapped[str] = mapped_column(Text, default="", nullable=False)
#: 表态顺手带进来的表单值(已按环节白名单筛过)
data: Mapped[JsonDict] = mapped_column(JsonDict, default=dict, nullable=False)
biz_key: Mapped[str] = mapped_column(String(191), default="", nullable=False)
status: Mapped[str] = mapped_column(String(16), default=STATUS_STAGED, nullable=False)
#: auto 模式那次调用的响应快照:同一个 bizKey 的第二次调用原样回这一份
response: Mapped[JsonDict] = mapped_column(JsonDict, default=dict, nullable=False)
#: 人确认 / 驳回的那一下(confirm 模式)
confirm_by: Mapped[str] = mapped_column(String(32), default="", nullable=False)
confirm_name: Mapped[str] = mapped_column(String(255), default="", nullable=False)
confirm_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
confirm_note: Mapped[str] = mapped_column(String(512), default="", nullable=False)
expires_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
class SystemSetting(Base, TimestampMixin):
__tablename__ = "oa_system_setting"
key: Mapped[str] = mapped_column(String(128), primary_key=True)
value: Mapped[JsonDict] = mapped_column(JsonDict, default=dict, nullable=False)
description: Mapped[str] = mapped_column(String(512), default="", nullable=False)
# ---------------------------------------------------------------------------
# 大模型接入 (系统设置 -> 大模型接入)
# One row = one callable model endpoint: an official API, a company gateway, or a
# self-hosted inference server. Which vendor it is only drives the form defaults
# and the help text; ``protocol`` is what actually decides how the request goes
# out, so a gateway that speaks someone else's wire format stays configurable.
# ---------------------------------------------------------------------------
class AiProvider(Base, TimestampMixin):
"""一条大模型服务商接入配置。
``provider`` 是服务商目录里的键(清单见 ``app.llmconfig.PROVIDERS``);
``protocol`` 决定报文格式(``openai`` / ``anthropic`` / ``gemini`` /
``ollama`` / ``azure_openai``),新建时跟着服务商带出,网关协议不一样就单独改它。
``api_key`` 只进不出:接口从不回显明文,界面上只看 ``api_key_set``,
与 MinIO SecretKey、Hub 目录密钥是同一套约定。
"""
__tablename__ = "oa_ai_provider"
__table_args__ = (UniqueConstraint("name", name="uq_oa_ai_provider_name"),)
id: Mapped[str] = mapped_column(String(32), primary_key=True, default=new_id)
name: Mapped[str] = mapped_column(String(128), nullable=False)
provider: Mapped[str] = mapped_column(String(64), default="custom", nullable=False, index=True)
protocol: Mapped[str] = mapped_column(String(32), default="openai", nullable=False)
#: 接口前缀,直接拼在后面的就是各家路径(openai 类填到 /v1,anthropic 填站点根)
base_url: Mapped[str] = mapped_column(String(512), default="", nullable=False)
api_key: Mapped[str] = mapped_column(String(512), default="", nullable=False)
#: Azure 的 api-version、Gemini 的 API 版本;其余服务商留空
api_version: Mapped[str] = mapped_column(String(64), default="", nullable=False)
#: 可选模型清单,界面上的下拉就列这些;留空表示手填模型名
models: Mapped[JsonList] = mapped_column(JsonList, default=list, nullable=False)
default_model: Mapped[str] = mapped_column(String(191), default="", nullable=False)
temperature: Mapped[float] = mapped_column(Float, default=0.7, nullable=False)
max_tokens: Mapped[int] = mapped_column(Integer, default=1024, nullable=False)
timeout_seconds: Mapped[int] = mapped_column(Integer, default=60, nullable=False)
#: 网关要求的额外请求头(例如 ``{"X-Stage": "prod"}``)
extra_headers: Mapped[JsonDict] = mapped_column(JsonDict, default=dict, nullable=False)
#: 随请求一起带走的各家私有参数(例如 ``{"top_p": 0.9, "thinking": {"type": "disabled"}}``)
extra_body: Mapped[JsonDict] = mapped_column(JsonDict, default=dict, nullable=False)
system_prompt: Mapped[str] = mapped_column(Text, default="", nullable=False)
description: Mapped[str] = mapped_column(Text, default="", nullable=False)
enabled: Mapped[bool] = mapped_column(Boolean, default=True, nullable=False)
#: 全局默认接入(业务侧没点名用哪条时用它);库里最多一条
is_default: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
order_number: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
# 最近一次「测试连通」的结果,界面上直接显示,省得翻日志
last_test_status: Mapped[str] = mapped_column(String(16), default="", nullable=False)
last_test_message: Mapped[str] = mapped_column(Text, default="", nullable=False)
last_test_model: Mapped[str] = mapped_column(String(191), default="", nullable=False)
last_test_ms: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
last_test_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
last_test_by: Mapped[str] = mapped_column(String(255), default="", nullable=False)
creator: Mapped[str] = mapped_column(String(32), default="", nullable=False)
creator_name: Mapped[str] = mapped_column(String(255), default="", nullable=False)
# ---------------------------------------------------------------------------
# Portal / 首页 (O2OA: x_cms_assemble_control + x_hotpic_assemble_control +
# x_meeting_assemble_control + x_calendar_assemble_control +
# x_file_assemble_control)
# The O2OA desktop 首页 stitches six panels together; these tables back the four
# content sources it pulls from besides the workflow surface API.
# ---------------------------------------------------------------------------
class CmsChannel(Base, TimestampMixin):
"""信息栏目 -- CMS column, e.g. 公司通知公告 / 新闻动态."""
__tablename__ = "oa_cms_channel"
id: Mapped[str] = mapped_column(String(32), primary_key=True, default=new_id)
name: Mapped[str] = mapped_column(String(255), nullable=False)
alias: Mapped[str] = mapped_column(String(255), default="", nullable=False)
description: Mapped[str] = mapped_column(Text, default="", nullable=False)
order_number: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
enabled: Mapped[bool] = mapped_column(Boolean, default=True, nullable=False)
class CmsDocument(Base, TimestampMixin):
"""信息/新闻 -- a published article; ``is_hot`` rows feed the 热点新闻 carousel."""
__tablename__ = "oa_cms_document"
id: Mapped[str] = mapped_column(String(32), primary_key=True, default=new_id)
channel: Mapped[str] = mapped_column(String(32), default="", nullable=False, index=True)
channel_name: Mapped[str] = mapped_column(String(255), default="", nullable=False)
title: Mapped[str] = mapped_column(String(512), nullable=False)
summary: Mapped[str] = mapped_column(Text, default="", nullable=False)
body: Mapped[str] = mapped_column(Text, default="", nullable=False)
cover: Mapped[str] = mapped_column(String(512), default="", nullable=False)
#: 「以附件为正文」:正文不再手打,而是直接看/下载这份附件(见 CmsAttachment)
body_attachment: Mapped[str] = mapped_column(String(32), default="", nullable=False)
author: Mapped[str] = mapped_column(String(255), default="", nullable=False)
author_identity: Mapped[str] = mapped_column(String(512), default="", nullable=False)
status: Mapped[str] = mapped_column(String(32), default="published", nullable=False, index=True)
is_hot: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False, index=True)
pinned: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
allow_anonymous: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
views: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
publish_time: Mapped[datetime | None] = mapped_column(DateTime, nullable=True, index=True)
stop_time: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
class CmsAttachment(Base, TimestampMixin):
"""资讯附件 -- 正文之外挂在信息上的文件,制度类常常就是"附件即正文".
与 :class:`Attachment` 分表存放:那张表整张都是围着流程转的(process / job /
work / activity / completed),资讯附件一样字段都没有,混在一起等于给每个
流程查询塞进一批死行;权限口径也不同——流程附件看的是单据归属,这里看的是
``portal:manage`` 加信息本身的可见性。跟 :class:`PortalFile` 一样,门户自己的
文件自己建表。
``document`` 为空 = 还没被任何信息认领(新建信息时先传后存),由上传接口按
``STALE_MINUTES`` 顺手回收。字节走 ``portal`` 这个用途,也就是跟封面图同一条
路由:配置齐全进 MinIO,否则按 ``fallback_to_local`` 落本地磁盘。
"""
__tablename__ = "oa_cms_attachment"
id: Mapped[str] = mapped_column(String(32), primary_key=True, default=new_id)
document: Mapped[str] = mapped_column(String(32), default="", nullable=False, index=True)
name: Mapped[str] = mapped_column(String(512), nullable=False)
extension: Mapped[str] = mapped_column(String(32), default="", nullable=False)
#: 存储位置串(``minio://`` / ``local://``),换后端不用洗库
storage: Mapped[str] = mapped_column(String(512), default="", nullable=False)
length: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
order_number: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
creator: Mapped[str] = mapped_column(String(32), default="", nullable=False)
creator_name: Mapped[str] = mapped_column(String(255), default="", nullable=False)
downloads: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
class Meeting(Base, TimestampMixin):
"""会议 -- 首页「我的会议 / 会议邀请」面板的数据源."""
__tablename__ = "oa_meeting"
id: Mapped[str] = mapped_column(String(32), primary_key=True, default=new_id)
title: Mapped[str] = mapped_column(String(512), nullable=False)
content: Mapped[str] = mapped_column(Text, default="", nullable=False)
location: Mapped[str] = mapped_column(String(512), default="", nullable=False)
link: Mapped[str] = mapped_column(String(512), default="", nullable=False)
number: Mapped[str] = mapped_column(String(64), default="", nullable=False)
password: Mapped[str] = mapped_column(String(64), default="", nullable=False)
start_time: Mapped[datetime] = mapped_column(DateTime, nullable=False, index=True)
end_time: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
unit: Mapped[str] = mapped_column(String(512), default="", nullable=False)
unit_name: Mapped[str] = mapped_column(String(255), default="", nullable=False)
creator: Mapped[str] = mapped_column(String(32), default="", nullable=False)
creator_person: Mapped[str] = mapped_column(String(255), default="", nullable=False)
creator_identity: Mapped[str] = mapped_column(String(512), default="", nullable=False)
status: Mapped[str] = mapped_column(String(32), default="scheduled", nullable=False, index=True)
class MeetingAttendee(Base, TimestampMixin):
"""会议参与人,``status`` 承载邀请的接受/拒绝语义."""
__tablename__ = "oa_meeting_attendee"
__table_args__ = (UniqueConstraint("meeting", "identity", name="uq_oa_meeting_identity"),)
id: Mapped[str] = mapped_column(String(32), primary_key=True, default=new_id)
meeting: Mapped[str] = mapped_column(String(32), nullable=False, index=True)
identity: Mapped[str] = mapped_column(String(512), nullable=False, index=True)
person: Mapped[str] = mapped_column(String(32), default="", nullable=False)
person_name: Mapped[str] = mapped_column(String(255), default="", nullable=False)
unit_name: Mapped[str] = mapped_column(String(255), default="", nullable=False)
role: Mapped[str] = mapped_column(String(32), default="attendee", nullable=False)
status: Mapped[str] = mapped_column(String(32), default="pending", nullable=False, index=True)
answer_time: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
class Schedule(Base, TimestampMixin):
"""日程 -- 首页右侧日程面板(月历 + 当日列表 + 今日计数)."""
__tablename__ = "oa_schedule"
id: Mapped[str] = mapped_column(String(32), primary_key=True, default=new_id)
title: Mapped[str] = mapped_column(String(512), nullable=False)
content: Mapped[str] = mapped_column(Text, default="", nullable=False)
location: Mapped[str] = mapped_column(String(512), default="", nullable=False)
start_time: Mapped[datetime] = mapped_column(DateTime, nullable=False, index=True)
end_time: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
all_day: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
color: Mapped[str] = mapped_column(String(32), default="", nullable=False)
owner: Mapped[str] = mapped_column(String(512), nullable=False, index=True)
owner_person: Mapped[str] = mapped_column(String(32), default="", nullable=False)
owner_name: Mapped[str] = mapped_column(String(255), default="", nullable=False)
shared_identities: Mapped[list] = mapped_column(MutableList.as_mutable(JSON), default=list, nullable=False)
remind: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
class PortalFile(Base, TimestampMixin):
"""网盘文件 -- 首页「网盘文件」面板,与流程附件共用磁盘目录."""
__tablename__ = "oa_file"
id: Mapped[str] = mapped_column(String(32), primary_key=True, default=new_id)
name: Mapped[str] = mapped_column(String(512), nullable=False)
extension: Mapped[str] = mapped_column(String(32), default="", nullable=False)
storage: Mapped[str] = mapped_column(String(512), default="", nullable=False)
length: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
folder: Mapped[str] = mapped_column(String(32), default="", nullable=False, index=True)
owner: Mapped[str] = mapped_column(String(512), nullable=False, index=True)
owner_person: Mapped[str] = mapped_column(String(32), default="", nullable=False)
owner_name: Mapped[str] = mapped_column(String(255), default="", nullable=False)
unit_name: Mapped[str] = mapped_column(String(255), default="", nullable=False)
shared_identities: Mapped[list] = mapped_column(MutableList.as_mutable(JSON), default=list, nullable=False)
downloads: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
# ---------------------------------------------------------------------------
# 存储回收:删记录时对象存储正好连不上,不能只留一行日志就当作没事
#
# ``storage_gc.drop_unless_referenced()`` 删不掉时在这张表里留一条,等后端回来了
# 再补删(状态页、审计脚本、下一次成功回收都会顺手重试)。没有这张表,MinIO 抖一次
# 就意味着桶里多一个再也没人认领的对象——数据库里的引用已经随业务记录一起没了。
# ---------------------------------------------------------------------------
class StoragePendingDelete(Base, TimestampMixin):
"""待补删对象 -- 业务记录已删,但对象存储那一刻删不掉的文件."""
__tablename__ = "oa_storage_pending_delete"
id: Mapped[str] = mapped_column(String(32), primary_key=True, default=new_id)
#: 位置串(``minio://`` / ``local://``),与业务表里存的是同一个写法
uri: Mapped[str] = mapped_column(String(512), nullable=False, index=True)
#: 它是干什么的(封面 / 资讯附件 / 流程附件……),只给排障的人看一眼
label: Mapped[str] = mapped_column(String(64), default="", nullable=False)
error: Mapped[str] = mapped_column(String(512), default="", nullable=False)
attempts: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
# ---------------------------------------------------------------------------
# 平台化底座:跨进程租约 / 消息渠道 / 开放平台
#
# 这一节的存在理由都是同一句话:**没有开发平台、只有站内信、单进程底座**这三件事
# 在客户现场迟早一起撞上,而它们需要的都是"配置存在库里 + 投递留痕 + 可重试"这一套。
# ---------------------------------------------------------------------------
class WorkerLease(Base, TimestampMixin):
"""跨进程租约 -- 多副本部署时"同一件事同一时刻只该有一个进程做"。
底座原本是单进程 uvicorn,进程内一把 ``threading.Lock`` 就够;运维一旦加
``--workers N`` 或起两个副本,"只有我会跑调度"这个假设就同时失效,同一条写回报文
会被两个进程各发一遍(上游两张凭证)。租约放库里而不是放进程内变量,才谈得上跨进程。
用**租约**而不是心跳:过期即可被接管,进程被 ``kill -9`` 不需要谁来清理残留。
"""
__tablename__ = "oa_worker_lease"
__table_args__ = (Index("idx_worker_lease_expiry", "expires_at"),)
#: 任务名:目前只有 ``scheduler``(后台调度主循环)。建表与初始化数据不用这张表——
#: 那张时候这张表还不存在,用的是 MySQL 命名锁,见 ``app/main.py: _startup``
name: Mapped[str] = mapped_column(String(64), primary_key=True)
#: 持有者标识:主机名 + 进程号,界面上要能看出是哪一台哪一个进程
holder: Mapped[str] = mapped_column(String(128), default="", nullable=False)
expires_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
taken_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
#: 续租次数:判断"是不是同一个进程一直占着",也是排查抖动的第一手数据
renewals: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
class NotifyChannel(Base, TimestampMixin):
"""消息渠道 -- 站内信之外,把人话送到邮箱和群机器人。
配置面刻意压到三件事:**发到哪**(SMTP 账号或机器人地址)、**发什么事**(``events``
勾选)、**以什么身份发**(签名密钥 / 发件人)。收件人不再单独配:站内信发给谁,
这一路就发给谁,邮箱地址从用户账号上取,账号没邮箱就在投递记录里写明跳过原因——
"配了渠道却不知道该发给谁"是这类功能最常见的失败方式。
"""
__tablename__ = "oa_notify_channel"
__table_args__ = (
UniqueConstraint("code", name="uq_notify_channel_code"),
Index("idx_notify_channel_kind", "kind", "enabled"),
)
KIND_EMAIL = "email"
KIND_DINGTALK = "dingtalk"
KIND_FEISHU = "feishu"
KIND_WECOM = "wecom"
#: 自定义 HTTP:自己接企业微信自建应用、钉钉工作通知、内部短信网关都走这一条
KIND_WEBHOOK = "webhook"
#: 统一身份 Hub 代发企业微信应用消息(对接文档 9.6):本系统不持有企微密钥,
#: 收件人按 Hub 账号解析,点开的免登也回到现成的 ``/api/v1/auth/sso/callback``
KIND_HUB_WECOM = "hub_wecom"
KINDS = (KIND_EMAIL, KIND_DINGTALK, KIND_FEISHU, KIND_WECOM, KIND_WEBHOOK, KIND_HUB_WECOM)
#: 需要 SMTP 参数的种类
SMTP_KINDS = (KIND_EMAIL,)
#: 需要回调地址的种类
URL_KINDS = (KIND_DINGTALK, KIND_FEISHU, KIND_WECOM, KIND_WEBHOOK)
#: 地址与密钥都不在渠道上、跟着统一身份配置走的种类
HUB_KINDS = (KIND_HUB_WECOM,)
id: Mapped[str] = mapped_column(String(32), primary_key=True, default=new_id)
code: Mapped[str] = mapped_column(String(64), nullable=False)
name: Mapped[str] = mapped_column(String(255), nullable=False)
kind: Mapped[str] = mapped_column(String(16), default=KIND_EMAIL, nullable=False)
enabled: Mapped[bool] = mapped_column(Boolean, default=True, nullable=False)
#: 订阅的通知事件(与 ``oa_notification.type`` 同一套取值:task / press / read / completed / expire …)
events: Mapped[list] = mapped_column(JsonList, default=list, nullable=False)
#: 渠道参数:SMTP(host/port/user/password/from) / 机器人 URL/secret /
#: Hub 代发(msgtype/with_link/title_limit/**receiver**:收件人按哪一列认,见
#: ``service/channels.py`` 的 ``HUB_RECEIVER_FIELDS``);密钥只进不出
config: Mapped[JsonDict] = mapped_column(JsonDict, default=dict, nullable=False)
#: 正文模板(可选):留空用系统默认文案;支持 {title} {body} {url} {person}
text_template: Mapped[str] = mapped_column(String(512), default="", nullable=False)
timeout_seconds: Mapped[int] = mapped_column(Integer, default=10, nullable=False)
retries: Mapped[int] = mapped_column(Integer, default=3, nullable=False)
remark: Mapped[str] = mapped_column(Text, default="", nullable=False)
creator: Mapped[str] = mapped_column(String(32), default="", nullable=False)
creator_name: Mapped[str] = mapped_column(String(255), default="", nullable=False)
last_sent_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
last_error: Mapped[str] = mapped_column(String(512), default="", nullable=False)
class NotifyDelivery(Base, TimestampMixin):
"""一次渠道投递的留痕与重试队列 -- 与发件箱同理:先落库再发,失败按退避重来。
邮件和群机器人都会抖。把它们当"调用失败就丢"的旁路,用户的感受就是"OA 从来不通知我",
而排错的人什么都看不到。
"""
__tablename__ = "oa_notify_delivery"
__table_args__ = (
Index("idx_notify_due", "status", "next_attempt_at"),
Index("idx_notify_identity", "identity", "create_time"),
Index("idx_notify_channel", "channel", "status"),
)
STATUS_PENDING = "pending"
STATUS_SENDING = "sending"
STATUS_SUCCESS = "success"
STATUS_FAILED = "failed"
#: 重试次数用满
STATUS_DEAD = "dead"
#: 没发出去的正常情形(这个人没有邮箱 / 这个事件没订阅),与失败分开统计
STATUS_SKIPPED = "skipped"
STATUSES = (STATUS_PENDING, STATUS_SENDING, STATUS_SUCCESS, STATUS_FAILED, STATUS_DEAD, STATUS_SKIPPED)
STATUS_OPEN = (STATUS_PENDING, STATUS_FAILED)
id: Mapped[str] = mapped_column(String(32), primary_key=True, default=new_time_id)
channel: Mapped[str] = mapped_column(String(64), default="", nullable=False)
kind: Mapped[str] = mapped_column(String(16), default="", nullable=False)
type: Mapped[str] = mapped_column(String(32), default="", nullable=False)
identity: Mapped[str] = mapped_column(String(512), default="", nullable=False)
person: Mapped[str] = mapped_column(String(32), default="", nullable=False)
person_name: Mapped[str] = mapped_column(String(255), default="", nullable=False)
#: 投递目标(邮箱地址 / 群机器人 URL);机器人地址带 access_token,界面上一律打码
target: Mapped[str] = mapped_column(String(512), default="", nullable=False)
#: ``target`` 这一串是按哪一列取来的(``user_id`` / ``account``),只有走统一身份
#: Hub 的渠道才写。收件人标识现在是渠道上可配的一项,光看一串数字分不清是
#: Hub 主键还是账号;人删了要重发、界面要说清"这条发给了谁的哪个号",都靠这一列。
#: 升级前的老记录留空,读的一路按值猜(纯数字只可能是主键)。
target_field: Mapped[str] = mapped_column(String(16), default="", nullable=False)
title: Mapped[str] = mapped_column(String(512), default="", nullable=False)
body: Mapped[str] = mapped_column(Text, default="", nullable=False)
job: Mapped[str] = mapped_column(String(32), default="", nullable=False)
work: Mapped[str] = mapped_column(String(32), default="", nullable=False)
task: Mapped[str] = mapped_column(String(32), default="", nullable=False)
process: Mapped[str] = mapped_column(String(32), default="", nullable=False)
#: 对应的站内信 id:同一条消息两条链路能对上
notification: Mapped[str] = mapped_column(String(32), default="", nullable=False)
status: Mapped[str] = mapped_column(String(16), default=STATUS_PENDING, nullable=False)
attempts: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
next_attempt_at: Mapped[datetime] = mapped_column(DateTime, default=localnow_second, nullable=False)
sent_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
last_error: Mapped[str] = mapped_column(Text, default="", nullable=False)
response: Mapped[JsonDict] = mapped_column(JsonDict, default=dict, nullable=False)
ms: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
class OpenApp(Base, TimestampMixin):
"""开放平台应用 -- 给外部系统一把可控的钥匙,而不是共享一个管理员账号。
没有这一层时的常态是:对方要接口,运维建一个真实员工账号给他,密码写进对方
的配置文件里,权限是他自己在本系统界面里点出来的那一套,出事连"谁在调"都说不清。
应用凭证解决的是**可回收**(停用即失效,不用改密码)与**可归责**(每条调用记到应用)。
"""
__tablename__ = "oa_open_app"
__table_args__ = (
UniqueConstraint("code", name="uq_open_app_code"),
UniqueConstraint("app_key", name="uq_open_app_key"),
)
id: Mapped[str] = mapped_column(String(32), primary_key=True, default=new_id)
code: Mapped[str] = mapped_column(String(64), nullable=False)
name: Mapped[str] = mapped_column(String(255), nullable=False)
enabled: Mapped[bool] = mapped_column(Boolean, default=True, nullable=False)
app_key: Mapped[str] = mapped_column(String(64), nullable=False)
#: 只存哈希:库被读到、备份被拷走,都换不出一把能用的密钥(与登录口令同一口径)
secret_hash: Mapped[str] = mapped_column(String(255), nullable=False)
#: 界面上认钥匙用的尾号提示,例如 ``a1b2****f9``
secret_hint: Mapped[str] = mapped_column(String(32), default="", nullable=False)
#: 授权范围(``work:read`` / ``work:write`` / ``task:read`` / ``task:write`` / ``process:read``)
scopes: Mapped[list] = mapped_column(JsonList, default=list, nullable=False)
#: 每分钟调用上限,0 = 不限;挡的是对方脚本写飞了,不是挡业务
rate_limit_qpm: Mapped[int] = mapped_column(Integer, default=300, nullable=False)
#: 访问令牌有效期(秒):默认 2 小时,够跑一轮批处理又不至于长期有效
token_ttl_seconds: Mapped[int] = mapped_column(Integer, default=7200, nullable=False)
remark: Mapped[str] = mapped_column(Text, default="", nullable=False)
creator: Mapped[str] = mapped_column(String(32), default="", nullable=False)
creator_name: Mapped[str] = mapped_column(String(255), default="", nullable=False)
last_used_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
class OpenToken(Base):
"""开放平台发出去的访问令牌 -- 存哈希、带过期,停用它所属的应用就一起作废。
用不透明令牌而不是自签 JWT:多副本不需要共享签名密钥,更重要的是**能吊销**。
对方系统被拖库时,第一件事是希望"立刻让那把钥匙失效"。
"""
__tablename__ = "oa_open_token"
__table_args__ = (Index("idx_open_token_app", "app", "expires_at"),)
token_hash: Mapped[str] = mapped_column(String(64), primary_key=True)
app: Mapped[str] = mapped_column(String(64), default="", nullable=False)
scopes: Mapped[list] = mapped_column(JsonList, default=list, nullable=False)
expires_at: Mapped[datetime] = mapped_column(DateTime, nullable=False)
create_time: Mapped[datetime] = mapped_column(DateTime, default=localnow_second, nullable=False)
class OpenWebhook(Base, TimestampMixin):
"""事件订阅 -- 单据发生关键变化时,本系统主动推一条给外部。
与「写回模板」(``oa_integration``)的分工:写回是**业务凭证**,报文格式由上游
定、发错要冲销;事件订阅是**通知**,信封格式由本系统定,丢了重推即可。两者都走
"同一事务入队 → 后台投递 → 退避重试 → 死信喊人",但表分开,因为对账口径完全不同。
"""
__tablename__ = "oa_open_webhook"
__table_args__ = (UniqueConstraint("code", name="uq_open_webhook_code"),)
id: Mapped[str] = mapped_column(String(32), primary_key=True, default=new_id)
code: Mapped[str] = mapped_column(String(64), nullable=False)
name: Mapped[str] = mapped_column(String(255), nullable=False)
enabled: Mapped[bool] = mapped_column(Boolean, default=True, nullable=False)
url: Mapped[str] = mapped_column(String(512), default="", nullable=False)
#: HMAC-SHA256 签名密钥;对方用同一个密钥校验 X-Unisoa-Signature
secret: Mapped[str] = mapped_column(String(128), default="", nullable=False)
events: Mapped[list] = mapped_column(JsonList, default=list, nullable=False)
#: 只推这些流程;空 = 全部
processes: Mapped[list] = mapped_column(JsonList, default=list, nullable=False)
#: 要不要带表单数据。默认关:事件里塞整份表单等于把业务数据复制给每一个订阅方
send_data: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
timeout_seconds: Mapped[int] = mapped_column(Integer, default=10, nullable=False)
retries: Mapped[int] = mapped_column(Integer, default=5, nullable=False)
remark: Mapped[str] = mapped_column(Text, default="", nullable=False)
creator: Mapped[str] = mapped_column(String(32), default="", nullable=False)
creator_name: Mapped[str] = mapped_column(String(255), default="", nullable=False)
last_sent_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
last_status: Mapped[str] = mapped_column(String(16), default="", nullable=False)
last_error: Mapped[str] = mapped_column(String(512), default="", nullable=False)
class OpenEvent(Base, TimestampMixin):
"""事件投递队列 -- 一条订阅一次事件一行,投递结果、重试、签名都记在这里。"""
__tablename__ = "oa_open_event"
__table_args__ = (
# idem 只做查重与排查,**不建唯一键**:入队发生在业务事务里,撞唯一键会把
# 用户那次"办结"一起回滚掉。事件推送重复一次只是多看一条通知,不值得这个代价。
Index("idx_open_event_idem", "idem"),
Index("idx_open_event_due", "status", "next_attempt_at"),
Index("idx_open_event_job", "job", "id"),
)
STATUS_PENDING = "pending"
STATUS_SENDING = "sending"
STATUS_SUCCESS = "success"
STATUS_FAILED = "failed"
STATUS_DEAD = "dead"
STATUS_UNKNOWN = "unknown"
STATUSES = (STATUS_PENDING, STATUS_SENDING, STATUS_SUCCESS, STATUS_FAILED, STATUS_DEAD, STATUS_UNKNOWN)
STATUS_OPEN = (STATUS_PENDING, STATUS_FAILED)
#: 按 id 排序即入队先后(见 ``new_time_id``):同一张单严格有序
id: Mapped[str] = mapped_column(String(32), primary_key=True, default=new_time_id)
webhook: Mapped[str] = mapped_column(String(64), default="", nullable=False)
event: Mapped[str] = mapped_column(String(32), default="", nullable=False)
job: Mapped[str] = mapped_column(String(32), default="", nullable=False)
work: Mapped[str] = mapped_column(String(32), default="", nullable=False)
serial: Mapped[str] = mapped_column(String(64), default="", nullable=False)
title: Mapped[str] = mapped_column(String(512), default="", nullable=False)
process: Mapped[str] = mapped_column(String(32), default="", nullable=False)
activity: Mapped[str] = mapped_column(String(32), default="", nullable=False)
payload: Mapped[JsonDict] = mapped_column(JsonDict, default=dict, nullable=False)
idem: Mapped[str] = mapped_column(String(191), default="", nullable=False)
status: Mapped[str] = mapped_column(String(16), default=STATUS_PENDING, nullable=False)
attempts: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
next_attempt_at: Mapped[datetime] = mapped_column(DateTime, default=localnow_second, nullable=False)
attempt_started_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
sent_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
last_error: Mapped[str] = mapped_column(Text, default="", nullable=False)
response: Mapped[JsonDict] = mapped_column(JsonDict, default=dict, nullable=False)
ms: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
#: 影子模式(没真发出去):与发件箱同一口径,别让人把样例当成对方已收到
shadowed: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
class OpenCall(Base):
"""开放接口调用留痕 -- 谁用哪把钥匙调了哪个接口、返回了什么。
有了它才有"开发平台"该有的三件事:**限流**(按应用数最近一分钟的调用数)、
**归责**(对方说"你们接口给我返回错了"时能翻出那一次)、**清理**(90 天前的记录删掉)。
不复用 ``oa_operation_log``:那张表没有按应用统计的索引,而且业务操作日志和机器
调用混在一起,两边的保留期与查看的人都不一样。
"""
__tablename__ = "oa_open_call"
__table_args__ = (
Index("idx_open_call_app", "app", "create_time"),
Index("idx_open_call_time", "create_time"),
)
id: Mapped[str] = mapped_column(String(32), primary_key=True, default=new_id)
app: Mapped[str] = mapped_column(String(64), default="", nullable=False)
app_name: Mapped[str] = mapped_column(String(255), default="", nullable=False)
method: Mapped[str] = mapped_column(String(8), default="", nullable=False)
path: Mapped[str] = mapped_column(String(255), default="", nullable=False)
status_code: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
#: 业务返回码(本系统统一信封里的 code),与 HTTP 状态分开看
code: Mapped[str] = mapped_column(String(32), default="", nullable=False)
error: Mapped[str] = mapped_column(String(512), default="", nullable=False)
#: 令牌是从哪把钥匙换来的:只存前 8 位,够对上一次会话,泄露了也换不回什么
token_hint: Mapped[str] = mapped_column(String(32), default="", nullable=False)
ip: Mapped[str] = mapped_column(String(64), default="", nullable=False)
ms: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
create_time: Mapped[datetime] = mapped_column(DateTime, default=localnow_second, nullable=False)