walk_dm2.py
17.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
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
"""4S 配件场景的验收:把手册里的六个故事按「真人会怎么操作」走一遍,每一步断言结果。
会改业务数据(下单、调拨、审批),所以跑之前先重灌数据,跑完界面上会留下一批可以看的记录:
./.venv/Scripts/python.exe scripts/setup_v10.py --wipe # 或只跑 seed_dealer_parts_demo.py
./.venv/Scripts/python.exe scripts/build_dm2_ontology.py
./.venv/Scripts/python.exe scripts/walk_dm2.py # 默认 9200;--port 换实例
最后一个故事是 v10 内核的闭环:登记缺件 → 对象一变就触发预警 → 拉起缺件处理流程卡 → 从超储店调拨
→ 审批 → 缺件单经状态机转处理中 → 预警自动恢复。
"""
from __future__ import annotations
import argparse
import sys
import time
from pathlib import Path
import requests
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
sys.stdout.reconfigure(encoding="utf-8")
BASE = "http://127.0.0.1:9200"
WS = "dealer_parts"
RESULTS: list[tuple[bool, str]] = []
def call(method: str, path: str, body=None, user: str = "admin", **params):
r = requests.request(method, BASE + path, json=body, params=params or None,
headers={"X-User-Id": user, "X-Workspace": WS}, timeout=180)
try:
return r.status_code, r.json()
except ValueError:
return r.status_code, r.text
def check(ok: bool, what: str, detail: str = "") -> bool:
RESULTS.append((bool(ok), what))
print((" ✓ " if ok else " ✗ ") + what + (f" {detail}" if detail and not ok else ""))
return bool(ok)
def objs(type_: str, user: str = "admin", limit: int = 50, sort=None, **eq) -> list[dict]:
filters = [{"property": k, "op": "eq", "value": v} for k, v in eq.items()]
s, r = call("POST", f"/api/kernel/objects/{type_}/query", {"filters": filters, "limit": limit, "sort": sort or []},
user=user)
if s != 200:
raise SystemExit(f"查「{type_}」失败:{r}")
return r["items"]
def one(type_: str, **eq) -> dict:
items = objs(type_, **eq)
if not items:
raise SystemExit(f"没找到 {type_} {eq}")
return items[0]
def metric(name: str, dims=None, **filters):
s, r = call("POST", "/api/kernel/metrics/query", {"metric": name, "dimensions": dims or [], "filters": filters})
if s != 200:
raise SystemExit(f"指标「{name}」取数失败:{r}")
return r
def prepare(action: str, key: str, user: str, **params) -> dict:
s, r = call("POST", f"/api/cap/actions/{action}/prepare", {"params": params, "object_key": key}, user=user)
if s != 200:
raise SystemExit(f"预览「{action}」失败:{r}")
return r
def propose(action: str, key: str, user: str, why: str = "", **params) -> tuple[int, dict]:
return call("POST", f"/api/cap/actions/{action}/propose",
{"params": params, "object_key": key, "reason": why}, user=user)
def decide(run_id: str, user: str, approve: bool = True, comment: str = "") -> tuple[int, dict]:
return call("POST", f"/api/cap/runs/{run_id}/decide", {"approve": approve, "comment": comment}, user=user)
def wait_run(run_id: str, until=("waiting", "done", "failed", "rejected", "cancelled"), secs: int = 60) -> dict:
for _ in range(secs * 2):
s, r = call("GET", f"/api/sop/runs/{run_id}")
if s == 200 and r["status"] in until:
return r
time.sleep(0.5)
return r
def flow(title: str) -> dict:
s, defs = call("GET", "/api/sop/defs")
return next(d for d in defs if d["title"] == title)
# ---------------------------------------------------------------- 各个故事
def story_read() -> None:
print("一、看数")
hoard = objs("门店库存", hoarding=1)
labels = [o["label"] for o in hoard]
check(any("苏州" in x and "火花塞" in x for x in labels), "囤货预警里有苏州店的火花塞", str(labels))
sz = next(o for o in hoard if "苏州" in o["label"] and "火花塞" in o["label"])["properties"]
check(sz["on_hand"] == 480 and sz["months"] == 12 and abs(sz["region_share"] - 0.7547) < 0.001,
"苏州店火花塞:在库 480、可用 12 个月、占区域 75.5%", str(sz))
from sqlalchemy import create_engine, text
from app.core.config import get_settings
with create_engine(get_settings().sqlalchemy_url, future=True).connect() as c: # 跟日期有关的数,和直接查库比
n_dead = c.execute(text("SELECT COUNT(*) FROM otlg_dm2_dealer_stock WHERE on_hand > 0 "
"AND DATEDIFF(CURDATE(), last_out_date) > 90")).scalar()
n_late = c.execute(text("SELECT COUNT(*) FROM otlg_dm2_work_order WHERE status = '待料' "
"AND promised_date < CURDATE()")).scalar()
check(len(objs("门店库存", dead=1)) == n_dead >= 3, f"呆滞件 {n_dead} 条(超过 90 天没出库,和查库一致)")
check(len(objs("门店库存", dealer_id="D05", can_order=1)) == 19, "常州店 19 个件可订货")
r = metric("库存金额", ["dealer_id"])
names = [m["label"] for m in r["col_meta"]]
check("库存金额(元)" in names and "value" not in names, "指标结果的数值列叫「库存金额(元)」", str(names))
row = {x[0]: x[-1] for x in r["rows"]}
check(round(row.get("D05", 0)) == 21397, "常州店库存金额 21,397 元", str(row))
check(metric("超期待料工单数")["value"] == n_late >= 3, f"超期待料工单 {n_late} 张(和查库一致)")
check(metric("主机厂可分配量", part_id="SP001")["value"] == 6, "主机厂火花塞可分配 6 个")
po = one("配件订单", po_no="PO20260144")
check(po["refs"]["dealer_id"]["label"] == "远航南京江宁店" and "机油滤清器" in po["label"],
"订单上的门店、配件显示成名称", po["label"])
def story_c_d() -> None:
print("二、故事 C、D:主机厂审核两张订单(计划员)")
p = prepare("通过订单", "PO20260144", "planner")
bad = [c["message"] for c in p["checks"] if not c["ok"]]
check(p["blocked"] and any("46" in m and "21" in m for m in bad), "南京店机滤订单通不过:可用 46 不低于许可线 21", str(bad))
s, r = propose("驳回订单", "PO20260144", "planner", reason="可用库存 46 高于订货许可线 21")
check(s == 200 and r["status"] == "done", "计划员驳回这张订单", str(r)[:200])
po = one("配件订单", po_no="PO20260144")["properties"]
check(po["status"] == "已驳回" and "46" in (po["reject_reason"] or ""), "驳回原因写回了订单", str(po))
p = prepare("通过订单", "PO20260149", "planner")
check(not p["blocked"] and [s["name"] for s in p["stages"] if not s["skip"]] == ["区域经理特批"],
"上海店氧传感器订单:规则都过,但配额已用完 → 要区域经理特批", str(p.get("stages")))
s, r = propose("通过订单", "PO20260149", "planner", "店内确实缺货,申请特批")
check(s == 200 and r["status"] == "pending_approval", "提交后等区域经理批", str(r)[:200])
s, mine = call("GET", "/api/cap/inbox", user="region_mgr")
return r["id"]
def story_b() -> None:
print("三、故事 B:常州店每日补货巡检(配件主管)")
d = flow("每日补货巡检")
s, run = call("POST", f"/api/sop/defs/{d['id']}/run", {"params": {"dealer": "D05"}}, user="parts_mgr")
check(s == 200, "发起巡检", str(run)[:300])
if s != 200:
return
run = wait_run(run["id"], until=("done", "failed", "waiting"), secs=120)
steps = {x["step_id"]: x for x in run["steps"]}
check(run["status"] in ("done", "waiting"), f"巡检跑完({run['status']})", str(run.get("error")))
out = (steps.get("orders") or {}).get("output") or {}
check((out.get("total") or 0) > 0, f"逐条下单:处理 {out.get('total')} 条", str(out))
dealer = one("门店", dealer_id="D05")["properties"]
check(dealer["credit_left"] < 4500, f"下单后赊销额度被占用(剩 {dealer['credit_left']})")
check((out.get("failed") or 0) > 0, f"额度不够的那些被挡住了:完成 {out.get('ok')} 条,没过 {out.get('failed')} 条", str(out)[:200])
s, runs = call("GET", "/api/cap/runs", user="parts_mgr", status="failed,done,pending_approval", limit=50)
return run["id"]
def story_a() -> None:
print("四、故事 A:无锡店火花塞缺件 → 调拨被拒 → 强制调拨")
sh = one("缺件单", shortage_id="SH20260010")
p = prepare("下缺件专订", "SH20260010", "parts_mgr", qty=4)
check(not p["blocked"], "缺件专订 4 个:校验能过(主机厂可分配 6)", str([c for c in p["checks"] if not c["ok"]]))
p = prepare("下常规订单", one("门店库存", dealer_id="D04", part_id="SP001")["key"], "parts_mgr", qty=4)
need = [s["name"] for s in p.get("stages") or [] if not s["skip"]]
check("区域经理特批" in need, "无锡店想走常规订单:配额已用完,要区域经理特批", str(need))
s, r = propose("发起店间调拨", "SH20260010", "parts_mgr", "苏州店超储", from_dealer="D03", qty=4)
check(s == 200 and r["status"] == "pending_approval", "配件主管发起店间调拨(苏州 → 无锡)", str(r)[:300])
rid = r["id"]
s, r = decide(rid, "store_gm", False, "本店备货自用")
check(s == 200 and r["status"] == "rejected", "调出店店总拒绝", str(r)[:200])
sh = one("缺件单", shortage_id="SH20260010")["properties"]
check("本店备货自用" in (sh["remark"] or ""), "被拒原因写回了缺件单", str(sh["remark"]))
s, r = propose("强制调拨", "SH20260010", "planner", "苏州店火花塞处于囤货预警", from_dealer="D03", qty=4)
check(s == 200 and r["status"] == "pending_approval", "计划员提请强制调拨", str(r)[:300])
s, r2 = decide(r["id"], "region_mgr", True, "同意")
check(s == 200 and r2["status"] == "done", "区域经理批准,调拨执行", str(r2)[:400])
sz = one("门店库存", dealer_id="D03", part_id="SP001")["properties"]
wx = one("门店库存", dealer_id="D04", part_id="SP001")["properties"]
sh = one("缺件单", shortage_id="SH20260010")["properties"]
check(sz["on_hand"] == 476 and wx["in_transit"] == 4 and sh["status"] == "处理中" and sh["handle_type"] == "店间调拨",
"一次批准改了四处:苏州在库 476、无锡在途 4、缺件单转处理中、生成调拨单",
f"{sz['on_hand']} {wx['in_transit']} {sh['status']} {sh['handle_type']}")
def story_flow_shortage() -> None:
print("五、流程卡「缺件处理」:常州店火花塞(配件主管)")
d = flow("缺件处理")
s, run = call("POST", f"/api/sop/defs/{d['id']}/run", {"params": {"shortage": "SH20260008"}}, user="parts_mgr")
check(s == 200, "发起流程", str(run)[:300])
if s != 200:
return
run = wait_run(run["id"], secs=90)
steps = {x["step_id"]: x for x in run["steps"]}
check("donors" in steps and steps["donors"]["status"] == "done", "查到了超储的店")
check(run["status"] == "waiting", f"流程停在等审批({run['status']})", str(run.get("error") or run.get("outcome")))
def story_f() -> None:
print("六、故事 F:超期未到的缺件专订到货(配件主管)")
s, r = propose("订单到货入库", "PO20260134", "parts_mgr", "货到了")
check(s == 200 and r["status"] == "done", "到货入库(自动执行)", str(r)[:300])
po = one("配件订单", po_no="PO20260134")["properties"]
sh = one("缺件单", shortage_id="SH20260009")["properties"]
wo = one("维修工单", wo_no=sh["wo_no"])["properties"]
check(po["status"] == "已到货" and sh["status"] == "已解决" and wo["status"] == "维修中",
"订单已到货、缺件单已解决、工单恢复维修", f"{po['status']} {sh['status']} {wo['status']}")
def story_watch() -> None:
print("七、监控")
s, ws = call("GET", "/api/watch")
for w in ws:
s, r = call("POST", f"/api/watch/{w['id']}/scan", None, dry="true")
hits = (r or {}).get("hit_count") if s == 200 else None
check(s == 200 and hits is not None, f"监控「{w['title']}」试扫:命中 {hits} 条", str(r)[:200])
def _wait(pred, secs: float = 30):
end = time.time() + secs
while time.time() < end:
got = pred()
if got:
return got
time.sleep(0.5)
return pred()
def story_v10() -> None:
print("八、v10 内核:接口、对象集、状态机、对象一变就触发的预警闭环")
from sqlalchemy import create_engine, text
from app.core.config import get_settings
eng = create_engine(get_settings().sqlalchemy_url, future=True)
with eng.connect() as c:
n_st = c.execute(text("SELECT COUNT(*) FROM otlg_dm2_dealer_stock")).scalar()
n_oem = c.execute(text("SELECT COUNT(*) FROM otlg_dm2_oem_stock")).scalar()
s, r = call("POST", "/api/kernel/objects/库存点/query", {"filters": [], "limit": 5})
check(s == 200 and r["total"] == n_st + n_oem, "接口「库存点」= 门店库存 + 主机厂库存", f"{r if s != 200 else r['total']}")
s, r = call("POST", "/api/kernel/object-sets/eval", {"set": "能救急的超储库存", "limit": 50})
labels = [o["label"] for o in r.get("items") or []] if s == 200 else []
check(any("D03" in x and "SP001" in x for x in labels) or any("苏州" in x for x in labels),
"对象集代数:缺件涉及的配件 → 走到各店库存 → 和超储求交,找到苏州店火花塞", str(r)[:300])
s, r = call("POST", "/api/cap/actions/下缺件专订/prepare", {"params": {"qty": 1}, "object_key": "SH20260006"},
user="parts_mgr")
check(s >= 400 or r.get("blocked"), "状态机:已解决的缺件单不能再转处理中", str(r)[:200])
wo = next(o for d in ("D04", "D06", "D01", "D02", "D05") for o in objs("维修工单", dealer_id=d, status="维修中", limit=5))
s, r = propose("登记缺件", wo["key"], "parts_mgr", "领料发现缺件", part="SP001", qty=2)
check(s == 200 and r["status"] == "done", "服务顾问登记缺件(自动执行)", str(r)[:300])
new = _wait(lambda: next((o for o in objs("缺件单", wo_no=wo["key"], part_id="SP001")), None), 10)
check(bool(new) and new["properties"]["status"] == "待处理", "新缺件单是初始状态「待处理」", str(new)[:200])
if not new:
return
s, ws = call("GET", "/api/watch")
wid = next(w["id"] for w in ws if w["title"] == "缺件单待处理")
def ev_of(state: str):
s, evs = call("GET", "/api/watch/alerts", state=state, watch_id=wid)
return next((e for e in evs or [] if (e.get("object") or {}).get("key") == new["key"]), None)
ev = _wait(lambda: (lambda e: e if e and e.get("fired") else None)(ev_of("open")), 30) or ev_of("open")
check(bool(ev), "对象一变就判:新缺件单马上开了预警事件(不用等排程)", "")
if not ev:
return
run_id = next((f["ref"] for f in ev.get("fired") or [] if f.get("ref_kind") == "sop_run"), "")
check(bool(run_id), "预警拉起了流程卡「缺件处理」", str(ev.get("fired"))[:200])
run = wait_run(run_id, until=("waiting", "done", "failed"), secs=60) if run_id else {}
check(run.get("status") == "waiting" and run.get("event_id") == ev["id"],
"流程卡找到超储的店、发起调拨,停在等审批;运行挂在预警事件上", str({k: run.get(k) for k in ("status", "error")}))
def pending():
s, runs = call("GET", "/api/cap/runs", status="pending_approval", limit=100)
return next((x for x in runs or [] if x.get("action_name") == "发起店间调拨"
and str(x.get("target_ref") or "").endswith(":" + new["key"])), None)
ar = _wait(pending, 10)
check(bool(ar), "生成了调拨审批单", "")
if not ar:
return
for u in ("store_gm", "region_mgr"):
s, r = decide(ar["id"], u, True, "同意")
s, ar2 = call("GET", f"/api/cap/runs/{ar['id']}")
check(ar2.get("status") == "done", "店总、区域经理两级审批后调拨执行", str(ar2)[:200])
sh = one("缺件单", shortage_id=new["key"])["properties"]
check(sh["status"] == "处理中" and sh["handle_type"] == "店间调拨", "状态机:缺件单 待处理 → 处理中(由调拨动作完成)",
f"{sh['status']} {sh['handle_type']}")
rec = _wait(lambda: ev_of("closed"), 30)
check(bool(rec) and rec["status"] == "已恢复", "处理方式定下来,预警自动恢复", str(rec)[:200])
run = wait_run(run_id, until=("done", "failed"), secs=30)
check(run.get("status") == "done", "流程卡走完", str(run.get("error"))[:200])
s, st = call("GET", "/api/watch/alerts/stats")
check(s == 200 and st["recovered"] >= 1 and st["avg_recover_hours"] is not None, "效果统计:恢复数、平均恢复用时",
str(st)[:200])
s, o = call("GET", f"/api/kernel/objects/缺件单/{new['key']}")
check(s == 200 and o.get("alerts") and o.get("changes"), "缺件单 360 视图里有它的预警和变化记录", str(list(o))[:200])
def main() -> None:
global BASE
ap = argparse.ArgumentParser()
ap.add_argument("--port", type=int, default=9200)
ap.add_argument("--only", default="")
args = ap.parse_args()
BASE = f"http://127.0.0.1:{args.port}"
stories = [story_read, story_c_d, story_b, story_a, story_flow_shortage, story_f, story_watch, story_v10]
for st in stories:
if args.only and args.only not in st.__name__:
continue
try:
st()
except SystemExit as e:
check(False, f"{st.__name__} 中断", str(e))
except Exception as e: # noqa: BLE001
check(False, f"{st.__name__} 出错", repr(e)[:300])
bad = [w for ok, w in RESULTS if not ok]
print(f"\n共 {len(RESULTS)} 项,通过 {len(RESULTS) - len(bad)},未过 {len(bad)}")
sys.exit(1 if bad else 0)
if __name__ == "__main__":
main()