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

Состав решения

добавьте позиции

-
+
+ + +
+

Проверка ёмкости

—

@@ -171,6 +175,8 @@ async function boot(){ $('#reqs').innerHTML=rq.map(g=>`
${g.group}
${g.items.map(i=>`${i}`).join('')}
`).join(''); room(); + setInterval(()=>{ try{ localStorage.setItem('combine_state', JSON.stringify(stateNow())); }catch(e){} }, 5000); + restoreFromHash(); } function pickDir(id){ $('#vendwrap').classList.remove('hidden'); @@ -202,8 +208,15 @@ async function reload(){ renderPositions(); renderSel(); } function renderPositions(){ + const comp=POS.completeness||{}; + const badge = comp.level==='sparse' + ? `
⚠ данные неполные: ${esc(comp.note)}
` + : comp.level==='partial' + ? `
ℹ ${esc(comp.note)}
` + : ''; + $('#positions').innerHTML = badge; const withItems=POS.groups.filter(p=>p.items.length); - $('#positions').innerHTML=withItems.map(p=>`

${p.name}${p.hint||''} · ${p.items.length}

+ $('#positions').innerHTML += withItems.map(p=>`

${p.name}${p.hint||''} · ${p.items.length}

@@ -350,6 +363,62 @@ async function checkOne(host,model){ ${esc(r.host)} + ${esc(r.device)} — ${esc(r.verdict)}
${r.condition?esc(r.condition):'условий нет'} · источник: ${esc(r.source||'матрица')}
`; } +/* ── проекты ── */ +function stateNow(){ + return {name: '', + room: {seats:+$('#seats').value, width:+$('#w').value, length:+$('#l').value}, + host: $('#host').value, need: [...NEED], + items: Object.keys(SEL).map(k=>({model:k, qty:SEL[k].qty}))}; +} +function applyState(st){ + if(!st) return; + if(st.room){ $('#seats').value=st.room.seats||10; $('#w').value=st.room.width||8; $('#l').value=st.room.length||10; room(); } + if(st.host){ $('#host').value=st.host; } + NEED=new Set(st.need||[]); + document.querySelectorAll('#reqs .tag').forEach(t=>{ + const on=NEED.has(t.dataset.n); + t.style.background=on?'#1f6feb33':''; t.style.color=on?'#79c0ff':''; + }); + SEL={}; + (st.items||[]).forEach(it=>{ SEL[it.model]={qty:it.qty,limit:99,role:'из проекта',cond:''}; }); + reload().then(()=>renderSel()); + if(st.name) $('#projinfo').textContent='проект: '+st.name; +} +async function saveProject(){ + const name=prompt('Название проекта:', $('#projinfo').textContent.replace('проект: ','')||'Новая конфигурация'); + if(!name) return; + const st=stateNow(); st.name=name; + const r=await fetch('/api/save',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(st)}).then(x=>x.json()); + if(r.ok){ $('#projinfo').innerHTML='проект сохранён: '+name+' · id '+r.id; history.replaceState(null,'','#p='+r.id); } + else $('#projinfo').textContent='ошибка сохранения: '+(r.error||'?'); +} +async function showProjects(){ + const r=await J('/api/projects'); + const list=(r.projects||[]).map(p=>`
+ ${esc(p.name||p.id)} + ${p.host||''} · ${p.items} поз. · ${(p.updated||'').slice(0,16)}
`).join(''); + $('#projinfo').innerHTML=`
проекты (${(r.projects||[]).length}): + ${list||'
пока нет
'}
`; +} +async function loadProject(id){ + const p=await J('/api/project?id='+id); + if(p.error){ $('#projinfo').textContent='не найдено'; return; } + applyState(p); +} +function shareLink(){ + const st=stateNow(); + const enc=btoa(unescape(encodeURIComponent(JSON.stringify(st)))).replace(/=+$/,''); + const url=location.origin+location.pathname+'#s='+enc; + navigator.clipboard?.writeText(url); + $('#projinfo').innerHTML='ссылка скопирована: '+url.slice(0,80)+'…'; +} +function restoreFromHash(){ + const h=location.hash||''; + if(h.startsWith('#p=')) return loadProject(h.slice(3)); + if(h.startsWith('#s=')){ + try{ const st=JSON.parse(decodeURIComponent(escape(atob(h.slice(3))))); applyState(st); }catch(e){} + } +} async function loadMatrix(){ if(!MATRIX){ MATRIX=await J('/api/matrix'); PORTS=await J('/api/ports'); } renderMatrix(); renderPorts(); diff --git a/ops/work/web/services/svc_catalog.py b/ops/work/web/services/svc_catalog.py new file mode 100644 index 0000000..852ed5a --- /dev/null +++ b/ops/work/web/services/svc_catalog.py @@ -0,0 +1,83 @@ +#!/usr/bin/env python3 +"""Сервис КАТАЛОГ (8101): устройства, порты, комплектация, функции, матрица.""" +import sys + +sys.path.insert(0, "/root/buryan-infra/ops/work/web") +from svc_base import serve # noqa +import combine_core as cc # noqa + +C = cc.Core() + + +def devices(q, body): + out = [] + for k, v in sorted(C.devices.items(), key=lambda x: x[1]["name"]): + ins, outs, src = C.ports(v["name"]) + out.append({"key": k, "name": v["name"], "role": v["role"], + "in": ins, "out": outs, "ports_source": src, + "features": sorted(C.feats.get(k, []))}) + return {"devices": out, "count": len(out)} + + +def device(q, body): + k = cc.norm((q.get("key") or [""])[0]) + if k not in C.devices: + return {"error": "not found"} + v = C.devices[k] + ins, outs, src = C.ports(v["name"]) + return {"key": k, "name": v["name"], "role": v["role"], + "ports": {"in": ins, "out": outs, "source": src}, + "attributes": C.attrs.get(k, {}), + "features": sorted(C.feats.get(k, [])), + "package": C.package(v["name"]), + "completeness": C.completeness(k)} + + +def ports(q, body): + out = [] + for k, v in sorted(C.devices.items(), key=lambda x: x[1]["name"]): + ins, outs, src = C.ports(v["name"]) + out.append({"device": v["name"], "role": v["role"], + "in": ins, "out": outs, "source": src, + "package": C.package(v["name"])["items"][:4]}) + return {"devices": out, "count": len(out)} + + +def hosts(q, body): + out = [] + for k, v in C.devices.items(): + if v["role"] != "codec" or not C.edges.get(k): + continue + out.append({"key": k, "name": v["name"], + "accessories": len(C.edges_of(k)), + "completeness": C.completeness(k)}) + return {"hosts": sorted(out, key=lambda x: x["name"])} + + +def matrix(q, body): + host_list = hosts(q, body)["hosts"] + accs = {} + for h in host_list: + for e in C.edges_of(h["key"]): + accs[cc.norm(e["to"])] = e["to"] + rows = [] + for h in host_list: + cells = {} + for e in C.edges_of(h["key"]): + q2 = e.get("max_qty") + cells[cc.norm(e["to"])] = q2 if q2 else 1 + ins, outs, src = C.ports(h["name"]) + rows.append({"host": h["name"], "cells": cells, + "ports": {"in": ins, "out": outs, "source": src}, + "completeness": h["completeness"]}) + return {"rows": rows, "accessories": sorted(accs.values()), + "hosts": [h["name"] for h in host_list]} + + +serve({ + "/devices": devices, + "/device": device, + "/ports": ports, + "/hosts": hosts, + "/matrix": matrix, +}, int(sys.argv[1]) if len(sys.argv) > 1 else 8101, "catalog") diff --git a/ops/work/web/services/svc_docs.py b/ops/work/web/services/svc_docs.py new file mode 100644 index 0000000..a80c1af --- /dev/null +++ b/ops/work/web/services/svc_docs.py @@ -0,0 +1,66 @@ +#!/usr/bin/env python3 +"""Сервис ДОКУМЕНТЫ (8105): даташиты и руководства по устройству. + +Ищет PDF в зеркале Nextcloud (/opt/work-hub/datasheets-src) и отдаёт ссылки. +""" +import os +import re +import sys + +sys.path.insert(0, "/root/buryan-infra/ops/work/web") +from svc_base import serve # noqa + +SRC = "/opt/work-hub/datasheets-src" +INDEX = {} + + +def build(): + for root, _, files in os.walk(SRC): + for f in files: + if not f.lower().endswith(".pdf"): + continue + path = os.path.join(root, f) + rel = os.path.relpath(path, SRC) + tokens = re.sub(r"[^a-z0-9]", " ", rel.lower()) + INDEX.setdefault(tokens, []).append({"file": f, "path": path, "rel": rel}) + return len(INDEX) + + +def docs(q, body): + dev = (q.get("device") or [""])[0] + if not dev: + return {"error": "device required"} + key = re.sub(r"[^a-z0-9]", "", dev.lower()) + hits = [] + for tokens, items in INDEX.items(): + if key and key in tokens.replace(" ", ""): + hits.extend(items) + kinds = {"datasheet": 0, "guide": 0, "other": 0} + out = [] + for h in hits[:20]: + low = h["file"].lower() + kind = ("datasheet" if "datasheet" in low or "ficha" in low + else "guide" if any(k in low for k in ("quick", "guide", "manual", "user")) + else "other") + kinds[kind] = kinds.get(kind, 0) + 1 + out.append({"name": h["file"], "kind": kind, "rel": h["rel"]}) + return {"device": dev, "count": len(out), "kinds": kinds, "docs": out} + + +def search(q, body): + s = re.sub(r"[^a-z0-9]", "", (q.get("q") or [""])[0].lower()) + if not s: + return {"error": "q required"} + out = [] + for tokens, items in INDEX.items(): + if s in tokens.replace(" ", ""): + out.extend(items[:3]) + return {"query": s, "count": len(out), + "docs": [{"name": x["file"], "rel": x["rel"]} for x in out[:30]]} + + +print("документов в индексе:", build(), flush=True) +serve({ + "/docs": docs, + "/search": search, +}, int(sys.argv[1]) if len(sys.argv) > 1 else 8105, "docs") diff --git a/ops/work/web/services/svc_draw.py b/ops/work/web/services/svc_draw.py new file mode 100644 index 0000000..84b5f89 --- /dev/null +++ b/ops/work/web/services/svc_draw.py @@ -0,0 +1,97 @@ +#!/usr/bin/env python3 +"""Сервис СХЕМА и КАБЕЛИ (8104): interconnect-diagram + кабельный журнал.""" +import sys + +sys.path.insert(0, "/root/buryan-infra/ops/work/web") +from svc_base import serve # noqa +import combine_core as cc # noqa + +C = cc.Core() + +COLOR = {"HDMI": "#2f81f7", "USB": "#3fb950", "USB-C": "#3fb950", "VCH": "#a371f7", + "LAN": "#d29922", "3.5mm": "#8b949e", "DP": "#a371f7", "RJ-9": "#8b949e", + "—": "#484f58"} + + +def _items(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 _esc(s): + return str(s).replace("<", "<").replace(">", ">").replace("&", "&") + + +def diagram(q, body): + """SVG-схема: порты хоста слева/справа, устройства вокруг, связи по разъёмам.""" + hk = cc.norm((q.get("host") or [""])[0]) + if hk not in C.devices: + return {"error": "хост не найден"} + host = C.devices[hk]["name"] + items = _items(q) + plan = C.port_plan(hk, items) + W, H = 1100, 620 + cx, cy, bw, bh = 550, 310, 210, 110 + parts = [f''] + # хост + parts.append(f'') + parts.append(f'{_esc(host)[:26]}') + parts.append(f'ports: {plan["source"]}') + for i, p in enumerate(plan["host_in"][:5]): + y = cy - bh//2 + 60 + i*14 + used = "•" if p in plan["used_in"] else "○" + parts.append(f'in {_esc(p)} {used}') + for i, p in enumerate(plan["host_out"][:5]): + y = cy - bh//2 + 60 + i*14 + used = "•" if p in plan["used_out"] else "○" + parts.append(f'{used} out {_esc(p)}') + # устройства + rows = [r for r in plan["rows"] if r["device"] not in ("", None)] + n = max(len(rows), 1) + for i, r in enumerate(rows): + a_top = 60 + step = (H - 120) / n + y = a_top + step * i + step/2 + x = 175 if i % 2 == 0 else 925 + col = COLOR.get(r["needs_port"], "#484f58") if r["ok"] else "#f85149" + dash = "" if r["ok"] else ' stroke-dasharray="6 4"' + parts.append(f'') + parts.append(f'') + parts.append(f'{_esc(r["device"])[:24]}') + parts.append(f'{("→ "+_esc(r["host_port"])) if r["ok"] else "нет порта"}' + f'{" ×"+str(r["qty"]) if r["qty"]>1 else ""}') + parts.append(f'{_esc(r["needs_port"] or "?")}') + parts.append("") + return {"host": host, "svg": "".join(parts), + "unresolved": plan["unresolved"], + "free_in": plan["free_in"], "free_out": plan["free_out"]} + + +def cables(q, body): + return C.cable_schedule((q.get("host") or [""])[0], _items(q)) + + +serve({ + "/diagram": diagram, + "/cables": cables, +}, int(sys.argv[1]) if len(sys.argv) > 1 else 8104, "draw") diff --git a/ops/work/web/services/svc_engine.py b/ops/work/web/services/svc_engine.py new file mode 100644 index 0000000..dd02761 --- /dev/null +++ b/ops/work/web/services/svc_engine.py @@ -0,0 +1,168 @@ +#!/usr/bin/env python3 +"""Сервис ДВИЖОК (8102): совместимость, группы, ёмкость, порты, кабели, BOM.""" +import re +import sys + +sys.path.insert(0, "/root/buryan-infra/ops/work/web") +from svc_base import serve # noqa +import combine_core as cc # noqa + +C = cc.Core() + + +def _need(q): + return [x for x in (q.get("need") or []) if x] + + +def groups(q, body): + hk = cc.norm((q.get("host") or [""])[0]) + need_n = {cc.norm(x) for x in _need(q)} + if hk not in C.devices: + return {"error": "хост не найден"} + out, used = [], set() + for g in C.GROUP_DEFS: + items = [] + if g["id"] == "infra": + for x in (C.infra.get("devices") or []): + items.append({"model": x["device"], "role": "infrastructure", + "max_qty": 4, "condition": x.get("why") or "", + "specs": x.get("specs") or {}}) + out.append({"id": g["id"], "name": g["name"], + "hint": "PoE-коммутаторы и хабы", "items": items}) + continue + for e in C.edges_of(hk): + t, k = e["to"], cc.norm(e["to"]) + if k in used: + continue + role = C.devices.get(k, {}).get("role") + if role not in g["roles"]: + continue + if g.get("skip") and re.match(g["skip"], t, re.I): + continue + if g.get("only") and not re.match(g["only"], t, re.I): + continue + if need_n and not need_n <= {cc.norm(x) for x in C.feats.get(k, set())}: + continue + used.add(k) + a = C.attrs.get(k, {}) + items.append({"model": t, "role": role, "max_qty": e.get("max_qty"), + "condition": (e.get("condition") or "").strip()[:160], + "power_w": a.get("power.consumption_w"), + "pickup_m": a.get("audio.pickup_m"), + "zoom": a.get("camera.zoom_optical") or a.get("camera.zoom_hybrid"), + "ports_vch": a.get("ports.vch")}) + if g["id"] == "mount": + have = {i["model"] for i in items} + for m in C.mounts_map.get(hk, []): + if m not in have: + items.append({"model": m, "role": "mount", "max_qty": 1, + "condition": "лист Mounts & Bracket"}) + if items: + out.append({"id": g["id"], "name": g["name"], "hint": "", + "items": sorted(items, key=lambda x: x["model"])}) + return {"host": C.devices[hk]["name"], "groups": out, + "completeness": C.completeness(hk)} + + +def check(q, body): + return C.check_pair((q.get("host") or [""])[0], (q.get("device") or [""])[0]) + + +def _items(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 capacity(q, body): + return C.capacity((q.get("host") or [""])[0], _items(q), q.get("infra") or []) + + +def port_plan(q, body): + return C.port_plan((q.get("host") or [""])[0], _items(q)) + + +def cables(q, body): + return C.cable_schedule((q.get("host") or [""])[0], _items(q)) + + +def bom(q, body): + hk = cc.norm((q.get("host") or [""])[0]) + if hk not in C.devices: + return {"error": "хост не найден"} + host = C.devices[hk]["name"] + seats = int((q.get("seats") or ["8"])[0]) + need = _need(q) + need_m = 3 if seats <= 6 else 6 if seats <= 12 else 8 if seats <= 16 else 10 + bom, warn = [], [] + bom.append({"role": "Хост", "model": host, "qty": 1, "why": "основа"}) + + def by_role(role): + return [e for e in C.edges_of(hk) + if C.devices.get(cc.norm(e["to"]), {}).get("role") == role] + + ha = {cc.norm(f) for f in C.feats.get(hk, [])} + for n in need: + if cc.norm(n) not in ha: + warn.append("хост не имеет «%s»" % n) + built = C.attrs.get(hk, {}).get("audio.pickup_m") + if built and built >= need_m: + bom.append({"role": "Микрофон", "model": "встроенный " + host, "qty": 1, + "why": "захват %s м ≥ %s м" % (built, need_m)}) + else: + cands = sorted(((C.attrs.get(cc.norm(e["to"]), {}).get("audio.pickup_m") or 0, e) + for e in by_role("audio")), key=lambda x: -x[0]) + if cands: + p, e = cands[0] + qty = max(1, -(-need_m // max(int(p), 1))) if p else 1 + bom.append({"role": "Микрофон", "model": e["to"], "qty": qty, + "why": "нужно %s м, у %s %s м" % (need_m, e["to"], p or "—")}) + cams = by_role("camera") + if cams: + cams.sort(key=lambda e: -((C.attrs.get(cc.norm(e["to"]), {}).get("camera.zoom_optical") or 0)), reverse=True) + bom.append({"role": "Камера", "model": cams[0]["to"], "qty": 1, + "why": "до %s шт" % (cams[0].get("max_qty") or "—")}) + for role, label in (("touch", "Панель"), ("sharing_or_hub", "Презентация")): + it = by_role(role) + if it: + bom.append({"role": label, "model": it[0]["to"], "qty": 1, "why": "совместимо"}) + disp = by_role("display") + bom.append({"role": "Дисплей", "model": disp[0]["to"] if disp else "внешний ТВ", + "qty": 1, "why": "совместим" if disp else "у Yealink нет дисплея"}) + mnts = C.mounts_map.get(hk) or [] + if mnts: + bom.append({"role": "Кронштейн", "model": mnts[0], "qty": 1, + "why": "вариантов %d" % len(mnts)}) + if any(cc.norm(x) == "dante" for x in need): + bom.append({"role": "Dante", "model": "CM50+CS10-D+AP08", "qty": 1, + "why": "нативный Dante-комплект"}) + items = [[b["model"], b["qty"]] for b in bom + if not b["model"].startswith(("встроенный", "внешний"))] + cap = C.capacity(hk, items) + included = [] + for b in bom: + pk = C.package(b["model"]) + if pk["items"]: + included.append({"device": b["model"], "items": pk["items"], "kits": pk["kits"]}) + return {"host": host, "seats": seats, "need_pickup": need_m, + "bom": bom, "warnings": warn, "capacity": cap, + "included": included, + "cables": C.cable_schedule(hk, items)} + + +serve({ + "/groups": groups, + "/check": check, + "/capacity": capacity, + "/ports": port_plan, + "/cables": cables, + "/bom": bom, +}, int(sys.argv[1]) if len(sys.argv) > 1 else 8102, "engine") diff --git a/ops/work/web/services/svc_project.py b/ops/work/web/services/svc_project.py new file mode 100644 index 0000000..4112995 --- /dev/null +++ b/ops/work/web/services/svc_project.py @@ -0,0 +1,88 @@ +#!/usr/bin/env python3 +"""Сервис ПРОЕКТЫ (8103): сохранение, список, версии, ссылки.""" +import json +import os +import re +import sys +import time + +sys.path.insert(0, "/root/buryan-infra/ops/work/web") +from svc_base import serve # noqa + +DIR = "/opt/work-hub/compat/projects" +os.makedirs(DIR, exist_ok=True) + + +def _ok(pid): + return bool(re.match(r"^[\w-]{1,32}$", str(pid))) + + +def lst(q, body): + out = [] + for f in sorted(os.listdir(DIR), reverse=True): + if not f.endswith(".json"): + continue + try: + d = json.load(open(os.path.join(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"), "versions": len(d.get("history") or [])}) + return {"projects": out[:100]} + + +def get(q, body): + pid = (q.get("id") or [""])[0] + if not _ok(pid): + return {"error": "bad id"} + p = os.path.join(DIR, pid + ".json") + if not os.path.exists(p): + return {"error": "not found"} + return json.load(open(p, encoding="utf-8")) + + +def save(body): + pid = (body or {}).get("id") or ("p%d" % int(time.time())) + if not _ok(pid): + return {"error": "bad id"} + path = os.path.join(DIR, str(pid) + ".json") + prev = {} + if os.path.exists(path): + try: + prev = json.load(open(path, encoding="utf-8")) + except Exception: + prev = {} + payload = dict(body or {}) + payload["id"] = pid + payload["updated"] = time.strftime("%Y-%m-%dT%H:%M:%S") + payload.setdefault("created", prev.get("created") or payload["updated"]) + hist = prev.get("history") or [] + if prev: + hist.append({"at": payload["updated"], + "items": prev.get("items") or [], + "host": prev.get("host")}) + hist = hist[-10:] + payload["history"] = hist + with open(path, "w", encoding="utf-8") as f: + json.dump(payload, f, ensure_ascii=False, indent=2) + return {"ok": True, "id": pid, "versions": len(hist)} + + +def remove(q, body): + pid = (q.get("id") or [""])[0] + if not _ok(pid): + return {"error": "bad id"} + p = os.path.join(DIR, pid + ".json") + if os.path.exists(p): + os.remove(p) + return {"ok": True} + return {"error": "not found"} + + +serve({ + "/list": lst, + "/get": get, + "/save": save, + "/delete": remove, +}, int(sys.argv[1]) if len(sys.argv) > 1 else 8103, "project") diff --git a/ops/work/web/svc_base.py b/ops/work/web/svc_base.py new file mode 100644 index 0000000..88df875 --- /dev/null +++ b/ops/work/web/svc_base.py @@ -0,0 +1,64 @@ +#!/usr/bin/env python3 +"""Общая база для сервисов комбайна: HTTP + JSON + CORS + роутинг.""" +import json +import socketserver +import sys +import urllib.parse +from http.server import BaseHTTPRequestHandler + +CORS = { + "Access-Control-Allow-Origin": "*", + "Access-Control-Allow-Methods": "GET, POST, OPTIONS", + "Access-Control-Allow-Headers": "Content-Type", +} + + +def serve(routes, port, name): + """routes: {path: callable(q: dict, body: dict|None) -> dict}""" + + class H(BaseHTTPRequestHandler): + def _send(self, obj, code=200): + body = json.dumps(obj, ensure_ascii=False).encode() + self.send_response(code) + self.send_header("Content-Type", "application/json; charset=utf-8") + self.send_header("Content-Length", str(len(body))) + for k, v in CORS.items(): + self.send_header(k, v) + self.end_headers() + self.wfile.write(body) + + def log_message(self, *a): + pass + + def do_OPTIONS(self): + self._send({}, 204) + + def _handle(self, body=None): + u = urllib.parse.urlparse(self.path) + q = {k: v for k, v in urllib.parse.parse_qs(u.query).items()} + fn = routes.get(u.path) + if not fn: + return self._send({"error": "not found", "path": u.path}, 404) + try: + return self._send(fn(q, body)) + except Exception as e: + import traceback + return self._send({"error": str(e), + "trace": traceback.format_exc()[-600:]}, 500) + + def do_GET(self): + self._handle() + + def do_POST(self): + try: + n = int(self.headers.get("Content-Length") or 0) + body = json.loads(self.rfile.read(n).decode() or "{}") + except Exception: + body = {} + self._handle(body) + + class S(socketserver.ThreadingTCPServer): + allow_reuse_address = True + + print("%s on :%d" % (name, port), flush=True) + S(("0.0.0.0", port), H).serve_forever()