templates.py
10.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
"""本体即代码:YAML 导入导出 + 行业模板包。
YAML 里元素之间用名称引用(`@对象名` 或直接写名称),导入时解析成 id,
这样模板可读、可 diff、可在客户之间复用。
- concepts:四种元素(对象 / 关系 / 函数 / 动作);
- roles:业务角色名单;
- sops:流程卡,由 SOP 模块注册的 section handler 处理;
- 旧格式(kind: metric / rule / calendar,capabilities 里的 skill / action)导入时自动换成四元组。
"""
from __future__ import annotations
from pathlib import Path
from typing import Any, Callable
import yaml
from fastapi import HTTPException
from ..governance import audit
from . import schema, service
TEMPLATE_DIR = Path(__file__).resolve().parents[2] / "templates"
# 其他 section(capabilities / sops)的导入导出由对应模块注册
_import_sections: dict[str, Callable[[list[dict]], dict]] = {}
_export_sections: dict[str, Callable[[], list[dict]]] = {}
def register_section(name: str, importer: Callable[[list[dict]], dict],
exporter: Callable[[], list[dict]]) -> None:
_import_sections[name] = importer
_export_sections[name] = exporter
_REF_FIELDS = {"function": ("calibre_rule", "object_type"),
"link_type": ("from_type", "to_type"), "action": ("target_type",)}
_SKIP_SPEC = ("ui", "risk_level")
def export_yaml(include_drafts: bool = True) -> str:
items = service.list_concepts(status="" if include_drafts else "published")
id2name = {c["id"]: c["name"] for c in items}
concepts = []
for brief in items:
c = service.get_concept(brief["id"])
spec = {k: v for k, v in (c.get("spec") or {}).items() if k not in _SKIP_SPEC}
for f in _REF_FIELDS.get(c["kind"], ()):
if spec.get(f) in id2name:
spec[f] = "@" + id2name[spec[f]]
_names_in_effects(spec, id2name)
entry: dict[str, Any] = {"kind": c["kind"], "name": c["name"]}
for k in ("display_name", "description"):
if c.get(k):
entry[k] = c[k]
if c.get("synonyms"):
entry["synonyms"] = c["synonyms"]
if spec:
entry["spec"] = spec
if c.get("bindings"):
entry["bindings"] = [{"ds_id": b["ds_id"], "target_kind": b["target_kind"],
"ref": b["ref"]} for b in c["bindings"]]
concepts.append(entry)
from ..governance import roles
doc: dict[str, Any] = {"version": 2, "concepts": concepts,
"roles": [{"name": r["name"], "description": r["description"]}
for r in roles.list_roles()]}
for name, fn in _export_sections.items():
try:
doc[name] = fn()
except Exception: # noqa: BLE001
doc[name] = []
return yaml.safe_dump(doc, allow_unicode=True, sort_keys=False, width=120)
def _names_in_effects(spec: dict, id2name: dict[str, str]) -> None:
"""动作效果里写的对象类型 id 换回名称,模板才能跨环境复用。"""
for e in spec.get("effects") or []:
args = e.get("args") or {}
if args.get("object_type") in id2name:
args["object_type"] = id2name[args["object_type"]]
def _legacy_items(doc: dict) -> tuple[list[dict], list[dict], list[str]]:
"""旧格式 → 四元组。返回 (元素条目, 角色, 提示)。
老模板里的周期函数(category=calendar)不再是元素:并进引用它的指标,成为指标自己的统计周期口径。"""
items, roles, notes = [], list(doc.get("roles") or []), []
periods: dict[str, dict] = {}
for it in list(doc.get("concepts") or []):
sp = it.get("spec") or {}
if it.get("kind") in ("function", "calendar") and (sp.get("category") == "calendar" or it.get("kind") == "calendar"):
per = {k: sp[k] for k in ("grain", "start_day", "start_month_offset", "end_day", "end_month_offset") if k in sp}
per["label"] = str(it.get("name") or "")
for n in [it.get("name"), *(it.get("synonyms") or [])]:
if n:
periods[str(n)] = per
for it in list(doc.get("concepts") or []) + list(doc.get("capabilities") or []):
sp = it.get("spec") or {}
if sp.get("category") == "calendar" or it.get("kind") == "calendar":
notes.append(f"{it.get('name')}:统计周期并进了引用它的指标(指标自己的周期口径),不再单独建元素")
continue
cal_ref = str(sp.get("calendar") or "").lstrip("@")
if cal_ref:
sp = {k: v for k, v in sp.items() if k != "calendar"}
if cal_ref in periods and not sp.get("period"):
sp["period"] = periods[cal_ref]
it = {**it, "spec": sp}
kind = it.get("kind")
if kind == "role":
roles.append({"name": it.get("name"), "description":
(it.get("spec") or {}).get("responsibilities") or it.get("description") or ""})
continue
if kind in ("process", "term", "dimension"):
notes.append(f"{it.get('name')}:{kind} 不再是元素(流程请建流程卡,术语写成同义词),已跳过")
continue
up = schema.element_kind(str(kind or ""), it.get("spec") or {})
if up is None:
items.append(it) # 交给后面报「无效条目」
continue
items.append({**it, "kind": up[0], "spec": up[1]})
return items, roles, notes
def _deref(v: Any) -> Any:
if isinstance(v, str) and v.startswith("@"):
found = service.find(v[1:])
return found["id"] if found else v[1:]
return v
def import_yaml(text: str, *, ds_map: dict[int, int] | None = None, overwrite: bool = False,
with_bindings: bool = True) -> dict:
"""导入。已存在的同名同类概念默认跳过(overwrite=True 时覆盖)。
ds_map:模板里的数据源编号 → 本地数据源编号。模板通常不带绑定,带了也要映射。
"""
try:
doc = yaml.safe_load(text) or {}
except yaml.YAMLError as e:
raise HTTPException(422, f"YAML 解析失败:{e}") from e
if not isinstance(doc, dict):
raise HTTPException(422, "YAML 顶层必须是对象")
items, role_items, notes = _legacy_items(doc)
created, updated, skipped, errors = [], [], [], []
from ..governance import roles
for r in role_items:
if r.get("name"):
roles.upsert(str(r["name"]), str(r.get("description") or ""))
# 对象先建:函数、关系、动作都可能引用它们(动作的校验还要看对象属性是否可写)
order = {"object_type": 0, "link_type": 1, "function": 2, "action": 3}
items.sort(key=lambda it: order.get(it.get("kind"), 9))
# 两遍:先建全部概念(引用可能指向后面的),再回填引用
pending_refs: list[tuple[str, str, dict]] = []
for it in items:
kind, name = it.get("kind"), str(it.get("name") or "").strip()
if kind not in schema.KINDS or not name:
errors.append(f"无效条目:{it!r}"[:200])
continue
spec = dict(it.get("spec") or {})
raw_refs = {f: spec.get(f) for f in _REF_FIELDS.get(kind, ()) if spec.get(f)}
for f in raw_refs:
spec[f] = ""
if kind == "action" and raw_refs.get("target_type"):
v = str(raw_refs.pop("target_type")) # 动作校验要当场知道对象,不能回填
spec["target_type"] = _deref(v if v.startswith("@") else "@" + v)
existing = service.find(name, kind)
try:
if existing and not overwrite:
skipped.append(name)
continue
if existing:
c = service.update_concept(existing["id"], display_name=it.get("display_name"),
description=it.get("description"),
synonyms=it.get("synonyms"), spec=spec)
updated.append(name)
else:
c = service.create_concept(kind, name, display_name=it.get("display_name", ""),
description=it.get("description", ""),
synonyms=it.get("synonyms"), spec=spec,
origin="template")
created.append(name)
if with_bindings:
for b in it.get("bindings") or []:
ds = int(b.get("ds_id") or 0)
ds = (ds_map or {}).get(ds, ds)
if ds:
service.set_binding(c["id"], ds, b["target_kind"], b.get("ref") or {})
if raw_refs:
pending_refs.append((c["id"], kind, raw_refs))
except HTTPException as e:
errors.append(f"{name}:{e.detail}")
for cid, kind, refs in pending_refs:
c = service.get_concept(cid)
spec = dict(c.get("spec") or {})
for f, v in refs.items():
spec[f] = _deref(v if str(v).startswith("@") else "@" + str(v))
service.update_concept(cid, spec=spec)
extra = {}
for name, fn in _import_sections.items():
if doc.get(name):
try:
extra[name] = fn(doc[name])
except HTTPException as e:
errors.append(f"{name}:{e.detail}")
audit.record("ontology.import", "ontology", "", f"导入 YAML:新增 {len(created)},"
f"更新 {len(updated)},跳过 {len(skipped)},错误 {len(errors)}")
return {"created": created, "updated": updated, "skipped": skipped, "errors": errors,
"notes": notes, "roles": len(role_items), "sections": extra}
def list_templates() -> list[dict]:
out = []
for p in sorted(TEMPLATE_DIR.glob("*.yaml")):
try:
doc = yaml.safe_load(p.read_text(encoding="utf-8")) or {}
except Exception: # noqa: BLE001
continue
items = doc.get("concepts") or []
count = {k: sum(1 for i in items if i.get("kind") == k)
for k in ("object_type", "link_type", "function", "action")}
out.append({"id": p.stem, "name": doc.get("name") or p.stem,
"description": doc.get("description") or "",
"concepts": len(items), "counts": count,
"roles": len(doc.get("roles") or []),
"sops": len(doc.get("sops") or [])})
return out
def apply_template(template_id: str, overwrite: bool = False) -> dict:
p = TEMPLATE_DIR / f"{template_id}.yaml"
if not p.exists() or p.parent != TEMPLATE_DIR:
raise HTTPException(404, "模板不存在")
return import_yaml(p.read_text(encoding="utf-8"), overwrite=overwrite, with_bindings=False)