diff --git a/ops/work/ARCHITECTURE.md b/ops/work/ARCHITECTURE.md new file mode 100644 index 0000000..b4cb06d --- /dev/null +++ b/ops/work/ARCHITECTURE.md @@ -0,0 +1,78 @@ +# Архитектура комбайна: сервисы + +Дата: 06.11.2026. Переход от одного файла к сервисам. + +## Сервисы (все запущены, systemd) + +| Сервис | Порт | За что отвечает | +|---|---|---| +| **combine-catalog** | 8101 | устройства, порты, комплектация, функции, матрица, полнота данных | +| **combine-engine** | 8102 | совместимость, группы, ёмкость VCH/PoE, **подсчёт портов**, **кабельный журнал**, BOM | +| **combine-project** | 8103 | сохранение, список, **версии** (история до 10), удаление | +| **combine-draw** | 8104 | **SVG-схема соединений**, кабельный журнал | +| **combine-docs** | 8105 | документы по устройству (даташиты из зеркала Nextcloud) | + +Общий код: `combine_core.py` — доменная логика (совместимость, порты, ёмкость, кабели). +База: `svc_base.py` — HTTP + JSON + CORS + роутинг. + +## Ключевые новые возможности + +### 1. Подсчёт портов (`/ports`) +Возвращает: какие порты хоста заняты, какие свободны, что не удалось подключить. +``` +/ports?host=meetingbara50&item=UVC86&item=CTP25 +→ free_in: [VCH, USB-C, LAN], free_out: [HDMI, USB, 3.5mm] +``` + +### 2. Кабельный журнал (`/cables`) +Что с чем соединяется и каким разъёмом, с пометкой «в комплекте». +``` +USB → UVC86 USB в комплекте +USB → CTP25 USB +USB → WPP30 USB-C в комплекте +``` + +### 3. Схема соединений (`/diagram`) +SVG с портами хоста слева/справа, устройствами и связями по типу разъёма. + +### 4. Версии проектов (`/save`) +При каждом сохранении — запись в историю (последние 10 версий). + +### 5. Документы (`/docs?device=UVC86`) +Индекс PDF из зеркала Nextcloud, поиск по модели, тип документа. + +## Приоритет портов + +Порты подбираются по роли устройства: +| Роль | Приоритет | +|---|---| +| дисплей | HDMI → DP → USB-C | +| камера | USB → USB-C → LAN → HDMI | +| аудио | VCH → USB → USB-C | +| панель | USB → LAN | + +## Проверено фактами + +``` +combine-catalog active /hosts 200 · /matrix 200 +combine-engine active /cables 4 кабеля, 0 нерешённых +combine-draw active /diagram SVG 2.9 КБ +combine-project active /list 200 +combine-docs active /docs 200 +``` + +## Известные дефекты + +1. **MeetingDisplay получает USB вместо HDMI** — у устройства есть извлечённые + порты, которые перекрывают правило роли. Требует выверки портов. +2. UI пока работает на старом `app.py` (порт 8095). Перенос на сервисы — следующий шаг. +3. Ёмкость цепочек VCH не считается по-настоящему: нужны порты in/out у + аксессуаров и ёмкость цепи (данные добываются LLM). + +## Что дальше + +1. Перевести интерфейс на сервисы (сейчас дублирование логики) +2. Экспорт: BOM в XLSX, схема в PNG/SVG +3. Чек-лист полноты проекта +4. Автозаполнение состава +5. Кабельный журнал — в UI отдельной вкладкой diff --git a/ops/work/web/app.py b/ops/work/web/app.py index 17b2586..c8cde92 100644 --- a/ops/work/web/app.py +++ b/ops/work/web/app.py @@ -13,6 +13,7 @@ import urllib.parse from http.server import BaseHTTPRequestHandler BASE = "/opt/work-hub/compat" +PROJECTS_DIR = "/opt/work-hub/compat/projects" # направления (в перспективе — все три, сейчас ВКС) VENDORS = [ @@ -352,6 +353,27 @@ class Data: return {"host": host, "host_ports": {"in": h_in, "out": h_out, "source": h_src}, "links": links} + # ── полнота данных по хосту ── data_completeness + def data_completeness(self, host_key): + hk = norm(host_key) + srcs = {} + for e in self.edges.get(hk, []): + srcs[e.get("source") or "?"] = srcs.get(e.get("source") or "?", 0) + 1 + total = sum(srcs.values()) + supported = sum(1 for e in self.edges.get(hk, []) if e.get("supported")) + if "matrix" in srcs and "accessories_list" in srcs: + level, note = "full", "два официальных источника: матрица + лист аксессуаров" + elif "matrix" in srcs: + level, note = "partial", "только матрица — лист аксессуаров не найден" + elif "accessories_list" in srcs: + level, note = "sparse", ("только лист аксессуаров (%d строк) — в основной " + "матрице Yealink этого хоста нет, данные могут быть " + "неполными" % total) + else: + level, note = "none", "связей нет — данных о совместимости не найдено" + return {"level": level, "note": note, "edges": total, + "supported": supported, "sources": srcs} + # ── группы оборудования ── def groups(self, host_key, need=None): need_n = {norm(x) for x in (need or [])} @@ -410,7 +432,8 @@ class Data: if items: out.append({"id": g["id"], "name": g["name"], "hint": "", "items": sorted(items, key=lambda x: x["model"])}) - return {"host": self.devices[hk]["name"], "groups": out} + return {"host": self.devices[hk]["name"], "groups": out, + "completeness": self.data_completeness(hk)} # ── проверка одной пары: хост + устройство ── def check_pair(self, host_key, accessory): @@ -836,6 +859,49 @@ class Data: D = Data() +def _ensure_dir(): + os.makedirs(PROJECTS_DIR, exist_ok=True) + + +def list_projects(): + _ensure_dir() + out = [] + for f in sorted(os.listdir(PROJECTS_DIR), reverse=True): + if not f.endswith(".json"): + continue + try: + d = json.load(open(os.path.join(PROJECTS_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 []), + "updated": d.get("updated")}) + return {"projects": out[:50]} + + +def load_project(pid): + if not pid or not re.match(r"^[\w-]{1,32}$", pid): + return {"error": "bad id"} + p = os.path.join(PROJECTS_DIR, pid + ".json") + if not os.path.exists(p): + return {"error": "not found"} + return json.load(open(p, encoding="utf-8")) + + +def save_project(payload): + _ensure_dir() + pid = payload.get("id") or ("p" + str(int(__import__("time").time()))) + if not re.match(r"^[\w-]{1,32}$", str(pid)): + return {"error": "bad id"} + payload["id"] = pid + payload["updated"] = __import__("time").strftime("%Y-%m-%dT%H:%M:%S") + if not payload.get("created"): + payload["created"] = payload["updated"] + with open(os.path.join(PROJECTS_DIR, str(pid) + ".json"), "w", encoding="utf-8") as f: + json.dump(payload, f, ensure_ascii=False, indent=2) + return {"ok": True, "id": pid} + + class H(BaseHTTPRequestHandler): def _out(self, obj, code=200, ctype="application/json; charset=utf-8"): body = obj if isinstance(obj, bytes) else json.dumps(obj, ensure_ascii=False).encode() @@ -878,6 +944,18 @@ class H(BaseHTTPRequestHandler): if p == "/api/positions": return self._out(D.positions(q.get("host", [""])[0], [x for x in q.get("need", []) if x])) + if p == "/api/projects": + return self._out(list_projects()) + if p == "/api/project": + pid = q.get("id", [""])[0] + return self._out(load_project(pid)) + if p == "/api/save": + try: + length = int(self.headers.get("Content-Length") or 0) + payload = json.loads(self.rfile.read(length).decode() or "{}") + except Exception as e: + return self._out({"error": "bad json: %s" % e}, 400) + return self._out(save_project(payload)) if p == "/api/gaps": return self._out({"missing": D.extra.get("missing") or []}) if p == "/api/kits": @@ -915,6 +993,18 @@ class H(BaseHTTPRequestHandler): return self._out({"error": "not found"}, 404) + def do_POST(self): + u = urllib.parse.urlparse(self.path) + if u.path == "/api/save": + try: + n = int(self.headers.get("Content-Length") or 0) + payload = json.loads(self.rfile.read(n).decode() or "{}") + except Exception as e: + return self._out({"error": "bad json: %s" % e}, 400) + return self._out(save_project(payload)) + return self._out({"error": "not found"}, 404) + + class S(socketserver.ThreadingTCPServer): allow_reuse_address = True diff --git a/ops/work/web/combine_core.py b/ops/work/web/combine_core.py new file mode 100644 index 0000000..0cf660d --- /dev/null +++ b/ops/work/web/combine_core.py @@ -0,0 +1,353 @@ +#!/usr/bin/env python3 +"""Ядро комбайна: модели данных и доменная логика. + +Используется всеми сервисами (catalog, engine, draw, project, docs). +Никакого HTTP здесь — только данные и расчёты. +""" +import glob +import json +import os +import re + +BASE = "/opt/work-hub/compat" +PROJECTS_DIR = os.path.join(BASE, "projects") + + +def norm(s): + return re.sub(r"[^a-z0-9]", "", str(s).lower()) + + +def load(name): + import yaml + p = os.path.join(BASE, name) + if not os.path.exists(p): + return {} + try: + return yaml.safe_load(open(p, encoding="utf-8")) or {} + except Exception: + return {} + + +class Core: + """Единая точка доступа к данным модели.""" + + POSITIONS_ROLE = { + "display": {"in": ["HDMI"], "out": []}, + "camera": {"in": ["LAN"], "out": ["USB", "HDMI"]}, + "audio": {"in": ["VCH"], "out": ["VCH"]}, + "speaker": {"in": ["VCH"], "out": []}, + "touch": {"in": ["LAN"], "out": ["USB"]}, + "sharing_or_hub": {"in": ["USB"], "out": ["HDMI"]}, + "codec": {"in": ["LAN"], "out": ["HDMI", "USB", "VCH"]}, + "mount": {"in": [], "out": []}, + "infrastructure": {"in": ["LAN"], "out": ["LAN"]}, + } + + ROLE_PORT_PREF = { + "display": ["HDMI", "DP", "USB-C"], + "camera": ["USB", "USB-C", "LAN", "HDMI"], + "audio": ["VCH", "USB", "USB-C"], + "speaker": ["VCH"], + "touch": ["USB", "LAN", "USB-C"], + "sharing_or_hub": ["USB", "USB-C", "HDMI", "VCH"], + } + + PORT_RANK = {"USB": 0, "USB-C": 1, "VCH": 2, "RJ-9": 3, "3.5mm": 4, + "LAN": 5, "HDMI": 6, "DP": 7} + + LINKABLE = { + ("HDMI", "HDMI"): "видео", + ("USB", "USB"): "данные", + ("USB-C", "USB-C"): "данные+видео", + ("USB", "USB-C"): "данные (переходник)", + ("USB-C", "USB"): "данные (переходник)", + ("VCH", "VCH"): "аудио+питание", + ("LAN", "LAN"): "сеть/PoE", + ("3.5mm", "3.5mm"): "аналоговый звук", + ("DP", "DP"): "видео", + ("RJ-9", "RJ-9"): "телефон", + } + + FEATURE_ROLE = { + "aec": "audio", "anc": "audio", "dante": "audio", "aes67": "audio", + "autoframing": "camera", "speakertracking": "camera", + "presentertracking": "camera", "4k": "camera", + "airplay": "sharing_or_hub", "miracast": "sharing_or_hub", + "usbc": "sharing_or_hub", "poe": "infrastructure", + "teams": "codec", "zoom": "codec", "h323": "codec", "sip": "codec", + } + + GROUP_DEFS = [ + {"id": "mic", "name": "Микрофоны", "roles": ["audio"], + "skip": r"^CP50|^CP965|^CPE|^CP\d|^PA\d|^CS10-D|^CLS120"}, + {"id": "speaker", "name": "Громкоговорители", "roles": ["speaker"], + "extra": r"^CS10-D|^CLS120|^MSpeaker"}, + {"id": "camera", "name": "Камеры", "roles": ["camera"]}, + {"id": "panel", "name": "Панели управления", "roles": ["touch", "remote"]}, + {"id": "sharing", "name": "Презентация и хабы", "roles": ["sharing_or_hub"]}, + {"id": "phone", "name": "Аудиоустройства и телефоны", "roles": ["audio"], + "only": r"^CP50|^CP965|^CPE|^CP\d|^PA\d"}, + {"id": "display", "name": "Дисплеи", "roles": ["display"]}, + {"id": "mount", "name": "Кронштейны", "roles": ["mount"]}, + {"id": "infra", "name": "Инфраструктура (PoE, хабы)", "roles": []}, + ] + + def __init__(self): + self.cat = load("catalog.yaml") + self.graph = load("graph.yaml") + self.values = load("values.yaml") + self.features = load("features.yaml") + self.protocols = load("protocols.yaml") + self.mounts = load("mounts.yaml") + self.dante = load("dante.yaml") + self.iface_v = load("interfaces_verified.yaml") + self.iface_a = load("interfaces.yaml") + self.pkg_v = load("package_verified.yaml") + self.pkg_a = load("package.yaml") + self.limits = load("limitations.yaml") + self.infra = load("infrastructure.yaml") + self.kits = load("kits.yaml") + self.extra = load("specs_extra.yaml") + self.i_extract = load("interfaces_extract.yaml") + self.s_extract = load("specs_extract.yaml") + self.p_extract = load("package_extract.yaml") + self.rebuild() + + def rebuild(self): + self.devices = {norm(d["name"]): {"name": d["name"], "role": d.get("role", "unknown")} + for d in self.cat.get("devices") or []} + self.edges = {} + for e in self.graph.get("edges") or []: + self.edges.setdefault(norm(e.get("from")), []).append(e) + self.attrs = {} + for x in self.values.get("devices") or []: + self.attrs[norm(x.get("device"))] = dict(x.get("attributes") or {}) + for x in (self.extra.get("devices") or []): + k = norm(x["device"]) + self.attrs.setdefault(k, {}) + for ak, av in (x.get("attributes") or {}).items(): + self.attrs[k].setdefault(ak, av) + for x in (self.s_extract.get("devices") or []): + k = norm(x["device"]) + self.attrs.setdefault(k, {}) + for ak, av in (x.get("attributes") or {}).items(): + self.attrs[k].setdefault(ak, av) + self.feats = {} + for src in (self.features, self.protocols): + for x in src.get("devices") or []: + f = x.get("features") or {} + self.feats.setdefault(norm(x.get("device")), set()).update( + f.keys() if isinstance(f, dict) else f) + for x in self.dante.get("dante_devices") or []: + self.feats.setdefault(norm(x.get("device")), set()).add("Dante") + self.iface_map = {norm(x["device"]): x for x in self.iface_v.get("devices") or []} + self.iface_auto = {norm(x["device"]): x for x in self.iface_a.get("devices") or []} + self.iface_ext = {norm(x["device"]): x for x in self.i_extract.get("devices") or [] + if x.get("in") or x.get("out")} + self.pkg_map = {norm(x["device"]): x for x in self.pkg_v.get("devices") or []} + self.pkg_llm = {norm(x["device"]): (x.get("items") or []) + for x in self.p_extract.get("devices") or []} + self.mounts_map = {} + for e in self.mounts.get("edges") or []: + self.mounts_map.setdefault(norm(e["host"]), []).append(e["mount"]) + + # ── порты ── + def ports(self, name): + k = norm(name) + if k in self.iface_map: + v = self.iface_map[k] + return list(v.get("in") or ["—"]), list(v.get("out") or ["—"]), "verified" + if k in self.iface_ext: + v = self.iface_ext[k] + return list(v.get("in") or ["—"]), list(v.get("out") or ["—"]), "datasheet-llm" + if k in self.iface_auto: + v = self.iface_auto[k] + ins = [p for p in (v.get("in") or []) if p] + outs = [p for p in (v.get("out") or []) if p] + if ins or outs: + return ins or ["—"], outs or ["—"], "auto" + role = self.devices.get(k, {}).get("role", "unknown") + d = self.POSITIONS_ROLE.get(role, {"in": ["LAN"], "out": ["—"]}) + return list(d["in"]), list(d["out"]) or ["—"], "role" + + # ── комплектация ── + def package(self, name): + k = norm(name) + p = self.pkg_map.get(k) + if p: + return {"items": p.get("items") or [], + "kits": p.get("optional_kits") or [], "source": "verified"} + if self.pkg_llm.get(k): + return {"items": self.pkg_llm[k], "kits": [], "source": "llm"} + for x in self.pkg_a.get("devices") or []: + if norm(x.get("device")) == k: + return {"items": x.get("items") or [], "kits": [], "source": "auto"} + return {"items": [], "kits": [], "source": None} + + # ── полнота данных ── + def completeness(self, host_key): + hk = norm(host_key) + srcs = {} + for e in self.edges.get(hk, []): + s = e.get("source") or "?" + srcs[s] = srcs.get(s, 0) + 1 + total = sum(srcs.values()) + if "matrix" in srcs and "accessories_list" in srcs: + level, note = "full", "два источника: матрица + лист аксессуаров" + elif "matrix" in srcs: + level, note = "partial", "только матрица" + elif "accessories_list" in srcs: + level, note = "sparse", ("только лист аксессуаров (%d строк) — в матрице хоста нет" + % total) + else: + level, note = "none", "связей нет" + return {"level": level, "note": note, "edges": total, "sources": srcs} + + # ── совместимость ── + def edges_of(self, host_key, supported_only=True): + out = [] + for e in self.edges.get(norm(host_key), []): + if supported_only and (not e.get("supported") or not e.get("usable", True)): + continue + out.append(e) + return out + + def check_pair(self, host_key, device): + hk, ak = norm(host_key), norm(device) + host = self.devices.get(hk, {}).get("name") + dev = self.devices.get(ak, {}).get("name") or device + if not host: + return {"error": "хост не найден"} + found = next((e for e in self.edges.get(hk, []) if norm(e["to"]) == ak), None) + if not found: + return {"host": host, "device": dev, "known": False, "supported": False, + "verdict": "нет в матрице для этого хоста"} + cond = re.sub(r"^[\u221a\u2713\u2714\u00d7\u2717\u2718\u2022\s]+", "", + found.get("condition") or "").strip() + if not found.get("usable", True): + verdict = "исключено: источники расходятся" + elif found.get("supported"): + q = found.get("max_qty") + verdict = "совместимо" + (" (до %s шт)" % q if q else "") + else: + verdict = "несовместимо" + return {"host": host, "device": dev, "known": True, + "supported": bool(found.get("supported")), + "usable": found.get("usable", True), + "max_qty": found.get("max_qty"), "condition": cond, + "source": found.get("source"), "verdict": verdict} + + # ── ёмкость и подсчёт портов ── + def capacity(self, host_key, items, infra_items=None): + hk = norm(host_key) + host = self.devices.get(hk, {}).get("name") + ha = self.attrs.get(hk, {}) + vch_ports = ha.get("ports.vch") + total_w, missing_w, vch_users = 0.0, [], 0 + qtys = {} + for row in items: + model, qty = row[0], int(row[1]) + qtys[model] = qtys.get(model, 0) + qty + limits = {norm(e["to"]): (e.get("max_qty"), e["to"]) + for e in self.edges.get(hk, []) if e.get("supported")} + issues = [] + for model, q in qtys.items(): + lim, name = limits.get(norm(model), (None, model)) + if lim and q > lim: + issues.append("%s: %d шт при лимите %d" % (name, q, lim)) + a = self.attrs.get(norm(model), {}) + w = a.get("power.consumption_w") + if w: + total_w += w * q + else: + missing_w.append(model) + if a.get("audio.pickup_m") or a.get("ports.vch"): + vch_users += q + + # инфраструктура добавляет порты и бюджет + extra_ports, extra_budget = 0, 0.0 + for inf in (infra_items or []): + for x in (self.infra.get("devices") or []): + if norm(x["device"]) == norm(inf): + sp = x.get("specs") or {} + extra_ports += int(sp.get("poe_ports") or 0) + extra_budget += float(sp.get("poe_budget_w") or 0) + + chains_needed = None + if vch_users and vch_ports is not None: + total_ports = int(vch_ports) + extra_ports + chains_needed = vch_users if total_ports < vch_users else 1 + if vch_users > total_ports: + issues.append("VCH: %d устройств на %d порт(а) — нужны цепочки или RCH40 E2" + % (vch_users, total_ports)) + return {"host": host, "vch_ports": vch_ports, "vch_users": vch_users, + "extra_ports": extra_ports, "extra_budget_w": extra_budget, + "total_power_w": round(total_w, 1), + "power_budget_w": extra_budget or None, + "missing_power": sorted(set(missing_w)), + "issues": issues, "chains_needed": chains_needed} + + # ── подсчёт портов (port accounting) ── + def port_plan(self, host_key, items): + hk = norm(host_key) + host = self.devices.get(hk, {}).get("name") + h_in, h_out, h_src = self.ports(host) + used_in, used_out = [], [] + rows = [] + for row in items: + model, qty = row[0], int(row[1]) if len(row) > 1 else 1 + a_in, a_out, src = self.ports(model) + need = [p for p in a_out if p != "—"] or [p for p in a_in if p != "—"] + port = need[0] if need else None + slot = None + if port: + cands = [] + # устройство -> вход хоста + for ap in [p for p in (a_out + a_in) if p != "—"]: + for hp in h_in: + if (ap, hp) in self.LINKABLE or (hp, ap) in self.LINKABLE: + cands.append((self.PORT_RANK.get(ap, 9), ap, hp)) + # выход хоста -> устройство + for hp in h_out: + for ap in [p for p in (a_in + a_out) if p != "—"]: + if (hp, ap) in self.LINKABLE or (ap, hp) in self.LINKABLE: + cands.append((self.PORT_RANK.get(ap, 9) + 100, ap, "out:" + hp)) + if cands: + role = self.devices.get(norm(model), {}).get("role") + pref = self.ROLE_PORT_PREF.get(role) or [] + + def rank(item): + r, ap, hp = item + if ap in pref: + return pref.index(ap) + return 90 + r + cands.sort(key=rank) + _, port, slot = cands[0] + if slot and slot.startswith("out:"): + used_out.append(slot[4:]) + elif slot: + used_in.append(slot) + rows.append({"device": model, "qty": qty, "needs_port": port, + "host_port": slot, "source": src, + "ok": bool(slot)}) + return {"host": host, "host_in": h_in, "host_out": h_out, "source": h_src, + "rows": rows, + "used_in": used_in, "used_out": used_out, + "free_in": [p for p in h_in if p not in used_in], + "free_out": [p for p in h_out if p not in used_out], + "unresolved": [r["device"] for r in rows if not r["ok"]]} + + # ── кабельный журнал ── + def cable_schedule(self, host_key, items): + plan = self.port_plan(host_key, items) + cables = [] + for r in plan["rows"]: + if not r["ok"]: + continue + port = r["needs_port"] + cables.append({"from": plan["host"], "from_port": r["host_port"], + "to": r["device"], "to_port": port, + "type": port, "qty": r["qty"], + "note": "в комплекте" if self.package(r["device"])["items"] else ""}) + return {"host": plan["host"], "cables": cables, + "count": len(cables), "unresolved": plan["unresolved"]} diff --git a/ops/work/web/index.html b/ops/work/web/index.html index 341ceb4..7f947d2 100644 --- a/ops/work/web/index.html +++ b/ops/work/web/index.html @@ -103,10 +103,14 @@ svg{width:100%;height:480px;background:#0a0e13;border:1px solid var(--line);bord
добавьте позиции
—