workspaces.py
8.35 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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
"""本体空间:一个行业 / 业务域一套本体。
元素、版本、动作、审批、SOP、审计、数据管道本来就按 `workspace` 隔离(身份里带着),
这里只补空间本身的登记、首页卡片统计和「当前本体总览」。
"""
from __future__ import annotations
import dataclasses
import re
from fastapi import HTTPException
from sqlalchemy import func, select
from ..core import identity
from ..core.dbx import iso, new_id, session
from ..governance import audit
from .models import Concept, Pipeline, Workspace
_ID = re.compile(r"^[a-z][a-z0-9_]{1,40}$")
def _dict(w: Workspace) -> dict:
return {"id": w.id, "display_name": w.display_name or w.id, "description": w.description or "",
"industry": w.industry or "", "status": w.status, "created_by": w.created_by,
"created_at": iso(w.created_at), "updated_at": iso(w.updated_at)}
def ensure(ws_id: str) -> None:
"""当前身份所在的空间没有登记过(老数据 / 环境变量指定的默认空间)就补登记。"""
with session() as s:
if s.get(Workspace, ws_id) is None:
# 环境变量指定的空间(如 v4)是部署细节,对用户一律叫「默认本体」
s.add(Workspace(id=ws_id, display_name="默认本体", created_by="system"))
s.commit()
def counts(ws_id: str) -> dict:
from ..sop.models import SopDefinition
with session() as s:
rows = s.execute(select(Concept.kind, Concept.spec_json).where(
Concept.workspace == ws_id, Concept.status != "deprecated")).all()
sops = s.scalar(select(func.count(SopDefinition.id)).where(
SopDefinition.workspace == ws_id, SopDefinition.status != "archived")) or 0
out = {"object_type": 0, "link_type": 0, "function": 0, "action": 0, "sop": int(sops)}
for kind, _ in rows:
out[kind] = out.get(kind, 0) + 1
return out
def list_all() -> list[dict]:
ensure(identity.current().workspace)
with session() as s:
rows = s.scalars(select(Workspace).where(Workspace.status == "active")
.order_by(Workspace.created_at)).all()
items = [_dict(w) for w in rows]
for it in items:
it["counts"] = counts(it["id"])
it["current"] = it["id"] == identity.current().workspace
return items
def get(ws_id: str) -> dict:
with session() as s:
w = s.get(Workspace, ws_id)
if w is None:
raise HTTPException(404, f"本体空间「{ws_id}」不存在")
out = _dict(w)
out["counts"] = counts(ws_id)
return out
def create(ws_id: str, display_name: str, description: str = "", industry: str = "",
template: str = "") -> dict:
ws_id = (ws_id or "").strip().lower()
if not ws_id: # 中文名起不出英文标识:不填就自动生成
ws_id = f"ws_{new_id('')[-8:].lower()}"
if not _ID.match(ws_id):
raise HTTPException(422, "空间标识只能用小写字母开头的字母、数字、下划线(2~41 位),如 manufacturing")
actor = identity.current()
with session() as s:
if s.get(Workspace, ws_id) is not None:
raise HTTPException(409, f"本体空间「{ws_id}」已存在")
name = (display_name or ws_id).strip()
if any((w.display_name or w.id) == name for w in s.scalars(select(Workspace)).all()):
raise HTTPException(409, f"已经有一个叫「{name}」的本体空间了,换个名字")
s.add(Workspace(id=ws_id, display_name=(display_name or ws_id)[:255],
description=description or "", industry=industry or "",
created_by=actor.id))
s.commit()
audit.record("workspace.create", "workspace", ws_id, f"新建本体「{display_name or ws_id}」")
if template:
from . import templates
tok = identity.set_current(dataclasses.replace(actor, workspace=ws_id))
try:
templates.apply_template(template)
finally:
identity.reset(tok)
return get(ws_id)
def update(ws_id: str, **fields) -> dict:
with session() as s:
w = s.get(Workspace, ws_id)
if w is None:
raise HTTPException(404, f"本体空间「{ws_id}」不存在")
for k in ("display_name", "description", "industry"):
if fields.get(k) is not None:
setattr(w, k, str(fields[k]))
s.commit()
return get(ws_id)
def archive(ws_id: str) -> dict:
if ws_id == identity.current().workspace:
raise HTTPException(409, "不能归档当前正在使用的本体,请先切换到别的本体")
with session() as s:
w = s.get(Workspace, ws_id)
if w is None:
raise HTTPException(404, f"本体空间「{ws_id}」不存在")
w.status = "archived"
s.commit()
audit.record("workspace.archive", "workspace", ws_id, f"归档本体「{ws_id}」")
return {"ok": True}
def overview() -> dict:
"""当前本体的首页:资产计数、映射情况、数据与运行时状态、建议的下一步。"""
from ..capability import actions
from ..governance import review
from ..text2sql import semantic
from . import service
actor = identity.current()
ws = actor.workspace
ensure(ws)
c = counts(ws)
items = service.list_concepts()
unmapped = [x for x in items if x["kind"] == "object_type" and not x.get("mapped")]
dss = semantic.list_datasources()
with session() as s:
pipes = s.scalars(select(Pipeline).where(Pipeline.workspace == ws)).all()
pipe_info = {"total": len(pipes), "ok": sum(1 for p in pipes if p.status == "ok"),
"failed": sum(1 for p in pipes if p.status == "failed"),
"last_run_at": iso(max((p.last_run_at for p in pipes if p.last_run_at), default=None))}
st = service.stats()
pending_reviews = sum(review.counts().values()) if actor.can("review") else 0
steps = []
if not dss:
steps.append({"key": "data", "title": "接入数据连接", "hint": "先接一个业务库,本体才能落到真实数据"})
if c["object_type"] == 0:
steps.append({"key": "modeling", "title": "AI 建模", "hint": "上传业务文档,AI 生成四元组草案"})
if unmapped:
steps.append({"key": "b_object", "title": f"完善对象映射({len(unmapped)} 个未映射)",
"hint": "对象要绑定到数据表,才能被查询、遍历与写回"})
if dss and c["object_type"] and not pipe_info["total"]:
steps.append({"key": "pipeline", "title": "配置数据管道", "hint": "同步对象骨架,打开影响分析与对象搜索"})
if st["dirty"]:
steps.append({"key": "publish", "title": f"提交变更提案({st['dirty']} 处未发布)",
"hint": "变更经审批后发布成新版本,运行时才会生效"})
# 动作要某个业务角色审批,却没人担任这个角色:审批单会一直卡着没人能批
from ..governance import roles as biz_roles
members = {r["name"]: r["members"] for r in biz_roles.list_roles()}
need = sorted({r for a in service.rt_by_kind("action")
for r in ((a.get("spec") or {}).get("approval") or {}).get("approver_roles") or []
if not members.get(r)})
if need:
steps.append({"key": "members", "title": f"给审批角色指派人员({'、'.join(need)})",
"hint": "动作要这些角色审批,现在没人担任,审批单会没人能批"})
from . import modeling
drafts = modeling.pending_count() if actor.can("build") else 0
if drafts:
steps.append({"key": "modeling", "title": f"决定 AI 建模草案({drafts} 条待定)",
"hint": "在 AI 建模页逐条查看,采纳即上线"})
if pending_reviews:
steps.append({"key": "inbox", "title": f"处理审核队列({pending_reviews} 条)",
"hint": "别处提交给你审核的变更与草案"})
return {"workspace": get(ws), "counts": c,
"mapped": {"object_total": c["object_type"], "object_unmapped": len(unmapped)},
"revision": st["revision"], "dirty": st["dirty"], "datasources": len(dss),
"pipelines": pipe_info, "pending_approvals": actions.count_pending(actor),
"pending_reviews": pending_reviews, "modeling_drafts": drafts, "next_steps": steps[:5]}