refs.py 12.3 KB
"""引用选项:函数 / 效果参数上的 x-ref 在这里变成「可选的东西」。

前端所有「填一个本体里的名字」的地方(SOP 步骤参数、动作效果、监控策略、MCP 试调用)都不再让人手填,
而是按参数的 x-ref 取这里的选项。选项包含草稿(status=draft),前端会标出来,
「引用了草稿」的地方在试运行时可用、正式运行前要先发布。

x-ref 取值:
  concept / object_type / link_type / action / function / metric / rule / decision / object_set / ai
  dimension:<参数>   —— 同表单里 <参数>(指标)可拆分的维度
  filters:<参数>     —— 同上,用于「只看哪些」
  property:<参数> / values:<参数> —— 同表单里 <参数>(对象类型)的属性
  conditions:<参数> / sort:<参数> —— 同上,用于「筛选条件」「排序」编辑器
  vars:<参数>        —— 同表单里 <参数>(规则 / 决策表 / 函数)需要的输入变量
  role / user / recipient / endpoint / datasource / sop / time
"""
from __future__ import annotations

from typing import Any

from fastapi import HTTPException

from ..kernel import schema
from ..kernel import service as ksvc

_FN_CATS = ("aggregate", "rule", "decision", "object_set", "ai")
# x-ref 的别名 → 函数类别
_CAT_OF = {"metric": "aggregate", "rule": "rule", "decision": "decision", "object_set": "object_set",
           "ai": "ai"}

TIME_OPTIONS = [
    ("current", "本期(本月)"), ("last", "上期(上月)"), ("prev:2", "上上期"),
    ("today", "今天"), ("yesterday", "昨天"), ("this_week", "本周"), ("last_week", "上周"),
    ("days:7", "近 7 天"), ("days:30", "近 30 天"), ("weeks:4", "近 4 周"),
    ("this_quarter", "本季度"), ("last_quarter", "上季度"), ("this_year", "今年"),
]

SYSTEM_ROLES = {"approver": "审批人", "builder": "实施工程师", "operator": "业务操作员", "admin": "管理员"}


# ---------------- 概念查找:已发布优先,其次工作副本 ----------------
def lookup(ref: str, kind: str | None = None, category: str | None = None) -> dict | None:
    """按 id / 名称 / 同义词找概念,取**工作副本**(含未发布的修改):配置时看到的应该是正在编辑的样子
    (刚给指标绑了维度,下拉里马上就该能选),「是否已发布」由 scan_refs 另行判断。"""
    if not ref:
        return None
    w = ksvc.find(ref, kind)
    if w is not None and (not category or (w.get("spec") or {}).get("category") == category):
        return ksvc.get_concept(w["id"])
    return ksvc.rt_find(ref, kind, category)


def resolve_id(ref: str, kind: str | None = None) -> str:
    """名称或 id → 概念 id;找不到原样返回(让调用方按「不存在」处理)。"""
    c = lookup(ref, kind)
    return c["id"] if c else (ref or "")


def same_ref(ref: str, concept: dict | None) -> bool:
    """ref(id 或名称或同义词)是否指这个概念。所有「按对象类型比较」的地方都走这里,
    不再各自比 id 或比名字(业务建模存名字、编辑器存 id,以前两边对不上)。"""
    if not ref or not concept:
        return False
    r = str(ref).strip().lower()
    names = [concept.get("id") or "", concept.get("name") or "", concept.get("display_name") or ""]
    names += list(concept.get("synonyms") or [])
    return any(r == str(x).strip().lower() for x in names if x)


def object_column(target_type: str, columns: list[str]) -> str:
    """动作作用于某类对象时,一行数据里哪一列是那个对象的主键:列名与对象名 / 主键属性名对得上的优先,
    都对不上就取第一列。流程卡配方和监控「按行提议动作」共用。"""
    if not target_type or not columns:
        return ""
    ot = lookup(target_type, "object_type") or {}
    spec = ot.get("spec") or {}
    key = spec.get("key_property") or ""
    cands = [ot.get("name") or "", ot.get("display_name") or "", key]
    cands += [p.get("display_name") or "" for p in spec.get("properties") or [] if p.get("name") == key]
    for c in columns:
        if c in cands or any(x and (x in c or c in x) for x in cands):
            return c
    return columns[0]


# ---------------- 选项 ----------------
def _concept_opt(c: dict, hint: str = "") -> dict:
    published = c.get("status") == "published" or bool(c.get("published"))
    return {"value": c["name"], "label": c.get("display_name") or c["name"], "id": c["id"],
            "status": "published" if published else "draft",
            "group": c.get("kind_label") or schema.kind_label(c["kind"], c.get("spec")),
            "hint": hint or (c.get("description") or "")[:60]}


def _concepts(kind: str, category: str | None = None) -> list[dict]:
    """工作副本里的概念(含草稿,不含已废弃)。已发布但工作副本有改动的也算已发布。"""
    items = ksvc.list_concepts(kind=kind)
    if category:
        items = [c for c in items if c.get("category") == category]
    return items


def _metric_hint(c: dict) -> str:
    full = lookup(c["id"], "function", "aggregate") or {}
    b = ksvc.rt_binding(full, "metric_expr") or {}
    unit = (full.get("spec") or {}).get("unit") or ""
    dims = list((b.get("ref") or {}).get("dimensions") or {})
    if not b:
        return "还没绑定取数表达式,取不了数"
    return ";".join(x for x in [f"单位 {unit}" if unit else "",
                                 f"可按 {'、'.join(dims[:4])} 拆分" if dims else "不可拆分"] if x)


def metric_dimensions(metric_ref: str) -> list[dict]:
    m = lookup(metric_ref, "function", "aggregate")
    if not m:
        return []
    b = ksvc.rt_binding(m, "metric_expr") or {}
    ref = b.get("ref") or {}
    out, seen = [], set()
    for name, col in (ref.get("dimensions") or {}).items():
        seen.add(name)
        out.append({"value": name, "label": name, "hint": f"列 {col}" if col and col != name else ""})
    for name in (m.get("spec") or {}).get("dimensions") or []:
        if name not in seen:
            out.append({"value": name, "label": name, "hint": "(在定义里声明,取数表达式还没绑定这一列)"})
    return out


def object_properties(ot_ref: str, writable_only: bool = False) -> list[dict]:
    ot = lookup(ot_ref, "object_type")
    if not ot:
        return []
    out = []
    for p in (ot.get("spec") or {}).get("properties") or []:
        if writable_only and not p.get("is_writable"):
            continue
        tags = [t for t, on in (("主键", p.get("is_key")), ("时间", p.get("is_time")),
                                ("维度", p.get("is_dimension")), ("可写", p.get("is_writable"))) if on]
        out.append({"value": p["name"], "label": p.get("display_name") or p["name"],
                    "hint": "、".join(tags), "type": p.get("data_type") or "string",
                    "enum": p.get("enum_values") or []})
    return out


def function_inputs(fn_ref: str, category: str | None = None) -> list[dict]:
    """函数的输入(按类型化签名,六类函数同一个样子)。"""
    from ..kernel import signature
    fn = lookup(fn_ref, "function", category)
    if not fn:
        return []
    return [{"value": i["name"], "label": i["label"], "type": i["type"], "required": bool(i.get("required")),
             "options": i.get("options") or [], "object_type": i.get("object_type") or "",
             "hint": i.get("description") or "", "default": i.get("default")}
            for i in signature.signature(fn)["inputs"]]


def options(ref: str, of: str = "") -> list[dict]:
    """ref 见模块说明;of 是依赖参数当前的值(如指标名、对象类型名)。"""
    base, _, _param = (ref or "").partition(":")
    if base in ("dimension", "filters"):
        return metric_dimensions(of)
    if base in ("property", "values", "conditions", "sort"):
        return object_properties(of, writable_only=(base == "property"))
    if base == "vars":
        return function_inputs(of)
    if base == "time":
        return [{"value": v, "label": label} for v, label in TIME_OPTIONS]
    if base == "concept":
        return [_concept_opt(c) for c in _concepts("")]
    if base in ("object_type", "link_type", "action"):
        return [_concept_opt(c) for c in _concepts(base)]
    if base == "function":
        return [_concept_opt(c) for c in _concepts("function")]
    if base in _CAT_OF:
        cat = _CAT_OF[base]
        items = _concepts("function", cat)
        return [_concept_opt(c, _metric_hint(c) if cat == "aggregate" else "") for c in items]
    if base == "role":
        from ..governance import roles
        biz = [{"value": r["name"], "label": r["name"], "group": "业务角色",
                "hint": "、".join(r["members"][:3]) or "还没有人担任"} for r in roles.list_roles()]
        return biz + [{"value": k, "label": v, "group": "系统角色"} for k, v in SYSTEM_ROLES.items()]
    if base in ("user", "recipient"):
        from ..governance import users
        us = [{"value": u["id"], "label": u["name"] or u["id"], "group": "人",
               "hint": "、".join(u["biz_roles"] or u["roles"])} for u in users.list_users() if u["enabled"]]
        if base == "user":
            return us
        return [{**o, "value": f"role:{o['value']}"} for o in options("role")] + us
    if base == "endpoint":
        from . import defs
        return [{"value": e["name"], "label": e.get("display_name") or e["name"],
                 "status": "published" if e["status"] == "published" else "draft",
                 "hint": f"{(e.get('spec') or {}).get('method', 'POST')} {(e.get('spec') or {}).get('url', '')}"[:60]}
                for e in defs.list_defs("endpoint")]
    if base == "datasource":
        from ..text2sql import semantic
        return [{"value": d["id"], "label": d.get("name") or f"数据源 {d['id']}",
                 "hint": d.get("db_type") or d.get("kind") or ""} for d in semantic.list_datasources()]
    if base == "sop":
        from ..sop import service as sop_service
        return [{"value": d["title"], "label": d["title"], "id": d["id"],
                 "status": "published" if d["current_version"] > 0 else "draft",
                 "hint": (d.get("description") or "")[:60]} for d in sop_service.list_defs()]
    raise HTTPException(422, f"不认识的引用类型:{ref}")


# ---------------- 扫描:一组参数引用了哪些本体元素(用于「引用了草稿」提示) ----------------
def _ref_kind(ref: str) -> tuple[str | None, str | None]:
    base = (ref or "").split(":")[0]
    if base in _CAT_OF:
        return "function", _CAT_OF[base]
    if base in ("object_type", "link_type", "action"):
        return base, None
    if base in ("function", "concept"):
        return ("function" if base == "function" else None), None
    return None, None


def scan_refs(schema_: dict, args: dict) -> list[dict]:
    """按 input_schema 的 x-ref 找出 args 引用的概念:[{param, ref, name, id, status}]。
    status=missing 表示名字对不上任何元素,draft 表示还没发布,changed 表示发布过但又改了还没发布
    (如刚给指标绑了取数表达式)—— 这两种试运行都能用,正式运行拿到的还是旧的。$变量 / =表达式 跳过。"""
    out = []
    for k, p in ((schema_ or {}).get("properties") or {}).items():
        ref = p.get("x-ref") or ""
        kind, cat = _ref_kind(ref)
        if kind is None and ref.split(":")[0] != "concept":
            continue
        vals: Any = (args or {}).get(k)
        for v in (vals if isinstance(vals, list) else [vals]):
            if not isinstance(v, str) or not v.strip() or v.startswith(("$", "=")):
                continue
            out += [{"param": k, "ref": ref, **x} for x in [pending(v, kind, cat)] if x]
    return out


def pending(name: str, kind: str | None, category: str | None = None) -> dict | None:
    """这个元素在正式运行时是不是「看不到 / 看到的是旧的」:{name, id, status},都发布了返回 None。"""
    w = ksvc.find(name, kind)
    if w is not None and category and (w.get("spec") or {}).get("category") != category:
        w = None
    if ksvc.rt_find(name, kind, category):
        return {"name": name, "id": w["id"], "status": "changed"} if w and w.get("dirty") else None
    return {"name": name, "id": (w or {}).get("id", ""), "status": "draft" if w else "missing"}