build_dm2_behavior.py 31.8 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
"""4S 配件场景的「会动的部分」:决策表、动作(含状态流转)、流程卡、预警规则。由 build_dm2_ontology.py 调用。"""
from __future__ import annotations


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


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


PART = {"name": "part", "label": "这个配件", "object_type": "配件", "where": [_w("part_id", "$obj.part_id")]}
DEALER = {"name": "dealer", "label": "这家门店", "object_type": "门店", "where": [_w("dealer_id", "$obj.dealer_id")]}
STOCK = {"name": "stock", "label": "本店这个配件的库存", "object_type": "门店库存",
         "where": [_w("dealer_id", "$obj.dealer_id"), _w("part_id", "$obj.part_id")]}
QUOTA = {"name": "quota", "label": "本月配额", "object_type": "月度配额",
         "where": [_w("dealer_id", "$obj.dealer_id"), _w("part_id", "$obj.part_id"), _w("month", "$this_month")]}
OEM = {"name": "oem", "label": "主机厂库存", "object_type": "主机厂库存", "where": [_w("part_id", "$obj.part_id")]}

PRIORITY = {"function": "订单优先级", "inputs": {"order_type": "$order_type", "amount": "=eff.amount"}}

DECISIONS = [{
    "name": "订单优先级", "description": "按订单类型和金额定审批的紧急程度",
    "spec": {"category": "decision", "hit_policy": "first",
             "inputs": [{"name": "order_type", "label": "订单类型", "type": "string"},
                        {"name": "amount", "label": "金额", "type": "number"}],
             "outputs": [{"name": "priority", "label": "优先级"}],
             "rows": [{"when": {"order_type": "'缺件专订'"}, "then": {"priority": "P1"}, "note": "有客户的车在等"},
                      {"when": {"order_type": "'紧急'"}, "then": {"priority": "P1"}, "note": ""},
                      {"when": {"amount": ">= 5000"}, "then": {"priority": "P2"}, "note": "大额"}],
             "default": {"priority": "P3"}},
}]

_PO_VALUES = {"po_no": "PO$now_id", "dealer_id": "$obj.dealer_id", "part_id": "$obj.part_id", "qty": "$qty",
              "amount": "=qty * part.dealer_price", "order_date": "$today"}

ACTIONS = [
    {"name": "下常规订单", "synonyms": ["订货", "补货", "下订单"],
     "description": "门店向主机厂订一个配件。只有可用库存低于订货许可线时才能下;管控件要占本月配额。",
     "spec": {
         "target_type": "门店库存",
         "params": [
             {"name": "qty", "label": "数量", "type": "integer", "required": True,
              "description": "必须是最小包装量的整数倍,不能超过建议订货量"},
             {"name": "order_type", "label": "订单类型", "type": "enum", "enum": ["常规", "紧急"], "default": "常规",
              "required": True, "description": "常规 5 天到;紧急 2 天到,另收 8% 加急运费(最低 30 元)"}],
         "lookups": [PART, DEALER, QUOTA],
         "criteria": [
             {"label": "订货许可线", "expression": "obj.available < obj.order_point",
              "message": "可用库存 $obj.available 不低于订货许可线 $obj.order_point,现在不能订这个件"},
             {"label": "最小包装量", "expression": "qty > 0 and qty % part.pack_qty == 0",
              "message": "数量要是最小包装量 $part.pack_qty 的整数倍"},
             {"label": "库存上限", "expression": "qty <= obj.max_stock - obj.available",
              "message": "订货后会超过库存上限 $obj.max_stock,最多可订 $obj.suggest_qty"},
             {"label": "赊销额度", "expression": "qty * part.dealer_price <= dealer.credit_left",
              "message": "金额超过了赊销额度剩余($dealer.credit_left 元)"}],
         "effects": [
             {"tool": "object.create", "label": "生成配件订单", "args": {"object_type": "配件订单", "values": {
                 **_PO_VALUES, "order_type": "$order_type", "status": "已发货",
                 "freight_fee": "=0 if order_type == '常规' else max(30, round(qty * part.dealer_price * 0.08, 2))",
                 "expected_date": "=add_days(today(), part.lead_days_normal if order_type == '常规' "
                                  "else part.lead_days_urgent)"}}},
             _write("门店库存", "$obj_key", "in_transit", "$qty", "add", "增加在途"),
             _write("门店", "$obj.dealer_id", "credit_used", "=qty * part.dealer_price", "add", "占用赊销额度"),
             _write("月度配额", "$quota.key", "used_qty", "$qty", "add", "占用本月配额",
                    when="part.is_controlled == '是' and quota.key != None")],
         "approval": {"mode": "manual", "decision": PRIORITY, "stages": [
             {"name": "店内审批", "approver_roles": ["店总"], "skip_when": "eff.amount < 5000"},
             {"name": "主机厂审核", "approver_roles": ["配件计划员"], "skip_when": "part.is_controlled != '是'"},
             {"name": "区域经理特批", "approver_roles": ["区域配件经理"],
              "skip_when": "part.is_controlled != '是' or qty <= quota.left_qty"}]}}},

    {"name": "下缺件专订", "synonyms": ["缺件专订", "专订"],
     "description": "有工单在等件时,凭缺件单向主机厂加急订货。不受订货许可线和配额限制,2 天到。",
     "spec": {
         "target_type": "缺件单",
         "params": [{"name": "qty", "label": "数量", "type": "integer", "required": True,
                     "description": "不能超过缺件数量"}],
         "lookups": [PART, DEALER, STOCK, OEM],
         "criteria": [
             {"label": "缺件单状态", "expression": "obj.status != '已解决'", "message": "这张缺件单已经解决了"},
             {"label": "数量", "expression": "qty > 0 and qty <= obj.qty_short",
              "message": "数量不能超过缺件数量 $obj.qty_short"},
             {"label": "主机厂可分配量", "expression": "oem.available >= qty",
              "message": "主机厂可分配量只有 $oem.available,不够订"},
             {"label": "赊销额度", "expression": "qty * part.dealer_price <= dealer.credit_left",
              "message": "金额超过了赊销额度剩余($dealer.credit_left 元)"}],
         "effects": [
             {"tool": "object.create", "label": "生成缺件专订", "args": {"object_type": "配件订单", "values": {
                 **_PO_VALUES, "order_type": "缺件专订", "shortage_id": "$obj_key", "status": "已发货",
                 "freight_fee": "=max(30, round(qty * part.dealer_price * 0.08, 2))",
                 "expected_date": "=add_days(today(), part.lead_days_urgent)"}}},
             _write("缺件单", "$obj_key", "handle_type", "缺件专订", label="登记处理方式"),
             _write("缺件单", "$obj_key", "ref_no", "PO$now_id", label="登记关联单号"),
             _write("缺件单", "$obj_key", "expected_date", "=add_days(today(), part.lead_days_urgent)",
                    label="登记预计到件"),
             _write("门店库存", "$stock.key", "in_transit", "$qty", "add", "增加在途", when="stock.key != None"),
             _write("门店", "$obj.dealer_id", "credit_used", "=qty * part.dealer_price", "add", "占用赊销额度"),
             _write("主机厂库存", "$oem.key", "allocated", "$qty", "add", "占用主机厂库存")],
         "transition": {"property": "status", "from": ["待处理", "处理中"], "to": "处理中"},
         "on_reject": [_write("缺件单", "$obj_key", "remark", "缺件专订被驳回:$reject_reason", label="登记驳回原因")],
         "approval": {"mode": "manual",
                      "decision": {"function": "订单优先级", "inputs": {"order_type": "缺件专订", "amount": "=eff.amount"}},
                      "stages": [
                          {"name": "店内确认", "approver_roles": ["店总"], "skip_when": "eff.amount < 5000"},
                          {"name": "主机厂审核", "approver_roles": ["配件计划员"], "skip_when": ""}]}}},
]


def _transfer(name: str, desc: str, criteria: list[dict], stages: list[dict]) -> dict:
    src = {"name": "src", "label": "调出门店的库存", "object_type": "门店库存",
           "where": [_w("dealer_id", "$from_dealer"), _w("part_id", "$obj.part_id")]}
    return {"name": name, "description": desc, "spec": {
        "target_type": "缺件单",
        "params": [{"name": "from_dealer", "label": "调出门店", "type": "object", "object_type": "门店",
                    "required": True, "description": "从哪家店调"},
                   {"name": "qty", "label": "数量", "type": "integer", "required": True,
                    "description": "不能超过缺件数量"}],
        "lookups": [PART, src, STOCK],
        "criteria": [
            {"label": "缺件单状态", "expression": "obj.status != '已解决'", "message": "这张缺件单已经解决了"},
            {"label": "调出门店", "expression": "from_dealer != obj.dealer_id", "message": "不能从自己店里调"},
            {"label": "数量", "expression": "qty > 0 and qty <= obj.qty_short",
             "message": "数量不能超过缺件数量 $obj.qty_short"},
            *criteria],
        "effects": [
            {"tool": "object.create", "label": "生成调拨单", "args": {"object_type": "调拨单", "values": {
                "transfer_no": "TR$now_id", "from_dealer_id": "$from_dealer", "to_dealer_id": "$obj.dealer_id",
                "part_id": "$obj.part_id", "qty": "$qty", "amount": "=qty * part.dealer_price",
                "shortage_id": "$obj_key", "status": "在途", "apply_date": "$today",
                "expected_date": "=add_days(today(), 1)"}}},
            _write("门店库存", "$src.key", "on_hand", "$qty", "sub", "调出门店减少在库"),
            _write("门店库存", "$stock.key", "in_transit", "$qty", "add", "调入门店增加在途", when="stock.key != None"),
            _write("缺件单", "$obj_key", "handle_type", "店间调拨", label="登记处理方式"),
            _write("缺件单", "$obj_key", "ref_no", "TR$now_id", label="登记关联单号"),
            _write("缺件单", "$obj_key", "expected_date", "=add_days(today(), 1)", label="登记预计到件")],
        "transition": {"property": "status", "from": ["待处理", "处理中"], "to": "处理中"},
        "on_reject": [_write("缺件单", "$obj_key", "remark", "调拨申请被拒:$reject_reason", label="登记被拒原因")],
        "approval": {"mode": "manual", "stages": stages}}}


ACTIONS += [
    _transfer("发起店间调拨", "从区域内另一家店调配件过来,1 天到。要对方店总同意、区域配件经理审批。",
              [{"label": "调出门店有货", "expression": "src.key != None and src.available - qty >= src.order_point",
                "message": "调出后对方的可用库存会低于它的订货许可线(现有 $src.available,许可线 $src.order_point)"}],
              [{"name": "调出店同意", "approver_roles": ["店总"], "skip_when": ""},
               {"name": "主机厂审批", "approver_roles": ["区域配件经理"], "skip_when": ""}]),
    _transfer("强制调拨", "调出门店这个件处于囤货预警时,区域配件经理可以不经对方同意直接调。",
              [{"label": "囤货预警", "expression": "src.hoarding == 1", "message": "调出门店这个件没有处于囤货预警,不能强制调拨"},
               {"label": "调出后不低于上限", "expression": "src.available - qty >= src.max_stock",
                "message": "强制调拨后,调出门店的可用库存不能低于它的库存上限 $src.max_stock"}],
              [{"name": "区域经理审批", "approver_roles": ["区域配件经理"], "skip_when": ""}]),

    {"name": "订单到货入库", "synonyms": ["到货", "入库"],
     "description": "订单的配件到店:在途转成在库;如果这张订单是为缺件单订的,缺件单关闭、工单恢复维修。",
     "spec": {
         "target_type": "配件订单", "params": [],
         "lookups": [STOCK,
                     {"name": "short", "label": "对应的缺件单", "object_type": "缺件单",
                      "where": [_w("shortage_id", "$obj.shortage_id")]},
                     {"name": "wo", "label": "对应的工单", "object_type": "维修工单", "where": [_w("wo_no", "$short.wo_no")]}],
         "criteria": [{"label": "订单状态", "expression": "obj.status == '已发货'",
                       "message": "只有已发货的订单才能入库(现在是 $obj.status)"}],
         "effects": [
             _write("配件订单", "$obj_key", "status", "已到货", label="订单改为已到货"),
             _write("配件订单", "$obj_key", "arrived_date", "$today", label="登记到货日期"),
             _write("门店库存", "$stock.key", "in_transit", "$obj.qty", "sub", "减少在途", when="stock.key != None"),
             _write("门店库存", "$stock.key", "on_hand", "$obj.qty", "add", "增加在库", when="stock.key != None"),
             {"tool": "object.transition", "label": "关闭缺件单", "when": "short.key != None",
              "args": {"object_type": "缺件单", "key": "$short.key", "property": "status", "to": "已解决"}},
             _write("缺件单", "$short.key", "resolved_date", "$today", label="登记解决日期", when="short.key != None"),
             _write("维修工单", "$wo.key", "status", "维修中", label="工单恢复维修",
                    when="wo.key != None and wo.status == '待料'")],
         "approval": {"mode": "auto"}}},

    {"name": "驳回订单", "description": "主机厂审核不通过:订单改为已驳回,并写明原因。",
     "spec": {
         "target_type": "配件订单",
         "params": [{"name": "reason", "label": "驳回原因", "type": "text", "required": True,
                     "description": "会写到订单上,门店能看到"}],
         "criteria": [{"label": "订单状态", "expression": "obj.status in ['店内待审批', '主机厂审核中']",
                       "message": "只有待审的订单才能驳回(现在是 $obj.status)"}],
         "effects": [_write("配件订单", "$obj_key", "status", "已驳回", label="订单改为已驳回"),
                     _write("配件订单", "$obj_key", "reject_reason", "$reason", label="登记驳回原因")],
         "approval": {"mode": "auto"}}},

    {"name": "通过订单", "description": "主机厂审核通过:订单发货,门店在途增加;管控件占本月配额,超配额要区域经理特批。",
     "spec": {
         "target_type": "配件订单", "params": [],
         "lookups": [PART, STOCK, QUOTA],
         "criteria": [
             {"label": "订单状态", "expression": "obj.status == '主机厂审核中'",
              "message": "只有主机厂审核中的订单才能通过(现在是 $obj.status)"},
             {"label": "订货许可线", "expression": "obj.order_type == '缺件专订' or stock.available < stock.order_point",
              "message": "门店可用库存 $stock.available 不低于订货许可线 $stock.order_point,应当驳回"},
             {"label": "库存上限", "expression": "obj.order_type == '缺件专订' or obj.qty <= stock.max_stock - stock.available",
              "message": "订货后会超过库存上限 $stock.max_stock,应当驳回"}],
         "effects": [
             _write("配件订单", "$obj_key", "status", "已发货", label="订单改为已发货"),
             _write("门店库存", "$stock.key", "in_transit", "$obj.qty", "add", "增加在途", when="stock.key != None"),
             _write("月度配额", "$quota.key", "used_qty", "$obj.qty", "add", "占用本月配额",
                    when="part.is_controlled == '是' and quota.key != None and obj.order_type != '缺件专订'")],
         "approval": {"mode": "manual", "stages": [
             {"name": "区域经理特批", "approver_roles": ["区域配件经理"],
              "skip_when": "part.is_controlled != '是' or obj.order_type == '缺件专订' or obj.qty <= quota.left_qty"}]}}},

    {"name": "登记缺件处理", "description": "记录是否已通知客户、是否安排了代步车。",
     "spec": {
         "target_type": "缺件单",
         "params": [{"name": "notified", "label": "已通知客户", "type": "boolean", "required": True, "description": ""},
                    {"name": "loaner", "label": "已安排代步车", "type": "boolean", "required": False,
                     "description": "预计等待超过 3 天要安排"},
                    {"name": "remark", "label": "备注", "type": "text", "required": False, "description": ""}],
         "lookups": [{"name": "wo", "label": "对应的工单", "object_type": "维修工单", "where": [_w("wo_no", "$obj.wo_no")]}],
         "effects": [
             _write("缺件单", "$obj_key", "customer_notified", "=('是' if notified else '否')", label="登记是否已通知客户"),
             _write("缺件单", "$obj_key", "remark", "$remark", label="登记备注", when="remark != None"),
             _write("维修工单", "$wo.key", "loaner_car", "是", label="登记已安排代步车",
                    when="loaner == True and wo.key != None")],
         "approval": {"mode": "auto"}}},

    {"name": "登记缺件", "synonyms": ["缺件", "报缺件"],
     "description": "维修工单领料时发现缺件:新建一张缺件单(待处理),工单改为待料。",
     "spec": {
         "target_type": "维修工单",
         "params": [{"name": "part", "label": "缺的配件", "type": "object", "object_type": "配件", "required": True,
                     "description": ""},
                    {"name": "qty", "label": "缺件数量", "type": "integer", "required": True, "description": ""}],
         "criteria": [{"label": "数量", "expression": "qty > 0", "message": "缺件数量要大于 0"}],
         "effects": [
             {"tool": "object.create", "label": "新建缺件单", "args": {"object_type": "缺件单", "values": {
                 "shortage_id": "SH$now_id", "wo_no": "$obj_key", "dealer_id": "$obj.dealer_id", "part_id": "$part",
                 "qty_short": "$qty", "found_date": "$today", "handle_type": "未处理", "status": "待处理",
                 "customer_notified": "否"}}},
             _write("维修工单", "$obj_key", "status", "待料", label="工单改为待料")],
         "approval": {"mode": "auto"}}},

    {"name": "调整库存管控线", "description": "主机厂调整某家店某个配件的订货许可线和库存上限。",
     "spec": {
         "target_type": "门店库存",
         "params": [{"name": "order_point", "label": "新的订货许可线", "type": "integer", "required": True, "description": ""},
                    {"name": "max_stock", "label": "新的库存上限", "type": "integer", "required": True, "description": ""},
                    {"name": "reason", "label": "调整原因", "type": "text", "required": True, "description": ""}],
         "criteria": [{"label": "上限高于许可线", "expression": "max_stock > order_point",
                       "message": "库存上限要大于订货许可线"}],
         "effects": [_write("门店库存", "$obj_key", "order_point", "$order_point", label="改订货许可线"),
                     _write("门店库存", "$obj_key", "max_stock", "$max_stock", label="改库存上限")],
         "approval": {"mode": "manual", "stages": [
             {"name": "区域经理审批", "approver_roles": ["区域配件经理"], "skip_when": ""}]}}},
]


def build(call, ids, OBJECTS) -> None:
    have = {c["name"]: c for c in call("GET", "/api/kernel/concepts", kind="function")}
    for d in DECISIONS:
        if d["name"] in have:
            call("PUT", f"/api/kernel/concepts/{have[d['name']]['id']}", {"description": d["description"], "spec": d["spec"]})
        else:
            call("POST", "/api/kernel/concepts", {"kind": "function", **d})
    have = {c["name"]: c for c in call("GET", "/api/kernel/concepts", kind="action")}
    for a in ACTIONS:
        body = {"display_name": a["name"], "description": a["description"], "synonyms": a.get("synonyms") or [],
                "spec": a["spec"]}
        if a["name"] in have:
            call("PUT", f"/api/kernel/concepts/{have[a['name']]['id']}", body)
        else:
            call("POST", "/api/kernel/concepts", {"kind": "action", "name": a["name"], **body})
    print(f"决策表 {len(DECISIONS)} 张,动作 {len(ACTIONS)} 个")


# ---------------------------------------------------------------- 流程卡与预警
def _all(*items) -> dict:
    return {"mode": "all", "items": [{"left": l, "op": o, "right": r} for l, o, r in items]}


FLOWS = [
    {"title": "缺件处理", "owner_role": "配件主管",
     "description": "有工单缺件时:先看区域内有没有超储的店可以调,再看主机厂够不够专订,都不行就通知客户等货。",
     "spec": {
         "params": [{"name": "shortage", "label": "缺件单", "type": "object", "object_type": "缺件单",
                     "required": True, "description": "要处理哪张缺件单"}],
         "start": "donors",
         "steps": [
             {"id": "donors", "type": "query", "title": "找这个件超储的店", "object_type": "门店库存", "limit": 1,
              "where": _all(("part_id", "eq", "$shortage.part_id"), ("overstock", "eq", 1)),
              "sort": [{"property": "months", "dir": "desc"}], "next": "oem"},
             {"id": "oem", "type": "query", "title": "看主机厂还能分多少", "object_type": "主机厂库存", "mode": "one",
              "where": _all(("part_id", "eq", "$shortage.part_id")), "next": "how"},
             {"id": "how", "type": "decision", "title": "怎么弄到件", "default": "tell", "branches": [
                 {"label": "区域内有店超储", "next": "pick", "cond": _all(("$donors.total", "gt", 0))},
                 {"label": "主机厂够分", "next": "vor", "cond": _all(("$oem.available", "ge", "$shortage.qty_short"))}]},
             {"id": "pick", "type": "foreach", "title": "从超储最多的店调", "items": "$donors.items", "next": "done",
              "body": {"start": "transfer", "steps": [
                  {"id": "transfer", "type": "action", "title": "发起店间调拨", "action": "发起店间调拨",
                   "object_key": "$shortage.key", "next": "e1",
                   "params": {"from_dealer": "$item.dealer_id", "qty": "$shortage.qty_short"}},
                  {"id": "e1", "type": "end", "title": "完"}]}},
             {"id": "vor", "type": "action", "title": "下缺件专订", "action": "下缺件专订", "object_key": "$shortage.key",
              "params": {"qty": "$shortage.qty_short"}, "next": "done"},
             {"id": "tell", "type": "human_task", "title": "通知客户等货", "role": "服务顾问", "sla_hours": 4,
              "instructions": "缺件单 $shortage.label:区域内没有店可调,主机厂可分配量只有 $oem.available。"
                              "请通知客户,预计等待超过 3 天要安排代步车。",
              "form": [{"name": "notified", "label": "已通知客户", "type": "boolean", "required": True},
                       {"name": "loaner", "label": "已安排代步车", "type": "boolean", "required": False}],
              "next": "log"},
             {"id": "log", "type": "action", "title": "登记处理情况", "action": "登记缺件处理", "object_key": "$shortage.key",
              "params": {"notified": "$tell.notified", "loaner": "$tell.loaner",
                         "remark": "区域内无货可调,主机厂库存不足,等下一批到库"}, "next": "done"},
             {"id": "done", "type": "end", "title": "结束", "outcome": "缺件单已安排处理"}]}},

    {"title": "每日补货巡检", "owner_role": "配件主管",
     "description": "查出本店可以订货的配件,按建议订货量逐条下常规订单;再看有没有超期未到的订单。",
     "spec": {
         "params": [{"name": "dealer", "label": "门店", "type": "object", "object_type": "门店", "required": True,
                     "description": "巡检哪家店"}],
         "start": "todo",
         "steps": [
             {"id": "todo", "type": "query", "title": "查可以订货的配件", "object_type": "门店库存", "limit": 50,
              "where": _all(("dealer_id", "eq", "$dealer.key"), ("can_order", "eq", 1), ("suggest_qty", "gt", 0)),
              "sort": [{"property": "months", "dir": "asc"}], "next": "orders"},
             {"id": "orders", "type": "foreach", "title": "逐条下订单", "items": "$todo.items", "next": "late",
              "body": {"start": "order", "steps": [
                  {"id": "order", "type": "action", "title": "下常规订单", "action": "下常规订单", "object_key": "$item.key",
                   "params": {"qty": "$item.suggest_qty", "order_type": "常规"}, "on_reject": "e2", "next": "e2"},
                  {"id": "e2", "type": "end", "title": "完"}]}},
             {"id": "late", "type": "query", "title": "查超期未到的订单", "object_type": "配件订单", "limit": 50,
              "where": _all(("dealer_id", "eq", "$dealer.key"), ("overdue", "eq", 1)), "next": "report"},
             {"id": "report", "type": "notify", "title": "告诉店总", "role": "店总", "next": "done",
              "subject": "$dealer.label 今日补货巡检",
              "body": "可订货的配件 $todo.total 个;超期未到的订单 $late.total 张。"},
             {"id": "done", "type": "end", "title": "结束", "outcome": "巡检完成"}]}},

    {"title": "区域囤货巡检", "owner_role": "配件计划员",
     "description": "查出区域内处于囤货预警的「门店 × 配件」,逐条交给区域配件经理决定怎么处理。",
     "spec": {
         "params": [], "start": "hoard",
         "steps": [
             {"id": "hoard", "type": "query", "title": "查囤货预警", "object_type": "门店库存", "limit": 50,
              "where": _all(("hoarding", "eq", 1)), "sort": [{"property": "region_share", "dir": "desc"}], "next": "each"},
             {"id": "each", "type": "foreach", "title": "逐条处理", "items": "$hoard.items", "next": "report",
              "body": {"start": "decide", "steps": [
                  {"id": "decide", "type": "human_task", "title": "决定怎么处理", "role": "区域配件经理", "sla_hours": 24,
                   "instructions": "「$item.label」在库 $item.on_hand,可用 $item.months 个月,库存上限 $item.max_stock。请决定怎么处理。",
                   "form": [{"name": "decision", "label": "处理意见", "type": "choice", "required": True,
                             "options": ["强制调拨给缺件的店", "通知门店挂调剂清单", "暂不处理"]},
                            {"name": "note", "label": "说明", "type": "text", "required": False}], "next": "e3"},
                  {"id": "e3", "type": "end", "title": "完"}]}},
             {"id": "report", "type": "notify", "title": "告诉计划员", "role": "配件计划员", "next": "done",
              "subject": "区域囤货巡检完成", "body": "囤货预警 $hoard.total 条。"},
             {"id": "done", "type": "end", "title": "结束", "outcome": "巡检完成"}]}},
]

DAILY = {"kind": "daily", "at": "10:00", "tz": "Asia/Shanghai", "misfire": "skip"}


def watches(sop_ids: dict[str, str]) -> list[dict]:
    return [
        {"title": "缺件单待处理", "owner_role": "配件主管",
         "description": "新开的缺件单马上拉起「缺件处理」流程卡;处理方式定下来(转处理中)就算恢复",
         "schedule": DAILY, "trigger": {"kind": "change", "properties": ["status"], "on": ["created", "changed"]},
         "source": {"kind": "object_set", "set": "未解决缺件单"},
         "condition": "status == '待处理'",
         "severity": {"mode": "rules", "level": "中", "rules": [{"when": "wait_days >= 2", "level": "高"}]},
         "strategies": [{"kind": "run_sop", "sop": sop_ids["缺件处理"], "params": {"shortage": "$key"}},
                        {"kind": "task", "role": "店总", "min_severity": "高", "title": "缺件单 $label 超过 48 小时没处理",
                         "instructions": "已经等了 $wait_days 天。请安排处理,并确认是否已通知客户。"}],
         "dedup": {"key": "$key", "cooldown_hours": 24}, "recovery": {"mode": "auto", "reopen_days": 3}},
        {"title": "囤货预警", "description": "单店占区域在库超过一半,且超储", "owner_role": "配件计划员",
         "schedule": DAILY, "source": {"kind": "object_set", "set": "囤货的库存"}, "condition": "hoarding == 1",
         "severity": {"mode": "fixed", "level": "中"},
         "strategies": [{"kind": "notify", "role": "区域配件经理", "subject": "囤货预警:$label",
                         "body": "在库 $on_hand,可用 $months 个月,库存上限 $max_stock。"}],
         "dedup": {"key": "$key", "cooldown_hours": 24}, "recovery": {"mode": "auto", "reopen_days": 7}},
        {"title": "待料工单超过承诺交车日", "description": "", "owner_role": "配件主管", "schedule": DAILY,
         "source": {"kind": "object", "object_type": "维修工单"}, "condition": "overdue_days > 0",
         "severity": {"mode": "rules", "level": "低",
                      "rules": [{"when": "overdue_days >= 5", "level": "高"}, {"when": "overdue_days >= 2", "level": "中"}]},
         "strategies": [{"kind": "notify", "role": "店总", "subject": "工单 $label 已超期 $overdue_days 天($severity)",
                         "body": "承诺交车日 $promised_date,现在还在等件。"}],
         "dedup": {"key": "$key", "cooldown_hours": 24}, "recovery": {"mode": "auto", "reopen_days": 3}},
        {"title": "订单超期未到", "description": "", "owner_role": "配件主管", "schedule": DAILY,
         "source": {"kind": "object", "object_type": "配件订单"}, "condition": "overdue == 1",
         "severity": {"mode": "fixed", "level": "中"},
         "strategies": [{"kind": "notify", "role": "配件主管", "subject": "订单 $label 超期未到",
                         "body": "预计到货 $expected_date,请联系主机厂。"}],
         "dedup": {"key": "$key", "cooldown_hours": 24}, "recovery": {"mode": "auto", "reopen_days": 3}},
    ]


def build_flows(call, ids, OBJECTS) -> None:
    have = {d["title"]: d for d in call("GET", "/api/sop/defs")}
    sop_ids: dict[str, str] = {}
    for f in FLOWS:
        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:
            raise SystemExit(f"流程卡「{f['title']}」有问题:{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']}")
        sop_ids[f["title"]] = d["id"]
    havew = {w["title"]: w for w in call("GET", "/api/watch")}
    ws = watches(sop_ids)
    for w in ws:
        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(FLOWS)} 张,预警规则 {len(ws)} 条")