[WORK] Заимствовано из других классов: lineage данных (источник+свежесть каждого параметра), единый список проблем (clash detection), шаблоны комнат
This commit is contained in:
1 parent
9fab1c5828
commit
8c3b3490ed
5 files changed
+223
-2
No files matched your search
@@ -274,6 +274,83 @@ class Core:
|
||||
d = self.POSITIONS_ROLE.get(role, {"in": ["LAN"], "out": ["—"]})
|
||||
return list(d["in"]), list(d["out"]) or ["—"], "role"
|
||||
|
||||
# ── прослеживаемость данных (как lineage в data-платформах) ──
|
||||
def lineage(self, name):
|
||||
"""По каждому атрибуту: значение, источник, файл, свежесть."""
|
||||
import os
|
||||
import time
|
||||
k = norm(name)
|
||||
out = []
|
||||
sources = [
|
||||
("manual", "overrides.yaml", "ручной ввод"),
|
||||
("verified", "interfaces_verified.yaml", "выверено по даташиту"),
|
||||
("values", "values.yaml", "извлечено из даташита"),
|
||||
("extra", "specs_extra.yaml", "доп. даташит"),
|
||||
("llm", "specs_extract.yaml", "извлечено LLM"),
|
||||
]
|
||||
for kind, fname, label in sources:
|
||||
p = os.path.join(BASE, fname)
|
||||
try:
|
||||
age_h = round((time.time() - os.path.getmtime(p)) / 3600, 1)
|
||||
except OSError:
|
||||
continue
|
||||
out.append({"source": kind, "file": fname, "label": label,
|
||||
"file_age_hours": age_h})
|
||||
attrs = self.attrs.get(k, {})
|
||||
rows = []
|
||||
for attr, val in sorted(attrs.items()):
|
||||
src = "values"
|
||||
if (getattr(self, "manual", {}) or {}).get(k, {}).get(attr) is not None:
|
||||
src = "manual"
|
||||
elif (getattr(self, "iface_map", {}) or {}).get(k) and attr.startswith(("ports.", "network.")):
|
||||
src = "verified"
|
||||
rows.append({"attr": attr, "value": val, "source": src,
|
||||
"verified": src in ("manual", "verified")})
|
||||
verified_count = sum(1 for r in rows if r["verified"])
|
||||
return {"device": self.devices.get(k, {}).get("name") or name,
|
||||
"attributes": rows, "total": len(rows),
|
||||
"verified": verified_count,
|
||||
"trust_pct": round(100.0 * verified_count / max(len(rows), 1), 1),
|
||||
"files": out,
|
||||
"package": self.package(name),
|
||||
"completeness": self.completeness(k)}
|
||||
|
||||
# ── единый список проблем (clash detection) ──
|
||||
def issues(self, host_key, items, infra=None):
|
||||
hk = norm(host_key)
|
||||
host = self.devices.get(hk, {}).get("name") or host_key
|
||||
out = []
|
||||
cap = self.capacity(hk, items, infra or [])
|
||||
for i in cap["issues"]:
|
||||
out.append({"level": "blocker", "kind": "capacity", "text": i})
|
||||
if cap["missing_power"]:
|
||||
out.append({"level": "warning", "kind": "data",
|
||||
"text": "нет данных о питании: " + ", ".join(cap["missing_power"][:6])})
|
||||
sig = self.signal_chains(hk, items)
|
||||
for r in sig["chains"]:
|
||||
if not r["ok"]:
|
||||
out.append({"level": "blocker", "kind": "signal",
|
||||
"text": "%s: %s" % (r["device"], r["reason"])})
|
||||
plan = self.port_plan(hk, items)
|
||||
if plan["unresolved"]:
|
||||
out.append({"level": "blocker", "kind": "port",
|
||||
"text": "нет порта для: " + ", ".join(plan["unresolved"])})
|
||||
comp = self.completeness(hk)
|
||||
if comp["level"] != "full":
|
||||
out.append({"level": "warning", "kind": "data",
|
||||
"text": "неполные данные: " + comp["note"]})
|
||||
for row in items:
|
||||
pk = self.package(row[0])
|
||||
if not pk["items"]:
|
||||
out.append({"level": "info", "kind": "package",
|
||||
"text": "%s: комплектация неизвестна" % row[0]})
|
||||
blockers = sum(1 for i in out if i["level"] == "blocker")
|
||||
warnings = sum(1 for i in out if i["level"] == "warning")
|
||||
return {"host": host, "issues": out, "blockers": blockers,
|
||||
"warnings": warnings, "ready": blockers == 0,
|
||||
"by_kind": {k: sum(1 for i in out if i["kind"] == k)
|
||||
for k in {i["kind"] for i in out}}}
|
||||
|
||||
# ── ручной ввод характеристики ──
|
||||
ALLOWED_ATTRS = {
|
||||
"audio.pickup_m": "м", "audio.spl_max": "dB SPL",
|
||||
|
||||
+41
-1
@@ -83,6 +83,7 @@ svg{width:100%;height:520px;background:#0a0e13;border:1px solid var(--line);bord
|
||||
<div class="tab" data-t="docs">Документы</div>
|
||||
<div class="tab" data-t="layout">План комнаты</div>
|
||||
<div class="tab" data-t="heat">Покрытие</div>
|
||||
<div class="tab" data-t="issues">Проблемы</div>
|
||||
<div class="tab" data-t="ask">Спросить</div>
|
||||
</div>
|
||||
|
||||
@@ -216,6 +217,23 @@ svg{width:100%;height:520px;background:#0a0e13;border:1px solid var(--line);bord
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- ПРОБЛЕМЫ -->
|
||||
<section id="sec-issues" class="hidden">
|
||||
<div class="card">
|
||||
<h3>Проблемы проекта</h3>
|
||||
<div id="issuesbox"><span class="muted">соберите состав</span></div>
|
||||
</div>
|
||||
<div class="card" style="margin-top:12px">
|
||||
<h3>Откуда данные (происхождение)</h3>
|
||||
<div style="display:flex;gap:8px;align-items:center;margin-bottom:10px">
|
||||
<input id="lndev" placeholder="модель, напр. UVC86" style="max-width:240px">
|
||||
<button class="btn sm" onclick="renderLineage()">Показать</button>
|
||||
<span id="lntrust" class="muted"></span>
|
||||
</div>
|
||||
<div id="lineagebox"><span class="muted">—</span></div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- СПРОСИТЬ -->
|
||||
<section id="sec-ask" class="hidden">
|
||||
<div class="card"><h3>Вопрос по модели</h3>
|
||||
@@ -264,12 +282,13 @@ function roomOut(){const w=+$('#w').value,l=+$('#l').value,s=+$('#seats').value;
|
||||
document.querySelectorAll('.tab').forEach(t=>t.onclick=()=>showTab(t.dataset.t));
|
||||
function showTab(n){
|
||||
document.querySelectorAll('.tab').forEach(t=>t.classList.toggle('on',t.dataset.t===n));
|
||||
['build','cables','diagram','layout','heat','matrix','docs','ask'].forEach(x=>$('#sec-'+x).classList.toggle('hidden',x!==n));
|
||||
['build','cables','diagram','layout','heat','matrix','docs','issues','ask'].forEach(x=>$('#sec-'+x).classList.toggle('hidden',x!==n));
|
||||
if(n==='diagram')renderDiagram();
|
||||
if(n==='cables')renderCables();
|
||||
if(n==='matrix')loadMatrix();
|
||||
if(n==='layout')renderPlanDrag();
|
||||
if(n==='heat')renderHeatmap();
|
||||
if(n==='issues')renderIssues();
|
||||
}
|
||||
|
||||
const DIRECTIONS=[
|
||||
@@ -518,6 +537,27 @@ function pickVendor(id){
|
||||
showTab('build');
|
||||
reload();
|
||||
}
|
||||
async function renderIssues(){
|
||||
const ks=Object.keys(SEL);
|
||||
if(!ks.length){$('#issuesbox').innerHTML='<span class="muted">соберите состав</span>';return;}
|
||||
const r=await J(`${SVC.engine}/issues?host=${$('#host').value}&${itemsQuery()}`);
|
||||
if(r.error){$('#issuesbox').innerHTML=`<div class="box bad">${esc(r.error)}</div>`;return;}
|
||||
const icon={blocker:'⛔', warning:'⚠️', info:'ℹ️'};
|
||||
$('#issuesbox').innerHTML=`<div class="muted" style="margin-bottom:8px">
|
||||
готов к закупке: <b>${r.ready?'да':'нет'}</b> · блокеров ${r.blockers} · предупреждений ${r.warnings}</div>
|
||||
${(r.issues||[]).map(i=>`<div class="chk"><i>${icon[i.level]||'•'}</i>
|
||||
<div><b>${esc(i.kind)}</b> <span class="muted">${esc(i.text)}</span></div></div>`).join('')}`;
|
||||
}
|
||||
async function renderLineage(){
|
||||
const dev=$('#lndev').value.trim(); if(!dev)return;
|
||||
const r=await J(`${SVC.engine}/lineage?device=${encodeURIComponent(dev)}`);
|
||||
if(r.error){$('#lineagebox').innerHTML=`<div class="box bad">${esc(r.error)}</div>`;return;}
|
||||
$('#lntrust').textContent=`выверено ${r.verified} из ${r.total} (${r.trust_pct}%)`;
|
||||
$('#lineagebox').innerHTML=`<table><tr><th>Параметр</th><th>Значение</th><th>Источник</th></tr>
|
||||
${(r.attributes||[]).map(a=>`<tr><td>${esc(a.attr)}</td><td><b>${esc(String(a.value))}</b></td>
|
||||
<td class="muted">${a.verified?'выверено':esc(a.source)}</td></tr>`).join('')}</table>
|
||||
<div class="muted" style="margin-top:6px">файлы: ${(r.files||[]).map(f=>esc(f.file)+' ('+f.file_age_hours+' ч)').join(' · ')}</div>`;
|
||||
}
|
||||
async function doAsk(){
|
||||
const q=$('#askq').value.trim(); if(!q)return;
|
||||
$('#askbox').innerHTML='<span class="muted">думаю…</span>';
|
||||
|
||||
@@ -652,6 +652,14 @@ def pdf(q, body):
|
||||
"content_type": "application/pdf"}
|
||||
|
||||
|
||||
def lineage(q, body):
|
||||
return C.lineage((q.get("device") or [""])[0])
|
||||
|
||||
|
||||
def issues(q, body):
|
||||
return C.issues((q.get("host") or [""])[0], _items(q), q.get("infra") or [])
|
||||
|
||||
|
||||
serve({
|
||||
"/groups": groups,
|
||||
"/check": check,
|
||||
@@ -671,5 +679,7 @@ serve({
|
||||
"/override": override,
|
||||
"/pack": pack,
|
||||
"/pdf": pdf,
|
||||
"/lineage": lineage,
|
||||
"/issues": issues,
|
||||
"/xlsx": xlsx,
|
||||
}, int(sys.argv[1]) if len(sys.argv) > 1 else 8102, "engine", before=C.reload_if_changed)
|
||||
@@ -10,6 +10,10 @@ sys.path.insert(0, "/root/buryan-infra/ops/work/web")
|
||||
from svc_base import serve # noqa
|
||||
|
||||
DIR = "/opt/work-hub/compat/projects"
|
||||
|
||||
|
||||
def _ensure(d):
|
||||
os.makedirs(d, exist_ok=True)
|
||||
os.makedirs(DIR, exist_ok=True)
|
||||
|
||||
|
||||
@@ -152,10 +156,60 @@ def import_project(q, body):
|
||||
return res
|
||||
|
||||
|
||||
TPL_DIR = "/opt/work-hub/compat/templates"
|
||||
|
||||
|
||||
def templates(q, body):
|
||||
"""Список шаблонов комнат."""
|
||||
_ensure(TPL_DIR)
|
||||
out = []
|
||||
for f in sorted(os.listdir(TPL_DIR)):
|
||||
if f.endswith(".json"):
|
||||
try:
|
||||
d = json.load(open(os.path.join(TPL_DIR, f), encoding="utf-8"))
|
||||
except Exception:
|
||||
continue
|
||||
out.append({"id": d.get("id"), "name": d.get("name"),
|
||||
"host": d.get("host"),
|
||||
"items": len(d.get("items") or [])})
|
||||
return {"templates": out}
|
||||
|
||||
|
||||
def save_template(q, body):
|
||||
"""Сохранить текущий состав как шаблон комнаты."""
|
||||
_ensure(TPL_DIR)
|
||||
body = body or {}
|
||||
name = (body.get("name") or "").strip()
|
||||
items = body.get("items") or []
|
||||
if not name or not items:
|
||||
return {"error": "нужны name и items"}
|
||||
tid = "t%d" % int(time.time())
|
||||
payload = {"id": tid, "name": name, "host": body.get("host"),
|
||||
"room": body.get("room") or {}, "need": body.get("need") or [],
|
||||
"items": items, "created": time.strftime("%Y-%m-%dT%H:%M:%S")}
|
||||
with open(os.path.join(TPL_DIR, tid + ".json"), "w", encoding="utf-8") as f:
|
||||
json.dump(payload, f, ensure_ascii=False, indent=2)
|
||||
return {"ok": True, "id": tid, "name": name}
|
||||
|
||||
|
||||
def get_template(q, body):
|
||||
_ensure(TPL_DIR)
|
||||
tid = (q.get("id") or [""])[0]
|
||||
if not _ok(tid):
|
||||
return {"error": "bad id"}
|
||||
p = os.path.join(TPL_DIR, tid + ".json")
|
||||
if not os.path.exists(p):
|
||||
return {"error": "not found"}
|
||||
return json.load(open(p, encoding="utf-8"))
|
||||
|
||||
|
||||
serve({
|
||||
"/list": lst,
|
||||
"/get": get,
|
||||
"/save": save,
|
||||
"/delete": remove,
|
||||
"/import": import_project,
|
||||
"/templates": templates,
|
||||
"/template": get_template,
|
||||
"/save-template": save_template,
|
||||
}, int(sys.argv[1]) if len(sys.argv) > 1 else 8103, "project")
|
||||
+41
-1
@@ -83,6 +83,7 @@ svg{width:100%;height:520px;background:#0a0e13;border:1px solid var(--line);bord
|
||||
<div class="tab" data-t="docs">Документы</div>
|
||||
<div class="tab" data-t="layout">План комнаты</div>
|
||||
<div class="tab" data-t="heat">Покрытие</div>
|
||||
<div class="tab" data-t="issues">Проблемы</div>
|
||||
<div class="tab" data-t="ask">Спросить</div>
|
||||
</div>
|
||||
|
||||
@@ -216,6 +217,23 @@ svg{width:100%;height:520px;background:#0a0e13;border:1px solid var(--line);bord
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- ПРОБЛЕМЫ -->
|
||||
<section id="sec-issues" class="hidden">
|
||||
<div class="card">
|
||||
<h3>Проблемы проекта</h3>
|
||||
<div id="issuesbox"><span class="muted">соберите состав</span></div>
|
||||
</div>
|
||||
<div class="card" style="margin-top:12px">
|
||||
<h3>Откуда данные (происхождение)</h3>
|
||||
<div style="display:flex;gap:8px;align-items:center;margin-bottom:10px">
|
||||
<input id="lndev" placeholder="модель, напр. UVC86" style="max-width:240px">
|
||||
<button class="btn sm" onclick="renderLineage()">Показать</button>
|
||||
<span id="lntrust" class="muted"></span>
|
||||
</div>
|
||||
<div id="lineagebox"><span class="muted">—</span></div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- СПРОСИТЬ -->
|
||||
<section id="sec-ask" class="hidden">
|
||||
<div class="card"><h3>Вопрос по модели</h3>
|
||||
@@ -264,12 +282,13 @@ function roomOut(){const w=+$('#w').value,l=+$('#l').value,s=+$('#seats').value;
|
||||
document.querySelectorAll('.tab').forEach(t=>t.onclick=()=>showTab(t.dataset.t));
|
||||
function showTab(n){
|
||||
document.querySelectorAll('.tab').forEach(t=>t.classList.toggle('on',t.dataset.t===n));
|
||||
['build','cables','diagram','layout','heat','matrix','docs','ask'].forEach(x=>$('#sec-'+x).classList.toggle('hidden',x!==n));
|
||||
['build','cables','diagram','layout','heat','matrix','docs','issues','ask'].forEach(x=>$('#sec-'+x).classList.toggle('hidden',x!==n));
|
||||
if(n==='diagram')renderDiagram();
|
||||
if(n==='cables')renderCables();
|
||||
if(n==='matrix')loadMatrix();
|
||||
if(n==='layout')renderPlanDrag();
|
||||
if(n==='heat')renderHeatmap();
|
||||
if(n==='issues')renderIssues();
|
||||
}
|
||||
|
||||
const DIRECTIONS=[
|
||||
@@ -518,6 +537,27 @@ function pickVendor(id){
|
||||
showTab('build');
|
||||
reload();
|
||||
}
|
||||
async function renderIssues(){
|
||||
const ks=Object.keys(SEL);
|
||||
if(!ks.length){$('#issuesbox').innerHTML='<span class="muted">соберите состав</span>';return;}
|
||||
const r=await J(`${SVC.engine}/issues?host=${$('#host').value}&${itemsQuery()}`);
|
||||
if(r.error){$('#issuesbox').innerHTML=`<div class="box bad">${esc(r.error)}</div>`;return;}
|
||||
const icon={blocker:'⛔', warning:'⚠️', info:'ℹ️'};
|
||||
$('#issuesbox').innerHTML=`<div class="muted" style="margin-bottom:8px">
|
||||
готов к закупке: <b>${r.ready?'да':'нет'}</b> · блокеров ${r.blockers} · предупреждений ${r.warnings}</div>
|
||||
${(r.issues||[]).map(i=>`<div class="chk"><i>${icon[i.level]||'•'}</i>
|
||||
<div><b>${esc(i.kind)}</b> <span class="muted">${esc(i.text)}</span></div></div>`).join('')}`;
|
||||
}
|
||||
async function renderLineage(){
|
||||
const dev=$('#lndev').value.trim(); if(!dev)return;
|
||||
const r=await J(`${SVC.engine}/lineage?device=${encodeURIComponent(dev)}`);
|
||||
if(r.error){$('#lineagebox').innerHTML=`<div class="box bad">${esc(r.error)}</div>`;return;}
|
||||
$('#lntrust').textContent=`выверено ${r.verified} из ${r.total} (${r.trust_pct}%)`;
|
||||
$('#lineagebox').innerHTML=`<table><tr><th>Параметр</th><th>Значение</th><th>Источник</th></tr>
|
||||
${(r.attributes||[]).map(a=>`<tr><td>${esc(a.attr)}</td><td><b>${esc(String(a.value))}</b></td>
|
||||
<td class="muted">${a.verified?'выверено':esc(a.source)}</td></tr>`).join('')}</table>
|
||||
<div class="muted" style="margin-top:6px">файлы: ${(r.files||[]).map(f=>esc(f.file)+' ('+f.file_age_hours+' ч)').join(' · ')}</div>`;
|
||||
}
|
||||
async function doAsk(){
|
||||
const q=$('#askq').value.trim(); if(!q)return;
|
||||
$('#askbox').innerHTML='<span class="muted">думаю…</span>';
|
||||
|
||||
Reference in new issue
Block a user