build_dm2_behavior.py 29.9 KB
"""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("缺件单", "$obj_key", "status", "处理中", 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", "占用主机厂库存")],
         "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="登记预计到件"),
            _write("缺件单", "$obj_key", "status", "处理中", label="缺件单转处理中")],
        "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"),
             _write("缺件单", "$short.key", "status", "已解决", label="关闭缺件单", when="short.key != None"),
             _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": "调整库存管控线", "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 _cond(left: str, op: str, right) -> dict:
    return {"mode": "all", "items": [{"left": left, "op": op, "right": right}]}


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

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

    {"title": "区域囤货巡检", "owner_role": "配件计划员",
     "description": "查出区域内处于囤货预警的「门店 × 配件」,逐条交给区域配件经理决定怎么处理。",
     "tree": {
         "params": [],
         "steps": [
             {"id": "hoard", "kind": "objects", "title": "查囤货预警", "object_type": "门店库存",
              "filters": [_w("hoarding", 1)], "sort": [{"property": "region_share", "dir": "desc"}], "limit": 50},
             {"id": "each", "kind": "foreach", "title": "逐条处理", "items": "$hoard.items", "limit": 20,
              "steps": [{"id": "decide", "kind": "task", "title": "决定怎么处理",
                         "assignee": {"kind": "role", "value": "区域配件经理"},
                         "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}],
                         "due_hours": 24}]},
             {"id": "pending", "kind": "objects", "title": "查待审核的订单", "object_type": "配件订单",
              "filters": [_w("status", "主机厂审核中")], "limit": 50},
             {"id": "report", "kind": "notify", "title": "告诉计划员", "to": {"kind": "role", "value": "配件计划员"},
              "subject": "区域囤货巡检完成",
              "body": "囤货预警 $hoard.total 条;待审核的订单 $pending.total 张。"},
             {"id": "done", "kind": "end", "title": "结束", "outcome": "巡检完成"}]}},
]

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


def _c(field: str, op: str, value) -> dict:
    return {"mode": "all", "items": [{"left": f"$item.{field}", "op": op, "right": value}]}
WATCHES = [
    {"title": "囤货预警", "description": "单店占区域在库超过一半,且超储", "owner_role": "配件计划员",
     "source": {"kind": "object", "object_type": "门店库存", "cond": _c("hoarding", "eq", True)},
     "condition": "hoarding == 1", "schedule": DAILY,
     "strategies": [{"kind": "notify", "role": "区域配件经理", "subject": "囤货预警:$label",
                     "body": "在库 $on_hand,可用 $months 个月,库存上限 $max_stock。"}]},
    {"title": "缺件单超过 48 小时没处理", "description": "", "owner_role": "配件主管",
     "source": {"kind": "object", "object_type": "缺件单", "cond": {"mode": "all", "items": [
         {"left": "$item.status", "op": "eq", "right": "待处理"}, {"left": "$item.wait_days", "op": "ge", "right": 2}]}},
     "condition": "status == '待处理' and wait_days >= 2",
     "schedule": DAILY,
     "strategies": [{"kind": "task", "role": "店总", "title": "缺件单 $label 超过 48 小时没处理",
                     "instructions": "已经等了 $wait_days 天。请安排处理,并确认是否已通知客户。"}]},
    {"title": "待料工单超过承诺交车日", "description": "", "owner_role": "配件主管",
     "source": {"kind": "object", "object_type": "维修工单", "cond": _c("overdue_days", "gt", 0)},
     "condition": "overdue_days > 0", "schedule": DAILY,
     "strategies": [{"kind": "notify", "role": "店总", "subject": "工单 $label 已超期 $overdue_days 天",
                     "body": "承诺交车日 $promised_date,现在还在等件。"}]},
    {"title": "订单超期未到", "description": "", "owner_role": "配件主管",
     "source": {"kind": "object", "object_type": "配件订单", "cond": _c("overdue", "eq", True)},
     "condition": "overdue == 1", "schedule": DAILY,
     "strategies": [{"kind": "notify", "role": "配件主管", "subject": "订单 $label 超期未到",
                     "body": "预计到货 $expected_date,请联系主机厂。"}]},
]


def build_flows(call, ids, OBJECTS) -> None:
    by_table = {t: OBJECTS[t][0] for t in ids}
    name2id = {by_table[t]: i for t, i in ids.items()}
    have = {d["title"]: d for d in call("GET", "/api/sop/defs")}
    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"], "tree": f["tree"],
                                                      "etag": d.get("draft_hash") or ""})
        errs = (d.get("validation") or {}).get("errors") or []
        if errs or d.get("tree_error"):
            print(f"  流程卡「{f['title']}」有问题:", d.get("tree_error") or errs[:4])
            continue
        r = call("POST", f"/api/sop/defs/{d['id']}/publish", {"note": "场景脚本"}, ok=(200, 201, 409, 422))
        print(f"  流程卡「{f['title']}」:", str(r.get("detail") or f"已发布 v{r.get('current_version')}")[:120])
    havew = {w["title"]: w for w in call("GET", "/api/watch")}
    for w in WATCHES:
        body = {**w, "enabled": True, "dedup": {"key": "$key", "cooldown_hours": 24},
                "source": {**w["source"], "object_type": name2id[w["source"]["object_type"]]}}
        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(WATCHES)} 个")