timeline.py 7.58 KB
"""补货单审计时间线:把一张补货单从触发到结束的所有留痕按时间合并,后台逐条可查、可导出(避免扯皮)。

  chat      企微收发原文(notify_logs:按 ref 精确关联的收发 + 单据存续期间没关联任何单的收到消息,标「未关联」)
  audit     人 / 系统 / 智能体 / 取数端的每个动作(操作日志:确认时提交的清单、改了哪些、页面打开 / 刷新 / 修改……),
            以及智能助手对每句话的处理摘要(atrs_ai_trace,完整过程在消息记录里按 log_id 看)
  event     流程事件(状态变化、每个零件的算量过程)
  task      下发给取数端的任务(类型、状态、耗时、错误、证据文件:建单 / 提交的请求响应快照、核对结果、截图)
  api       取数端调用 DMS 接口的每一次(接口、状态、traceId、耗时、行数;完整请求 / 响应在证据文件里)
  snapshot  推给用户的每一版清单、用户确认时提交的清单、确认提交采购单时的清单(完整内容另取)
"""
from __future__ import annotations

import datetime as dt

from ...core import db
from ...core.db import and_, or_, select
from ...models import api_calls_t, audit_t, evidence_t, notify_logs_t, snapshots_t
from ...services import aitrace
from ...services import audit as audit_svc
from ...services import edge, events, links


def _t(v) -> str:
    return v.strftime("%Y-%m-%d %H:%M:%S") if isinstance(v, dt.datetime) else str(v or "")


def build(run: dict) -> list[dict]:
    rid, sid = run["id"], run["store_id"]
    ref = f"restock:run:{rid}"
    start = run["created_at"] - dt.timedelta(minutes=1)
    end = (run["closed_at"] or db.now()) + dt.timedelta(minutes=5)
    out: list[dict] = []
    for m in db.rows(select(notify_logs_t).where(notify_logs_t.c.store_id == sid, or_(
            notify_logs_t.c.ref == ref,
            # 没关联任何单的收到消息(没 @ 助手、闲聊、旧版本没打 ref 的):单据存续期间的作为旁证,标「未关联」
            and_(notify_logs_t.c.direction == "in", notify_logs_t.c.ref.is_(None),
                 notify_logs_t.c.ts >= start, notify_logs_t.c.ts <= end)))
            .order_by(notify_logs_t.c.id)):
        linked = m["ref"] == ref
        out.append({"ts": _t(m["ts"]), "kind": "chat", "level": "info" if m["ok"] is not False else "error",
                    "title": ("收到 " if m["direction"] == "in" else "发出 → ") + (m["target_name"] or "")
                    + ("" if linked else "(未关联)"),
                    "text": m["content"] or "", "detail": {"event": m["event"], "ok": m["ok"], "error": m["error"],
                                                          "msg_id": m["msg_id"]}})
    for a in db.rows(select(audit_t).where(audit_t.c.ref == ref).order_by(audit_t.c.id)):
        out.append({"ts": _t(a["ts"]), "kind": "audit", "level": "info",
                    "title": "%s:%s" % (a["actor_name"] or a["actor_type"],
                                        audit_svc.ACTION_CN.get(a["action"]) or a["action"]),
                    "text": a["action"], "detail": {"actor_type": a["actor_type"], "ip": a["ip"], "ua": a["ua"],
                                                    "before": a["before"], "after": a["after"],
                                                    "detail": a["detail"], "task_id": a["task_id"]}})
    for t in aitrace.by_ref(sid, ref):
        tools = "、".join(c["tool"] for c in t["calls"] if not c.get("duplicate")) or "没调用工具"
        out.append({"ts": _t(t["ts"]), "kind": "audit", "level": "error" if t["error"] else "info",
                    "title": f"智能助手:处理「{t['sender']}」的话",
                    "text": f"{tools} → {aitrace.RESULT_CN.get(t['result'], t['result'])}({t['seconds']} 秒)",
                    "detail": {"log_id": t["log_id"], "text": t["text"], "error": t["error"]}})
    for e in events.recent(sid, ref, 2000):
        out.append({"ts": _t(e["ts"]), "kind": "event", "level": e["level"] or "info", "title": "流程",
                    "text": e["msg"], "detail": {"source": e["source"]}})
    for t in edge.tasks(sid, 100, ref=ref):
        out.append({"ts": _t(t["created_at"]), "kind": "task", "level": "error" if t["status"] in (
            "failed", "late_failed", "unknown", "expired") else "info",
                    "title": f"下发取数端任务 {t['type']}", "text": f"{t['status']}" + (f":{t['error']}" if t["error"] else ""),
                    "detail": {"task_id": t["id"], "dispatched_at": _t(t["dispatched_at"]),
                               "finished_at": _t(t["finished_at"]), "error_code": t["error_code"],
                               "steps": [{"step": s["step"], "detail": s["detail"], "status": s["status"],
                                          "ms": s["duration_ms"], "error": s["error"]} for s in edge.steps(t["id"])],
                               "evidence": [{"id": f["id"], "kind": f["kind"], "name": f["name"],
                                             "url": links.evidence_url(f["id"])}
                                            for f in db.rows(select(evidence_t.c.id, evidence_t.c.kind, evidence_t.c.name)
                                                             .where(evidence_t.c.task_id == t["id"])
                                                             .order_by(evidence_t.c.id))]}})
    for c in db.rows(select(api_calls_t).where(api_calls_t.c.ref == ref).order_by(api_calls_t.c.id)):
        out.append({"ts": _t(c["ts"]), "kind": "api", "level": "info" if c["ok"] else "error",
                    "title": f"DMS 接口 {c['endpoint']}",
                    "text": f"HTTP {c['status']} code={c['code'] or '-'} {c['elapsed_ms']}ms"
                            + (f" {c['rows']} 行" if c["rows"] is not None else "") + (f" {c['error']}" if c["error"] else ""),
                    "detail": {"task_id": c["task_id"], "seq": c["seq"], "trace_id": c["trace_id"],
                               "message": c["message"], "evidence_id": c["evidence_id"],
                               "evidence_url": links.evidence_url(c["evidence_id"]) if c["evidence_id"] else ""}})
    for s in db.rows(select(snapshots_t.c.id, snapshots_t.c.kind, snapshots_t.c.fetch_seq, snapshots_t.c.actor,
                            snapshots_t.c.ip, snapshots_t.c.created_at, snapshots_t.c.data)
                     .where(snapshots_t.c.run_id == rid).order_by(snapshots_t.c.id)):
        data = db.jload(s["data"], {}) or {}
        sm = data.get("summary") or {}
        out.append({"ts": _t(s["created_at"]), "kind": "snapshot", "level": "info",
                    "title": {"pushed": "推给用户的清单", "refreshed": "刷新后的清单", "confirmed": "用户确认的清单(建单)",
                              "single_quote": "单次补货查询结果",
                              "submit_confirmed": "确认提交采购单时的清单"}.get(s["kind"], s["kind"]),
                    "text": f"第 {s['fetch_seq'] or '-'} 轮取数:{sm.get('total', 0)} 种零件,要订 {sm.get('order_count', 0)} 项"
                            f" {sm.get('order_qty', 0)} 件 ¥{sm.get('amount', 0)}" + (f"({s['actor']})" if s["actor"] else ""),
                    "detail": {"snapshot_id": s["id"], "ip": s["ip"], "changes": data.get("changes")}})
    out.sort(key=lambda x: (x["ts"], ["chat", "audit", "event", "task", "api", "snapshot"].index(x["kind"])))
    return out


def snapshot(run_id: int, snap_id: int) -> dict | None:
    r = db.one(select(snapshots_t).where(snapshots_t.c.id == snap_id, snapshots_t.c.run_id == run_id))
    return db.plain(r) if r else None