build_inv_ontology.py 43.6 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 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628
"""把「库存补货」场景建进 v10:本体空间、数据源、值类型、对象(含接口、多表组合、本体自建)、关系(含中间表)、
状态机、指标(含统计周期口径、快照)、决策表、对象集、动作(含状态流转)、预警触发的流程卡、带检测量的预警规则。
走的是界面用的同一套接口,所以它同时是 v10 内核的验收脚本。

    ./.venv/Scripts/python.exe scripts/build_inv_ontology.py               # 建在 9200 的 inventory 空间
    ./.venv/Scripts/python.exe scripts/build_inv_ontology.py --port 9201

业务表要先灌好:scripts/setup_v10.py(或单独跑 seed_inventory_demo.py)。
"""
from __future__ import annotations

import argparse
import datetime as dt
import sys
import time
from collections import defaultdict
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_"


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 r.status_code not in ok:
        raise SystemExit(f"{method} {path} → {r.status_code}:{r.text[:800]}")
    return r.json() if "json" in r.headers.get("content-type", "") else r.text


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


def _cond(left: str, op: str, right) -> dict:
    return {"mode": "all", "items": [{"left": left, "op": op, "right": right}]}


def _write(obj: str, key: str, values: dict, label: str, when: str = "") -> dict:
    e = {"tool": "object.write", "label": label, "args": {"object_type": obj, "key": key, "values": values}}
    if when:
        e["when"] = when
    return e


def _add(obj: str, key: str, prop: str, value, label: str, op: str = "add", when: str = "") -> dict:
    e = {"tool": "object.write", "label": label,
         "args": {"object_type": obj, "key": key, "property": prop, "op": op, "value": value}}
    if when:
        e["when"] = when
    return e


# ---------------------------------------------------------------- 值类型
VALUE_TYPES = [
    ("件数", "库存、出库、采购的数量:不能是负数", {"base_type": "integer", "min": 0, "unit": "件", "format": "quantity",
                                         "message": "数量不能是负数"}),
    ("准时率", "0 到 1 之间的比例,显示成百分比", {"base_type": "number", "min": 0, "max": 1, "precision": 4,
                                         "format": "percent", "message": "准时率要在 0 到 1 之间"}),
    ("仓库编号", "W 加两位数字", {"base_type": "string", "pattern": r"^W\d{2}$", "message": "仓库编号是 W 加两位数字,如 W01"}),
]

# ---------------------------------------------------------------- 对象
# 名称 → (说明, spec, 绑定 ref);绑定的 ds_id 用业务库,本体自建(managed)的用 0
SUPPLIER_STATUS = {"states": [{"value": "正常", "tone": "ok"}, {"value": "延期", "tone": "warn"},
                              {"value": "暂停", "tone": "danger"}],
                   "initial": "正常",
                   "transitions": [{"from": ["正常"], "to": "延期", "action": "标记供应延期"},
                                   {"from": ["延期", "暂停"], "to": "正常", "action": "恢复正常供货"},
                                   {"from": ["正常", "延期"], "to": "暂停", "action": "暂停合作"}]}
PO_STATUS = {"states": [{"value": "待审批", "tone": "warn"}, {"value": "已下单", "tone": "info"},
                        {"value": "已到货", "tone": "ok", "terminal": True},
                        {"value": "已取消", "tone": "neutral", "terminal": True}],
             "initial": "待审批",
             "transitions": [{"from": ["待审批"], "to": "已下单", "action": "审批采购单"},
                             {"from": ["已下单"], "to": "已到货", "action": "到货入库"},
                             {"from": ["待审批", "已下单"], "to": "已取消", "action": "取消采购单"}]}
SUGG_STATUS = {"states": [{"value": "待处理", "tone": "warn"}, {"value": "已采纳", "tone": "ok", "terminal": True},
                          {"value": "已驳回", "tone": "neutral", "terminal": True}],
               "initial": "待处理",
               "transitions": [{"from": ["待处理"], "to": "已采纳", "action": "采纳补货建议"},
                               {"from": ["待处理"], "to": "已驳回", "action": "驳回补货建议"}]}

OBJECTS = {
    "供应商": ("给我们供货的厂家;合作状态由动作改变", {
        "properties": [
            {"name": "供应商编号", "is_key": True}, {"name": "名称"}, {"name": "联系人"}, {"name": "电话"},
            {"name": "标准交期", "data_type": "integer", "unit": "天"},
            {"name": "准时率", "data_type": "number", "value_type": "准时率", "track": True},
            {"name": "合作状态", "is_dimension": True, "lifecycle": SUPPLIER_STATUS}],
        "label_property": "名称"},
        {"table": T + "supplier", "key_column": "supplier_id", "label_column": "supplier_name",
         "columns": {"供应商编号": "supplier_id", "名称": "supplier_name", "联系人": "contact", "电话": "phone",
                     "标准交期": "lead_days", "准时率": "on_time_rate", "合作状态": "status"}}),
    "仓库": ("我们自己的仓", {
        "properties": [{"name": "仓库编号", "is_key": True, "value_type": "仓库编号"}, {"name": "名称"},
                       {"name": "城市", "is_dimension": True}, {"name": "主管"}],
        "label_property": "名称"},
        {"table": T + "warehouse", "key_column": "warehouse_id", "label_column": "warehouse_name",
         "columns": {"仓库编号": "warehouse_id", "名称": "warehouse_name", "城市": "city", "主管": "manager"}}),
    "商品": ("我们分销的商品", {
        "properties": [{"name": "商品编号", "is_key": True}, {"name": "名称"}, {"name": "品类", "is_dimension": True},
                       {"name": "单位"}, {"name": "采购单价", "data_type": "number", "value_type": "金额"},
                       {"name": "主供应商"}, {"name": "补货批量", "data_type": "integer", "value_type": "件数"}],
        "label_property": "名称"},
        {"table": T + "product", "key_column": "product_id", "label_column": "product_name",
         "columns": {"商品编号": "product_id", "名称": "product_name", "品类": "category", "单位": "unit",
                     "采购单价": "unit_price", "主供应商": "supplier_id", "补货批量": "reorder_qty"}}),
    # 多表组合:库存主表 + 商品表(带出商品名、单价、补货批量),计算属性 + 记录历史
    "库存位": ("某个仓里的某个商品:在库、在途、安全库存,算出可用、缺口和建议补货量", {
        "properties": [
            {"name": "编号", "data_type": "integer", "is_key": True},
            {"name": "仓库编号", "is_dimension": True}, {"name": "商品编号", "is_dimension": True},
            {"name": "商品名"}, {"name": "单位"}, {"name": "采购单价", "data_type": "number", "value_type": "金额"},
            {"name": "补货批量", "data_type": "integer"},
            {"name": "在库", "data_type": "integer", "value_type": "件数", "is_writable": True, "track": True},
            {"name": "在途", "data_type": "integer", "value_type": "件数", "is_writable": True, "track": True},
            {"name": "安全库存", "data_type": "integer", "value_type": "件数", "is_writable": True},
            {"name": "盘点时间", "data_type": "datetime"},
            {"name": "可用", "data_type": "integer", "expression": "在库 + 在途", "track": True, "format": "quantity"},
            {"name": "缺口", "data_type": "integer", "expression": "max(0, 安全库存 - 可用)", "format": "quantity"},
            {"name": "缺口比例", "data_type": "number", "expression": "round(safe_div(缺口, 安全库存), 2)",
             "format": "percent"},
            {"name": "建议补货量", "data_type": "integer", "format": "quantity",
             "expression": "max(补货批量, ceil(max(0, 安全库存 * 2 - 可用) / 补货批量) * 补货批量)"},
            {"name": "库存金额", "data_type": "number", "expression": "在库 * 采购单价", "format": "money", "unit": "元"}],
        "title_template": "{仓库编号}·{商品名}"},
        {"kind": "view", "table": T + "stock", "key_column": "stock_id",
         "joins": [{"alias": "p", "table": T + "product", "from_column": "product_id", "to_column": "product_id"}],
         "columns": {"编号": "stock_id", "仓库编号": "warehouse_id", "商品编号": "product_id",
                     "商品名": "p.product_name", "单位": "p.unit", "采购单价": "p.unit_price",
                     "补货批量": "p.reorder_qty", "在库": "on_hand", "在途": "in_transit",
                     "安全库存": "safety_stock", "盘点时间": "updated_at"}}),
    "采购单": ("向供应商下的采购单;状态只能经由动作流转", {
        "properties": [
            {"name": "采购单号", "is_key": True}, {"name": "商品编号", "is_dimension": True},
            {"name": "收货仓库", "is_dimension": True}, {"name": "供应商编号", "is_dimension": True},
            {"name": "数量", "data_type": "integer", "value_type": "件数"},
            {"name": "金额", "data_type": "number", "value_type": "金额"},
            {"name": "状态", "is_dimension": True, "lifecycle": PO_STATUS},
            {"name": "下单日期", "data_type": "date"}, {"name": "预计到货", "data_type": "date"},
            {"name": "实际到货", "data_type": "date", "is_writable": True},
            {"name": "超期天数", "data_type": "integer", "format": "quantity", "unit": "天",
             "expression": "max(0, days_between(预计到货, today())) if 状态 == '已下单' else 0"}],
        "title_template": "{采购单号} {商品编号}×{数量}",
        "implements": [{"interface": "库存单据", "mapping": {"单号": "采购单号", "仓库": "收货仓库", "商品": "商品编号",
                                                         "数量": "数量", "日期": "下单日期"}}]},
        {"table": T + "purchase_order", "key_column": "po_no",
         "columns": {"采购单号": "po_no", "商品编号": "product_id", "收货仓库": "warehouse_id", "供应商编号": "supplier_id",
                     "数量": "qty", "金额": "amount", "状态": "status", "下单日期": "order_date",
                     "预计到货": "expected_date", "实际到货": "arrived_date"}}),
    "出库单": ("销售发货流水", {
        "properties": [
            {"name": "出库单号", "is_key": True}, {"name": "仓库编号", "is_dimension": True},
            {"name": "商品编号", "is_dimension": True}, {"name": "数量", "data_type": "integer", "value_type": "件数"},
            {"name": "出库日期", "data_type": "date"}, {"name": "客户", "is_dimension": True}],
        "title_template": "{出库单号} {商品编号}×{数量}",
        "implements": [{"interface": "库存单据", "mapping": {"单号": "出库单号", "仓库": "仓库编号", "商品": "商品编号",
                                                         "数量": "数量", "日期": "出库日期"}}]},
        {"table": T + "outbound", "key_column": "out_no",
         "columns": {"出库单号": "out_no", "仓库编号": "warehouse_id", "商品编号": "product_id", "数量": "qty",
                     "出库日期": "out_date", "客户": "customer"}}),
    # 本体自建:业务库里没有这张表,系统在本体存储里建
    "补货建议": ("系统或人提出的补货建议;采纳后变成一张待审批的采购单", {
        "properties": [
            {"name": "库存位"}, {"name": "仓库编号", "is_dimension": True}, {"name": "商品编号", "is_dimension": True},
            {"name": "建议数量", "data_type": "integer", "value_type": "件数"}, {"name": "原因", "data_type": "text"},
            {"name": "状态", "is_dimension": True, "lifecycle": SUGG_STATUS}],
        "title_template": "{仓库编号}·{商品编号} 补 {建议数量}"},
        {"kind": "managed"}),
}
INTERFACE = ("库存单据", "进出库存的单据:采购单(进)和出库单(出)都是", {
    "abstract": True, "properties": [{"name": "单号"}, {"name": "仓库", "is_dimension": True},
                                     {"name": "商品", "is_dimension": True},
                                     {"name": "数量", "data_type": "integer"}, {"name": "日期", "data_type": "date"}]})

# 关系:(名称, 起点, 终点, 基数, 绑定 ref)
LINKS = [
    ("库存所在仓库", "库存位", "仓库", "n:1", {"from_column": "warehouse_id", "to_column": "warehouse_id"}),
    ("库存对应商品", "库存位", "商品", "n:1", {"from_column": "product_id", "to_column": "product_id"}),
    ("主供应商", "商品", "供应商", "n:1", {"from_column": "supplier_id", "to_column": "supplier_id"}),
    ("可供货", "供应商", "商品", "n:n", {"via_table": T + "supply_offer", "via_from": "supplier_id",
                                     "via_to": "product_id",
                                     "props": {"报价": "offer_price", "交期": "lead_days", "主供": "is_primary"}}),
    ("采购的商品", "采购单", "商品", "n:1", {"from_column": "product_id", "to_column": "product_id"}),
    ("收货仓库", "采购单", "仓库", "n:1", {"from_column": "warehouse_id", "to_column": "warehouse_id"}),
    ("采购单供应商", "采购单", "供应商", "n:1", {"from_column": "supplier_id", "to_column": "supplier_id"}),
    ("出库的商品", "出库单", "商品", "n:1", {"from_column": "product_id", "to_column": "product_id"}),
    ("发货仓库", "出库单", "仓库", "n:1", {"from_column": "warehouse_id", "to_column": "warehouse_id"}),
    ("建议补的库存位", "补货建议", "库存位", "n:1", {"from_column": "库存位", "to_column": "stock_id"}),
]

PERIOD_SETTLE = {"grain": "month", "start_day": 26, "start_month_offset": -1, "end_day": 25, "end_month_offset": 0,
                 "label": "结算月"}
# 指标:(名称, 同义词, 说明, spec, 绑定 ref)
METRICS = [
    ("日出库量", ["出库量", "发货量", "今天出了多少"], "每天发出去多少件,可以按仓库、商品拆开",
     {"category": "aggregate", "unit": "件", "format": "quantity", "direction": "neutral", "period": {"grain": "day"}},
     {"base_table": T + "outbound", "expression": "SUM(qty)", "time_column": "out_date",
      "dimensions": {"仓库": "warehouse_id", "商品": "product_id"}, "dimension_types": {"仓库": "仓库", "商品": "商品"}}),
    ("月出库量", ["结算月出库量"], "按结算月(上月 26 日到本月 25 日)统计的出库件数",
     {"category": "aggregate", "unit": "件", "format": "quantity", "direction": "neutral", "period": PERIOD_SETTLE},
     {"base_table": T + "outbound", "expression": "SUM(qty)", "time_column": "out_date",
      "dimensions": {"仓库": "warehouse_id", "商品": "product_id"}, "dimension_types": {"仓库": "仓库", "商品": "商品"}}),
    ("采购金额", ["采购额"], "没取消的采购单金额合计,按结算月统计",
     {"category": "aggregate", "unit": "元", "format": "money", "direction": "neutral", "period": PERIOD_SETTLE},
     {"base_table": T + "purchase_order", "expression": "SUM(amount)", "time_column": "order_date",
      "filters": ["status <> '已取消'"], "dimensions": {"供应商": "supplier_id", "仓库": "warehouse_id"},
      "dimension_types": {"供应商": "供应商", "仓库": "仓库"}}),
    ("在库总量", ["库存总量", "有多少货"], "仓里现有的件数(时点数:每天拍一次快照,才能和上月比)",
     {"category": "aggregate", "unit": "件", "format": "quantity", "direction": "neutral",
      "history": {"enabled": True, "every": "daily", "dimensions": ["仓库"]}},
     {"base_table": T + "stock", "expression": "SUM(on_hand)",
      "dimensions": {"仓库": "warehouse_id", "商品": "product_id"}, "dimension_types": {"仓库": "仓库", "商品": "商品"}}),
    ("低库存位数", ["缺货的有几个", "低于安全库存的"], "可用(在库 + 在途)低于安全库存的库存位个数",
     {"category": "aggregate", "unit": "个", "format": "quantity", "direction": "lower_better",
      "history": {"enabled": True, "every": "daily", "dimensions": []}},
     {"base_set": "低库存位", "expression": "COUNT(*)", "dimensions": {"仓库": "warehouse_id"},
      "dimension_types": {"仓库": "仓库"}}),
]

DECISIONS = [
    ("缺货严重度", "按缺口占安全库存的比例定预警的严重度", {
        "category": "decision", "hit_policy": "first",
        "inputs": [{"name": "缺口比例", "label": "缺口比例", "type": "number"}],
        "outputs": [{"name": "severity", "label": "严重度"}],
        "rows": [{"when": {"缺口比例": ">= 0.6"}, "then": {"severity": "高"}, "note": "缺了一大半"},
                 {"when": {"缺口比例": ">= 0.3"}, "then": {"severity": "中"}, "note": ""}],
        "default": {"severity": "低"},
        "tests": [{"name": "缺一大半", "inputs": {"缺口比例": 0.75}, "expect": {"result.severity": "高"}},
                  {"name": "缺一点", "inputs": {"缺口比例": 0.1}, "expect": {"result.severity": "低"}}]}),
]
RULES = [
    ("需要加急补货", "可用不到安全库存的三成,就该加急", {
        "category": "rule", "object_type": "库存位", "rule_kind": "judgement",
        "expression": "obj.可用 < obj.安全库存 * 0.3", "params": [],
        "text": "可用(在库 + 在途)低于安全库存的 30%"}),
]
OBJECT_SETS = [
    ("低库存位", "可用(在库 + 在途)低于安全库存的库存位", {
        "category": "object_set", "base": "库存位", "where": _cond("缺口", "gt", 0),
        "sort": [{"property": "缺口比例", "dir": "desc"}]}),
    ("延期供应商供的商品", "合作状态是「延期」的供应商作为主供应商的商品", {
        "category": "object_set", "base": "供应商", "where": _cond("合作状态", "eq", "延期"),
        "around": [{"link": "主供应商"}]}),
    ("受延期影响的低库存位", "主供应商在延期、又已经低于安全库存的库存位(最该找替代供应商的)", {
        "category": "object_set", "base": "延期供应商供的商品", "around": [{"link": "库存对应商品"}],
        "combine": [{"op": "intersect", "set": "低库存位"}]}),
    ("超期在途采购单", "已下单、过了预计到货日还没到的采购单", {
        "category": "object_set", "base": "采购单", "where": _cond("超期天数", "gt", 0),
        "sort": [{"property": "超期天数", "dir": "desc"}]}),
    ("待处理补货建议", "还没人采纳或驳回的补货建议", {
        "category": "object_set", "base": "补货建议", "where": _cond("状态", "eq", "待处理")}),
]

STOCK_OF_PO = {"name": "stock", "label": "收货仓的这个商品的库存", "object_type": "库存位",
               "where": [_w("仓库编号", "$obj.收货仓库"), _w("商品编号", "$obj.商品编号")]}
ACTIONS = [
    {"name": "生成补货建议", "synonyms": ["建议补货", "提补货建议"],
     "description": "对一个库存位提出补货建议(本体里新建一条「补货建议」,状态待处理),由采购员决定采纳还是驳回。",
     "spec": {"target_type": "库存位",
              "params": [{"name": "qty", "label": "建议数量", "type": "integer", "required": True,
                          "description": "一般按补货批量的整数倍"},
                         {"name": "reason", "label": "原因", "type": "text", "required": False, "description": ""}],
              "criteria": [{"label": "数量", "expression": "qty > 0", "message": "建议数量要大于 0"}],
              "effects": [{"tool": "object.create", "label": "新建补货建议", "args": {"object_type": "补货建议", "values": {
                  "库存位": "$obj_key", "仓库编号": "$obj.仓库编号", "商品编号": "$obj.商品编号", "建议数量": "$qty",
                  "原因": "$reason", "状态": "待处理"}}}],
              "approval": {"mode": "auto"}}},
    {"name": "采纳补货建议", "synonyms": ["采纳", "按建议下单"],
     "description": "采纳一条补货建议:按建议数量向主供应商生成一张待审批的采购单,建议改为已采纳。",
     "spec": {"target_type": "补货建议", "params": [],
              "lookups": [{"name": "prod", "label": "这个商品", "object_type": "商品",
                           "where": [_w("商品编号", "$obj.商品编号")]}],
              "transition": {"property": "状态", "from": ["待处理"], "to": "已采纳"},
              "effects": [{"tool": "object.create", "label": "生成采购单", "args": {"object_type": "采购单", "values": {
                  "采购单号": "PO$now_id", "商品编号": "$obj.商品编号", "收货仓库": "$obj.仓库编号",
                  "供应商编号": "$prod.主供应商", "数量": "$obj.建议数量", "金额": "=obj.建议数量 * prod.采购单价",
                  "状态": "待审批", "下单日期": "$today", "预计到货": "=add_days(today(), 5)"}}}],
              "approval": {"mode": "manual", "stages": [{"name": "采购员确认", "approver_roles": ["采购员"], "skip_when": ""}]}}},
    {"name": "驳回补货建议", "description": "不采纳这条补货建议,写明原因。",
     "spec": {"target_type": "补货建议",
              "params": [{"name": "reason", "label": "原因", "type": "text", "required": True, "description": ""}],
              "transition": {"property": "状态", "from": ["待处理"], "to": "已驳回"},
              "approval": {"mode": "auto"}}},
    {"name": "审批采购单", "synonyms": ["批采购单", "下单"],
     "description": "采购单审批通过:状态改为已下单,收货仓的在途增加。金额 1 万以上要采购经理批,5 万以上还要总经理批。",
     "spec": {"target_type": "采购单", "params": [], "lookups": [STOCK_OF_PO],
              "transition": {"property": "状态", "from": ["待审批"], "to": "已下单"},
              "effects": [_add("库存位", "$stock.key", "在途", "$obj.数量", "增加在途", when="stock.key != None")],
              "approval": {"mode": "manual", "stages": [
                  {"name": "采购经理审批", "approver_roles": ["采购经理"], "skip_when": "obj.金额 < 10000"},
                  {"name": "总经理审批", "approver_roles": ["总经理"], "skip_when": "obj.金额 < 50000"}]}}},
    {"name": "到货入库", "synonyms": ["到货", "入库", "收货"],
     "description": "采购单的货到了:在途转成在库,登记到货日期。",
     "spec": {"target_type": "采购单", "params": [], "lookups": [STOCK_OF_PO],
              "transition": {"property": "状态", "from": ["已下单"], "to": "已到货"},
              "effects": [_write("采购单", "$obj_key", {"实际到货": "$today"}, "登记到货日期"),
                          _add("库存位", "$stock.key", "在途", "$obj.数量", "减少在途", op="sub", when="stock.key != None"),
                          _add("库存位", "$stock.key", "在库", "$obj.数量", "增加在库", when="stock.key != None")],
              "approval": {"mode": "auto"}}},
    {"name": "取消采购单", "description": "取消一张还没到货的采购单;已下单的要把在途扣回来。",
     "spec": {"target_type": "采购单",
              "params": [{"name": "reason", "label": "原因", "type": "text", "required": True, "description": ""}],
              "lookups": [STOCK_OF_PO],
              "transition": {"property": "状态", "from": ["待审批", "已下单"], "to": "已取消"},
              "effects": [_add("库存位", "$stock.key", "在途", "$obj.数量", "扣回在途", op="sub",
                               when="stock.key != None and obj.状态 == '已下单'")],
              "approval": {"mode": "auto"}}},
    {"name": "发货出库", "synonyms": ["出库", "发货"],
     "description": "从一个库存位发一批货:生成出库单,在库减少。",
     "spec": {"target_type": "库存位",
              "params": [{"name": "qty", "label": "数量", "type": "integer", "required": True, "description": ""},
                         {"name": "customer", "label": "客户", "type": "string", "required": True, "description": ""}],
              "criteria": [{"label": "在库够发", "expression": "qty > 0 and qty <= obj.在库",
                            "message": "在库只有 $obj.在库,不够发 $qty"}],
              "effects": [{"tool": "object.create", "label": "生成出库单", "args": {"object_type": "出库单", "values": {
                  "出库单号": "OUT$now_id", "仓库编号": "$obj.仓库编号", "商品编号": "$obj.商品编号", "数量": "$qty",
                  "出库日期": "$today", "客户": "$customer"}}},
                  _add("库存位", "$obj_key", "在库", "$qty", "减少在库", op="sub")],
              "approval": {"mode": "auto"}}},
    {"name": "调整安全库存", "description": "调整一个库存位的安全库存。",
     "spec": {"target_type": "库存位",
              "params": [{"name": "safety", "label": "新的安全库存", "type": "integer", "required": True, "description": ""},
                         {"name": "reason", "label": "原因", "type": "text", "required": True, "description": ""}],
              "effects": [_write("库存位", "$obj_key", {"安全库存": "$safety"}, "改安全库存")],
              "approval": {"mode": "manual", "stages": [{"name": "仓库主管审批", "approver_roles": ["仓库主管"], "skip_when": ""}]}}},
    {"name": "标记供应延期", "description": "供应商交付出问题:合作状态改为延期。",
     "spec": {"target_type": "供应商", "params": [{"name": "reason", "label": "原因", "type": "text", "required": True,
                                                   "description": ""}],
              "transition": {"property": "合作状态", "from": ["正常"], "to": "延期"}, "approval": {"mode": "auto"}}},
    {"name": "恢复正常供货", "description": "供应商恢复正常:合作状态改回正常。",
     "spec": {"target_type": "供应商", "params": [],
              "transition": {"property": "合作状态", "from": ["延期", "暂停"], "to": "正常"}, "approval": {"mode": "auto"}}},
    {"name": "暂停合作", "description": "暂停和这家供应商的合作,要采购经理批。",
     "spec": {"target_type": "供应商", "params": [{"name": "reason", "label": "原因", "type": "text", "required": True,
                                                   "description": ""}],
              "transition": {"property": "合作状态", "from": ["正常", "延期"], "to": "暂停"},
              "approval": {"mode": "manual", "stages": [{"name": "采购经理审批", "approver_roles": ["采购经理"],
                                                          "skip_when": ""}]}}},
]

ROLES = [("仓库主管", "管仓、看库存、处理出库异常"), ("采购员", "处理补货建议、催货"),
         ("采购经理", "批 1 万以上的采购单、暂停供应商"), ("总经理", "批 5 万以上的采购单")]
USERS = [("wh_mgr", "仓库主管·刘洋", ["operator"], ["仓库主管"]),
         ("buyer", "采购员·陈晨", ["operator", "approver"], ["采购员"]),
         ("buy_mgr", "采购经理·何静", ["operator", "approver"], ["采购经理"]),
         ("gm", "总经理·唐卫国", ["operator", "approver"], ["总经理"])]

def _all(*items) -> dict:
    return {"mode": "all", "items": [{"left": l, "op": o, "right": r} for l, o, r in items]}


FLOW_SPIKE = {
    "title": "出库突增补货核查", "owner_role": "仓库主管",
    "description": "某个商品在某个仓出库量突然比平时高很多:没有在等处理的补货建议,就对这个库存位生成一条,再告诉采购员。",
    "spec": {
        "params": [{"name": "warehouse", "label": "仓库", "type": "string", "required": True, "description": "仓库编号"},
                   {"name": "product", "label": "商品", "type": "string", "required": True, "description": "商品编号"}],
        "start": "stock",
        "steps": [
            {"id": "stock", "type": "query", "title": "查这个库存位", "object_type": "库存位", "limit": 1,
             "where": _all(("仓库编号", "eq", "$warehouse"), ("商品编号", "eq", "$product")), "next": "pending"},
            {"id": "pending", "type": "query", "title": "看有没有还没处理的补货建议", "object_type": "补货建议", "limit": 5,
             "where": _all(("仓库编号", "eq", "$warehouse"), ("商品编号", "eq", "$product"), ("状态", "eq", "待处理")),
             "next": "gate"},
            {"id": "gate", "type": "decision", "title": "要不要补", "default": "missing", "branches": [
                {"label": "已经有补货建议在等处理", "next": "remind", "cond": _all(("$pending.total", "gt", 0))},
                {"label": "找到了库存位", "next": "each", "cond": _all(("$stock.total", "gt", 0))}]},
            {"id": "remind", "type": "notify", "title": "提醒采购员", "role": "采购员", "next": "done",
             "subject": "$event.title:已有补货建议待处理",
             "body": "仓库 $warehouse 商品 $product 今天出库 $event.value 件,已有 $pending.total 条补货建议还没处理。"},
            {"id": "each", "type": "foreach", "title": "对这个库存位", "items": "$stock.items", "next": "tell",
             "body": {"start": "suggest", "steps": [
                 {"id": "suggest", "type": "action", "title": "生成补货建议", "action": "生成补货建议",
                  "object_key": "$item.key", "next": "e",
                  "params": {"qty": "$item.建议补货量",
                             "reason": "出库突增:今天 $event.value 件,近 14 天日均 $event.baseline 件"}},
                 {"id": "e", "type": "end", "title": "完"}]}},
            {"id": "tell", "type": "notify", "title": "告诉采购员", "role": "采购员", "next": "done",
             "subject": "$event.title:已生成补货建议",
             "body": "仓库 $warehouse 商品 $product 出库突增(严重度 $event.severity),已按建议补货量生成补货建议,请尽快处理。"},
            {"id": "missing", "type": "notify", "title": "告诉仓库主管", "role": "仓库主管", "next": "done",
             "subject": "$event.title:找不到库存位", "body": "仓库 $warehouse 没有商品 $product 的库存位,请核对。"},
            {"id": "done", "type": "end", "title": "结束", "outcome": "已核查"}]}}

HOURLY = {"kind": "interval", "every_minutes": 60}
DAILY8 = {"kind": "daily", "at": "08:00", "tz": "Asia/Shanghai", "misfire": "skip"}


def watches(sop_id: str) -> list[dict]:
    return [
        {"title": "出库量异常突增", "owner_role": "仓库主管",
         "description": "某个仓某个商品今天的出库量偏离近 14 天日均 3 个标准差以上(且不少于 30 件)",
         "schedule": HOURLY, "trigger": {"kind": "schedule"},
         "source": {"kind": "metric", "metric": "日出库量", "dimensions": ["仓库", "商品"]},
         "detectors": [{"name": "基线", "fn": "avg", "field": "value", "window": 14},
                       {"name": "偏离", "fn": "zscore", "field": "value", "window": 14},
                       {"name": "涨幅", "fn": "pct_change", "field": "value"}],
         "condition": "偏离 >= 3 and value >= 30",
         "severity": {"mode": "rules", "level": "中", "rules": [{"when": "偏离 >= 8", "level": "高"}]},
         "strategies": [{"kind": "run_sop", "sop": sop_id, "params": {"warehouse": "$仓库", "product": "$商品"}},
                        {"kind": "notify", "role": "仓库主管", "min_severity": "高",
                         "subject": "$label 出库突增($severity)", "body": "今天出库 $value 件,近 14 天日均 $基线 件。"}],
         "dedup": {"key": "$key", "cooldown_hours": 24}, "recovery": {"mode": "auto", "reopen_days": 7}},
        {"title": "库存跌破安全库存", "owner_role": "仓库主管",
         "description": "库存位一变(发货、到货、审批采购单)马上判;严重度按缺口比例查决策表",
         "schedule": DAILY8, "trigger": {"kind": "change", "properties": ["在库", "在途", "安全库存"]},
         "source": {"kind": "object_set", "set": "低库存位"},
         "condition": "缺口 > 0",
         "severity": {"mode": "decision", "level": "中", "function": "缺货严重度", "inputs": {"缺口比例": "$缺口比例"}},
         "strategies": [{"kind": "task", "role": "采购员", "min_severity": "高",
                         "title": "$label 缺货严重:可用 $可用 / 安全库存 $安全库存",
                         "instructions": "建议补 $建议补货量。先看「待处理补货建议」里有没有,没有就对这个库存位发起「生成补货建议」。"},
                        {"kind": "notify", "role": "仓库主管", "subject": "$label 跌破安全库存($severity)",
                         "body": "可用 $可用,安全库存 $安全库存,缺口 $缺口。"}],
         "dedup": {"key": "$key", "cooldown_hours": 24}, "recovery": {"mode": "auto", "reopen_days": 7}},
        {"title": "采购单超期未到", "owner_role": "采购员", "description": "已下单、过了预计到货日还没到",
         "schedule": {"kind": "daily", "at": "09:00", "tz": "Asia/Shanghai", "misfire": "skip"},
         "source": {"kind": "object_set", "set": "超期在途采购单"},
         "condition": "超期天数 > 0",
         "severity": {"mode": "rules", "level": "低",
                      "rules": [{"when": "超期天数 >= 5", "level": "高"}, {"when": "超期天数 >= 2", "level": "中"}]},
         "strategies": [{"kind": "task", "role": "采购员", "title": "催货:$label 已超期 $超期天数 天",
                         "instructions": "供应商 $供应商编号,预计 $预计到货 到货。联系供应商确认新的到货日期。"}],
         "dedup": {"key": "$key", "cooldown_hours": 24}, "recovery": {"mode": "auto", "reopen_days": 3}},
    ]


# ---------------------------------------------------------------- 构建
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": "3 个仓、5 家供应商、20 个商品的分销库存", "industry": "商贸分销"})
        print("新建本体空间", WS)
    else:   # 带着空间头的请求会自动建出空间(名字是默认的):补上名字
        call("PUT", f"/api/kernel/workspaces/{WS}", {"id": WS, "display_name": "鲜达商贸 · 库存补货",
                                                      "description": "3 个仓、5 家供应商、20 个商品的分销库存", "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"]
    j: dict = {}
    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 upsert(kind: str, name: str, spec: dict, description: str = "", synonyms: list | None = None,
           display_name: str = "") -> dict:
    have = {c["name"]: c for c in call("GET", "/api/kernel/concepts", kind=kind)}
    body = {"description": description, "spec": spec, "synonyms": synonyms or []}
    if display_name:
        body["display_name"] = display_name
    if name in have:
        return call("PUT", f"/api/kernel/concepts/{have[name]['id']}", body)
    return call("POST", "/api/kernel/concepts", {"kind": kind, "name": name, **body})


def bind(cid: str, ds_id: int, target_kind: str, ref: dict) -> None:
    call("PUT", f"/api/kernel/concepts/{cid}/bindings", {"ds_id": ds_id, "target_kind": target_kind, "ref": ref})


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}」:v{(r.get('published') or {}).get('rev', '?')}")


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 build_semantic(ds_id: int) -> dict[str, str]:
    for name, desc, spec in VALUE_TYPES:
        upsert("value_type", name, spec, desc)
    upsert("object_type", INTERFACE[0], INTERFACE[2], INTERFACE[1])
    ids = {}
    for name, (desc, spec, ref) in OBJECTS.items():
        c = upsert("object_type", name, spec, desc)
        bind(c["id"], 0 if ref.get("kind") == "managed" else ds_id, "table", ref)
        ids[name] = c["id"]
    for name, a, b, card, ref in LINKS:
        spec = {"from_type": a, "to_type": b, "cardinality": card}
        if card == "n:n":
            spec["inverse_name"] = "供货商"
        c = upsert("link_type", name, spec)
        bind(c["id"], ds_id, "join", ref)
    print(f"值类型 {len(VALUE_TYPES)} 个,接口 1 个,对象 {len(OBJECTS)} 个,关系 {len(LINKS)} 条")
    return ids


def build_logic(ds_id: int) -> None:
    for name, desc, spec in RULES + DECISIONS + OBJECT_SETS:
        upsert("function", name, spec, desc)
    for name, syn, desc, spec, ref in METRICS:
        c = upsert("function", name, {**spec, "formula_text": desc}, desc, syn)
        bind(c["id"], ds_id, "metric_expr", ref)
    for a in ACTIONS:
        upsert("action", a["name"], a["spec"], a["description"], a.get("synonyms"), display_name=a["name"])
    print(f"规则 {len(RULES)}、决策表 {len(DECISIONS)}、对象集 {len(OBJECT_SETS)}、指标 {len(METRICS)}、动作 {len(ACTIONS)}")


def build_flows() -> None:
    have = {d["title"]: d for d in call("GET", "/api/sop/defs")}
    f = FLOW_SPIKE
    d = have.get(f["title"]) or call("POST", "/api/sop/defs", {"title": f["title"]})
    d = call("GET", f"/api/sop/defs/{d['id']}")
    d = call("PUT", f"/api/sop/defs/{d['id']}", {"title": f["title"], "description": f["description"],
                                                  "owner_role": f["owner_role"], "spec": f["spec"],
                                                  "etag": d.get("draft_hash") or ""})
    errs = (d.get("validation") or {}).get("errors") or []
    if errs or d.get("tree_error"):
        raise SystemExit(f"流程卡「{f['title']}」有问题:{d.get('tree_error') or errs[:4]}")
    r = call("POST", f"/api/sop/defs/{d['id']}/publish", {"note": "场景脚本"}, ok=(200, 201, 409, 422))
    if r.get("detail"):
        raise SystemExit(f"流程卡「{f['title']}」发布失败:{r['detail']}")
    print(f"流程卡「{f['title']}」已发布 v{r.get('current_version')}")
    havew = {w["title"]: w for w in call("GET", "/api/watch")}
    for w in watches(d["id"]):
        body = {**w, "enabled": True}
        if w["title"] in havew:
            call("PUT", f"/api/watch/{havew[w['title']]['id']}", body)
        else:
            call("POST", "/api/watch", body)
    print(f"预警规则 {len(watches(''))} 条")


def sync_index() -> None:
    call("POST", "/api/kernel/pipelines/ensure")
    job = call("POST", "/api/kernel/pipelines/run-all")["job_id"]
    for _ in range(300):
        j = call("GET", f"/api/jobs/{job}")
        if j.get("status") in ("done", "failed", "error", "succeeded", "success"):
            break
        time.sleep(1)
    st = call("GET", "/api/kernel/pipeline/status", ok=(200, 404))
    print(f"对象索引同步:{j.get('status')}", str(st)[:160] if isinstance(st, dict) else "")


def backfill_stock_history(days: int = 30) -> None:
    """库存位「在库」的历史走势:从出库流水和到货记录往回倒推(系统上线前没有快照)。"""
    from sqlalchemy import create_engine, text

    from app.core.config import get_settings
    eng = create_engine(get_settings().sqlalchemy_url, future=True)
    today = dt.date.today()
    since = today - dt.timedelta(days=days)
    with eng.connect() as c:
        stock = {(r.warehouse_id, r.product_id): (r.stock_id, r.on_hand) for r in c.execute(text(
            f"SELECT stock_id, warehouse_id, product_id, on_hand FROM {T}stock"))}
        out = defaultdict(int)
        for r in c.execute(text(f"SELECT warehouse_id, product_id, out_date, SUM(qty) q FROM {T}outbound "
                                f"WHERE out_date > :d GROUP BY warehouse_id, product_id, out_date"), {"d": since}):
            out[(r.warehouse_id, r.product_id, r.out_date)] += int(r.q)
        arr = defaultdict(int)
        for r in c.execute(text(f"SELECT warehouse_id, product_id, arrived_date, SUM(qty) q FROM {T}purchase_order "
                                f"WHERE status = '已到货' AND arrived_date > :d GROUP BY warehouse_id, product_id, arrived_date"),
                           {"d": since}):
            arr[(r.warehouse_id, r.product_id, r.arrived_date)] += int(r.q)
    points = []
    for (w, p), (sid, on_hand) in stock.items():
        level = int(on_hand or 0)
        for back in range(0, days + 1):
            day = today - dt.timedelta(days=back)
            if back:
                points.append({"key": str(sid), "value": level, "at": f"{day.isoformat()}T20:00:00"})
            level += out.get((w, p, day), 0) - arr.get((w, p, day), 0)      # 倒推到前一天晚上
            level = max(level, 0)
    r = call("POST", "/api/kernel/series/backfill", {"object_type": "库存位", "property": "在库", "points": points})
    print(f"库存位「在库」历史补了 {r['written']} 个点(近 {days} 天)")


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(ds_id)
    build_logic(ds_id)
    publish("库存补货:语义层、逻辑层、动作")
    call("POST", "/api/kernel/storage/sync")
    build_flows()
    sync_index()
    backfill_stock_history()
    print("\n库存补货场景建好了:http://127.0.0.1:%d (右上角切到「鲜达商贸 · 库存补货」)" % args.port)


if __name__ == "__main__":
    main()