unis-oa/backend/app/api/dicts.py

364 lines
16 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.

"""数据字典接口 -- 字典分类与字典项的维护.
字典是给表单设计器当「公共选项来源」用的:一处维护,所有引用它的表单都跟着变。
读取选项只需要登录(运行时要渲染表单),改字典要表单设计权限。
"""
from __future__ import annotations
import re
from fastapi import APIRouter, Depends, Query
from sqlalchemy import select
from sqlalchemy.orm import Session
from .. import models, schemas, serializers
from ..db import get_db
from ..deps import CurrentUser, current_user, require_permission
from ..envelope import bad_request, not_found, ok
from ..service import dicts, fetch
router = APIRouter(tags=["dicts"])
#: 字典编码要能安全地出现在表单定义里,只留字母数字下划线中划线。
CODE_RE = re.compile(r"^[A-Za-z0-9_-]{1,64}$")
def _source_fields(db: Session, body: schemas.DictTypeBody) -> dict:
"""把「选项来源」那三格收拾干净:来源不认识就挡掉,外部来源要当场对得上列表型数据源。
当场校验的理由很直白:选项来自外部的字典,配错要到有人开单打开下拉才发现,
而那时看到的是一个空白下拉——没人会想到是三个月前绑错了一张取值型的数据源。
"""
source = str(body.source or models.DictType.SOURCE_MANUAL).strip()
if source not in models.DictType.SOURCES:
raise bad_request("选项来源只支持手工维护(manual)或外部数据源(data_source)")
code = str(body.source_code or "").strip()
args = body.source_args or {}
if not isinstance(args, dict):
raise bad_request("同步入参要写成「入参名: 取值写法」这样的键值对")
if source == models.DictType.SOURCE_REMOTE:
problem = dicts.remote_problem(
models.DictType(source=source, source_code=code), fetch.get_source(db, code)
)
if problem:
raise bad_request(problem)
else:
code, args = "", {}
return {"source": source, "source_code": code, "source_args": args}
def _guard_item(db: Session, item: models.DictItem) -> None:
"""这一项让不让人改,不让就一句话说明白为什么。
以前是整本字典一刀切:选项来自数据源就不许手改。可人补的那一项根本不是同步写下来的,
拦着它只会把人逼去改数据源、或者干脆换个字典。现在按行的主人判(``dicts.item_is_manual``),
上游那一项仍然挡住——它的名称、附加值、顺序都由上游给,改了也活不过下一次同步。
"""
problem = dicts.item_write_problem(item, dicts.get_type(db, item.type))
if problem:
raise bad_request(problem)
@router.get("/process/dicts")
def list_dicts(
db: Session = Depends(get_db),
_: CurrentUser = Depends(current_user),
keyword: str = Query(""),
enabled: str = Query(""),
) -> dict:
return ok(dicts.list_types(db, keyword, enabled.lower() in ("1", "true", "yes")))
@router.post("/process/dicts", dependencies=[Depends(require_permission("design:form"))])
def create_dict(
body: schemas.DictTypeBody, user: CurrentUser = Depends(current_user), db: Session = Depends(get_db)
) -> dict:
code = (body.code or "").strip()
if not CODE_RE.match(code):
raise bad_request("字典编码只能用字母、数字、下划线和中划线,且不能为空")
if dicts.get_type(db, code) is not None:
raise bad_request(f"字典编码已存在: {code}")
row = models.DictType(
code=code,
name=(body.name or code).strip(),
description=body.description,
tree=body.tree,
enabled=body.enabled,
order_number=body.order_number,
creator=user.person_id,
creator_name=user.display_name,
**_source_fields(db, body)
)
db.add(row)
db.commit()
dicts.invalidate(row.code)
return ok(serializers.dict_type(row))
@router.put("/process/dicts/{dict_id}", dependencies=[Depends(require_permission("design:form"))])
def update_dict(dict_id: str, body: schemas.DictTypeBody, db: Session = Depends(get_db)) -> dict:
row = db.get(models.DictType, dict_id)
if row is None:
raise not_found("字典不存在")
payload = body.model_dump(exclude_none=True)
code = str(payload.get("code") or "").strip()
previous_code = row.code
if code and code != row.code:
if not CODE_RE.match(code):
raise bad_request("字典编码只能用字母、数字、下划线和中划线,且不能为空")
clash = db.execute(
select(models.DictType).where(models.DictType.code == code, models.DictType.id != row.id)
).scalar_one_or_none()
if clash is not None:
raise bad_request(f"字典编码已存在: {code}")
# 表单里存的是编码,改编码等于把所有引用打断;跟着一起搬字典项,至少不自断。
for item in dicts.item_rows(db, row.code):
item.type = code
row.code = code
for key, value in _source_fields(db, body).items():
setattr(row, key, value)
for key, value in payload.items():
if key in ("code", "source", "source_code", "source_args"):
continue
setattr(row, key, value)
db.commit()
# 改了编码的话两份都要清:旧编码那份没人再读了,但别让它活到 TTL 结束
dicts.invalidate(row.code)
if previous_code != row.code:
dicts.invalidate(previous_code)
return ok(serializers.dict_type(row))
@router.delete("/process/dicts/{dict_id}", dependencies=[Depends(require_permission("design:form"))])
def delete_dict(dict_id: str, db: Session = Depends(get_db)) -> dict:
row = db.get(models.DictType, dict_id)
if row is None:
raise not_found("字典不存在")
# 删字典是设计期动作:正在被表单引用的照样让删,但把引用者回给前端提示一句,
# 免得线上下拉悄悄变空白。
used = dicts.used_by_forms(db, row.code)
for item in dicts.item_rows(db, row.code):
db.delete(item)
db.delete(row)
db.commit()
dicts.invalidate(row.code)
return ok({"deleted": True, "usedByForms": used})
@router.get("/process/dicts/{code}/items")
def list_dict_items(
code: str,
db: Session = Depends(get_db),
_: CurrentUser = Depends(current_user),
enabled: str = Query(""),
) -> dict:
row = dicts.get_type(db, code)
if row is None:
raise not_found("字典不存在")
items = dicts.items_of(db, row.code, enabled_only=enabled.lower() in ("1", "true", "yes"))
return ok({"type": serializers.dict_type(row), "items": items})
@router.post("/process/dicts/{code}/items", dependencies=[Depends(require_permission("design:form"))])
def create_dict_item(code: str, body: schemas.DictItemBody, db: Session = Depends(get_db)) -> dict:
row = dicts.get_type(db, code)
if row is None:
raise not_found("字典不存在")
value = (body.value or "").strip()
if not value:
raise bad_request("字典项取值不能为空")
clash = _find_item(db, row.code, value)
if clash is not None:
# 最常见的撞车是"上游撤了这一项、可这张单子还要用":别让人去猜,直接指出活路
hint = ""
if dicts.is_remote(row) and not dicts.item_is_manual(dicts.item_source(clash), str(row.source or "")):
hint = ",这一项来自数据源,要自己定就点「接手为手工维护」"
raise bad_request(f"字典项取值已存在: {value}{hint}")
item = models.DictItem(
type=row.code,
# 人敲进去的这一行归人:外部字典里靠这个标记躲开同步覆盖
source=models.DictItem.SOURCE_MANUAL,
value=value,
label=(body.label or value).strip(),
parent=(body.parent or "").strip(),
extra=body.extra or {},
color=body.color,
enabled=body.enabled,
order_number=body.order_number,
)
db.add(item)
db.commit()
dicts.invalidate(row.code)
return ok(serializers.dict_item(item))
@router.post("/process/dicts/{code}/items/import", dependencies=[Depends(require_permission("design:form"))])
def import_dict_items(code: str, body: schemas.DictImportBody, db: Session = Depends(get_db)) -> dict:
"""批量导入字典项:一次贴一批(Excel / CSV 来的),逐条回「新增 / 覆盖 / 跳过 / 没收」。
表格解析在前端做完,这里只收结构化的行:设计页预览表上看到的结论与真正落库
走的是同一份数据,不会出现「预览看着对、导进来是另一回事」。
取值已存在怎么办由 ``mode`` 说了算(跳过 / 覆盖),跟同步一样**不删**没出现的项——
导入是补一批,不是宣布这就是全部。
选项来自数据源的字典也能导:上游缺了几十项一行一行敲太累。导进来的新行标成手工
维护,撞上上游那一项的原样放过(口径见 :func:`service.dicts.import_items`)。
"""
row = dicts.get_type(db, code)
if row is None:
raise not_found("字典不存在")
mode = str(body.mode or "skip").strip()
if mode not in ("skip", "overwrite"):
raise bad_request("导入方式只支持 skip(跳过已存在)或 overwrite(覆盖已存在)")
return ok(dicts.import_items(db, row, items=body.items, mode=mode))
@router.put("/process/dict-items/{item_id}", dependencies=[Depends(require_permission("design:form"))])
def update_dict_item(item_id: str, body: schemas.DictItemBody, db: Session = Depends(get_db)) -> dict:
item = db.get(models.DictItem, item_id)
if item is None:
raise not_found("字典项不存在")
_guard_item(db, item)
value = (body.value or item.value).strip()
if not value:
raise bad_request("字典项取值不能为空")
clash = _find_item(db, item.type, value)
if clash is not None and clash.id != item.id:
raise bad_request(f"字典项取值已存在: {value}")
parent = (body.parent or "").strip()
if parent and parent == value:
raise bad_request("字典项不能把自己设为上级")
item.value = value
item.label = (body.label or value).strip()
item.parent = parent
item.extra = body.extra or {}
item.color = body.color
item.enabled = body.enabled
item.order_number = body.order_number
db.commit()
dicts.invalidate(item.type)
return ok(serializers.dict_item(item))
@router.delete("/process/dict-items/{item_id}", dependencies=[Depends(require_permission("design:form"))])
def delete_dict_item(item_id: str, db: Session = Depends(get_db)) -> dict:
item = db.get(models.DictItem, item_id)
if item is None:
raise not_found("字典项不存在")
_guard_item(db, item)
children = db.execute(
select(models.DictItem).where(models.DictItem.type == item.type, models.DictItem.parent == item.value)
).scalars().all()
if children:
raise bad_request(f"「{item.label or item.value}」下面还有 {len(children)} 个子项,先把子项移走再删")
db.delete(item)
db.commit()
dicts.invalidate(item.type)
return ok({"deleted": True})
@router.post("/process/dict-items/{item_id}/own", dependencies=[Depends(require_permission("design:form"))])
def own_dict_item(
item_id: str, body: schemas.DictItemOwnBody, db: Session = Depends(get_db)
) -> dict:
"""把一项字典项接手成手工维护,或者交还给同步。
只有外部来源的字典需要它:上游撤掉了一项、可历史单据上还要用这个名字,接手之后
同步就不会再动它;反过来说,人补的那一项如果上游后来也给了,交还回去就并回上游那份。
"""
item = db.get(models.DictItem, item_id)
if item is None:
raise not_found("字典项不存在")
row = dicts.get_type(db, item.type)
if row is None:
raise not_found("字典不存在")
if not dicts.is_remote(row):
raise bad_request(f"「{row.name}」的选项是手工维护的,本来就没有同步会盖它")
item = dicts.set_item_source(db, item, row, body.source)
return ok(serializers.dict_item(item))
@router.post("/process/dicts/{code}/sync", dependencies=[Depends(require_permission("design:form"))])
def sync_dict_items(
code: str,
body: schemas.DictSyncBody,
user: CurrentUser = Depends(current_user),
db: Session = Depends(get_db),
) -> dict:
"""按绑定的数据源拉一次选项:``dryRun`` 只看不落库,给设计页那张预览表用。
手动同步和开表单时的自动刷新走的是同一个 :func:`service.dicts.sync`,
所以「预览看到的」与「同步之后落库的」永远是同一份口径。
"""
row = dicts.get_type(db, code)
if row is None:
raise not_found("字典不存在")
if not dicts.is_remote(row):
raise bad_request("这个字典的选项是手工维护的,没有可同步的数据源")
result = dicts.sync(db, row, actor=user, dry_run=bool(body.dry_run))
return ok(result)
@router.get("/process/dicts/usage/{code}")
def dict_usage(code: str, db: Session = Depends(get_db), _: CurrentUser = Depends(current_user)) -> dict:
return ok({"forms": dicts.used_by_forms(db, code)})
@router.post("/process/dicts/values")
def dict_values(
body: schemas.DictValuesBody, db: Session = Depends(get_db), _actor: CurrentUser = Depends(current_user)
) -> dict:
"""按编码批量取字典项,运行时的下拉、级联、只读态文本都从这一份里出。
一次把表单用到了哪些字典都带上,渲染一张表单只发一个请求;只回启用的字典
与启用的字典项,停用的选项不会悄悄出现在新单上。
"""
cache = dicts.DictCache(db)
out: dict[str, list[dict]] = {}
refreshed = False
for code in body.codes or []:
code = str(code or "").strip()
if not code or code in out:
continue
row = dicts.get_type(db, code)
if row is None or not row.enabled:
out[code] = []
continue
# 外部来源的字典先刷到不过期再读;刷失败也照读上一次同步下来的那份,
# 上游抖一下不该让填单页面的下拉变空白
if dicts.ensure_fresh(db, row, actor=_actor):
refreshed = True
cache = dicts.DictCache(db)
out[code] = cache.items(code)
if refreshed:
# 同步要落字典项与调用留痕,这条读接口平时没人提交,自己收
db.commit()
return ok(out)
@router.post("/process/dicts/options", dependencies=[Depends(require_permission("design:form"))])
def preview_options(body: schemas.DictPreviewBody, db: Session = Depends(get_db)) -> dict:
"""设计器试算:按当前样例数据把某个字段的可选项、可见性、必填算一遍。"""
cache = dicts.DictCache(db)
field = dict(body.field or {})
data = dict(body.data or {})
options = dicts.effective_options(field, data, cache)
# 演的是「这一格此刻」:条件路由命中哪一条,就按那一条的显示 / 存值两列投影
view = dicts.option_view(field, data)
return ok(
{
# 演的是「填单的人此刻看到什么、选了会存什么」:按这一格配的显示 / 存值两列投影
"options": dicts.project_options(view, options) if options is not None else [],
"constrained": options is not None,
"state": dicts.state_of(field, data),
"dependsOn": dicts.depends_on(field),
}
)
def _find_item(db: Session, code: str, value: str) -> models.DictItem | None:
return db.execute(
select(models.DictItem).where(models.DictItem.type == code, models.DictItem.value == value)
).scalar_one_or_none()