walk_inv.py 19.4 KB
"""库存补货场景走查(v10 内核验收):按真实业务一步步走,每一步都断言。

    ./.venv/Scripts/python.exe scripts/walk_inv.py               # 9200
    ./.venv/Scripts/python.exe scripts/walk_inv.py --port 9201

前提:setup_v10.py 灌好数据、build_inv_ontology.py 建好本体。走查会真的写业务库(生成补货建议、采购单、到货入库),
想重来就重跑 setup_v10.py(业务表)+ build_inv_ontology.py。
"""
from __future__ import annotations

import argparse
import datetime as dt
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 = "inventory"
BASE = "http://127.0.0.1:9200"
T = "otlg_dm_"
PASSED: list[str] = []
FAILED: list[str] = []


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={"X-User-Id": user, "X-Workspace": WS}, timeout=180)
    if ok and r.status_code not in ok:
        raise AssertionError(f"{method} {path} → {r.status_code}:{r.text[:600]}")
    try:
        return r.json()
    except ValueError:
        return r.text


def raw(method: str, path: str, body=None, user: str = "admin"):
    return requests.request(method, BASE + path, json=body, headers={"X-User-Id": user, "X-Workspace": WS}, timeout=180)


def check(name: str, cond: bool, detail: str = "") -> None:
    (PASSED if cond else FAILED).append(name)
    print(("  ✓ " if cond else "  ✗ ") + name + ("" if cond or not detail else f"   ← {detail}"))


def sql(q: str, **p):
    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:
        return c.execute(text(q), p).fetchall()


def query(ot: str, filters: list | None = None, limit: int = 50) -> dict:
    return call("POST", f"/api/kernel/objects/{ot}/query", {"filters": filters or [], "limit": limit})


def f(prop: str, value, op: str = "eq") -> dict:
    return {"property": prop, "op": op, "value": value}


def watch_id(title: str) -> str:
    return next(w["id"] for w in call("GET", "/api/watch") if w["title"] == title)


def wait(pred, seconds: float = 20.0, step: float = 0.5):
    end = time.time() + seconds
    while time.time() < end:
        got = pred()
        if got:
            return got
        time.sleep(step)
    return pred()


def propose(action: str, key: str, params: dict | None = None, user: str = "admin", ok=(200, 201)) -> dict:
    return call("POST", f"/api/cap/actions/{action}/propose", {"params": params or {}, "object_key": key,
                                                              "reason": "走查"}, user=user, ok=ok)


def approve_all(run_id: str, users: list[str]) -> dict:
    """按顺序让这几个人去批(不该他批的那一段会被跳过),直到不再是待审批。"""
    run = call("GET", f"/api/cap/runs/{run_id}")
    for u in users:
        if run["status"] != "pending_approval":
            break
        r = raw("POST", f"/api/cap/runs/{run_id}/decide", {"approve": True, "comment": "同意"}, user=u)
        if r.status_code in (200, 201):
            run = r.json()
    return wait(lambda: (lambda x: x if x["status"] not in ("pending_approval", "executing", "approved") else None)(
        call("GET", f"/api/cap/runs/{run_id}")), 15) or call("GET", f"/api/cap/runs/{run_id}")


# ---------------------------------------------------------------- 1 语义与映射
def step_semantic() -> None:
    print("\n【1】语义层与数据来源")
    n_po = sql(f"SELECT COUNT(*) FROM {T}purchase_order")[0][0]
    n_out = sql(f"SELECT COUNT(*) FROM {T}outbound")[0][0]
    docs = query("库存单据", limit=5)
    check("接口「库存单据」= 采购单 + 出库单(两类对象合并查询)", docs["total"] == n_po + n_out,
          f"{docs['total']} vs {n_po}+{n_out}")
    check("接口上的对象带着它具体是哪一类", all(o.get("impl_type") for o in docs["items"]))
    st = query("库存位", [f("仓库编号", "W02"), f("商品编号", "P013")])["items"][0]
    p = st["properties"]
    check("多表组合:库存位带出商品名和单价", bool(p.get("商品名")) and float(p.get("采购单价") or 0) > 0, str(p)[:120])
    check("计算属性:可用 = 在库 + 在途", int(p["可用"]) == int(p["在库"]) + int(p["在途"]))
    sugg0 = query("补货建议")
    check("本体自建对象「补货建议」可以查(业务库里没有这张表)", isinstance(sugg0.get("total"), int))
    s002 = call("POST", "/api/kernel/object-sets/eval", {"spec": {"base": "供应商", "where": {"mode": "all", "items": [
        {"left": "供应商编号", "op": "eq", "right": "S002"}]}, "around": [{"link": "可供货"}]}, "limit": 50})
    n_offer = sql(f"SELECT COUNT(*) FROM {T}supply_offer WHERE supplier_id = 'S002'")[0][0]
    check("中间表关系「可供货」:清风生活用品能供的商品(含替代供应的纸品)", s002["total"] == n_offer,
          f"{s002['total']} vs {n_offer}")
    vt = {v["name"] for v in call("GET", "/api/kernel/value-types")}
    check("值类型:本体里建的 + 内置的都在", {"件数", "准时率", "仓库编号", "金额"} <= vt, str(sorted(vt))[:200])
    bad = raw("POST", "/api/cap/actions/调整安全库存/prepare", {"params": {"safety": -10, "reason": "试"},
                                                              "object_key": str(st["key"])})
    body = bad.text
    check("值类型校验:安全库存不能写成负数", bad.status_code >= 400 or "负数" in body or "不能" in body, body[:200])


# ---------------------------------------------------------------- 2 逻辑层
def step_logic() -> None:
    print("\n【2】逻辑层:对象集与指标")
    low_sql = sql(f"SELECT COUNT(*) FROM {T}stock WHERE on_hand + in_transit < safety_stock")[0][0]
    low = call("POST", "/api/kernel/object-sets/eval", {"set": "低库存位", "limit": 100})
    check("对象集「低库存位」和直接查库一致", low["total"] == low_sql, f"{low['total']} vs {low_sql}")
    hit_sql = sql(f"""SELECT COUNT(*) FROM {T}stock s JOIN {T}product p ON p.product_id = s.product_id
                      JOIN {T}supplier u ON u.supplier_id = p.supplier_id
                      WHERE u.status = '延期' AND s.on_hand + s.in_transit < s.safety_stock""")[0][0]
    hit = call("POST", "/api/kernel/object-sets/eval", {"set": "受延期影响的低库存位", "limit": 100})
    check("对象集代数:延期供应商 → 沿关系走到商品 → 走到库存位 → 和低库存位求交", hit["total"] == hit_sql and hit_sql > 0,
          f"{hit['total']} vs {hit_sql}")
    today = dt.date.today()
    want = sql(f"SELECT COALESCE(SUM(qty),0) FROM {T}outbound WHERE warehouse_id='W02' AND product_id='P013' AND out_date=:d",
               d=today)[0][0]
    m = call("POST", "/api/kernel/metrics/query", {"metric": "日出库量", "dimensions": ["仓库", "商品"],
                                                  "filters": {"仓库": "W02", "商品": "P013"}, "time": "current"})
    got = (m.get("rows") or [[None, None, None]])[0][-1] if m.get("rows") else m.get("value")
    check("指标「日出库量」按天的统计周期:今天杭州仓矿泉水", float(got or 0) == float(want), f"{got} vs {want} {str(m)[:160]}")
    mm = call("POST", "/api/kernel/metrics/query", {"metric": "月出库量", "time": "current"})
    per = mm.get("period") or {}
    start = (per.get("start") if isinstance(per, dict) else "") or str(mm.get("time") or "")
    check("指标自己的统计周期口径「结算月」(上月 26 日起)", "26" in str(mm.get("period")) or "结算月" in str(mm),
          str(mm.get("period"))[:160] + start)
    lc = call("POST", "/api/kernel/metrics/query", {"metric": "低库存位数"})
    check("指标建在对象集上:低库存位数 = 对象集总数", float(lc.get("value") or 0) == low["total"], str(lc)[:160])


# ---------------------------------------------------------------- 3 动态层:出库突增 → 预警 → 流程卡
def step_spike() -> dict:
    print("\n【3】出库突增 → 预警事件 → 流程卡 → 补货建议")
    wid = watch_id("出库量异常突增")
    dry = call("POST", f"/api/watch/{wid}/scan", {"dry": True})
    keys = {(h.get("仓库"), h.get("商品")) for h in dry["hits"]}
    check("检测量算出来:杭州仓矿泉水、上海仓抽纸偏离基线被命中", {("W02", "P013"), ("W01", "P005")} <= keys, str(keys))
    check("没有误报:只命中埋了突增的两个", len(keys) == 2, str(keys))
    top = next((h for h in dry["hits"] if h.get("仓库") == "W02"), None) or {}
    check("偏离倍数 ≥ 3、基线是近 14 天日均", float(top.get("偏离") or 0) >= 3 and float(top.get("基线") or 0) > 0,
          str(top)[:200])
    r = call("POST", f"/api/watch/{wid}/scan", {"dry": False})
    check("正式扫描开出两条预警事件", r.get("opened") == 2, str(r)[:200])
    evs = call("GET", "/api/watch/alerts", state="open", watch_id=wid)
    ev = next((e for e in evs if "W02" in e["key"]), None)
    check("预警事件带严重度、现值、基线、偏离", bool(ev) and ev["severity"] in ("高", "中") and ev["value"] and ev["baseline"],
          str(ev)[:300])
    sev_w01 = next((e["severity"] for e in evs if "W01" in e["key"]), "")
    check("严重度按条件分级:矿泉水(偏离更大)高,抽纸中", ev and ev["severity"] == "高" and sev_w01 == "中",
          f"{ev and ev['severity']} / {sev_w01}")
    run_ref = next((x["ref"] for x in (ev or {}).get("fired") or [] if x.get("ref_kind") == "sop_run"), "")
    check("预警拉起了流程卡「出库突增补货核查」", bool(run_ref), str((ev or {}).get("fired"))[:200])
    run = wait(lambda: (lambda x: x if x["status"] in ("done", "failed", "error") else None)(
        call("GET", f"/api/sop/runs/{run_ref}")), 30) if run_ref else {}
    check("流程卡跑完了,运行挂在预警事件上", bool(run) and run["status"] == "done" and run.get("event_id") == ev["id"],
          str({k: run.get(k) for k in ("status", "error", "event_id")}) if run else "")
    sugg = query("补货建议", [f("仓库编号", "W02"), f("商品编号", "P013")])
    check("流程卡生成了补货建议(本体自建对象,状态待处理)",
          sugg["total"] == 1 and sugg["items"][0]["properties"]["状态"] == "待处理", str(sugg["items"])[:200])
    ev2 = call("GET", f"/api/watch/alerts/{ev['id']}") if ev else {}
    check("流程卡走完,预警事件进入「待验证」", ev2.get("status") == "待验证", ev2.get("status", ""))
    again = call("POST", f"/api/watch/{wid}/scan", {"dry": False})
    check("一直命中但在冷却期内:不重复拉流程卡", again.get("opened") == 0 and not again.get("fired"), str(again)[:200])
    return {"event": ev, "suggestion": sugg["items"][0] if sugg["items"] else None}


# ---------------------------------------------------------------- 4 低库存:变化即时触发 + 决策表定严重度
def step_low_stock() -> dict:
    print("\n【4】库存跌破安全库存:决策表定严重度、对象一变就判")
    wid = watch_id("库存跌破安全库存")
    r = call("POST", f"/api/watch/{wid}/scan", {"dry": False})
    evs = call("GET", "/api/watch/alerts", state="open", watch_id=wid)
    low = call("POST", "/api/kernel/object-sets/eval", {"set": "低库存位", "limit": 100})
    check("每个低库存位一条预警事件", len(evs) == low["total"], f"{len(evs)} vs {low['total']} {str(r)[:120]}")
    sev = {e["object"]["key"]: e["severity"] for e in evs if e.get("object")}
    w03 = query("库存位", [f("仓库编号", "W03"), f("商品编号", "P007")])["items"][0]
    check("缺口比例 ≥ 0.6 的(南京仓湿巾)决策表判为高", sev.get(str(w03["key"])) == "高", str(sev)[:200])
    tasks = call("GET", "/api/cap/tasks", user="buyer")
    items = tasks if isinstance(tasks, list) else tasks.get("items") or tasks.get("tasks") or []
    check("严重度为高的派了待办给采购员(低的只通知)", any("缺货严重" in (t.get("title") or "") for t in items), str(items)[:200])
    return {"watch": wid}


# ---------------------------------------------------------------- 5 动作层:采纳 → 审批 → 到货,状态机
def step_actions(sugg: dict, low_watch: str) -> None:
    print("\n【5】动作与状态机:采纳补货建议 → 审批采购单 → 到货入库")
    if not sugg:
        check("有补货建议可以走", False)
        return
    st_before = query("库存位", [f("仓库编号", "W02"), f("商品编号", "P013")])["items"][0]
    run = propose("采纳补货建议", sugg["key"], user="wh_mgr")
    check("采纳补货建议要采购员确认", run["status"] == "pending_approval", run["status"])
    run = approve_all(run["id"], ["buyer"])
    check("采购员确认后执行完", run["status"] == "done", f"{run['status']} {run.get('error')}")
    s = call("GET", f"/api/kernel/objects/补货建议/{sugg['key']}")
    sp = (s.get("object") or s).get("properties") or {}
    check("状态机:补货建议 待处理 → 已采纳", sp.get("状态") == "已采纳", str(sp)[:160])
    pos = query("采购单", [f("商品编号", "P013"), f("收货仓库", "W02"), f("状态", "待审批")])
    check("生成了一张待审批的采购单(初始状态)", pos["total"] == 1, str(pos["items"])[:200])
    if not pos["items"]:
        return
    po = pos["items"][0]
    amount = float(po["properties"]["金额"])
    run = propose("审批采购单", po["key"], user="buyer")
    check("采购单 1 万以上要采购经理批", run["status"] == "pending_approval" and amount >= 10000, f"{run['status']} {amount}")
    run = approve_all(run["id"], ["buy_mgr", "gm"])
    check("采购经理批完执行", run["status"] == "done", f"{run['status']} {run.get('error')}")
    po2 = call("GET", f"/api/kernel/objects/采购单/{po['key']}")
    check("状态机:采购单 待审批 → 已下单", ((po2.get("object") or po2).get("properties") or {}).get("状态") == "已下单")
    st_after = query("库存位", [f("仓库编号", "W02"), f("商品编号", "P013")])["items"][0]
    check("动作写回业务库:在途增加了采购数量",
          int(st_after["properties"]["在途"]) == int(st_before["properties"]["在途"]) + int(po["properties"]["数量"]))

    def recovered():
        evs = call("GET", "/api/watch/alerts", state="closed", watch_id=low_watch)
        return next((e for e in evs if e.get("object") and e["object"]["key"] == str(st_after["key"])), None)
    ok_low = int(st_after["properties"]["可用"]) >= int(st_after["properties"]["安全库存"])
    if ok_low:
        rec = wait(recovered, 20)
        check("对象一变就判:在途补上后「库存跌破安全库存」的预警自动恢复", bool(rec) and rec["status"] == "已恢复",
              str(rec)[:200])
    bad = raw("POST", f"/api/cap/actions/到货入库/prepare", {"params": {}, "object_key": po["key"]})
    run = propose("到货入库", po["key"], user="wh_mgr")
    check("到货入库(自动执行)", run["status"] == "done", f"{run['status']} {run.get('error')}")
    st_arr = query("库存位", [f("仓库编号", "W02"), f("商品编号", "P013")])["items"][0]
    check("到货:在途转成在库", int(st_arr["properties"]["在库"]) == int(st_after["properties"]["在库"]) + int(po["properties"]["数量"])
          and int(st_arr["properties"]["在途"]) == int(st_before["properties"]["在途"]))
    again = raw("POST", f"/api/cap/actions/到货入库/propose", {"params": {}, "object_key": po["key"], "reason": "再来一次"},
                user="wh_mgr")
    check("状态机拦住非法流转:已到货的不能再入库", again.status_code >= 400 or again.json().get("status") in ("failed", "rejected"),
          again.text[:200])
    _ = bad


# ---------------------------------------------------------------- 6 时间层
def step_time() -> None:
    print("\n【6】时间层:变化记录、历史走势、某个时点的样子")
    st = query("库存位", [f("仓库编号", "W02"), f("商品编号", "P013")])["items"][0]
    h = call("GET", f"/api/kernel/objects/库存位/{st['key']}/history", property="在库")
    pts = h.get("points") or []
    check("在库的历史走势(补的近 30 天 + 动作写入后的点)", len(pts) >= 30, f"{len(pts)} 个点")
    ch = h.get("changes") or []
    check("每次写入都留了变化记录(来自动作)", any(c.get("source") == "action" for c in ch), str(ch[:2])[:200])
    yesterday = (dt.datetime.now() - dt.timedelta(days=1)).isoformat(timespec="seconds")
    past = call("GET", f"/api/kernel/objects/库存位/{st['key']}/history", as_of=yesterday)
    was = (past.get("as_of") or {}).get("properties") or past.get("as_of") or {}
    check("as_of:回放到昨天,在途还是采购前的数", str(was.get("在途")) not in ("", "None") and
          int(was.get("在途") or 0) < int(st["properties"]["在途"]) + 1, str(past.get("as_of"))[:200])


# ---------------------------------------------------------------- 7 决策即数据
def step_effect() -> None:
    print("\n【7】决策即数据:预警、动作、流程运行都是本体里的对象,效果指标靠本体自己算")
    stats = call("GET", "/api/watch/alerts/stats")
    check("效果统计:有预警、有恢复", stats["total"] >= 3 and stats["recovered"] >= 1, str(stats)[:200])
    evs = query("预警事件", limit=200)
    check("系统对象「预警事件」可以像业务对象一样查", evs["total"] == stats["total"], f"{evs['total']} vs {stats['total']}")
    runs = query("动作记录", limit=200)
    check("系统对象「动作记录」", runs["total"] >= 4, str(runs["total"]))
    m = call("POST", "/api/kernel/metrics/query", {"metric": "预警数"})
    check("内置效果指标「预警数」和统计一致", float(m.get("value") or 0) == stats["total"], str(m)[:160])
    rec = call("POST", "/api/kernel/metrics/query", {"metric": "平均恢复用时"})
    check("内置效果指标「平均恢复用时」算得出来", rec.get("value") is not None, str(rec)[:160])
    st = query("库存位", [f("仓库编号", "W02"), f("商品编号", "P013")])["items"][0]
    o = call("GET", f"/api/kernel/objects/库存位/{st['key']}")
    al = o.get("alerts") or []
    check("对象 360 视图里看得到它的预警和变化", bool(al) and bool(o.get("changes")), str(list(o))[:200])


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}"
    for fn in (step_semantic, step_logic):
        try:
            fn()
        except AssertionError as e:
            check(fn.__name__, False, str(e)[:300])
    got: dict = {}
    try:
        got = step_spike()
    except AssertionError as e:
        check("step_spike", False, str(e)[:300])
    low: dict = {}
    try:
        low = step_low_stock()
    except AssertionError as e:
        check("step_low_stock", False, str(e)[:300])
    for fn, args_ in ((step_actions, (got.get("suggestion"), low.get("watch", ""))), (step_time, ()), (step_effect, ())):
        try:
            fn(*args_)
        except AssertionError as e:
            check(fn.__name__, False, str(e)[:300])
    print(f"\n走查:通过 {len(PASSED)} 项,失败 {len(FAILED)} 项")
    for x in FAILED:
        print("  ✗", x)
    sys.exit(1 if FAILED else 0)


if __name__ == "__main__":
    main()