fourcal-pms/backend/app/dicts.py

458 lines
20 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters!

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

"""数据字典服务:代码枚举 + 库内维护,一份取值喂到前端。
单一事实来源本来是 model 里的 ``LABELS``,但"能在界面上改一改取值"这件事代码给不了——
加一个客户等级、把一个阶段名从"S3-预算评估"改成"S3-预算评审"都得发版。所以现在分两层:
* **代码层**(本文件的 :data:`SPECS`):业务分支依赖的枚举,启动时同步进 ``dict_type``
/ ``dict_item``,标成 ``source=system``。代码永远是这份的兜底:库是空的、表还没建、
字典被误删,读到的仍是代码里的取值,系统不会因为字典没种好就白屏。
* **库内层**(``dict_type`` / ``dict_item``):运行期的事实来源。「系统 → 数据字典」
改的就是这一层,改完立刻生效,还能建代码里根本没有的自定义字典。
读取走进程内缓存(下拉框取值是典型读多写少),写接口改完调 :func:`invalidate`。
多进程部署时其他 worker 最长滞后 :data:`CACHE_TTL_SECONDS`,改完在界面上刷新一下即可。
"""
from __future__ import annotations
import threading
import time
from dataclasses import dataclass, field
from typing import Any, Iterable, Mapping
from sqlalchemy import select
from sqlalchemy.orm import Session
from .models import (
AccountSource,
Action,
BusinessModule,
CandidateType,
Certainty,
CostType,
DictItem,
DictSource,
DictType,
DictValueType,
Effect,
FlowStatus,
IncomeType,
InstanceStatus,
IndustryScene,
MilestoneStatus,
NodeType,
OtherCostBucket,
ProductCategory,
PermKind,
ProjectMemberRole,
ProjectMilestone,
ProjectSource,
ProjectStage,
ProjectType,
PurchaseType,
RevisionStatus,
SaleStage,
ScopeType,
SignType,
Status,
SubjectType,
TaskStatus,
UnderwrittenMode,
WbsTaskStatus,
YesNo,
)
#: 进程内缓存的存活时间(秒)。写接口会当场失效,这个值只兜多进程部署的跨进程延迟。
CACHE_TTL_SECONDS = 60
@dataclass(frozen=True)
class DictSpec:
"""代码里定义的一份字典。"""
code: str
name: str
group: str
items: tuple[tuple[Any, str], ...]
value_type: str = DictValueType.STRING
remark: str = ""
#: value -> 状态色,只为让前端徽章有地方取色;留空由前端自己判
tags: Mapping[Any, str] = field(default_factory=dict)
def options(self) -> list[dict[str, Any]]:
return [{"value": value, "label": label} for value, label in self.items]
def _numbered(labels: Mapping[Any, str]) -> tuple[str, tuple[tuple[Any, str], ...]]:
"""整数键的 LABELS:按值排序,返回 (取值类型, 条目)。"""
items = list(labels.items())
if all(isinstance(key, int) for key, _ in items):
items.sort(key=lambda kv: kv[0])
return DictValueType.INT, tuple(items)
return DictValueType.STRING, tuple(items)
def _enum(code: str, name: str, group: str, labels: Mapping[Any, str], *,
remark: str = "", tags: Mapping[Any, str] | None = None) -> DictSpec:
value_type, items = _numbered(labels)
return DictSpec(code=code, name=name, group=group, items=items,
value_type=value_type, remark=remark, tags=tags or {})
#: 审批里"状态色"的推荐值,与前端 StatusBadge 那份默认色一致;界面上可以改。
_STATUS_TAGS = {
"draft": "gray", "reviewing": "warning", "pending": "warning", "approved": "success",
"done": "success", "rejected": "danger", "withdrawn": "gray", "canceled": "gray",
"skipped": "gray", "transferred": "info", "published": "success", "offline": "gray",
}
def _specs() -> dict[str, DictSpec]:
specs = [
# 项目
_enum("projectType", "项目类型", "项目", ProjectType.LABELS),
_enum("projectStage", "项目阶段", "项目", ProjectStage.LABELS),
_enum("underwrittenMode", "垫资模式", "项目", UnderwrittenMode.LABELS),
_enum("projectMemberRole", "项目成员种类", "项目", ProjectMemberRole.LABELS),
_enum("certainty", "项目把握度", "项目", Certainty.LABELS),
_enum("industryScene", "行业场景应用", "项目", IndustryScene.LABELS,
remark="取值沿用老四算 project.industry_scene 的实际分布;0 表示老数据只填了描述"),
_enum("saleStage", "公司销售阶段", "项目", SaleStage.LABELS,
remark="老库这一列没有注释,档位名是可改的初始值;分支与迁移只认编码"),
_enum("yesNo", "是/否", "项目", YesNo.LABELS,
remark="是否二次合作、是否汇智中标这类下拉框;0 与 -1 都显示为未填"),
_enum("milestoneStatus", "里程碑状态", "项目", MilestoneStatus.LABELS,
remark="已逾期由系统按计划日期现算,不落库"),
_enum("wbsTaskStatus", "WBS 任务状态", "项目", WbsTaskStatus.LABELS),
# 明细分类
_enum("incomeType", "收入明细类别", "立项预算", IncomeType.LABELS),
_enum("purchaseType", "采购明细类别", "立项预算", PurchaseType.LABELS),
_enum("costType", "成本明细类别", "立项预算", CostType.LABELS),
_enum("revisionStatus", "版本状态", "立项预算", RevisionStatus.LABELS,
tags=_STATUS_TAGS),
_enum("productCategory", "产品归属", "立项预算", ProductCategory.LABELS,
remark="取值决定金额投影到项目主档的哪一列,改动前先和财务确认"),
_enum("otherCostBucket", "费用归属", "立项预算", OtherCostBucket.LABELS,
remark="计算器按这一列决定费用进利润公式的哪一层"),
# 组织
_enum("accountStatus", "账号状态", "组织", Status.LABELS,
remark="组织与账号共用;Hub 导出的 status 也是这套数字"),
_enum("accountSource", "账号来源", "组织", AccountSource.LABELS),
# 权限
_enum("permKind", "权限节点类型", "权限", PermKind.LABELS),
_enum("effect", "数据策略效果", "权限", Effect.LABELS),
_enum("scopeType", "数据范围", "权限", ScopeType.LABELS),
_enum("subjectType", "策略主体类型", "权限", SubjectType.LABELS),
_enum("dataOperator", "数据条件运算符", "权限", {
"eq": "等于", "ne": "不等于", "gt": "大于", "gte": "大于等于",
"lt": "小于", "lte": "小于等于", "in": "属于", "not_in": "不属于",
"contains": "包含", "not_contains": "不包含",
"is_null": "为空", "is_not_null": "不为空",
}),
_enum("logicOp", "条件组合方式", "权限", {"and": "全部满足 (and)", "or": "任一满足 (or)"}),
_enum("dynamicValue", "动态取值", "权限", {
"$account_id": "当前登录人",
"$org_unit_ids": "当前人所在部门",
"$org_unit_ids_with_children": "当前人所在部门及下级",
}),
# 审批
_enum("businessModule", "审批业务模块", "审批", BusinessModule.LABELS),
_enum("flowStatus", "流程状态", "审批", FlowStatus.LABELS, tags=_STATUS_TAGS),
_enum("nodeType", "流程节点类型", "审批", NodeType.LABELS),
_enum("signType", "多人办理方式", "审批", SignType.LABELS),
_enum("candidateType", "候选人来源", "审批", CandidateType.LABELS),
_enum("emptyStrategy", "找不到审批人时", "审批", {
"error": "报错并阻止送审", "skip": "跳过该节点", "admin": "转给系统管理员",
}),
_enum("timeoutAction", "审批超时处理", "审批", {
"none": "不处理", "remind": "自动催办", "auto_approve": "自动通过",
}),
_enum("instanceStatus", "审批实例状态", "审批", InstanceStatus.LABELS,
tags=_STATUS_TAGS),
_enum("taskStatus", "审批待办状态", "审批", TaskStatus.LABELS, tags=_STATUS_TAGS),
_enum("approvalAction", "审批动作", "审批", Action.LABELS),
]
return {spec.code: spec for spec in specs}
#: 代码内置字典清单;:func:`sync` 按这份补齐库里的字典,界面上删不掉的也是这份。
SPECS: dict[str, DictSpec] = _specs()
_LOCK = threading.RLock()
#: 两份缓存:下拉框只看在用的条目,取显示名时停用的也算(历史数据还得显示名字)。
_CACHE: dict[str, dict[str, Any]] = {
"options": {"at": 0.0, "data": {}},
"labels": {"at": 0.0, "data": {}},
}
# ---------------------------------------------------------------------------
# 纯代码层(不碰库,建库前的兜底)
# ---------------------------------------------------------------------------
def code_options() -> dict[str, list[dict[str, Any]]]:
return {code: spec.options() for code, spec in SPECS.items()}
# ---------------------------------------------------------------------------
# 缓存
# ---------------------------------------------------------------------------
def invalidate() -> None:
"""让缓存作废;所有写接口都要调,否则界面改完取值看不到变化。"""
with _LOCK:
for bucket in _CACHE.values():
bucket["at"] = 0.0
bucket["data"] = {}
def _coerce(value_type: str, raw: str) -> Any:
if value_type == DictValueType.INT:
try:
return int(raw)
except (TypeError, ValueError):
# 界面上手滑填了非数字:宁可原样下发也别让整份字典读不出来
return raw
return raw
def _load(db: Session) -> dict[str, list[dict[str, Any]]]:
"""一次把全部字典读进内存。字典表只有几百行,逐类查不如一把捞。"""
types = db.execute(
select(DictType).where(DictType.is_deleted.is_(False)).order_by(DictType.id)
).scalars().all()
if not types:
return code_options()
rows = db.execute(
select(DictItem, DictType)
.join(DictType, DictType.id == DictItem.dict_type_id)
.where(DictItem.is_deleted.is_(False), DictItem.enabled.is_(True),
DictType.enabled.is_(True))
.order_by(DictItem.dict_type_id, DictItem.sort, DictItem.id)
).all()
grouped: dict[str, list[dict[str, Any]]] = {row.code: [] for row in types if not row.enabled}
for item, parent in rows:
option: dict[str, Any] = {
"value": _coerce(parent.value_type, item.value), "label": item.label}
if item.tag:
option["tag"] = item.tag
if item.remark:
option["remark"] = item.remark
grouped.setdefault(parent.code, []).append(option)
for code, spec in SPECS.items(): # 库里还没有这一类时退回代码取值
grouped.setdefault(code, spec.options())
return grouped
def _cached(db: Session) -> dict[str, list[dict[str, Any]]]:
return _memo("options", db, _load)
def _memo(name: str, db: Session, loader: Any) -> dict[str, list[dict[str, Any]]]:
bucket = _CACHE[name]
now = time.monotonic()
with _LOCK:
fresh = now - bucket["at"] < CACHE_TTL_SECONDS and bucket["data"]
data = bucket["data"] if fresh else loader(db)
if not fresh:
bucket.update(at=now, data=data)
return data
# ---------------------------------------------------------------------------
# 读接口
# ---------------------------------------------------------------------------
def build(db: Session | None = None) -> dict[str, list[dict[str, Any]]]:
"""前端 ``/bootstrap`` 要的整份字典。
不传库就退化成代码取值:建库之前、健康检查这类路径都要能应答。
"""
if db is None:
return code_options()
return dict(_cached(db))
def options(db: Session, code: str, *, include_disabled: bool = False) -> list[dict[str, Any]]:
"""某个字典的取值。``include_disabled`` 时直查库,维护页要用停用的那些。"""
if not include_disabled:
return list(_cached(db).get(code) or [])
return items(db, code, include_disabled=True)
def items(db: Session, code: str, *, include_disabled: bool = False) -> list[dict[str, Any]]:
"""维护页视角的条目(带 id、排序、启停),不走缓存。"""
row = db.execute(select(DictType).where(DictType.code == code,
DictType.is_deleted.is_(False))).scalars().first()
if row is None:
spec = SPECS.get(code)
return [{"id": None, "value": str(value), "label": label, "sort": index * 10 + 10,
"enabled": True, "tag": spec.tags.get(value, ""), "builtin": True,
"remark": ""}
for index, (value, label) in enumerate(spec.items)] if spec else []
statement = (select(DictItem).where(DictItem.dict_type_id == row.id,
DictItem.is_deleted.is_(False))
.order_by(DictItem.sort, DictItem.id))
rows = db.execute(statement).scalars().all()
return [{"id": item.id, "value": _coerce(row.value_type, item.value),
"label": item.label, "sort": item.sort, "enabled": bool(item.enabled),
"tag": item.tag, "builtin": bool(item.builtin), "remark": item.remark}
for item in rows if include_disabled or item.enabled]
def label_from_code(code: str, value: Any, default: str = "") -> str:
"""代码取值 → 显示名,不碰库。给签名里拿不到 Session 的小工具函数用。"""
if value is None or value == "":
return default
spec = SPECS.get(code)
if spec:
for item_value, item_label in spec.items:
if item_value == value or str(item_value) == str(value):
return item_label
return default
def label(db: Session, code: str, value: Any, default: str = "") -> str:
"""取显示名。库里没有这一项就退回代码里的名字,取不到再退回调用方给的兜底。
读路径上给接口用(列表页那几列 ``xxxLabel``),所以字典停用的条目也要能查出名字——
停用只是从下拉框里摘掉,不代表历史数据上的值不该显示。
"""
if value is None or value == "":
return default
for row in _all_with_disabled(db).get(code, []):
if row["value"] == value or str(row["value"]) == str(value):
return row["label"]
spec = SPECS.get(code)
if spec:
for item_value, item_label in spec.items:
if item_value == value or str(item_value) == str(value):
return item_label
return default
def _all_with_disabled(db: Session) -> dict[str, list[dict[str, Any]]]:
return _memo("labels", db, _load_labels)
def _load_labels(db: Session) -> dict[str, list[dict[str, Any]]]:
rows = db.execute(
select(DictItem, DictType)
.join(DictType, DictType.id == DictItem.dict_type_id)
.where(DictItem.is_deleted.is_(False))
.order_by(DictItem.dict_type_id, DictItem.sort, DictItem.id)
).all()
grouped: dict[str, list[dict[str, Any]]] = {}
for item, parent in rows:
grouped.setdefault(parent.code, []).append(
{"value": _coerce(parent.value_type, item.value), "label": item.label})
for code, spec in SPECS.items():
grouped.setdefault(code, [{"value": value, "label": lab} for value, lab in spec.items])
return grouped
# ---------------------------------------------------------------------------
# 写接口(维护页与 seed 共用)
# ---------------------------------------------------------------------------
def sync(db: Session) -> dict[str, int]:
"""把代码字典同步进库:缺的补上,已有的不动。
刻意不覆盖已有条目——界面上改过的名字被一次重启冲掉,比名字对不上更难查。
想把某类字典恢复成代码取值,用维护页的「恢复默认」。
"""
created_types = created_items = 0
types = {row.code: row for row in
db.execute(select(DictType)).scalars().all()}
for code, spec in SPECS.items():
parent = types.get(code)
if parent is None:
parent = DictType(code=code, name=spec.name, group=spec.group,
value_type=spec.value_type, source=DictSource.SYSTEM,
enabled=True, remark=spec.remark)
db.add(parent)
db.flush()
types[code] = parent
created_types += 1
elif parent.source != DictSource.SYSTEM:
# 有人先手工建了同名编码:认下来,但别把它改造成系统字典,
# 否则"恢复默认"会往一份自定义取值里灌代码枚举。
continue
existing = {row.value for row in
db.execute(select(DictItem).where(DictItem.dict_type_id == parent.id)
).scalars().all()}
for index, (value, label_text) in enumerate(spec.items):
raw = str(value)
if raw in existing:
continue
db.add(DictItem(dict_type_id=parent.id, value=raw, label=label_text,
sort=index * 10 + 10, enabled=True,
tag=spec.tags.get(value, ""), builtin=True, remark=""))
created_items += 1
db.flush()
invalidate()
return {"types": created_types, "items": created_items}
def reset_items(db: Session, code: str) -> int:
"""把某个代码字典的取值恢复成代码定义(改名回来、误停的恢复)。"""
spec = SPECS.get(code)
if spec is None:
raise ValueError(f"{code} 不是代码内置字典,没有默认值可恢复")
parent = db.execute(select(DictType).where(DictType.code == code,
DictType.is_deleted.is_(False))).scalars().first()
if parent is None:
sync(db)
return 0
rows = db.execute(select(DictItem).where(DictItem.dict_type_id == parent.id)
.order_by(DictItem.id)).scalars().all()
by_value = {row.value: row for row in rows}
for index, (value, label_text) in enumerate(spec.items):
row = by_value.get(str(value))
if row is None:
db.add(DictItem(dict_type_id=parent.id, value=str(value), label=label_text,
sort=index * 10 + 10, enabled=True,
tag=spec.tags.get(value, ""), builtin=True, remark=""))
continue
row.label, row.sort, row.enabled, row.is_deleted = label_text, index * 10 + 10, True, False
row.tag = spec.tags.get(value, "")
count = len(spec.items)
for row in rows:
if row.value not in {str(value) for value, _ in spec.items}:
row.is_deleted = True
db.flush()
invalidate()
return count
def normalize_value(value_type: str, value: Any) -> str:
"""把界面传来的取值折成库里存的字符串。整数型字典不接受非数字。"""
text = str(value).strip()
if value_type == DictValueType.INT:
try:
return str(int(text))
except (TypeError, ValueError):
raise ValueError(f"该字典的取值类型是整数,{value!r} 不是整数") from None
if not text:
raise ValueError("取值不能为空")
return text
def export(db: Session, codes: Iterable[str] | None = None) -> dict[str, list[dict[str, Any]]]:
"""按需取几类字典(前端懒加载用)。
点名了但系统里确实没有的编码不出现在结果里——前端把"缺键"当成"这份字典不存在",
比回一串空数组更好判断(空数组也可能是整类停用)。
"""
data = _cached(db)
if codes is None:
return dict(data)
return {code: list(data[code]) for code in codes if code in data}