schema.py 18.1 KB
"""元模型:本体只有四种元素 —— 对象、关系、函数、动作。

这里是**唯一**定义「本体是什么」的地方,里面不能出现任何具体行业的词 ——
行业内容全部是数据(模板包 / 抽取提议 / 用户录入)。

- 对象 object_type:可被指认、有属性的业务实体;属性可标「主键 / 时间 / 维度 / 可写」。
- 关系 link_type:两个对象之间的关系,带方向与基数,绑定到 join。
- 函数 function:对对象的计算,按 category 走各自的确定性引擎:
  aggregate 聚合(指标,编译成 SQL)· rule 规则(安全表达式)· calendar 周期(统计窗口)·
  decision 决策表(多维查表 / 分级)· ml 模型推理(调用登记过的模型端点)·
  ai AI 分析(提示 + 只读函数白名单,结果仅供参考,不作为权威结果)。
  原则:大模型只起草、只做参考分析;权威结果一律来自确定性引擎。
- 动作 action:改变业务状态的操作 = 参数 + 前置校验 + 效果(只能调用已注册的系统效果);审批方式按动作上的策略。

角色放在「成员与角色」,流程放在「流程卡(SOP)」,术语就是任意元素上的同义词 —— 都不再是单独的概念。
每个元素可以标一个「域」(spec.domain,如 财务 / 质量 / 订单),只用于分组浏览。
"""
from __future__ import annotations

import re
from typing import Any

KINDS: dict[str, dict[str, str]] = {
    "object_type": {"label": "对象", "desc": "业务里可被指认、有属性的实体,如客户、订单、网点"},
    "link_type": {"label": "关系", "desc": "两个对象之间的关系,带方向与基数"},
    "function": {"label": "函数", "desc": "对对象的计算:聚合指标、规则、周期、决策表、AI 分析"},
    "action": {"label": "动作", "desc": "改变业务状态的操作,只能调用系统效果;审批方式可设成人工、自动或满足条件时自动"},
}

FN_CATEGORIES: dict[str, dict[str, str]] = {
    "aggregate": {"label": "聚合", "desc": "可量化的度量(指标),绑定取数表达式后确定性编译成 SQL",
                  "engine": "SQL 编译器"},
    "rule": {"label": "规则", "desc": "口径、判定或计算,写成可求值表达式", "engine": "安全 AST 求值"},
    "calendar": {"label": "周期", "desc": "统计窗口,如自然月、自定义起止日的业务月", "engine": "周期解析"},
    "decision": {"label": "决策表", "desc": "多条件查表 / 分级,一行一条规则", "engine": "决策表引擎"},
    "ml": {"label": "模型推理", "desc": "调用登记过的机器学习模型端点,按输入输出定义取预测值",
           "engine": "模型端点"},
    "ai": {"label": "AI 分析(参考)", "desc": "提示词 + 允许使用的只读函数,产出结构化结论;结果仅供参考",
           "engine": "大模型(只读)"},
}

# 旧写法(模板、AI 提议、导入)里的类别 → 新的四元组
LEGACY_FN = {"metric": "aggregate", "rule": "rule", "calendar": "calendar", "skill": "ai",
             "decision": "decision", "ml": "ml"}

DATA_TYPES = ("string", "number", "integer", "boolean", "date", "datetime", "enum", "text")
RULE_KINDS = ("judgement", "calibre", "calculation")
DIRECTIONS = ("higher_better", "lower_better", "neutral")
CARDINALITY = ("1:1", "1:n", "n:1", "n:n")
# 属性怎么显示:金额 / 数量 / 百分比 / 状态(带颜色的标签);空 = 按数据类型的默认样子
FORMATS = ("", "money", "quantity", "percent", "status")
TONES = ("ok", "warn", "danger", "info", "neutral")

_IDENT = re.compile(r"^[A-Za-z_一-鿿][\w一-鿿$]*$")


class SpecError(ValueError):
    pass


def _str(v: Any, default: str = "") -> str:
    return str(v).strip() if v is not None else default


def _list_str(v: Any) -> list[str]:
    if isinstance(v, str):
        v = re.split(r"[,,、;\n]", v)
    return [str(x).strip() for x in (v or []) if str(x).strip()]


def kind_label(kind: str, spec: dict | None = None) -> str:
    if kind == "function":
        cat = (spec or {}).get("category") or ""
        if cat in FN_CATEGORIES:
            return f"函数·{FN_CATEGORIES[cat]['label']}"
    return KINDS.get(kind, {}).get("label", kind)


def type_key(c: dict) -> str:
    """细分类型:函数取 category(aggregate/rule/...),其余就是 kind。给链接、目录、画布分组用。"""
    if c.get("kind") == "function":
        return (c.get("spec") or {}).get("category") or "rule"
    return c.get("kind") or ""


def upgrade(kind: str, spec: dict | None) -> tuple[str, dict] | None:
    """把旧类别(metric/rule/calendar/skill)翻译成四元组;不再是概念的(角色/流程/术语/维度)返回 None。"""
    spec = dict(spec or {})
    if kind in KINDS:
        return kind, spec
    if kind in LEGACY_FN:
        spec.setdefault("category", LEGACY_FN[kind])
        return "function", spec
    return None


def normalize_spec(kind: str, spec: dict | None) -> dict:
    """按 kind 规整 spec,缺的补默认值,错的抛 SpecError。"""
    if kind not in KINDS:
        raise SpecError(f"未知的元素类别:{kind}(只有 对象/关系/函数/动作)")
    spec = dict(spec or {})
    ui = spec.get("ui") if isinstance(spec.get("ui"), dict) else None
    out = _NORMALIZERS[kind](spec)
    domain = _str(spec.get("domain"))[:32]
    if domain:
        out["domain"] = domain
    pos = (ui or {}).get("pos")
    if isinstance(pos, dict):                 # 画布位置:纯展示信息,原样保留
        try:
            out["ui"] = {"pos": {"x": float(pos.get("x") or 0), "y": float(pos.get("y") or 0)}}
        except (TypeError, ValueError):
            pass
    return out


def _object_type(spec: dict) -> dict:
    props = []
    seen = set()
    for p in spec.get("properties") or []:
        if not isinstance(p, dict):
            continue
        name = _str(p.get("name"))
        if not name:
            continue
        if name in seen:
            raise SpecError(f"属性重名:{name}")
        seen.add(name)
        dt = _str(p.get("data_type"), "string") or "string"
        if dt not in DATA_TYPES:
            dt = "string"
        fmt = _str(p.get("format"))
        expr = _str(p.get("expression"))
        if expr:
            from . import rules
            try:
                rules.parse(expr)
            except rules.RuleError as e:
                raise SpecError(f"属性「{name}」的计算公式有误:{e}") from e
        tones = {str(k): str(v) for k, v in (p.get("tones") or {}).items()
                 if str(v) in TONES} if isinstance(p.get("tones"), dict) else {}
        item = {"name": name, "display_name": _str(p.get("display_name")),
                "data_type": dt, "description": _str(p.get("description")),
                "is_key": bool(p.get("is_key")), "is_time": bool(p.get("is_time")),
                "is_dimension": bool(p.get("is_dimension")),
                # 算出来的属性没有对应的列,不能被动作改
                "is_writable": bool(p.get("is_writable")) and not expr,
                "enum_values": _list_str(p.get("enum_values")),
                "format": fmt if fmt in FORMATS else "", "unit": _str(p.get("unit"))[:16],
                "expression": expr, "tones": tones}
        # 别名:是 / 否属性代表的那一类记录的叫法(「逾期订单」= is_overdue 为是的订单),问数时认得
        syn = _list_str(p.get("synonyms"))[:12]
        if syn:
            item["synonyms"] = syn
        # 常见取值:文档里提到的具体取值(某个客户名、某个品类),问数时用来写筛选条件,不是别名
        hints = _list_str(p.get("value_hints"))[:30]
        if hints:
            item["value_hints"] = hints
        # 本体自有属性:业务表里没有这一列,值由本系统保存(动作写、读的时候叠上去)
        if _str(p.get("storage")) == "ontology" and not expr:
            item["storage"] = "ontology"
        props.append(item)
    keys = [p["name"] for p in props if p["is_key"]]
    if len(keys) > 1:
        raise SpecError("对象只能有一个主键属性")
    label = _str(spec.get("label_property"))
    if label and props and label not in seen:
        raise SpecError(f"显示属性 {label} 不在属性列表中")
    return {"properties": props, "key_property": keys[0] if keys else "",
            "label_property": label, "title_template": _str(spec.get("title_template"))[:200]}


_CARD_ALIAS = {"many_to_one": "n:1", "one_to_many": "1:n", "one_to_one": "1:1", "many_to_many": "n:n",
               "m:1": "n:1", "1:m": "1:n", "m:n": "n:n", "n:m": "n:n"}


def _link_type(spec: dict) -> dict:
    card = (_str(spec.get("cardinality"), "n:1") or "n:1").lower().replace(":", ":")
    card = _CARD_ALIAS.get(card, card)
    if card not in CARDINALITY:
        raise SpecError(f"基数只能是 {'/'.join(CARDINALITY)}")
    return {"from_type": _str(spec.get("from_type")), "to_type": _str(spec.get("to_type")),
            "cardinality": card, "inverse_name": _str(spec.get("inverse_name"))}


# ---------------- 函数 ----------------
def _fn_aggregate(spec: dict) -> dict:
    direction = _str(spec.get("direction"), "neutral") or "neutral"
    if direction not in DIRECTIONS:
        direction = "neutral"
    fmt = _str(spec.get("format"))
    from .signature import norm_inputs
    compare = _str(spec.get("compare"))
    return {"unit": _str(spec.get("unit")), "direction": direction,
            "format": fmt if fmt in FORMATS else "",
            "calibre_rule": _str(spec.get("calibre_rule")), "calendar": _str(spec.get("calendar")),
            "dimensions": _list_str(spec.get("dimensions")),
            "formula_text": _str(spec.get("formula_text")),
            # 参数化筛选:每个输入绑定到一个维度,调用时给值就按它过滤(如 某维度 = 输入的值)
            "inputs": [i for i in norm_inputs(spec.get("inputs"), "string") if i.get("dimension")],
            "compare": compare if compare in ("mom", "yoy") else ""}


def _fn_rule(spec: dict) -> dict:
    from . import rules
    kind = _str(spec.get("rule_kind"), "judgement") or "judgement"
    if kind not in RULE_KINDS:
        kind = "judgement"
    expr = _str(spec.get("expression"))
    params = _list_str(spec.get("params"))
    if expr:
        try:
            names = rules.free_names(expr)
        except rules.RuleError as e:
            raise SpecError(f"规则表达式不合法:{e}") from e
        # 表达式里用到但没声明的变量自动补进参数表,免得录入时来回改
        for n in names:
            if n not in params:
                params.append(n)
    from .signature import norm_inputs
    typed = {i["name"]: i for i in norm_inputs(spec.get("inputs"), "any")}
    inputs = [typed.get(n) or {"name": n, "label": n, "type": "any", "required": True, "description": ""} for n in params]
    out_type = _str(spec.get("output_type"))
    return {"rule_kind": kind, "expression": expr, "params": params, "inputs": inputs,
            "output_type": out_type if out_type in ("boolean", "number", "string", "date", "any") else "",
            "message": _str(spec.get("message")),
            "text": _str(spec.get("text")), "examples": list(spec.get("examples") or [])}


def _fn_calendar(spec: dict) -> dict:
    def _day(v: Any, default: Any) -> Any:
        if v in (None, ""):
            return default
        if str(v).lower() == "last":
            return "last"
        try:
            d = int(v)
        except (TypeError, ValueError) as e:
            raise SpecError(f"日期必须是 1~31 或 last:{v}") from e
        if not 1 <= d <= 31:
            raise SpecError(f"日期必须是 1~31 或 last:{v}")
        return d

    def _off(v: Any) -> int:
        try:
            return int(v or 0)
        except (TypeError, ValueError):
            return 0
    grain = _str(spec.get("grain"), "month") or "month"
    return {"grain": grain if grain in ("day", "week", "month", "quarter", "year") else "month",
            "week_start": max(1, min(7, _off(spec.get("week_start")) or 1)),
            "start_month": max(1, min(12, _off(spec.get("start_month")) or 1)),
            "start_day": _day(spec.get("start_day"), 1),
            "start_month_offset": _off(spec.get("start_month_offset")),
            "end_day": _day(spec.get("end_day"), "last"),
            "end_month_offset": _off(spec.get("end_month_offset")),
            "applies_when": _str(spec.get("applies_when")),
            "text": _str(spec.get("text"))}


def _fn_decision(spec: dict) -> dict:
    from . import decision
    try:
        return decision.normalize(spec)
    except decision.DecisionError as e:
        raise SpecError(str(e)) from e


def _fn_ai(spec: dict) -> dict:
    from fastapi import HTTPException

    from ..capability import defs
    try:
        return defs.validate_skill(spec)
    except HTTPException as e:
        raise SpecError(str(e.detail)) from e


def _fn_ml(spec: dict) -> dict:
    def fields(v: Any, what: str) -> list[dict]:
        out = []
        for x in v or []:
            if isinstance(x, str):
                x = {"name": x}
            if not isinstance(x, dict) or not _str(x.get("name")):
                continue
            item = {"name": check_ident(x["name"], what), "label": _str(x.get("label")),
                    "type": _str(x.get("type"), "number") or "number"}
            if _str(x.get("path")):
                item["path"] = _str(x.get("path"))
            out.append(item)
        return out
    try:
        timeout = max(1.0, min(float(spec.get("timeout") or 15), 120.0))
    except (TypeError, ValueError):
        timeout = 15.0
    return {"endpoint": _str(spec.get("endpoint")), "inputs": fields(spec.get("inputs"), "输入名"),
            "outputs": fields(spec.get("outputs"), "输出名"),
            "request_path": _str(spec.get("request_path"), "inputs") if spec.get("request_path") is not None else "inputs",
            "result_path": _str(spec.get("result_path")), "timeout": timeout, "text": _str(spec.get("text"))}


_FN = {"aggregate": _fn_aggregate, "rule": _fn_rule, "calendar": _fn_calendar,
       "decision": _fn_decision, "ml": _fn_ml, "ai": _fn_ai}


def _function(spec: dict) -> dict:
    cat = _str(spec.get("category"), "rule") or "rule"
    cat = LEGACY_FN.get(cat, cat)
    if cat not in FN_CATEGORIES:
        raise SpecError(f"函数类别只能是 {'/'.join(FN_CATEGORIES)}")
    return {"category": cat, "object_type": _str(spec.get("object_type")), **_FN[cat](spec),
            "tests": _tests(spec.get("tests"))}


def _tests(v: Any) -> list[dict]:
    """函数的测试用例:给定输入,期望输出里某些字段等于某个值(expect 的键是输出里的路径,如 result / result.level)。"""
    out = []
    for i, t in enumerate(v or [], 1):
        if not isinstance(t, dict):
            continue
        expect = t.get("expect") if isinstance(t.get("expect"), dict) else {}
        out.append({"name": _str(t.get("name")) or f"用例 {i}", "inputs": dict(t.get("inputs") or {}),
                    "expect": {str(k): x for k, x in expect.items() if str(k).strip()}})
    return out[:50]


def _action(spec: dict) -> dict:
    from fastapi import HTTPException

    from ..capability import defs
    try:
        norm, risk = defs.validate_action(spec)
    except HTTPException as e:
        raise SpecError(str(e.detail)) from e
    return {**norm, "risk_level": risk}


_NORMALIZERS = {"object_type": _object_type, "link_type": _link_type, "function": _function,
                "action": _action}


# ---------------- 绑定 ----------------
BINDING_KINDS = {
    "object_type": "table",
    "function": "metric_expr",      # 只有聚合函数需要绑定取数表达式
    "link_type": "join",
}


def check_ident(name: str, what: str) -> str:
    name = _str(name)
    parts = name.split(".")
    if not name or any(not _IDENT.match(p) for p in parts):
        raise SpecError(f"{what}「{name}」不是合法的标识符")
    return name


def normalize_binding(kind: str, ref: dict) -> dict:
    ref = dict(ref or {})
    if kind == "table":
        cols = {str(k): check_ident(v, "列名") for k, v in (ref.get("columns") or {}).items() if v}
        return {"table": check_ident(ref.get("table", ""), "表名"),
                "key_column": check_ident(ref.get("key_column", ""), "主键列"),
                "label_column": (check_ident(ref["label_column"], "显示列")
                                 if ref.get("label_column") else ""),
                "columns": cols}
    if kind == "metric_expr":
        dims = {str(k): check_ident(v, "维度列") for k, v in (ref.get("dimensions") or {}).items() if v}
        expr = _str(ref.get("expression"))
        if not expr:
            raise SpecError("指标表达式不能为空")
        if ";" in expr:
            raise SpecError("指标表达式不能包含分号")
        base_object = _str(ref.get("base_object"))
        if not base_object and not _str(ref.get("base_table")):
            raise SpecError("指标要选统计哪个对象(或哪张表)")
        return {"base_table": check_ident(ref.get("base_table", ""), "基表") if _str(ref.get("base_table")) else "",
                "base_object": base_object,
                "expression": expr,
                "time_column": (check_ident(ref["time_column"], "时间列")
                                if ref.get("time_column") else ""),
                "object_key_column": (check_ident(ref["object_key_column"], "对象键列")
                                      if ref.get("object_key_column") else ""),
                "filters": [f for f in _list_str(ref.get("filters")) if ";" not in f],
                "dimensions": dims,
                # 维度 → 对象类型(id 或名称):声明后取数时自动带出对象名称,提问也知道「按仓库」指的是哪个对象
                "dimension_types": {str(k): _str(v) for k, v in (ref.get("dimension_types") or {}).items()
                                    if v and str(k) in dims}}
    if kind == "join":
        return {"from_column": check_ident(ref.get("from_column", ""), "关联列"),
                "to_column": check_ident(ref.get("to_column", ""), "关联列")}
    raise SpecError(f"未知的绑定类型:{kind}")