traverse.py 10 KB
"""关系遍历与实例级影响分析:顺着关系网从一个对象往外推。

「这台机台出了问题 → 哪些批次受影响 → 连累哪些订单 → 交期会不会破」——
过去要跨好几个系统人肉查,这里在数据管道同步好的关系边(otlg_link_edge)上做 BFS。
最后一层的对象再回业务库实时取一次最新属性,保证结论用的是现在的数据。
"""
from __future__ import annotations

from collections import deque

from fastapi import HTTPException
from sqlalchemy import func, or_, select

from ..core import identity
from ..core.dbx import iso, jload, session
from . import objects, service
from .models import LinkEdge, ObjectIndex

MAX_DEPTH = 4


def _names() -> tuple[dict[str, str], dict[str, str]]:
    from . import sysobjects
    types = {c["id"]: c["name"] for c in service.rt_by_kind("object_type")}
    links = {c["id"]: c["name"] for c in service.rt_by_kind("link_type")}
    links.update({lid: x["name"] for lid, x in sysobjects.LINKS.items()})
    return types, links


def _sys_types() -> set[str]:
    from . import sysobjects
    return set(sysobjects.BY_ID)


def _parent_side() -> dict[str, str]:
    """每条关系哪一端是「上级」:关联列正好是那一端的主键(被外键指向的一方)。返回 {link_id: from/to}。
    关系的方向是业务起的名字(供应商「供货」商品),不代表外键方向,所以不能按 from/to 判断。"""
    out: dict[str, str] = {}
    for lt in service.rt_by_kind("link_type"):
        jb = service.rt_binding(lt, "join")
        spec = lt.get("spec") or {}
        if not jb:
            continue
        for side in ("from", "to"):
            ot = service.rt_get(spec.get(f"{side}_type") or "") or {}
            tb = service.rt_binding(ot, "table") if ot else None
            if tb and jb["ref"].get(f"{side}_column") == tb["ref"].get("key_column"):
                out[lt["id"]] = side
                break
    return out


def _allowed(actor: identity.Actor, type_id: str, props: dict) -> bool:
    """数据范围:设了范围的对象类型,骨架里对应属性不在允许值里(或没同步到)就不给看。"""
    scope = (actor.scope or {}).get(type_id) or {}
    for prop, vals in scope.items():
        if vals and str(props.get(prop)) not in {str(v) for v in vals}:
            return False
    return True


def _cache(ws: str, keys: dict[str, set[str]]) -> dict[tuple[str, str], tuple[str, dict, object]]:
    out = {}
    with session() as s:
        for t, ks in keys.items():
            for r in s.scalars(select(ObjectIndex).where(
                    ObjectIndex.workspace == ws, ObjectIndex.concept_id == t,
                    ObjectIndex.obj_key.in_(list(ks)))).all():
                out[(t, r.obj_key)] = (r.label, (jload(r.props_json, {}) or {}).get("p") or {}, r.synced_at)
    return out


def traverse(type_ref: str, key: str, *, depth: int = 3, links: list[str] | None = None,
             limit: int = 300, hub_stop: bool = False) -> dict:
    """hub_stop:沿外键「往上」走到的上级对象(库存 → 仓库)只记录、不再往外扩。
    影响分析要这样:供应商出问题波及它的商品、商品的库存,但不会绕道仓库把全仓库存都算进来。"""
    ot = objects.object_type(type_ref)
    actor = identity.current()
    ws = actor.workspace
    depth = max(1, min(int(depth or 3), MAX_DEPTH))
    types, link_names = _names()
    link_ids = None
    if links:
        link_ids = {lid for lid, n in link_names.items() if lid in links or n in links}
    parent = _parent_side() if hub_stop else {}
    root = (ot["id"], str(key))
    root_cache = _cache(ws, {root[0]: {root[1]}})
    if root not in root_cache and root[0] in _sys_types():
        root_cache[root] = (objects.labels(root[0], [root[1]]).get(root[1], root[1]), {}, None)
    if root not in root_cache:
        raise HTTPException(422, f"{ot['name']}「{key}」不在已同步的骨架里:请先在「数据管道」里同步这个对象类型")
    seen: dict[tuple[str, str], dict] = {root: {"depth": 0, "via": None}}
    edges_out: list[dict] = []
    frontier = [root]
    truncated = False
    with session() as s:
        for d in range(1, depth + 1):
            if not frontier:
                break
            by_type: dict[str, list[str]] = {}
            for t, k in frontier:
                by_type.setdefault(t, []).append(k)
            conds = []
            for t, ks in by_type.items():
                conds.append((LinkEdge.from_type == t) & LinkEdge.from_key.in_(ks))
                conds.append((LinkEdge.to_type == t) & LinkEdge.to_key.in_(ks))
            stmt = select(LinkEdge).where(LinkEdge.workspace == ws, or_(*conds))
            if link_ids is not None:
                stmt = stmt.where(LinkEdge.link_id.in_(link_ids or {"-"}))
            nxt = []
            fset = set(frontier)
            for e in s.scalars(stmt.limit(limit * 20)).all():
                a, b = (e.from_type, e.from_key), (e.to_type, e.to_key)
                src, dst, direction = (a, b, "out") if a in fset else (b, a, "in")
                edges_out.append({"link_id": e.link_id, "link": link_names.get(e.link_id, e.link_id),
                                  "from": f"{a[0]}:{a[1]}", "to": f"{b[0]}:{b[1]}"})
                if dst in seen:
                    continue
                if len(seen) >= limit:
                    truncated = True
                    continue
                seen[dst] = {"depth": d, "via": {"link": link_names.get(e.link_id, e.link_id),
                                                 "direction": direction, "from": f"{src[0]}:{src[1]}"},
                             "context": bool(parent) and parent.get(e.link_id) == ("to" if direction == "out" else "from")}
                if not seen[dst]["context"]:
                    nxt.append(dst)
            frontier = nxt
    keys: dict[str, set[str]] = {}
    for t, k in seen:
        keys.setdefault(t, set()).add(k)
    cache = _cache(ws, keys)
    for t in set(keys) & _sys_types():            # 系统对象不进索引:名称现查
        names = objects.labels(t, list(keys[t]))
        for k in keys[t]:
            cache.setdefault((t, k), (names.get(k, k), {}, None))
    nodes, hidden = [], 0
    for (t, k), info in seen.items():
        label, props, _ = cache.get((t, k), (k, {}, None))
        if (t, k) != root and not _allowed(actor, t, props):
            hidden += 1
            continue
        nodes.append({"id": f"{t}:{k}", "type_id": t, "type_name": types.get(t, t), "key": k,
                      "label": label, "depth": info["depth"], "via": info["via"], "properties": props,
                      "context": bool(info.get("context"))})
    visible = {n["id"] for n in nodes}
    edges_out = list({(e["from"], e["to"], e["link_id"]): e for e in edges_out
                      if e["from"] in visible and e["to"] in visible}.values())
    by_type: dict[str, int] = {}
    for n in nodes:
        if n["depth"]:
            by_type[n["type_name"]] = by_type.get(n["type_name"], 0) + 1
    with session() as s2:
        synced = s2.scalar(select(func.max(ObjectIndex.synced_at)).where(
            ObjectIndex.workspace == ws, ObjectIndex.concept_id.in_(list(keys))))
    return {"root": {"id": f"{root[0]}:{root[1]}", "type_name": ot["name"], "key": root[1],
                     "label": root_cache[root][0]},
            "depth": depth, "nodes": nodes, "edges": edges_out, "by_type": by_type,
            "hidden": hidden, "truncated": truncated, "synced_at": iso(synced)}


def instance_impact(type_ref: str, key: str, *, depth: int = 3, refresh: int = 10) -> dict:
    """影响分析:遍历 + 按层汇总 + 最外层实时取最新属性 + 能对受影响对象做的动作。"""
    t = traverse(type_ref, key, depth=depth, hub_stop=True)
    layers: dict[int, dict[str, list[dict]]] = {}
    context: dict[str, int] = {}                      # 只是「涉及」的上级对象,不算受影响
    for n in t["nodes"]:
        if not n["depth"]:
            continue
        if n.get("context"):
            context[n["type_name"]] = context.get(n["type_name"], 0) + 1
            continue
        layers.setdefault(n["depth"], {}).setdefault(n["type_name"], []).append(n)
    far = max(layers) if layers else 0
    live = []
    if far:
        for n in [x for grp in layers[far].values() for x in grp][:refresh]:
            try:
                o = objects.get(n["type_id"], n["key"])
                dn = {p["name"]: p.get("display_name") or p["name"]
                      for p in (objects.object_type(n["type_id"]).get("spec") or {}).get("properties") or []}
                live.append({"id": n["id"], "type_name": n["type_name"], "key": n["key"], "label": n["label"] or o["label"],
                             "properties": {dn.get(k, k): v for k, v in o["properties"].items()}})
            except HTTPException:
                continue
    affected_types = {n["type_id"] for n in t["nodes"] if n["depth"] and not n.get("context")}
    acts = [{"name": a["name"], "display_name": a.get("display_name") or a["name"],
             "object_type": (a.get("spec") or {}).get("target_type")}
            for a in service.rt_by_kind("action")
            if (a.get("spec") or {}).get("target_type") in affected_types]
    affected: dict[str, int] = {}
    for g in layers.values():
        for name, items in g.items():
            affected[name] = affected.get(name, 0) + len(items)
    parts = [f"{name} {cnt}" for name, cnt in affected.items()]
    summary = (f"从{t['root']['type_name']}「{t['root']['label']}」出发 {t['depth']} 跳内影响:"
               + ("、".join(parts) if parts else "没有找到受影响的对象")
               + (f";涉及 {'、'.join(f'{k} {v}' for k, v in context.items())}" if context else ""))
    return {**t, "layers": [{"depth": d, "groups": [{"type_name": k, "count": len(v),
                                                     "items": v[:50]} for k, v in g.items()]}
                            for d, g in sorted(layers.items())],
            "by_type": affected, "context": context, "live": live, "actions": acts, "summary": summary}