build_dm2_ontology.py
24.9 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
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
"""把「4S 店配件库存与缺件处理」场景建进 v10:本体空间、数据源、值类型、对象(含接口)、关系、状态机、指标、
决策表、对象集、动作(含状态流转)、流程卡、预警规则、角色和成员。走的是界面用的同一套接口,所以它同时是验收脚本。
./.venv/Scripts/python.exe scripts/build_dm2_ontology.py # 建在 9200 的 dealer_parts 空间
./.venv/Scripts/python.exe scripts/build_dm2_ontology.py --port 9201 # 换个实例
业务表要先灌好:scripts/setup_v10.py(或单独跑 seed_dealer_parts_demo.py)。场景说明见 docs/demo2_4S/。
"""
from __future__ import annotations
import argparse
import sys
import time
from pathlib import Path
import requests
ROOT = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(ROOT))
sys.stdout.reconfigure(encoding="utf-8")
WS = "dealer_parts"
BASE = "http://127.0.0.1:9200"
HEAD = {"X-User-Id": "admin", "X-Workspace": WS}
def call(method: str, path: str, body=None, ok=(200, 201), user: str = "admin", **params):
r = requests.request(method, BASE + path, json=body, params=params or None,
headers={**HEAD, "X-User-Id": user}, timeout=120)
if r.status_code not in ok:
raise SystemExit(f"{method} {path} → {r.status_code}:{r.text[:600]}")
return r.json() if "json" in r.headers.get("content-type", "") else r.text
# ---------------------------------------------------------------- 对象
# 表 → (对象名, 标题模板, {列: (显示名, 格式, 单位)}, 可修改的列, 算出来的属性, 状态颜色)
T = "otlg_dm2_"
OBJECTS = {
"dealer": ("门店", "", {
"dealer_id": ("店号",), "dealer_name": ("门店名称",), "city": ("城市",), "level": ("级别", "status"),
"parts_manager": ("配件主管",), "general_manager": ("店总",),
"credit_limit": ("赊销额度", "money", "元"), "credit_used": ("已用额度", "money", "元")},
["credit_used"],
[("credit_left", "剩余额度", "credit_limit - credit_used", "number", "money", "元")],
{"level": {"A": "ok", "B": "info", "C": "neutral"}}),
"part": ("配件", "", {
"part_id": ("配件编号",), "part_name": ("配件名称",), "category": ("品类",),
"flow_class": ("流速分类", "status"), "unit": ("单位",),
"dealer_price": ("进货价", "money", "元"), "retail_price": ("零售价", "money", "元"),
"pack_qty": ("最小包装量", "quantity"), "lead_days_normal": ("常规到货天数", "quantity", "天"),
"lead_days_urgent": ("紧急到货天数", "quantity", "天"), "is_controlled": ("配额管控", "status")},
[], [],
{"is_controlled": {"是": "warn", "否": "neutral"},
"flow_class": {"快流": "ok", "中流": "info", "慢流": "neutral"}}),
"oem_stock": ("主机厂库存", "{part_id}", {
"part_id": ("配件",), "warehouse_name": ("仓库",), "on_hand": ("在库", "quantity"),
"allocated": ("已分配", "quantity"), "monthly_capacity": ("月供应能力", "quantity"),
"supply_status": ("供应状态", "status"), "next_replenish_date": ("下一批到库",),
"updated_at": ("更新时间",)},
["allocated", "supply_status"],
[("available", "可分配量", "on_hand - allocated", "number", "quantity", "")],
{"supply_status": {"正常": "ok", "紧张": "warn", "配额管控": "danger"}}),
"dealer_stock": ("门店库存", "{dealer_id} · {part_id}", {
"stock_id": ("库存编号",), "dealer_id": ("门店",), "part_id": ("配件",),
"on_hand": ("在库", "quantity"), "reserved": ("预留", "quantity"), "in_transit": ("在途", "quantity"),
"order_point": ("订货许可线", "quantity"), "max_stock": ("库存上限", "quantity"),
"avg_monthly_usage": ("月均用量", "quantity"), "last_out_date": ("最近出库",),
"updated_at": ("更新时间",)},
["on_hand", "in_transit", "reserved", "order_point", "max_stock"],
[("available", "可用库存", "on_hand - reserved + in_transit", "number", "quantity", ""),
("months", "可用月数", "round(safe_div(on_hand - reserved + in_transit, avg_monthly_usage), 1)",
"number", "quantity", "个月"),
("can_order", "可订货", "available < order_point", "boolean", "status", ""),
("suggest_qty", "建议订货量",
"max(0, floor((max_stock - available) / 配件.pack_qty) * 配件.pack_qty)", "number", "quantity", ""),
("overstock", "超储", "available > max_stock", "boolean", "status", ""),
("stock_amount", "库存金额", "on_hand * 配件.dealer_price", "number", "money", "元"),
("region_share", "区域占比", "round(share(on_hand, part_id), 4)", "number", "percent", ""),
("hoarding", "囤货预警", "overstock and region_share > 0.5", "boolean", "status", ""),
("idle_days", "未出库天数", "days_between(last_out_date, today())", "number", "quantity", "天"),
("dead", "呆滞", "on_hand > 0 and idle_days > 90", "boolean", "status", "")],
{"can_order": {"1": "info", "0": "neutral"}, "overstock": {"1": "warn", "0": "neutral"},
"hoarding": {"1": "danger", "0": "neutral"}, "dead": {"1": "warn", "0": "neutral"}}),
"quota": ("月度配额", "{dealer_id} · {part_id} · {month}", {
"quota_id": ("配额编号",), "dealer_id": ("门店",), "part_id": ("配件",), "month": ("月份",),
"quota_qty": ("配额量", "quantity"), "used_qty": ("已用量", "quantity")},
["quota_qty", "used_qty"],
[("left_qty", "配额剩余", "quota_qty - used_qty", "number", "quantity", "")], {}),
"work_order": ("维修工单", "{wo_no} {plate_no}", {
"wo_no": ("工单号",), "dealer_id": ("门店",), "plate_no": ("车牌",), "car_model": ("车型",),
"customer_name": ("客户",), "service_advisor": ("服务顾问",), "repair_type": ("维修类型", "status"),
"open_date": ("开单日期",), "promised_date": ("承诺交车",), "finished_date": ("完工日期",),
"status": ("状态", "status"), "loaner_car": ("代步车", "status")},
["status", "loaner_car"],
[("overdue_days", "超期天数",
"max(0, days_between(promised_date, today())) if status == '待料' else 0", "number", "quantity", "天")],
{"status": {"待料": "danger", "维修中": "info", "已完工": "ok", "已交车": "neutral"},
"loaner_car": {"是": "ok", "否": "neutral"}}),
"work_order_part": ("工单用料", "{wo_no} · {part_id}", {
"line_id": ("用料编号",), "wo_no": ("工单",), "part_id": ("配件",), "qty_need": ("需求数量", "quantity"),
"qty_issued": ("已领数量", "quantity"), "status": ("状态", "status"), "issue_date": ("领料日期",)},
[], [], {"status": {"已领料": "ok", "已预留": "info", "缺件": "danger"}}),
"shortage": ("缺件单", "{shortage_id} {part_id}", {
"shortage_id": ("缺件单号",), "wo_no": ("工单",), "dealer_id": ("门店",), "part_id": ("配件",),
"qty_short": ("缺件数量", "quantity"), "found_date": ("发现日期",), "handle_type": ("处理方式", "status"),
"ref_no": ("关联单号",), "expected_date": ("预计到件",), "resolved_date": ("解决日期",),
"status": ("状态", "status"), "customer_notified": ("已通知客户", "status"), "remark": ("备注",)},
["handle_type", "ref_no", "expected_date", "resolved_date", "customer_notified", "remark"],
[("wait_days", "等待天数", "days_between(found_date, coalesce(resolved_date, today()))",
"number", "quantity", "天")],
{"status": {"待处理": "danger", "处理中": "warn", "已解决": "ok"},
"handle_type": {"未处理": "danger", "店间调拨": "info", "缺件专订": "info", "等常规到货": "warn"},
"customer_notified": {"是": "ok", "否": "warn"}}),
"purchase_order": ("配件订单", "{po_no} {part_id} ×{qty}", {
"po_no": ("订单号",), "dealer_id": ("门店",), "part_id": ("配件",), "qty": ("数量", "quantity"),
"amount": ("金额", "money", "元"), "freight_fee": ("加急运费", "money", "元"),
"order_type": ("订单类型", "status"), "shortage_id": ("缺件单",), "status": ("状态", "status"),
"reject_reason": ("驳回原因",), "order_date": ("下单日期",), "expected_date": ("预计到货",),
"arrived_date": ("到货日期",)},
["status", "reject_reason", "arrived_date", "expected_date"],
[("overdue", "超期未到", "status == '已发货' and expected_date < today()", "boolean", "status", "")],
{"status": {"店内待审批": "warn", "主机厂审核中": "warn", "已驳回": "danger", "已发货": "info",
"已到货": "ok", "已取消": "neutral"},
"order_type": {"常规": "neutral", "紧急": "warn", "缺件专订": "danger"},
"overdue": {"1": "danger", "0": "neutral"}}),
"transfer_order": ("调拨单", "{transfer_no} {part_id} ×{qty}", {
"transfer_no": ("调拨单号",), "from_dealer_id": ("调出门店",), "to_dealer_id": ("调入门店",),
"part_id": ("配件",), "qty": ("数量", "quantity"), "amount": ("金额", "money", "元"),
"shortage_id": ("缺件单",), "status": ("状态", "status"), "apply_date": ("申请日期",),
"expected_date": ("预计到货",), "arrived_date": ("到货日期",), "remark": ("备注",)},
["status", "arrived_date", "remark"], [],
{"status": {"待调出店确认": "warn", "待主机厂审批": "warn", "在途": "info", "已完成": "ok",
"已拒绝": "danger"}}),
}
# 状态机:缺件单的状态只能经由动作流转(处理方式定了才转处理中,配件到了才算解决)
LIFECYCLES = {("shortage", "status"): {
"states": [{"value": "待处理", "tone": "danger"}, {"value": "处理中", "tone": "warn"},
{"value": "已解决", "tone": "ok", "terminal": True}],
"initial": "待处理",
"transitions": [*({"from": ["待处理", "处理中"], "to": "处理中", "action": a}
for a in ("下缺件专订", "发起店间调拨", "强制调拨")),
{"from": ["待处理", "处理中"], "to": "已解决", "action": "订单到货入库"}]}}
# 值类型:库存数量不能是负数(动作、流程写进去的时候统一校验)
VALUE_TYPES = [("配件数量", "库存、在途、预留的件数:不能是负数",
{"base_type": "integer", "min": 0, "format": "quantity", "message": "配件数量不能是负数"})]
VALUE_TYPE_OF = {("dealer_stock", c): "配件数量" for c in ("on_hand", "reserved", "in_transit")}
# 接口:「库存点」—— 门店库存和主机厂库存都是,查某个配件全区域的货一次查全
INTERFACE = ("库存点", "放着配件的地方:门店库存、主机厂区域库存都实现它", {
"abstract": True, "properties": [{"name": "配件", "is_dimension": True}, {"name": "在库", "data_type": "number"},
{"name": "可用", "data_type": "number"}]})
IMPLEMENTS = {"dealer_stock": {"配件": "part_id", "在库": "on_hand", "可用": "available"},
"oem_stock": {"配件": "part_id", "在库": "on_hand", "可用": "available"}}
def _cond(left: str, op: str, right) -> dict:
return {"mode": "all", "items": [{"left": left, "op": op, "right": right}]}
OBJECT_SETS = [
("未解决缺件单", "还没到件的缺件单", {"category": "object_set", "base": "缺件单",
"where": _cond("status", "ne", "已解决")}),
("可调出的库存", "超储的「门店 × 配件」:可以调给缺件的店", {"category": "object_set", "base": "门店库存",
"where": _cond("overstock", "eq", 1),
"sort": [{"property": "months", "dir": "desc"}]}),
("囤货的库存", "单店占区域在库超过一半、且超储", {"category": "object_set", "base": "门店库存",
"where": _cond("hoarding", "eq", 1)}),
("缺件涉及的配件", "未解决缺件单缺的那些配件", {"category": "object_set", "base": "未解决缺件单",
"around": [{"link": "缺件单所缺配件"}]}),
("能救急的超储库存", "缺件涉及的配件里,哪些店超储、可以调出来", {
"category": "object_set", "base": "缺件涉及的配件", "around": [{"link": "库存对应配件"}],
"combine": [{"op": "intersect", "set": "可调出的库存"}]}),
]
# 关系:(名称, 起点表, 终点表, 起点列, 终点列)
LINKS = [
("库存所属门店", "dealer_stock", "dealer", "dealer_id", "dealer_id"),
("库存对应配件", "dealer_stock", "part", "part_id", "part_id"),
("主机厂库存对应配件", "oem_stock", "part", "part_id", "part_id"),
("配额所属门店", "quota", "dealer", "dealer_id", "dealer_id"),
("配额对应配件", "quota", "part", "part_id", "part_id"),
("工单所属门店", "work_order", "dealer", "dealer_id", "dealer_id"),
("用料所属工单", "work_order_part", "work_order", "wo_no", "wo_no"),
("用料对应配件", "work_order_part", "part", "part_id", "part_id"),
("缺件单来自工单", "shortage", "work_order", "wo_no", "wo_no"),
("缺件单所属门店", "shortage", "dealer", "dealer_id", "dealer_id"),
("缺件单所缺配件", "shortage", "part", "part_id", "part_id"),
("订单下单门店", "purchase_order", "dealer", "dealer_id", "dealer_id"),
("订单所订配件", "purchase_order", "part", "part_id", "part_id"),
("订单解决缺件单", "purchase_order", "shortage", "shortage_id", "shortage_id"),
("调拨调出门店", "transfer_order", "dealer", "from_dealer_id", "dealer_id"),
("调拨调入门店", "transfer_order", "dealer", "to_dealer_id", "dealer_id"),
("调拨所调配件", "transfer_order", "part", "part_id", "part_id"),
("调拨解决缺件单", "transfer_order", "shortage", "shortage_id", "shortage_id"),
]
# 指标:(名称, 同义词, 对象, 聚合表达式, 过滤, 单位, 格式, 方向, 说明)
METRICS = [
("库存金额", ["库存资金", "压了多少钱"], "门店库存", "SUM(stock_amount)", [], "元", "money", "lower_better",
"在库数量 × 进货价,各店各配件合计"),
("呆滞金额", ["呆滞库存金额"], "门店库存", "SUM(stock_amount)", ["dead = 1"], "元", "money", "lower_better",
"超过 90 天没有出库的在库配件占压的资金"),
("超储金额", [], "门店库存", "SUM(stock_amount)", ["overstock = 1"], "元", "money", "lower_better",
"可用库存超过库存上限的配件占压的资金"),
("在库数量", ["库存数量", "有多少货"], "门店库存", "SUM(on_hand)", [], "件", "quantity", "neutral",
"门店里当前的实物数量"),
("可订货配件数", ["可以订的件"], "门店库存", "COUNT(*)", ["can_order = 1"], "个", "quantity", "neutral",
"可用库存低于订货许可线的「门店 × 配件」数"),
("囤货预警数", ["囤货"], "门店库存", "COUNT(*)", ["hoarding = 1"], "条", "quantity", "lower_better",
"单店占区域在库超过一半、且超储的「门店 × 配件」数"),
("待料工单数", ["等件的车", "在等件的工单"], "维修工单", "COUNT(*)", ["status = '待料'"], "张", "quantity",
"lower_better", "状态为待料的工单数"),
("超期待料工单数", ["超期工单"], "维修工单", "COUNT(*)", ["overdue_days > 0"], "张", "quantity", "lower_better",
"待料且已过承诺交车日期的工单数"),
("未解决缺件单数", ["缺件单数", "缺件"], "缺件单", "COUNT(*)", ["status <> '已解决'"], "张", "quantity",
"lower_better", "还没有到件的缺件单数"),
("缺件等待天数", ["平均等待天数"], "缺件单", "ROUND(AVG(wait_days), 1)", [], "天", "quantity", "lower_better",
"从发现缺件到配件到店平均等几天;未解决的算到今天"),
("配额使用率", [], "月度配额", "ROUND(SUM(used_qty) / NULLIF(SUM(quota_qty), 0), 4)", [], "", "percent",
"neutral", "已用量 ÷ 配额量"),
("主机厂可分配量", ["主机厂还有多少"], "主机厂库存", "SUM(available)", [], "件", "quantity", "higher_better",
"主机厂在库 − 已分配"),
("超期订单数", ["超期未到的订单"], "配件订单", "COUNT(*)", ["overdue = 1"], "张", "quantity", "lower_better",
"已发货、过了预计到货日还没到的订单数"),
]
ROLES = [("服务顾问", "接车开工单、通知客户"), ("配件主管", "管本店库存、发起订货和调拨、处理缺件单"),
("店总", "审批大额订货、同意或拒绝调货"), ("配件计划员", "主机厂:审核管控件订单和缺件专订"),
("区域配件经理", "主机厂:特批超限订单、审批调拨、处理囤货")]
USERS = [("parts_mgr", "配件主管·华丽君", ["operator"], ["配件主管"]),
("store_gm", "店总·邹海涛", ["operator", "approver"], ["店总"]),
("advisor", "服务顾问·小韩", ["operator"], ["服务顾问"]),
("planner", "计划员·周敏", ["operator", "approver"], ["配件计划员"]),
("region_mgr", "区域经理·吴峰", ["operator", "approver"], ["区域配件经理"])]
def ensure_workspace() -> None:
ws = {w["id"] for w in call("GET", "/api/kernel/workspaces")}
if WS not in ws:
call("POST", "/api/kernel/workspaces", {"id": WS, "display_name": "远航汽车 · 配件",
"description": "4S 店配件库存与缺件处理", "industry": "汽车售后"})
print("新建本体空间", WS)
else: # 带着空间头的请求会自动建出空间(名字是默认的):补上名字
call("PUT", f"/api/kernel/workspaces/{WS}", {"id": WS, "display_name": "远航汽车 · 配件",
"description": "4S 店配件库存与缺件处理", "industry": "汽车售后"})
def ensure_datasource() -> int:
from app.core.config import get_settings
st = get_settings()
for ds in call("GET", "/api/sql/datasources"):
if ds["name"] == "配件业务库":
ds_id = ds["id"]
break
else:
ds_id = call("POST", "/api/sql/datasources", {
"name": "配件业务库", "ds_type": "mysql", "host": st.db_host, "port": st.db_port,
"db_name": st.db_name, "username": st.db_user, "password": st.db_password,
"extra": {"tables": T + "*", "writeback": True}})["id"]
job = call("POST", f"/api/sql/datasources/{ds_id}/introspect")["job_id"]
for _ in range(120):
j = call("GET", f"/api/jobs/{job}")
if j.get("status") in ("done", "failed", "error", "succeeded", "success"):
break
time.sleep(1)
n = len(call("GET", f"/api/sql/datasources/{ds_id}/models"))
print(f"数据源 {ds_id}:{n} 张表({j.get('status')})")
return ds_id
def concepts(kind: str) -> dict[str, dict]:
return {c["name"]: c for c in call("GET", "/api/kernel/concepts", kind=kind)}
def build_semantic() -> None:
have = concepts("value_type")
for name, desc, spec in VALUE_TYPES:
if name in have:
call("PUT", f"/api/kernel/concepts/{have[name]['id']}", {"description": desc, "spec": spec})
else:
call("POST", "/api/kernel/concepts", {"kind": "value_type", "name": name, "description": desc, "spec": spec})
have = concepts("object_type")
name, desc, spec = INTERFACE
if name in have:
call("PUT", f"/api/kernel/concepts/{have[name]['id']}", {"description": desc, "spec": spec})
else:
call("POST", "/api/kernel/concepts", {"kind": "object_type", "name": name, "description": desc, "spec": spec})
print(f"值类型 {len(VALUE_TYPES)} 个,接口 1 个")
def build_objects(ds_id: int) -> dict[str, str]:
have = concepts("object_type")
ids: dict[str, str] = {}
for table, (name, title, cols, writable, derived, tones) in OBJECTS.items():
c = have.get(name) or call("POST", "/api/kernel/from-table", {"ds_id": ds_id, "table": T + table, "name": name})
c = call("GET", f"/api/kernel/concepts/{c['id']}")
props = []
for p in c["spec"]["properties"]:
if p.get("expression"):
continue
meta = cols.get(p["name"]) or (p["name"],)
one = {**p, "display_name": meta[0], "format": meta[1] if len(meta) > 1 else "",
"unit": meta[2] if len(meta) > 2 else "", "is_writable": p["name"] in writable,
"tones": tones.get(p["name"]) or {}}
if (table, p["name"]) in LIFECYCLES:
one["lifecycle"] = LIFECYCLES[(table, p["name"])]
if (table, p["name"]) in VALUE_TYPE_OF:
one["value_type"] = VALUE_TYPE_OF[(table, p["name"])]
props.append(one)
for pname, label, expr, dtype, fmt, unit in derived:
props.append({"name": pname, "display_name": label, "data_type": dtype, "expression": expr,
"format": fmt, "unit": unit, "tones": tones.get(pname) or {}})
spec = {**c["spec"], "properties": props, "title_template": title}
if table in IMPLEMENTS:
spec["implements"] = [{"interface": INTERFACE[0], "mapping": IMPLEMENTS[table]}]
call("PUT", f"/api/kernel/concepts/{c['id']}", {"spec": spec})
ids[table] = c["id"]
print(f"对象 {len(ids)} 个")
return ids
def build_links(ds_id: int, ids: dict[str, str]) -> None:
have = concepts("link_type")
for name, a, b, ca, cb in LINKS:
c = have.get(name) or call("POST", "/api/kernel/concepts", {
"kind": "link_type", "name": name,
"spec": {"from_type": ids[a], "to_type": ids[b], "cardinality": "n:1"}})
call("PUT", f"/api/kernel/concepts/{c['id']}/bindings",
{"ds_id": ds_id, "target_kind": "join", "ref": {"from_column": ca, "to_column": cb}})
print(f"关系 {len(LINKS)} 条")
def build_metrics(ds_id: int, ids: dict[str, str]) -> None:
have = concepts("function")
by_name = {OBJECTS[t][0]: i for t, i in ids.items()}
for name, syn, obj, expr, filters, unit, fmt, direction, desc in METRICS:
c = have.get(name) or call("POST", "/api/kernel/concepts", {
"kind": "function", "name": name, "description": desc, "synonyms": syn,
"spec": {"category": "aggregate", "object_type": by_name[obj], "unit": unit, "format": fmt,
"direction": direction, "formula_text": desc}})
call("PUT", f"/api/kernel/concepts/{c['id']}/bindings", {
"ds_id": ds_id, "target_kind": "metric_expr",
"ref": {"base_object": by_name[obj], "expression": expr, "filters": filters}})
for name, desc, spec in OBJECT_SETS:
c = have.get(name)
if c:
call("PUT", f"/api/kernel/concepts/{c['id']}", {"description": desc, "spec": spec})
else:
call("POST", "/api/kernel/concepts", {"kind": "function", "name": name, "description": desc, "spec": spec})
print(f"指标 {len(METRICS)} 个,对象集 {len(OBJECT_SETS)} 个")
def build_people() -> None:
have = {r["name"] for r in call("GET", "/api/gov/roles")}
for name, desc in ROLES:
if name not in have:
call("POST", "/api/gov/roles", {"name": name, "description": desc})
for uid, name, roles, biz in USERS:
call("PUT", f"/api/gov/users/{uid}", {"name": name, "roles": roles, "biz_roles": biz})
print(f"角色 {len(ROLES)} 个,成员 {len(USERS)} 个")
def publish(note: str) -> None:
r = call("POST", "/api/kernel/publish", {"note": note, "approve_now": True}, ok=(200, 201, 409, 422))
if "没有待发布的变更" in str(r.get("detail") or ""):
print(f"发布「{note}」:没有新的变更")
return
if r.get("status") != "accepted":
raise SystemExit(f"发布「{note}」没通过:{str(r)[:800]}")
print(f"发布「{note}」:已发布")
def main() -> None:
global BASE
ap = argparse.ArgumentParser()
ap.add_argument("--port", type=int, default=9200)
args = ap.parse_args()
BASE = f"http://127.0.0.1:{args.port}"
ensure_workspace()
ds_id = ensure_datasource()
build_people()
build_semantic()
ids = build_objects(ds_id)
build_links(ds_id, ids)
publish("对象与关系")
build_metrics(ds_id, ids)
from scripts import build_dm2_behavior as beh
beh.build(call, ids, OBJECTS)
publish("指标、决策表与动作")
beh.build_flows(call, ids, OBJECTS)
call("POST", "/api/kernel/pipelines/ensure")
job = call("POST", "/api/kernel/pipelines/run-all")["job_id"]
for _ in range(300):
if call("GET", f"/api/jobs/{job}").get("status") in ("done", "failed", "error"):
break
time.sleep(1)
print(f"4S 配件场景建好了:{BASE}(右上角切到「远航汽车 · 配件」)")
if __name__ == "__main__":
main()