workbench.py
5.76 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
"""工作台:老板和员工每天打开系统看到的第一页。
搭建者看「本体首页」(资产、映射、下一步);业务人员只关心四件事:
1. 今天的关键数字怎么样(已发布指标的当前值);
2. 有什么等我处理(待我审批的动作、变更提案、派给我的待办);
3. 我提交的事办得怎么样;
4. 常用的流程和问题,一点就能用。
全部只读、按当前身份过滤,指标取数失败的直接跳过,不让一个坏指标拖垮整页。
"""
from __future__ import annotations
import logging
from ..core import identity
from . import metrics, service
log = logging.getLogger(__name__)
MAX_KPIS = 8
def _kpis() -> list[dict]:
ms = [m for m in service.rt_by_kind("function", "aggregate") if service.rt_binding(m, "metric_expr")][:MAX_KPIS]
# 以前一个一个取,八个指标就是八次串行 SQL;现在一起发出去
results = metrics.query_many([{"ref": m["name"], "limit": 1, "question": f"[工作台] {m['name']}"} for m in ms])
out = []
for m, r in zip(ms, results):
if isinstance(r, Exception): # 单个指标失败不影响整页
log.info("工作台指标 %s 取数失败:%s", m["name"], str(getattr(r, "detail", r))[:120])
continue
sp = m.get("spec") or {}
v = r.get("value")
if v is None and r.get("rows"):
v = r["rows"][0][-1]
dims = list(((service.rt_binding(m, "metric_expr") or {}).get("ref") or {}).get("dimensions") or {})
ot = service.rt_get(sp.get("object_type") or "") or {}
label = {p["name"]: p.get("display_name") or p["name"] for p in (ot.get("spec") or {}).get("properties") or []}
dims = [label.get(d, d) for d in dims] # 维度用业务叫法(仓库编号),取数时按显示名也认
out.append({"name": m["name"], "value": v, "unit": sp.get("unit") or "", "format": sp.get("format") or "",
"direction": sp.get("direction") or "neutral", "formula": sp.get("formula_text") or "",
"dimensions": dims, "run_id": r.get("run_id")})
return out
def _questions(kpis: list[dict]) -> list[str]:
"""按本体里真有的东西给几个能直接问的问题(不瞎编指标名,不带指标不支持的时间范围)。"""
qs = []
for k in kpis[:3]:
qs.append(f"{k['name']}按{k['dimensions'][0]}拆开看是多少?" if k["dimensions"] else f"现在的{k['name']}是多少?")
return qs[:4]
def _alerts() -> list[dict]:
"""正在发生的预警(最多 6 条),工作台上直接看到。"""
try:
from ..watch import events
return [{"id": a["id"], "watch": a["rule"], "watch_id": a["watch_id"], "label": a["title"],
"severity": a["severity"], "status": a["status"], "first_seen_at": a["first_seen_at"]}
for a in events.list_events(status="open", limit=6)]
except Exception: # noqa: BLE001
log.debug("读取预警失败", exc_info=True)
return []
def _merge_questions(pinned: list[str], generated: list[str]) -> list[str]:
"""自己存的常用问题排在前面,再补系统按指标生成的。"""
return list(dict.fromkeys(pinned + generated))[:8]
def workbench() -> dict:
from ..capability import actions, tasks
from ..governance import audit
from ..sop import service as sop_service
actor = identity.current()
kpis = _kpis()
approvals = [r for r in actions.pending_for(actor) if r.get("can_approve")] if actor.can("approve") else []
releases = [r for r in service.list_releases("pending") if r.get("can_decide")] \
if actor.can("review") or actor.can("approve") else []
my_tasks = tasks.list_tasks(scope="mine", status="open", limit=5)
mine = [r for r in actions.list_runs(limit=50) if actor.id in (r["initiator_id"], r["submitted_by"])][:5]
sops = [{"id": d["id"], "title": d["title"], "description": d.get("description") or "",
"run_count": d.get("run_count") or 0}
for d in sop_service.list_defs(status="published")][:6]
feed = audit.query(workspace=actor.workspace, limit=8, business=True)["items"]
from ..memory import service as memory
try:
pinned, habits = memory.pinned_questions(), memory.suggestions()
except Exception: # noqa: BLE001
log.debug("读取经验中枢失败", exc_info=True)
pinned, habits = [], []
def brief(r: dict) -> dict:
pv = r.get("preview") or {}
return {"id": r["id"], "action_name": r["action_name"], "priority": r["priority"], "status": r["status"],
"summary": pv.get("target_label") or pv.get("summary") or r.get("reason") or "",
"submitted_name": r.get("submitted_name") or "",
"created_at": r["created_at"], "initiator_id": r["initiator_id"]}
return {"user": {"id": actor.id, "name": actor.name, "roles": actor.roles, "biz_roles": actor.biz_roles,
"can_run": actor.can("operate")},
"kpis": kpis,
"todo": {"approvals": [brief(r) for r in approvals[:5]], "approvals_total": len(approvals),
"releases": [{"id": r["id"], "title": r["title"], "created_by": r.get("created_by")}
for r in releases[:3]],
"tasks": [{"id": t["id"], "title": t["title"], "due_at": t.get("due_at"),
"role": t.get("role")} for t in my_tasks]},
"mine": [brief(r) for r in mine], "sops": sops,
"questions": _merge_questions(pinned, _questions(kpis)),
"pinned": pinned, "habits": habits, "alerts": _alerts(),
"feed": [{"ts": x.get("ts"), "actor": x.get("actor_name") or x.get("actor_id"),
"summary": x.get("summary")} for x in feed]}