types.py 13.3 KB
"""流程卡里的数据类型:每一步产出什么(输出结构),后面的步骤能引用哪些字段。

结构的写法(和 kernel/signature.py 同一套):
    {type: object, label, fields: [{name, label, type, ...(字段本身也是一个结构)}]}
    {type: array, label, items: 结构}
    {type: string|number|integer|boolean|date|any, label}

编辑器按它画「插入数据」的级联菜单(只列上游步骤,字段带类型);校验按它检查 `$变量.字段` 写得对不对。
结构推不出来的(如任意系统函数)给 any,校验时不深究。
"""
from __future__ import annotations

from typing import Any

from ..kernel.signature import arr, field, obj

_NUM = ("number", "integer", "decimal", "float")


def _ptype(dt: str) -> str:
    dt = (dt or "string").lower()
    if dt in _NUM:
        return "number"
    if dt in ("date", "datetime"):
        return "date"
    if dt == "boolean":
        return "boolean"
    return "string"


def object_fields(ot_ref: str, only: list[str] | None = None) -> list[dict]:
    """一类对象的扁平字段:key、label、各属性。"""
    from ..kernel import service as ksvc
    ot = ksvc.rt_find(ot_ref, "object_type") if ot_ref else None
    if ot is None:
        return [field("key", "主键", "string"), field("label", "名称", "string")]
    out = [field("key", "主键", "string"), field("label", "名称", "string")]
    for p in (ot.get("spec") or {}).get("properties") or []:
        if only and p["name"] not in only:
            continue
        out.append(field(p["name"], p.get("display_name") or p["name"], _ptype(p.get("data_type")),
                         **({"options": p["enum_values"]} if p.get("enum_values") else {})))
    return out


def _include_fields(ot_ref: str, include: list[dict] | None, depth: int = 1) -> list[dict]:
    from ..kernel import objects
    from ..kernel import service as ksvc
    ot = ksvc.rt_find(ot_ref, "object_type") if ot_ref else None
    out: list[dict] = []
    if ot is None:
        return out
    for inc in include or []:
        try:
            side = objects._find_side(ot, str(inc.get("link") or ""))
        except Exception:  # noqa: BLE001
            continue
        name = str(inc.get("as") or side["label"])
        other = side["other"]["name"]
        row = obj(object_fields(other, [str(f) for f in inc.get("fields") or []] or None)
                  + (_include_fields(other, inc.get("include"), depth + 1) if depth < 3 else []), other)
        many = str(inc.get("mode") or ("one" if side["single"] else "list")) == "list"
        out.append({**(arr(row, f"{name}(多条)") if many else row), "name": name,
                    "label": name, "object_type": other})
        for a in inc.get("aggs") or []:
            fn = str(a.get("fn") or "count")
            label = str(a.get("as") or f"{name}{objects.AGG_FNS.get(fn, fn)}")
            out.append(field(label, label, "number"))
    return out


def query_schema(step: dict) -> dict:
    ot = str(step.get("object_type") or "")
    row_fields = object_fields(ot, [str(f) for f in step.get("fields") or []] or None) + \
        _include_fields(ot, step.get("include"))
    if step.get("mode") == "one":
        return obj(row_fields + [field("found", "找到了吗", "boolean")], ot)
    return obj([{**arr(obj(row_fields, ot), "每一个"), "name": "items", "label": f"每一个{ot}"},
                field("total", "满足条件的总数", "number")], ot)


def param_schema(p: dict) -> dict:
    t = p.get("type") or "string"
    if t == "object" and p.get("object_type"):
        return obj(object_fields(p["object_type"]), p.get("label") or "")
    if t == "period":
        return obj([field("start", "开始日期", "date"), field("end", "结束日期", "date"),
                    field("period", "期号", "string")], p.get("label") or "")
    if t == "list":
        return arr(obj([field(c["name"], c.get("label") or c["name"], c.get("type") or "string")
                        for c in p.get("columns") or []]), p.get("label") or "")
    return {"type": {"number": "number", "boolean": "boolean", "date": "date"}.get(t, "string"),
            "label": p.get("label") or ""}


def _metric_schema(metric: str, dims: list[str]) -> dict:
    from ..kernel import metrics
    from ..kernel import service as ksvc
    m = ksvc.rt_find(metric, "function", "aggregate") if metric else None
    ref = (ksvc.rt_binding(m, "metric_expr") or {}).get("ref") or {} if m else {}
    cols = []
    for d in dims:
        cols.append(field(d, d, "string"))
        if metrics.dim_object_type(ref, d):          # 维度是一类对象:结果里还有一列它的名称
            cols.append(field(f"{d}名称", f"{d}名称", "string"))
    row = obj(cols + [field("value", "数值", "number")])
    return obj([field("value", "数值(没拆分时)", "number"),
                {**arr(row), "name": "items", "label": "拆分后的每一行"},
                field("period", "统计时间", "string")], metric)


def function_schema(name: str, args: dict) -> dict:
    """系统函数的输出结构。"""
    from ..kernel import service as ksvc
    from ..kernel import signature
    args = args or {}
    if name == "metric.query":
        return _metric_schema(str(args.get("metric") or ""), [str(d) for d in args.get("dimensions") or []])
    if name in ("object.query", "object.search"):
        ot = str(args.get("object_type") or "")
        return obj([{**arr(obj(object_fields(ot), ot)), "name": "items", "label": f"每一个{ot}"},
                    field("total", "总数", "number")])
    if name == "object.get":
        return obj(object_fields(str(args.get("object_type") or "")))
    if name == "object.fetch":
        return query_schema(args)
    if name in ("function.eval", "rule.eval", "decision.eval"):
        ref = str(args.get("name") or args.get("rule") or args.get("table") or "")
        fn = ksvc.rt_find(ref, "function") if ref else None
        if fn:
            return signature.signature(fn)["outputs"]
    if name == "object_set.query":
        from ..kernel import objectset
        try:
            fn = objectset.resolve(str(args.get("set") or ""))
        except Exception:  # noqa: BLE001
            fn = None
        if fn:
            return signature.signature(fn)["outputs"]
    if name == "data.ask":
        return obj([field("value", "数值", "number"), {**arr(obj([])), "name": "items", "label": "每一行"},
                    field("summary", "说明", "string")])
    return {"type": "any", "label": name}


def _ai_schema(step: dict) -> dict:
    outs = step.get("outputs") or []
    fields = [field(o["name"], o.get("label") or o["name"], o.get("type") or "string",
                    **({"options": o["options"]} if o.get("options") else {})) for o in outs] or \
        [field("conclusion", "结论", "string"), field("points", "要点", "list")]
    return obj(fields + [field("confidence", "把握程度(0~1)", "number"),
                         field("ai_judged", "由 AI 判断", "boolean")], "AI 结论(参考)")


def step_schema(step: dict, spec: dict | None = None) -> dict | None:
    """这一步产出的数据结构;不产出数据的步骤返回 None。"""
    t = step.get("type")
    if t == "query":
        return query_schema(step)
    if t == "function":
        return function_schema(step.get("function") or "", step.get("args") or {})
    if t == "compute":
        return obj([field(a["name"], a.get("label") or a["name"], a.get("type") or "any")
                    for a in step.get("assign") or [] if a.get("name")])
    if t == "skill":
        return _ai_schema(step)
    if t == "human_task":
        return obj([field(f["name"], f.get("label") or f["name"],
                          {"choice": "string", "text": "string"}.get(f.get("type"), f.get("type") or "string"))
                    for f in step.get("form") or []])
    if t == "action":
        return obj([field("status", "结果(done / rejected)", "string"), field("action_run_id", "动作记录", "string")])
    if t == "write":
        keys = [field(op["as"], op["as"], "list" if op.get("op") == "create_rows" else "string")
                for op in step.get("ops") or [] if op.get("as")]
        return obj([field("status", "结果(done / rejected)", "string"), field("action_run_id", "动作记录", "string"),
                    {**obj(keys), "name": "keys", "label": "新建 / 修改的主键"}])
    if t == "foreach":
        collect = step.get("collect") or ""
        item: dict = {"type": "any"}
        if collect:
            for b in (step.get("body") or {}).get("steps") or []:
                if (b.get("output") or "") == collect:
                    item = step_schema(b, spec) or {"type": "any"}
        return obj([field("total", "处理了几条", "number"), field("ok", "完成几条", "number"),
                    field("failed", "失败几条", "number"), field("rejected", "被驳回几条", "number"),
                    {**arr(item), "name": "results", "label": "每一条的结果"}])
    if t == "subprocess":
        return _subflow_schema(step.get("sop") or "")
    return None


def _subflow_schema(sop_id: str) -> dict:
    """子流程的输出:它「结束」节点定义的输出。直接读定义(不走 service.get —— 那会校验子流程,
    子流程又推它的子流程……两张卡互相调用时就绕不出来了)。"""
    from ..core.dbx import jload, session
    from .models import SopDefinition
    with session() as s:
        d = s.get(SopDefinition, sop_id) if sop_id else None
        if d is None:
            return {"type": "any"}
        sub = {"title": d.title, "spec": jload(d.draft_spec_json, {}) or {}}
    fields = []
    for st in (sub.get("spec") or {}).get("steps") or []:
        if st.get("type") == "end":
            fields += [field(o["name"], o.get("label") or o["name"], o.get("type") or "any")
                       for o in st.get("outputs") or [] if o.get("name")]
    return obj(list({f["name"]: f for f in fields}.values()), sub["title"])


def item_schema(src: dict | None) -> dict:
    """逐条处理的「当前这一条」:数据来源是数组就取元素结构;是 {items: [...]} 就取 items 的元素。"""
    if not src:
        return {"type": "any"}
    if src.get("type") == "array":
        return src.get("items") or {"type": "any"}
    for f in src.get("fields") or []:
        if f["name"] in ("items", "rows", "results") and f.get("type") == "array":
            return f.get("items") or {"type": "any"}
    return {"type": "any"}


def resolve(schema: dict | None, parts: list[Any]) -> dict | None:
    """沿路径走进结构:找不到返回 None;碰到 any 一律放行(返回 any)。"""
    cur = schema
    for p in parts:
        if cur is None:
            return None
        t = cur.get("type")
        if t == "any":
            return cur
        if isinstance(p, int):
            if t != "array":
                return None
            cur = cur.get("items") or {"type": "any"}
            continue
        if t == "array":
            # 列表上直接取字段:如 $q.items.数量 —— 取每个元素的这个字段,结果是列表
            inner = resolve(cur.get("items"), [p])
            return arr(inner) if inner else None
        if t != "object":
            return None
        nxt = next((f for f in cur.get("fields") or [] if f["name"] == p), None)
        if nxt is None:
            # 对象结构推不全(没有字段定义)时放行
            return {"type": "any"} if not cur.get("fields") else None
        cur = nxt
    return cur


def outputs(spec: dict) -> list[dict]:
    """能被引用的数据:[{id, var, title, kind, scope, schema}]。
    参数在前(id = param:<名>);循环体里多一项「当前这一条」(var = item)与「第几条」(var = index)。
    scope:所在循环的步骤 id(顶层为空)—— 循环体里的结果只在同一个循环体里可见。"""
    out: list[dict] = []
    for p in spec.get("params") or []:
        out.append({"id": f"param:{p['name']}", "var": p["name"], "title": p.get("label") or p["name"],
                    "kind": "param", "scope": "", "schema": param_schema(p)})

    def walk(steps: list[dict], scope: str) -> None:
        for st in steps:
            sch = step_schema(st, spec)
            if sch is not None and st.get("output"):
                out.append({"id": st["id"], "var": st["output"], "title": st.get("title") or st["id"],
                            "kind": st["type"], "scope": scope, "schema": sch})
            if st.get("type") == "foreach":
                head = str(st.get("items") or "").lstrip("$")
                from ..capability.actions import path_parts
                parts = path_parts(head) if head else []
                src = next((o for o in out if parts and o["var"] == parts[0]), None)
                src_schema = resolve(src["schema"], parts[1:]) if src else None
                out.append({"id": f"{st['id']}:item", "var": "item", "title": "这一条", "kind": "item",
                            "scope": st["id"], "schema": item_schema(src_schema)})
                out.append({"id": f"{st['id']}:index", "var": "index", "title": "第几条", "kind": "item",
                            "scope": st["id"], "schema": {"type": "number", "label": "第几条"}})
                walk((st.get("body") or {}).get("steps") or [], st["id"])
    walk(spec.get("steps") or [], "")
    return out