walk_dm2.py
11.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
"""4S 配件场景的验收:把手册里的六个故事按「真人会怎么操作」走一遍,每一步断言结果。
会改业务数据(下单、调拨、审批),所以跑之前先重灌数据,跑完界面上会留下一批可以看的记录:
./.venv/Scripts/python.exe scripts/seed_dealer_parts_demo.py
./.venv/Scripts/python.exe scripts/build_dm2_ontology.py
./.venv/Scripts/python.exe scripts/walk_dm2.py # 默认 9100;--port 换实例
"""
from __future__ import annotations
import argparse
import sys
import time
import requests
sys.stdout.reconfigure(encoding="utf-8")
BASE = "http://127.0.0.1:9100"
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))
check(len(objs("门店库存", dead=1)) == 3, "呆滞件 3 条")
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"] == 3, "超期待料工单 3 张")
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 main() -> None:
global BASE
ap = argparse.ArgumentParser()
ap.add_argument("--port", type=int, default=9100)
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]
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()