fourcal-pms/backend/app/api/dicts.py

308 lines
12 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.

"""数据字典接口:前端取值的读接口 + 「系统 → 数据字典」的维护接口。
读写分开挂在不同前缀下:``/dicts`` 只要求登录(任何页面都要拉取值),
``/system/dicts`` 要 ``system:dict:view`` / ``system:dict:edit``。
"""
from __future__ import annotations
import re
from typing import Any
from fastapi import APIRouter
from pydantic import BaseModel, Field
from sqlalchemy import func, select
from .. import dicts as store
from ..deps import DbSession, PrincipalOf
from ..envelope import conflict, forbidden, not_found, ok
from ..models import DictItem, DictSource, DictType, DictValueType
router = APIRouter(prefix="/dicts", tags=["dicts"])
admin = APIRouter(prefix="/system/dicts", tags=["system"])
#: 字典编码要能当 JS 属性名用(bootstrap 里直接 enums.projectStage),
#: 所以钉成 camelCase;一旦建了就别再改,前端是按它取值的。
CODE_RE = re.compile(r"^[a-z][A-Za-z0-9]{1,63}$")
def _need(db, current: PrincipalOf, code: str) -> None:
if not current.permission.can(code):
raise forbidden(f"缺少权限:{code}")
# ---------------------------------------------------------------------------
# 读:给前端下拉框
# ---------------------------------------------------------------------------
@router.get("")
def dict_data(db: DbSession, current: PrincipalOf, types: str = "") -> dict[str, Any]:
"""按需取几类字典的取值;``types`` 留空给全量。
全量已经随 ``/bootstrap`` 下发过一次,这条是给懒加载和自定义字典用的,
所以只要登录就能读——下拉框取值不是敏感信息,权限管的是能不能改。
"""
codes = [code for code in (part.strip() for part in types.split(",")) if code]
return ok(store.export(db, codes or None))
# ---------------------------------------------------------------------------
# 维护:字典类型
# ---------------------------------------------------------------------------
def _type_view(row: DictType, total: int, usable: int) -> dict[str, Any]:
return {
"id": row.id, "code": row.code, "name": row.name, "group": row.group,
"valueType": row.value_type, "source": row.source,
"sourceLabel": DictSource.LABELS.get(row.source, row.source),
"builtin": row.source == DictSource.SYSTEM,
# TINYINT 存布尔,直接回给前端是 1/0,Toggle 组件要的是真布尔
"enabled": bool(row.enabled), "remark": row.remark,
"itemCount": total, "enabledCount": usable,
"codeDefined": row.code in store.SPECS,
}
@admin.get("")
def list_types(db: DbSession, current: PrincipalOf, keyword: str = "",
group: str = "") -> dict[str, Any]:
_need(db, current, "system:dict:view")
statement = select(DictType).where(DictType.is_deleted.is_(False))
if group:
statement = statement.where(DictType.group == group)
if keyword:
like = f"%{keyword}%"
statement = statement.where(DictType.name.like(like) | DictType.code.like(like))
rows = db.execute(statement.order_by(DictType.group, DictType.id)).scalars().all()
counts = dict(db.execute(
select(DictItem.dict_type_id, func.count())
.where(DictItem.is_deleted.is_(False)).group_by(DictItem.dict_type_id)).all())
enabled_counts = dict(db.execute(
select(DictItem.dict_type_id, func.count())
.where(DictItem.is_deleted.is_(False), DictItem.enabled.is_(True))
.group_by(DictItem.dict_type_id)).all())
return ok([_type_view(row, counts.get(row.id, 0), enabled_counts.get(row.id, 0))
for row in rows])
@admin.get("/groups")
def list_groups(db: DbSession, current: PrincipalOf) -> dict[str, Any]:
"""维护页的分组筛选。代码字典自带分组,自建字典自己填,这里按库里的去重。"""
_need(db, current, "system:dict:view")
rows = db.execute(select(DictType.group).where(DictType.is_deleted.is_(False))
.distinct()).scalars().all()
return ok(sorted({row or "common" for row in rows}))
class DictTypeBody(BaseModel):
code: str = Field(min_length=1, max_length=64)
name: str = Field(min_length=1, max_length=128)
group: str = "common"
valueType: str = DictValueType.STRING
enabled: bool = True
remark: str = ""
@admin.post("")
def create_type(body: DictTypeBody, db: DbSession, current: PrincipalOf) -> dict[str, Any]:
_need(db, current, "system:dict:edit")
code = body.code.strip()
if not CODE_RE.match(code):
raise conflict("invalid_code", "字典编码只能用 camelCase 字母数字,且以字母开头")
if code in store.SPECS:
raise conflict("reserved_code", f"{code} 是代码内置字典,换一个编码或到列表里改它")
if db.execute(select(DictType).where(DictType.code == code)).scalars().first():
raise conflict("duplicated_code", "字典编码已存在")
if body.valueType not in DictValueType.LABELS:
raise conflict("invalid_value_type", "取值类型只能是文本或整数")
row = DictType(code=code, name=body.name.strip(), group=(body.group or "common").strip(),
value_type=body.valueType, source=DictSource.CUSTOM,
enabled=body.enabled, remark=body.remark)
db.add(row)
db.commit()
store.invalidate()
return ok({"id": row.id})
@admin.put("/{type_id}")
def update_type(type_id: int, body: DictTypeBody, db: DbSession,
current: PrincipalOf) -> dict[str, Any]:
_need(db, current, "system:dict:edit")
row = db.get(DictType, type_id)
if row is None or row.is_deleted:
raise not_found("字典不存在")
if row.source == DictSource.SYSTEM:
# 内置字典的编码与取值类型是代码契约的一部分:前端按编码取值、按类型换算,
# 改了就对不上,所以只让改名字、分组、说明和启停。
if body.valueType != row.value_type:
raise conflict("builtin_type", "代码内置字典的取值类型不能改")
elif body.code.strip() != row.code:
raise conflict("immutable_code", "字典编码已被前端引用,不能改")
if body.valueType not in DictValueType.LABELS:
raise conflict("invalid_value_type", "取值类型只能是文本或整数")
row.name = body.name.strip()
row.group = (body.group or "common").strip()
row.enabled = body.enabled
row.remark = body.remark
db.commit()
store.invalidate()
return ok({"id": row.id})
@admin.delete("/{type_id}")
def delete_type(type_id: int, db: DbSession, current: PrincipalOf) -> dict[str, Any]:
_need(db, current, "system:dict:edit")
row = db.get(DictType, type_id)
if row is None or row.is_deleted:
raise not_found("字典不存在")
if row.source == DictSource.SYSTEM:
raise conflict("builtin_type", "代码内置字典不能删除;整类不想用可以停用")
row.is_deleted = True
for item in db.execute(select(DictItem).where(DictItem.dict_type_id == row.id,
DictItem.is_deleted.is_(False))
).scalars().all():
item.is_deleted = True
db.commit()
store.invalidate()
return ok({"deleted": True})
@admin.post("/{code}/reset")
def reset_type(code: str, db: DbSession, current: PrincipalOf) -> dict[str, Any]:
"""把代码内置字典恢复成代码定义:改名改乱了、误停了几项,一键回来。"""
_need(db, current, "system:dict:edit")
try:
count = store.reset_items(db, code)
except ValueError as exc:
raise conflict("not_builtin", str(exc)) from None
db.commit()
store.invalidate() # 提交后再失效,免得把提交前的快照重新装回缓存
return ok({"code": code, "count": count})
# ---------------------------------------------------------------------------
# 维护:字典条目
# ---------------------------------------------------------------------------
@admin.get("/{code}/items")
def list_items(code: str, db: DbSession, current: PrincipalOf) -> dict[str, Any]:
_need(db, current, "system:dict:view")
rows = store.items(db, code, include_disabled=True)
spec = store.SPECS.get(code)
return ok({
"code": code,
"defined": spec is not None,
"codeValues": [str(value) for value, _ in spec.items] if spec else [],
"items": rows,
})
class DictItemBody(BaseModel):
#: 整数型字典的前端会把 3 原样传上来,这里收 str|int,落库前统一折成字符串;
#: 空值由 :func:`normalize_value` 挡,min_length 对整数用不上
value: str | int
label: str = Field(min_length=1, max_length=128)
sort: int = 100
enabled: bool = True
tag: str = ""
remark: str = ""
def _type_or_404(db: DbSession, code: str) -> DictType:
row = db.execute(select(DictType).where(DictType.code == code,
DictType.is_deleted.is_(False))
).scalars().first()
if row is None:
raise not_found("字典不存在")
return row
@admin.post("/{code}/items")
def create_item(code: str, body: DictItemBody, db: DbSession,
current: PrincipalOf) -> dict[str, Any]:
_need(db, current, "system:dict:edit")
parent = _type_or_404(db, code)
value = _normalized(parent, body.value)
if db.execute(select(DictItem).where(DictItem.dict_type_id == parent.id,
DictItem.value == value,
DictItem.is_deleted.is_(False))
).scalars().first():
raise conflict("duplicated_value", f"取值 {value} 已存在")
row = DictItem(dict_type_id=parent.id, value=value, label=body.label.strip(),
sort=body.sort, enabled=body.enabled, tag=body.tag.strip(),
builtin=False, remark=body.remark)
db.add(row)
db.commit()
store.invalidate()
return ok({"id": row.id})
@admin.put("/items/{item_id}")
def update_item(item_id: int, body: DictItemBody, db: DbSession,
current: PrincipalOf) -> dict[str, Any]:
_need(db, current, "system:dict:edit")
row = db.get(DictItem, item_id)
if row is None or row.is_deleted:
raise not_found("字典项不存在")
parent = db.get(DictType, row.dict_type_id)
if parent is None:
raise not_found("字典不存在")
value = row.value
if str(body.value).strip() != row.value:
if row.builtin:
raise conflict("builtin_item",
"代码内置取值不能改,业务代码按它判分支;要改名字请改「显示名称」")
value = _normalized(parent, body.value)
clash = db.execute(select(DictItem).where(
DictItem.dict_type_id == parent.id, DictItem.value == value,
DictItem.is_deleted.is_(False), DictItem.id != row.id)).scalars().first()
if clash:
raise conflict("duplicated_value", f"取值 {value} 已存在")
row.value, row.label, row.sort = value, body.label.strip(), body.sort
row.enabled, row.tag, row.remark = body.enabled, body.tag.strip(), body.remark
db.commit()
store.invalidate()
return ok({"id": row.id})
@admin.delete("/items/{item_id}")
def delete_item(item_id: int, db: DbSession, current: PrincipalOf) -> dict[str, Any]:
_need(db, current, "system:dict:edit")
row = db.get(DictItem, item_id)
if row is None or row.is_deleted:
raise not_found("字典项不存在")
if row.builtin:
raise conflict("builtin_item", "代码内置取值不能删除,从下拉框里摘掉请改用「停用」")
row.is_deleted = True
db.commit()
store.invalidate()
return ok({"deleted": True})
@admin.post("/items/{item_id}/toggle")
def toggle_item(item_id: int, db: DbSession, current: PrincipalOf) -> dict[str, Any]:
"""界面上那枚开关走这条:只翻启停,不用把整份表单提交一遍。"""
_need(db, current, "system:dict:edit")
row = db.get(DictItem, item_id)
if row is None or row.is_deleted:
raise not_found("字典项不存在")
row.enabled = not row.enabled
db.commit()
store.invalidate()
return ok({"id": row.id, "enabled": bool(row.enabled)})
def _normalized(parent: DictType, value: str) -> str:
try:
return store.normalize_value(parent.value_type, value)
except ValueError as exc:
raise conflict("invalid_value", str(exc)) from None