unis-oa/backend/app/models.py

2285 lines
132 KiB
Python
Raw 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_identity`` / ``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 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]
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`` 在两张表之间绕环(``oa_identity.unit_id`` 同样是裸 BIGINT)。
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"),
# 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)
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)
last_login_at: Mapped[datetime | None] = mapped_column(timestamp3(), nullable=True)
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]
)
identities: Mapped[list["Identity"]] = relationship(
"Identity", back_populates="person", cascade="all, delete-orphan"
)
# --- 派生字段:来自 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 Identity(Base, TimestampMixin):
"""A person acting inside a unit -- O2OA "身份"."""
__tablename__ = "oa_identity"
__table_args__ = (
UniqueConstraint("person_id", "name", name="uq_oa_identity_person_name"),
)
id: Mapped[str] = mapped_column(String(32), primary_key=True, default=new_id)
name: Mapped[str] = mapped_column(String(255), nullable=False)
person_id: Mapped[int] = mapped_column(
u_bigint(), ForeignKey("users.id", ondelete="CASCADE"), nullable=False, index=True
)
person_name: Mapped[str] = mapped_column(String(255), default="", nullable=False)
unit_id: Mapped[int | None] = mapped_column(u_bigint(), nullable=True, index=True)
unit_name: Mapped[str] = mapped_column(String(255), default="", nullable=False)
unit_path: Mapped[str] = mapped_column(String(512), default="", nullable=False)
distinguished_name: Mapped[str] = mapped_column(
String(512), unique=True, nullable=False, index=True
)
parent_org: Mapped[str] = mapped_column(String(512), default="", nullable=False)
is_default: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
person: Mapped["User"] = relationship("User", back_populates="identities")
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``,而且上游挂了
表单照样打得开,选项停在最后一次同步那份。
"""
__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`` 是联动带出的附加值(单价、负责人、库存…)。"""
__tablename__ = "oa_dict_item"
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)
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"),
)
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)
PROVIDER_HTTP = "http"
PROVIDER_MOCK = "mock"
PROVIDER_PROCESS = "process"
PROVIDERS = (PROVIDER_HTTP, PROVIDER_MOCK, PROVIDER_PROCESS)
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)
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)
trigger_event: Mapped[str] = mapped_column(String(24), default=EVENT_COMPLETED, nullable=False)
#: trigger_event=activity 时的环节 id
event_key: Mapped[str] = mapped_column(String(32), default="", 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"),
)
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)
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 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)
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 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)
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)
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)
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)
duration: Mapped[int] = mapped_column(Integer, default=0, 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"),)
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)
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)
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)
duration: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
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)
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)
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)
#: 办这一步时改动过的表单字段:[{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
)
duration: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
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)
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)
duration: Mapped[int] = mapped_column(Integer, default=0, 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"),)
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)
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)
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)
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)
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)
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)
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"
#: ``type`` 里"跟着某条批注/审批意见一起发出去"的几种取值。这类附件不进单据的
#: 附件清单,而是跟着那条记录一起显示(见 api.support.list_attachments)。
KIND_COMMENT = "comment"
KIND_OPINION = "opinion"
KIND_LINKED = (KIND_COMMENT, KIND_OPINION)
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)
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):
__tablename__ = "oa_operation_log"
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"
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"
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, index=True)
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)
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 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)
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 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)
# ---------------------------------------------------------------------------
# 平台化底座:跨进程租约 / 消息渠道 / 开放平台
#
# 这一节的存在理由都是同一句话:**没有开发平台、只有站内信、单进程底座**这三件事
# 在客户现场迟早一起撞上,而它们需要的都是"配置存在库里 + 投递留痕 + 可重试"这一套。
# ---------------------------------------------------------------------------
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)
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"
KINDS = (KIND_EMAIL, KIND_DINGTALK, KIND_FEISHU, KIND_WECOM, KIND_WEBHOOK)
#: 需要 SMTP 参数的种类
SMTP_KINDS = (KIND_EMAIL,)
#: 需要回调地址的种类
URL_KINDS = (KIND_DINGTALK, KIND_FEISHU, KIND_WECOM, KIND_WEBHOOK)
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;密钥只进不出
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)
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)