[WORK] Ручной режим схем: сервис combine-drawedit (:8106) — таскать узлы, подписи, линии, сохранение в compat/layouts, экспорт SVG. Кнопка «Ручной режим» в разделе Схема. svc_base научился отдавать HTML. Проверено: load/save/render и UI
This commit is contained in:
1 parent
ad57ba27d5
commit
43075028a5
4 files changed
+364
-2
No files matched your search
@@ -0,0 +1,68 @@
|
||||
# Ручной режим схем в Комбайне (12.11.2026)
|
||||
|
||||
## Задача
|
||||
|
||||
Авто-схема (`svc_draw.py`, :8104) расставляет узлы по жёсткому алгоритму
|
||||
(центр + два столбца) — на практике получается нечитаемо. Нужно было дать
|
||||
возможность поправить схему **руками**: подвинуть, подписать, дорисовать.
|
||||
|
||||
## Что сделано
|
||||
|
||||
### Сервис `combine-drawedit` (:8106)
|
||||
|
||||
Новый файл `ops/work/web/services/svc_drawedit.py`:
|
||||
|
||||
| Маршрут | Назначение |
|
||||
|---|---|
|
||||
| `GET /editor` | страница-редактор (SVG, мышь) |
|
||||
| `GET /load?host=…` | узлы авто-раскладки + сохранённые позиции |
|
||||
| `POST /save` | сохранить раскладку (нужен `X-Token` с правом записи) |
|
||||
| `GET /render?host=…` | готовый SVG из сохранённой раскладки |
|
||||
|
||||
Раскладки: `/opt/work-hub/compat/layouts/<хост>.json`
|
||||
(узлы с координатами, подписи, линии).
|
||||
|
||||
### Возможности редактора
|
||||
|
||||
* **таскать узлы** мышью — позиция запоминается по имени устройства;
|
||||
* **подписи** — кнопка «+ Подпись», текст перетаскивается;
|
||||
* **линии** — кнопка «+ Линия», две точки кликом;
|
||||
* **сохранить** — пишет раскладку (в аудит `audit.jsonl`);
|
||||
* **сброс** — вернуть авто-раскладку;
|
||||
* **экспорт SVG** — скачать готовую схему.
|
||||
|
||||
### Кнопка в интерфейсе
|
||||
|
||||
В разделе «Схема» добавлена кнопка **«Ручной режим»** → открывает редактор
|
||||
для выбранного хоста и текущего состава.
|
||||
|
||||
### Правка общей базы
|
||||
|
||||
`svc_base.py` научился отдавать HTML: `{"__html": "..."}`.
|
||||
Это точечное дополнение, остальные сервисы не затронуты.
|
||||
|
||||
## Проверка
|
||||
|
||||
```
|
||||
GET :8106/editor?host=MeetingBar+A30&item=A40:2 → 200
|
||||
GET :8106/load → 2 узла (A40 @175,185 · CPE40 @925,435)
|
||||
POST :8106/save (X-Token) → ok: узлов 1, подписей 1, линий 1
|
||||
GET :8106/render → SVG с подписью и линией
|
||||
UI :8095 → кнопка «Ручной режим» есть
|
||||
```
|
||||
|
||||
Все сервисы Комбайна active: web, catalog, engine, project, draw, docs, drawedit.
|
||||
|
||||
## Как пользоваться
|
||||
|
||||
1. Открыть Комбайн (`http://192.168.1.10:8095`), собрать состав.
|
||||
2. Раздел **Схема** → кнопка **«Ручной режим»**.
|
||||
3. Подвинуть узлы, добавить подписи/линии.
|
||||
4. Ввести `X-Token` (роль editor/admin из `compat/access.yaml`) → **Сохранить**.
|
||||
5. «Экспорт SVG» — забрать картинку.
|
||||
|
||||
## Ловушка
|
||||
|
||||
`/save` защищён токеном (общий механизм `svc_base`): без заголовка `X-Token`
|
||||
с правом записи вернётся 403. Токен хранится в `compat/access.yaml`,
|
||||
в браузере — только в поле ввода (не сохраняется).
|
||||
@@ -195,6 +195,7 @@ svg{width:100%;height:520px;background:#0a0e13;border:1px solid var(--line);bord
|
||||
<div id="svgbox"><span class="muted">соберите состав</span></div>
|
||||
<div style="margin-top:10px;display:flex;gap:8px">
|
||||
<button class="btn sm ghost" onclick="downloadSvg()">Скачать SVG</button>
|
||||
<button class="btn sm" onclick="openDrawEditor()">Ручной режим</button>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
@@ -281,7 +282,8 @@ svg{width:100%;height:520px;background:#0a0e13;border:1px solid var(--line);bord
|
||||
</main>
|
||||
<script>
|
||||
const SVC={catalog:'http://192.168.1.10:8101',engine:'http://192.168.1.10:8102',
|
||||
project:'http://192.168.1.10:8103',draw:'http://192.168.1.10:8104',docs:'http://192.168.1.10:8105'};
|
||||
project:'http://192.168.1.10:8103',draw:'http://192.168.1.10:8104',docs:'http://192.168.1.10:8105',
|
||||
drawedit:'http://192.168.1.10:8106'};
|
||||
let HOSTS=[],SEL={},NEED=new Set(),GRP=null,MATRIX=null,LASTDIY=null;
|
||||
const $=s=>document.querySelector(s);
|
||||
const esc=s=>String(s).replace(/[<>&]/g,c=>({'<':'<','>':'>','&':'&'}[c]));
|
||||
@@ -442,6 +444,11 @@ async function renderDiagram(){
|
||||
window.LAST_SVG=r.svg;
|
||||
}
|
||||
function downloadSvg(){
|
||||
function openDrawEditor(){
|
||||
const host=$('#host').value;
|
||||
if(!host){alert('выберите хост');return;}
|
||||
window.open(`${SVC.drawedit}/editor?host=${encodeURIComponent(host)}&${q()}`,'_blank');
|
||||
}
|
||||
const svg=window.LAST_SVG||''; if(!svg){alert('сначала схема');return;}
|
||||
const blob=new Blob([svg],{type:'image/svg+xml'});
|
||||
const a=document.createElement('a'); a.href=URL.createObjectURL(blob);
|
||||
@@ -745,4 +752,4 @@ async function searchDocs(){
|
||||
boot();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
</html>
|
||||
@@ -0,0 +1,276 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Ручной режим схем Комбайна (8106): двигать узлы, подписи, линии.
|
||||
|
||||
Зачем: авто-схема (svc_draw.py, :8104) строит узлы по жёсткому алгоритму и
|
||||
получается нечитаемой. Здесь ту же схему можно поправить руками — позиции
|
||||
узлов, подписи и произвольные линии сохраняются в
|
||||
/opt/work-hub/compat/layouts/<хост>.json и переиспользуются.
|
||||
|
||||
Страница: /editor?host=MeetingBar%20A30&item=A40:2
|
||||
Данные: /load?host=... (GET)
|
||||
Сохранение:/save (POST, нужен X-Token с правом записи)
|
||||
Экспорт: /render?host=... (GET, отдаёт SVG)
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
|
||||
sys.path.insert(0, "/root/buryan-infra/ops/work/web")
|
||||
from svc_base import serve # noqa: E402
|
||||
import combine_core as cc # noqa: E402
|
||||
|
||||
C = cc.Core()
|
||||
BASE = "/opt/work-hub/compat"
|
||||
LAY = os.path.join(BASE, "layouts")
|
||||
os.makedirs(LAY, exist_ok=True)
|
||||
W, H = 1100, 620
|
||||
|
||||
COLOR = {"HDMI": "#2f81f7", "USB": "#3fb950", "USB-C": "#3fb950", "VCH": "#a371f7",
|
||||
"LAN": "#d29922", "3.5mm": "#8b949e", "DP": "#a371f7", "RJ-9": "#8b949e",
|
||||
"—": "#484f58"}
|
||||
|
||||
|
||||
def esc(s):
|
||||
return (str(s).replace("&", "&").replace("<", "<").replace(">", ">")
|
||||
.replace('"', """))
|
||||
|
||||
|
||||
def items_of(q):
|
||||
out = []
|
||||
for raw in (q.get("item") or []):
|
||||
if ":" in raw:
|
||||
m, n = raw.rsplit(":", 1)
|
||||
try:
|
||||
out.append([m, int(n)])
|
||||
except ValueError:
|
||||
pass
|
||||
else:
|
||||
out.append([raw, 1])
|
||||
return out
|
||||
|
||||
|
||||
def path_of(hk):
|
||||
return os.path.join(LAY, hk + ".json")
|
||||
|
||||
|
||||
def auto_layout(hk, q):
|
||||
"""Узлы и связи так же, как в авто-схеме, но в виде данных."""
|
||||
if hk not in C.devices:
|
||||
return None
|
||||
host = C.devices[hk]["name"]
|
||||
plan = C.port_plan(hk, items_of(q))
|
||||
rows = [r for r in plan["rows"] if r["device"] not in ("", None)]
|
||||
n = max(len(rows), 1)
|
||||
nodes = []
|
||||
for i, r in enumerate(rows):
|
||||
step = (H - 120) / n
|
||||
nodes.append({
|
||||
"id": "n%d" % i,
|
||||
"label": r["device"],
|
||||
"sub": ("→ " + str(r["host_port"])) if r["ok"] else "нет порта",
|
||||
"note": r["needs_port"] or "?",
|
||||
"ok": bool(r["ok"]),
|
||||
"x": 175 if i % 2 == 0 else 925,
|
||||
"y": round(60 + step * i + step / 2, 1),
|
||||
})
|
||||
return {"host": host, "hk": hk, "nodes": nodes, "edges": [],
|
||||
"texts": [], "lines": [], "W": W, "H": H,
|
||||
"free_in": plan["free_in"], "free_out": plan["free_out"],
|
||||
"unresolved": plan["unresolved"]}
|
||||
|
||||
|
||||
def load(q, body):
|
||||
hk = cc.norm((q.get("host") or [""])[0])
|
||||
base = auto_layout(hk, q)
|
||||
if not base:
|
||||
return {"error": "хост не найден", "host": (q.get("host") or [""])[0]}
|
||||
try:
|
||||
saved = json.load(open(path_of(hk), encoding="utf-8"))
|
||||
except Exception:
|
||||
saved = None
|
||||
if saved:
|
||||
by_label = {str(n.get("label")): n for n in (saved.get("nodes") or [])}
|
||||
for n in base["nodes"]:
|
||||
s = by_label.get(str(n["label"]))
|
||||
if s:
|
||||
n["x"], n["y"] = s.get("x", n["x"]), s.get("y", n["y"])
|
||||
base["texts"] = saved.get("texts") or []
|
||||
base["lines"] = saved.get("lines") or []
|
||||
base["saved"] = True
|
||||
return base
|
||||
|
||||
|
||||
def save(q, body):
|
||||
body = body or {}
|
||||
hk = cc.norm(body.get("host") or "")
|
||||
if not hk:
|
||||
return {"error": "не указан хост"}
|
||||
data = {"host": body.get("host"), "nodes": body.get("nodes") or [],
|
||||
"texts": body.get("texts") or [], "lines": body.get("lines") or [],
|
||||
"updated": __import__("time").strftime("%Y-%m-%dT%H:%M:%S")}
|
||||
json.dump(data, open(path_of(hk), "w", encoding="utf-8"),
|
||||
ensure_ascii=False, indent=1)
|
||||
return {"ok": True, "saved": path_of(hk),
|
||||
"nodes": len(data["nodes"]), "texts": len(data["texts"]),
|
||||
"lines": len(data["lines"])}
|
||||
|
||||
|
||||
def render(q, body):
|
||||
"""SVG из сохранённой раскладки."""
|
||||
d = load(q, body)
|
||||
if d.get("error"):
|
||||
return d
|
||||
cx, cy, bw, bh = W // 2, H // 2, 210, 110
|
||||
p = ['<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 %d %d" width="%d" '
|
||||
'height="%d" style="background:#0a0e13">' % (W, H, W, H)]
|
||||
p.append('<rect x="%d" y="%d" width="%d" height="%d" rx="12" fill="#132239" '
|
||||
'stroke="#2f81f7" stroke-width="2"/>' % (cx - bw // 2, cy - bh // 2, bw, bh))
|
||||
p.append('<text x="%d" y="%d" fill="#e6edf3" font-size="14" font-weight="600">%s</text>'
|
||||
% (cx - bw // 2 + 14, cy - bh // 2 + 24, esc(d["host"])[:26]))
|
||||
for n in d["nodes"]:
|
||||
col = "#3fb950" if n.get("ok") else "#f85149"
|
||||
p.append('<path d="M %d %d L %s %s" stroke="%s" stroke-width="2" opacity="0.7" '
|
||||
'fill="none"/>' % (cx, cy, n["x"], n["y"], col))
|
||||
p.append('<rect x="%s" y="%s" width="210" height="60" rx="10" fill="#161b22" '
|
||||
'stroke="%s" stroke-width="1.4"/>' % (n["x"] - 105, n["y"] - 30, col))
|
||||
p.append('<text x="%s" y="%s" text-anchor="middle" fill="#e6edf3" font-size="12" '
|
||||
'font-weight="600">%s</text>' % (n["x"], n["y"] - 6, esc(n["label"])[:24]))
|
||||
p.append('<text x="%s" y="%s" text-anchor="middle" fill="#8b949e" font-size="9.5">'
|
||||
'%s</text>' % (n["x"], n["y"] + 10, esc(n.get("sub", ""))))
|
||||
for ln in d.get("lines") or []:
|
||||
p.append('<line x1="%s" y1="%s" x2="%s" y2="%s" stroke="%s" stroke-width="2"/>'
|
||||
% (ln.get("x1"), ln.get("y1"), ln.get("x2"), ln.get("y2"),
|
||||
ln.get("color", "#8b949e")))
|
||||
for t in d.get("texts") or []:
|
||||
p.append('<text x="%s" y="%s" fill="%s" font-size="%s">%s</text>'
|
||||
% (t.get("x"), t.get("y"), t.get("color", "#e6edf3"),
|
||||
t.get("size", 12), esc(t.get("text", ""))))
|
||||
p.append("</svg>")
|
||||
return {"ok": True, "svg": "".join(p)}
|
||||
|
||||
|
||||
EDITOR = r"""<!doctype html><html lang="ru"><head><meta charset="utf-8">
|
||||
<title>Схема — ручной режим</title>
|
||||
<style>
|
||||
body{margin:0;background:#0a0e13;color:#e6edf3;font-family:Segoe UI,system-ui,sans-serif}
|
||||
header{padding:10px 16px;background:#0d1117;border-bottom:1px solid #233040;
|
||||
display:flex;gap:10px;align-items:center;flex-wrap:wrap}
|
||||
button{background:#21262d;color:#e6edf3;border:1px solid #30363d;border-radius:6px;
|
||||
padding:6px 10px;cursor:pointer;font-size:13px}
|
||||
button.pri{background:#238636;border-color:#2ea043}
|
||||
input{background:#0d1117;border:1px solid #30363d;color:#e6edf3;border-radius:6px;
|
||||
padding:5px 8px;font-size:13px}
|
||||
#wrap{position:relative;width:1100px;margin:14px auto}
|
||||
svg{background:#0a0e13;border:1px solid #233040;border-radius:10px;display:block}
|
||||
.node{cursor:move}
|
||||
#hint{margin-left:auto;color:#8b949e;font-size:12px}
|
||||
</style></head><body>
|
||||
<header>
|
||||
<b>Схема: ручной режим</b>
|
||||
<span id="hostName"></span>
|
||||
<button class="pri" onclick="saveAll()">Сохранить</button>
|
||||
<button onclick="addText()">+ Подпись</button>
|
||||
<button onclick="mode= (mode==='line'?'move':'line');this.textContent = mode==='line'?'Линия: ткни 2 точки':'+ Линия'">+ Линия</button>
|
||||
<button onclick="resetLayout()">Сброс</button>
|
||||
<button onclick="exportSvg()">Экспорт SVG</button>
|
||||
<input id="tok" type="password" placeholder="X-Token (editor)" size="18">
|
||||
<span id="hint"></span>
|
||||
</header>
|
||||
<div id="wrap"><svg id="svg" width="1100" height="620"></svg></div>
|
||||
<script>
|
||||
let L=null, mode='move', drag=null, lineStart=null;
|
||||
const q=new URLSearchParams(location.search);
|
||||
const svg=document.getElementById('svg');
|
||||
function n(t,a){const e=document.createElementNS('http://www.w3.org/2000/svg',t);
|
||||
for(const k in a)e.setAttribute(k,a[k]);return e;}
|
||||
async function loadAll(){
|
||||
const r=await fetch('/load?'+q.toString()); const d=await r.json();
|
||||
if(d.error){document.getElementById('hint').textContent=d.error;return;}
|
||||
L=d; document.getElementById('hostName').textContent=d.host;
|
||||
draw(); document.getElementById('hint').textContent=d.saved?'сохранённая раскладка':'авто-раскладка';
|
||||
}
|
||||
function draw(){
|
||||
while(svg.firstChild)svg.removeChild(svg.firstChild);
|
||||
const cx=550,cy=310;
|
||||
svg.appendChild(n('rect',{x:cx-105,y:cy-55,width:210,height:110,rx:12,
|
||||
fill:'#132239',stroke:'#2f81f7','stroke-width':2}));
|
||||
const t=n('text',{x:cx-91,y:cy-31,fill:'#e6edf3','font-size':14,'font-weight':600});
|
||||
t.textContent=(L.host||'').slice(0,26); svg.appendChild(t);
|
||||
(L.nodes||[]).forEach(nd=>{
|
||||
const col=nd.ok?'#3fb950':'#f85149';
|
||||
svg.appendChild(n('path',{d:`M ${cx} ${cy} L ${nd.x} ${nd.y}`,stroke:col,
|
||||
'stroke-width':2,opacity:'0.7',fill:'none'}));
|
||||
const g=n('g',{class:'node','data-id':nd.id});
|
||||
g.appendChild(n('rect',{x:nd.x-105,y:nd.y-30,width:210,height:60,rx:10,
|
||||
fill:'#161b22',stroke:col,'stroke-width':1.4}));
|
||||
const a=n('text',{x:nd.x,y:nd.y-6,'text-anchor':'middle',fill:'#e6edf3',
|
||||
'font-size':12,'font-weight':600}); a.textContent=(nd.label||'').slice(0,24); g.appendChild(a);
|
||||
const b=n('text',{x:nd.x,y:nd.y+10,'text-anchor':'middle',fill:'#8b949e','font-size':9.5});
|
||||
b.textContent=nd.sub||''; g.appendChild(b);
|
||||
g.addEventListener('mousedown',e=>{drag={id:nd.id,dx:e.offsetX-nd.x,dy:e.offsetY-nd.y};e.preventDefault();});
|
||||
svg.appendChild(g);
|
||||
});
|
||||
(L.lines||[]).forEach(ln=>{
|
||||
svg.appendChild(n('line',{x1:ln.x1,y1:ln.y1,x2:ln.x2,y2:ln.y2,
|
||||
stroke:ln.color||'#8b949e','stroke-width':2}));
|
||||
});
|
||||
(L.texts||[]).forEach(tx=>{
|
||||
const e=n('text',{x:tx.x,y:tx.y,fill:tx.color||'#e6edf3','font-size':tx.size||12,
|
||||
style:'cursor:move'});
|
||||
e.textContent=tx.text||''; e.addEventListener('mousedown',ev=>{
|
||||
drag={text:tx,dx:ev.offsetX-tx.x,dy:ev.offsetY-tx.y};ev.preventDefault();});
|
||||
svg.appendChild(e);
|
||||
});
|
||||
}
|
||||
svg.addEventListener('mousemove',e=>{
|
||||
if(!drag)return;
|
||||
if(drag.id){const nd=L.nodes.find(x=>x.id===drag.id); nd.x=e.offsetX-drag.dx; nd.y=e.offsetY-drag.dy;}
|
||||
if(drag.text){drag.text.x=e.offsetX-drag.dx; drag.text.y=e.offsetY-drag.dy;}
|
||||
draw();
|
||||
});
|
||||
svg.addEventListener('mouseup',()=>{drag=null;});
|
||||
svg.addEventListener('click',e=>{
|
||||
if(mode!=='line')return;
|
||||
const p={x:e.offsetX,y:e.offsetY};
|
||||
if(!lineStart){lineStart=p;document.getElementById('hint').textContent='вторая точка…';return;}
|
||||
L.lines=L.lines||[]; L.lines.push({x1:lineStart.x,y1:lineStart.y,x2:p.x,y2:p.y,color:'#8b949e'});
|
||||
lineStart=null; mode='move'; document.getElementById('hint').textContent='линия добавлена'; draw();
|
||||
});
|
||||
function addText(){
|
||||
const s=prompt('Текст подписи:'); if(!s)return;
|
||||
L.texts=L.texts||[]; L.texts.push({text:s,x:200,y:60,color:'#e6edf3',size:12}); draw();
|
||||
}
|
||||
async function saveAll(){
|
||||
const token=document.getElementById('tok').value;
|
||||
if(!token){document.getElementById('hint').textContent='нужен X-Token';return;}
|
||||
const body={host:L.host,nodes:L.nodes,texts:L.texts,lines:L.lines};
|
||||
const r=await fetch('/save',{method:'POST',headers:{'Content-Type':'application/json','X-Token':token},
|
||||
body:JSON.stringify(body)});
|
||||
const d=await r.json();
|
||||
document.getElementById('hint').textContent=d.ok?('сохранено: узлов '+d.nodes+', линий '+d.lines):(d.error||'ошибка');
|
||||
}
|
||||
async function resetLayout(){
|
||||
if(!confirm('Вернуть авто-раскладку? Сохранение сотрёт ручную.'))return;
|
||||
const r=await fetch('/load?'+q.toString()+'&fresh=1'); const d=await r.json();
|
||||
L.nodes=d.nodes; L.texts=[]; L.lines=[]; draw();
|
||||
document.getElementById('hint').textContent='авто-раскладка (не сохранено)';
|
||||
}
|
||||
function exportSvg(){
|
||||
const blob=new Blob([new XMLSerializer().serializeToString(svg)],{type:'image/svg+xml'});
|
||||
const a=document.createElement('a'); a.href=URL.createObjectURL(blob);
|
||||
a.download=(L.host||'schema')+'.svg'; a.click();
|
||||
}
|
||||
loadAll();
|
||||
</script></body></html>"""
|
||||
|
||||
|
||||
def editor(q, body):
|
||||
return {"__html": EDITOR}
|
||||
|
||||
|
||||
serve({
|
||||
"/load": load,
|
||||
"/save": save,
|
||||
"/render": render,
|
||||
"/editor": editor,
|
||||
}, int(sys.argv[1]) if len(sys.argv) > 1 else 8106, "drawedit", before=C.reload_if_changed)
|
||||
@@ -59,6 +59,17 @@ def serve(routes, port, name, before=None):
|
||||
self.wfile.write(data)
|
||||
|
||||
def _send(self, obj, code=200):
|
||||
# страницы: {"__html": "<!doctype html>..."} — отдаём как text/html
|
||||
if isinstance(obj, dict) and obj.get("__html") is not None:
|
||||
data = obj["__html"].encode("utf-8")
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Type", "text/html; charset=utf-8")
|
||||
self.send_header("Content-Length", str(len(data)))
|
||||
for k, v in CORS.items():
|
||||
self.send_header(k, v)
|
||||
self.end_headers()
|
||||
self.wfile.write(data)
|
||||
return
|
||||
if isinstance(obj, dict) and obj.get("__file__"):
|
||||
return self._send_file(obj["__file__"], obj.get("filename", "file"),
|
||||
obj.get("content_type", "application/octet-stream"))
|
||||
|
||||
Reference in new issue
Block a user