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

298 lines
12 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_manual(db: Session, code: str) -> None:
"""选项来自数据源的字典,字典项由同步维护:在这儿手改会被下一次同步盖掉。"""
row = dicts.get_type(db, code)
if dicts.is_remote(row):
raise bad_request(f"「{row.name}」的选项来自数据源 {row.source_code},请改数据源或点「同步」,手改会被下一次同步覆盖")
@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()
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()
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()
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()
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("字典不存在")
_guard_manual(db, row.code)
value = (body.value or "").strip()
if not value:
raise bad_request("字典项取值不能为空")
if _find_item(db, row.code, value) is not None:
raise bad_request(f"字典项取值已存在: {value}")
item = models.DictItem(
type=row.code,
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()
return ok(serializers.dict_item(item))
@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_manual(db, item.type)
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()
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_manual(db, item.type)
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()
return ok({"deleted": True})
@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)
return ok(
{
"options": 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()