1743 lines
81 KiB
Python
1743 lines
81 KiB
Python
#!/usr/bin/env python3
|
||
"""Комбайн: веб-интерфейс (v2) — направления, сценарии, чипы, Link View.
|
||
|
||
Модель схемы повторяет Yealink Room Designer:
|
||
устройство = блок с ВХОДАМИ слева и ВЫХОДАМИ справа
|
||
связи — только между однотипными портами (HDMI→HDMI, USB→USB, VCH→VCH, LAN→LAN)
|
||
"""
|
||
import json
|
||
import os
|
||
import re
|
||
import glob
|
||
import socketserver
|
||
import time
|
||
import urllib.parse
|
||
from http.server import BaseHTTPRequestHandler
|
||
|
||
BASE = "/opt/work-hub/compat"
|
||
PROJECTS_DIR = "/opt/work-hub/compat/projects"
|
||
|
||
# направления (в перспективе — все три, сейчас ВКС)
|
||
VENDORS = [
|
||
{"id": "yealink", "name": "Yealink", "ready": True,
|
||
"note": "ВКС / PRO AV"},
|
||
{"id": "poly", "name": "Poly", "ready": True, "note": "15 моделей в каталоге (VCS)"},
|
||
{"id": "logitech", "name": "Logitech", "ready": True, "note": "16 моделей в каталоге (VCS)"},
|
||
{"id": "vinteo", "name": "VINTEO", "ready": True, "note": "4 модели в каталоге (VCS)"},
|
||
{"id": "iva", "name": "IVA", "ready": True, "note": "1 модель в каталоге (VCS)"},
|
||
{"id": "hitrolink", "name": "Hitrolink", "ready": True, "note": "31 модель в каталоге (VCS)"},
|
||
{"id": "cisco", "name": "Cisco", "ready": False, "note": "скоро"},
|
||
{"id": "other", "name": "Другие", "ready": False, "note": "по запросу"},
|
||
]
|
||
|
||
DIRECTIONS = [
|
||
{"id": "vcs", "name": "ВКС", "note": "видеоконференции: комнаты, бары, кодеки",
|
||
"ready": True},
|
||
{"id": "telephony", "name": "Телефония", "note": "SIP-аппараты, DECT, гарнитуры, линии",
|
||
"ready": True},
|
||
{"id": "webrtc", "name": "WebRTC", "note": "браузерные решения, шлюзы", "ready": False},
|
||
]
|
||
|
||
DOMAIN_LABELS = {
|
||
"vcs": "ВКС", "telephony": "Телефония", "pro_av": "PRO AV",
|
||
"infrastructure": "Инфраструктура", "passive": "Пассив",
|
||
"software": "Софт", "unknown": "Не разобрано",
|
||
}
|
||
CLASS_LABELS = {
|
||
"vcs.bar.compact": "Компакт-бар",
|
||
"vcs.bar.room": "Видеобар для переговорной",
|
||
"vcs.board": "Интерактивная панель",
|
||
"vcs.terminal.room": "Терминал / кодек",
|
||
"vcs.terminal.pc": "ПК-терминал",
|
||
"vcs.byod.kit": "BYOD-комплект",
|
||
"vcs.kit.room": "Комплект ВКС",
|
||
"vcs.camera.usb": "USB-камера",
|
||
"vcs.camera.ptz": "PTZ-камера",
|
||
"vcs.audio": "Аудио / микрофоны",
|
||
"vcs.control.touch": "Панель управления",
|
||
"vcs.sharing": "Презентация / BYOD",
|
||
"vcs.accessory": "Аксессуар",
|
||
"vcs.other": "Прочее",
|
||
"telephony.sip.desk": "SIP-телефон",
|
||
"telephony.sip.conference": "Конференц-телефон",
|
||
"telephony.dect": "DECT-телефон",
|
||
"telephony.headset": "Гарнитура",
|
||
"telephony.accessory": "Аксессуар телефонии",
|
||
"passive.display": "Дисплей",
|
||
"passive.mount": "Крепление",
|
||
"passive.power": "Питание",
|
||
"infrastructure.network": "Сеть / инфраструктура",
|
||
}
|
||
MARKET_LABELS = {"ru": "РФ", "global": "Global", "both": "РФ + Global"}
|
||
ROLE_LABELS = { "codec": "Кодек / терминал", "pc": "ПК", "kit": "Комплект",
|
||
"camera": "Камера", "audio": "Аудио", "speaker": "Спикер",
|
||
"touch": "Панель", "display": "Дисплей", "mount": "Крепление",
|
||
"sharing_hub": "Презентация", "phone": "Телефон", "headset": "Гарнитура",
|
||
"power": "Питание", "unknown": "Не разобрано", "accessory": "Аксессуар",
|
||
"terminal": "Терминал / ПК", "infra": "Инфраструктура",
|
||
"sharing": "Презентация / BYOD", "mic": "Микрофоны", "panel": "Панель",
|
||
"extra": "Дополнительно",
|
||
}
|
||
|
||
|
||
def domain_label(v):
|
||
return DOMAIN_LABELS.get(v, str(v or "—"))
|
||
|
||
|
||
def class_label(v):
|
||
return CLASS_LABELS.get(v) or str(v or "—").replace(".", " · ").replace("_", " ").title()
|
||
|
||
|
||
def role_label(v):
|
||
return ROLE_LABELS.get(v, str(v or "—").title())
|
||
|
||
|
||
def market_label(v):
|
||
return MARKET_LABELS.get(v, str(v or "—"))
|
||
|
||
|
||
def norm(s):
|
||
return re.sub(r"[^a-z0-9]", "", str(s).lower())
|
||
|
||
|
||
def load_yaml(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 Data:
|
||
def __init__(self):
|
||
self.cat = load_yaml("catalog.yaml")
|
||
# аналоги смотрят все вендорские ветки, но основной конструктор — Yealink
|
||
self.analog_devices = []
|
||
seen = set()
|
||
for f in [os.path.join(BASE, "catalog.yaml")] + sorted(glob.glob(os.path.join(BASE, "catalog-*.yaml"))):
|
||
if not os.path.exists(f):
|
||
continue
|
||
c = load_yaml(os.path.basename(f))
|
||
for d in c.get("devices") or []:
|
||
key = (d.get("vendor"), d.get("name") or d.get("model"))
|
||
if key in seen:
|
||
continue
|
||
seen.add(key)
|
||
self.analog_devices.append(d)
|
||
self.graph = load_yaml("graph.yaml")
|
||
self.values = load_yaml("values.yaml")
|
||
self.features = load_yaml("features.yaml")
|
||
self.protocols = load_yaml("protocols.yaml")
|
||
self.mounts = load_yaml("mounts.yaml")
|
||
self.iface = load_yaml("interfaces_verified.yaml")
|
||
self.iface_auto = load_yaml("interfaces.yaml")
|
||
self.pkg = load_yaml("package.yaml")
|
||
self.pkg_ver = load_yaml("package_verified.yaml")
|
||
self.kits = load_yaml("kits.yaml")
|
||
self.extra = load_yaml("specs_extra.yaml")
|
||
self.infra = load_yaml("infrastructure.yaml")
|
||
self.limits = load_yaml("limitations.yaml")
|
||
self.dante = load_yaml("dante.yaml")
|
||
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 = {norm(x.get("device")): x.get("attributes") or {}
|
||
for x in self.values.get("devices") or []}
|
||
self.feats = {}
|
||
for x in self.features.get("devices") or []:
|
||
self.feats.setdefault(norm(x.get("device")), set()).update(x.get("features") or [])
|
||
for x in self.protocols.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")
|
||
# доп. характеристики из specs_extra.yaml (проверено)
|
||
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)
|
||
if x.get("package"):
|
||
self.pkg_map_extra = getattr(self, "pkg_map_extra", {})
|
||
self.pkg_map_extra[k] = x["package"]
|
||
|
||
self.pkg_map = {}
|
||
for x in (self.pkg_ver.get("devices") or []):
|
||
self.pkg_map[norm(x["device"])] = x
|
||
self.iface_map = {}
|
||
self.iface_auto_map = {}
|
||
for x in (self.iface.get("devices") or []):
|
||
self.iface_map[norm(x["device"])] = x
|
||
for x in (self.iface_auto.get("devices") or []):
|
||
self.iface_auto_map[norm(x["device"])] = x
|
||
self.mounts_map = {}
|
||
for e in self.mounts.get("edges") or []:
|
||
self.mounts_map.setdefault(norm(e["host"]), []).append(e["mount"])
|
||
|
||
# ── хосты ──
|
||
def hosts(self):
|
||
out = []
|
||
for k, v in self.devices.items():
|
||
if v["role"] not in ("codec", "pc"):
|
||
continue
|
||
if v["role"] != "pc" and not self.edges.get(k):
|
||
continue
|
||
acc = [e for e in self.edges.get(k, []) if e.get("supported")]
|
||
out.append({"key": k, "name": v["name"], "accessories": len(acc)})
|
||
return sorted(out, key=lambda x: x["name"])
|
||
|
||
# ── все доступные требования ──
|
||
def requirements(self):
|
||
groups = {
|
||
"Аудио": ["AEC", "ANC", "Dante", "AES67", "Wireless Microphone",
|
||
"Speaker Tracking", "Audio Fence"],
|
||
"Видео": ["Auto Framing", "Presenter Tracking", "4K", "IntelliFrame"],
|
||
"ВКС": ["Teams", "Zoom", "H.323", "SIP"],
|
||
"Сеть": ["PoE", "Wi-Fi", "Bluetooth", "802.1X", "VLAN", "SRTP"],
|
||
"Презентация": ["AirPlay", "Miracast", "USB-C"],
|
||
}
|
||
return [{"group": g, "items": items} for g, items in groups.items()]
|
||
|
||
def device_row(self, key):
|
||
d = self.devices[key]
|
||
return {"key": key, "name": d["name"], "role": d["role"],
|
||
"features": sorted(self.feats.get(key, [])),
|
||
"attributes": self.attrs.get(key, {}),
|
||
"accessories": [{"model": e["to"], "supported": e.get("supported"),
|
||
"max_qty": e.get("max_qty"),
|
||
"condition": e.get("condition"),
|
||
"usable": e.get("usable", True)}
|
||
for e in self.edges.get(key, [])],
|
||
"mounts": self.mounts_map.get(key, [])}
|
||
|
||
# ── порты по роли (если в даташите не указаны) ──
|
||
PORTS_BY_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"]},
|
||
"mount": {"in": [], "out": []},
|
||
"codec": {"in": ["LAN"], "out": ["HDMI", "USB", "VCH"]},
|
||
"pc": {"in": ["USB", "LAN"], "out": ["HDMI"]},
|
||
}
|
||
|
||
# ── порты устройства для схемы ──
|
||
def ports(self, name):
|
||
iv = self.iface_map.get(norm(name))
|
||
if iv: # проверено по даташиту
|
||
return (list(iv.get("in") or []) or ["—"],
|
||
list(iv.get("out") or []) or ["—"])
|
||
a = self.attrs.get(norm(name), {})
|
||
ins, outs = [], []
|
||
out_map = (("ports.hdmi_out", "HDMI"), ("ports.usb", "USB"), ("ports.vch", "VCH"))
|
||
in_map = (("ports.hdmi_in", "HDMI"),)
|
||
for aid, label in out_map:
|
||
n = a.get(aid)
|
||
if n:
|
||
outs += [label] * int(n)
|
||
for aid, label in in_map:
|
||
n = a.get(aid)
|
||
if n:
|
||
ins += [label] * int(n)
|
||
role = self.devices.get(norm(name), {}).get("role", "unknown")
|
||
dflt = self.PORTS_BY_ROLE.get(role, {"in": ["LAN"], "out": ["—"]})
|
||
if not ins:
|
||
ins = list(dflt["in"])
|
||
if not outs:
|
||
outs = list(dflt["out"]) or ["—"]
|
||
return ins, outs
|
||
|
||
# ── ГРУППЫ оборудования (как в Yealink Room Calculator) ── GROUPS_V2
|
||
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"], "skip": None},
|
||
{"id": "panel", "name": "Панели управления", "roles": ["touch", "remote"], "skip": None},
|
||
{"id": "sharing", "name": "Презентация и хабы", "roles": ["sharing_or_hub"],
|
||
"skip": None},
|
||
{"id": "phone", "name": "Аудиоустройства и телефоны",
|
||
"roles": ["audio"], "only": r"^CP50|^CP965|^CPE|^CP\d|^PA\d"},
|
||
{"id": "display", "name": "Дисплеи", "roles": ["display"], "skip": None},
|
||
{"id": "mount", "name": "Кронштейны", "roles": ["mount"], "skip": None},
|
||
{"id": "infra", "name": "Инфраструктура (PoE, хабы)", "roles": [], "skip": None},
|
||
]
|
||
|
||
# ── ПОЗИЦИОННЫЙ конструктор: места установки ──
|
||
POSITIONS = [
|
||
{"id": "rack", "name": "Стойка / шкаф",
|
||
"hint": "кодек, DSP, коммутатор",
|
||
"roles": ["sharing_or_hub", "power"]},
|
||
{"id": "table", "name": "Стол",
|
||
"hint": "настольные микрофоны, панели, докстанции",
|
||
"roles": ["audio", "touch", "remote"]},
|
||
{"id": "ceiling", "name": "Потолок",
|
||
"hint": "потолочные микрофоны и громкоговорители",
|
||
"roles": ["audio", "speaker", "sensor"]},
|
||
{"id": "wall", "name": "Стена / экран",
|
||
"hint": "камеры, дисплеи",
|
||
"roles": ["camera", "display"]},
|
||
{"id": "perimeter", "name": "Периметр",
|
||
"hint": "кронштейны и крепления",
|
||
"roles": ["mount", "headset"]},
|
||
]
|
||
|
||
# позиция по имени устройства (важнее роли: VCM38 — потолочный, хотя роль audio)
|
||
POSITION_RULES = [
|
||
(r"^VCM|^CM50|^CS10-D|^CLS120|^MSpeaker|^CS10\b", "ceiling"),
|
||
(r"^CM20|^CS10|^CP50|^CPE|^CP965|^CP\d|^CTP|^MTouch|^VCR|^MB-Remote|^PA\d", "table"),
|
||
(r"^UVC|^MB-CAM|^MB-12X|^SmartVision|MeetingDisplay|^ETV|^VCC", "wall"),
|
||
(r"^MCore|^VCH|^WPP|^AP0|^AVBridge|^AVHub|^BYOD|^YPS|^PVB|^PVT|MeetingEye|^A\d|^MeetingBoard|^MB-FS|^Roomcast", "rack"),
|
||
(r"[Mm]ount|Bracket|Stand|^MB-Tray|^MB-Wall|^MD-", "perimeter"),
|
||
]
|
||
|
||
def pos_of(self, name):
|
||
for pat, pos in self.POSITION_RULES:
|
||
if re.match(pat, str(name)):
|
||
return pos
|
||
return None
|
||
|
||
def positions(self, host_key, need=None):
|
||
"""Позиции комнаты: в каждой только совместимые с хостом устройства."""
|
||
need_n = {norm(x) for x in (need or [])}
|
||
hk = norm(host_key)
|
||
if hk not in self.devices:
|
||
return {"error": "хост не найден"}
|
||
host_role = self.devices[hk]["role"]
|
||
# у бара камера обычно встроенная — позицию камеры скрываем, если нет совместимых
|
||
out = []
|
||
for pos in self.POSITIONS:
|
||
items = []
|
||
for e in self.edges.get(hk, []):
|
||
t = e["to"]
|
||
r = self.devices.get(norm(t), {}).get("role")
|
||
if r not in pos["roles"]:
|
||
continue
|
||
# уточнение по позиции устройства
|
||
real_pos = self.pos_of(t)
|
||
if real_pos and real_pos != pos["id"]:
|
||
continue
|
||
if not e.get("supported") or not e.get("usable", True):
|
||
continue
|
||
a = self.attrs.get(norm(t), {})
|
||
f = {norm(x) for x in self.feats.get(norm(t), set())}
|
||
if need_n and not need_n <= f:
|
||
continue
|
||
items.append({
|
||
"model": t, "role": r,
|
||
"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 pos["id"] == "perimeter":
|
||
for m in self.mounts_map.get(hk, []):
|
||
items.append({"model": m, "role": "mount", "max_qty": 1,
|
||
"condition": "лист Mounts & Bracket",
|
||
"power_w": None, "pickup_m": None, "zoom": None,
|
||
"ports_vch": None})
|
||
uniq = {}
|
||
for i in items:
|
||
uniq.setdefault(i["model"], i)
|
||
items = sorted(uniq.values(), key=lambda x: x["model"])
|
||
out.append({"id": pos["id"], "name": pos["name"], "hint": pos["hint"],
|
||
"items": items})
|
||
return {"host": self.devices[hk]["name"], "host_role": host_role,
|
||
"positions": out}
|
||
|
||
# какие разъёмы соединяются между собой
|
||
LINKABLE = {
|
||
("HDMI", "HDMI"): "видео",
|
||
("USB", "USB"): "данные",
|
||
("USB-C", "USB-C"): "данные + видео",
|
||
("USB", "USB-C"): "данные (через переходник)",
|
||
("VCH", "VCH"): "аудио + питание",
|
||
("LAN", "LAN"): "сеть / PoE",
|
||
("3.5mm", "3.5mm"): "аналоговый звук",
|
||
("DP", "DP"): "видео",
|
||
}
|
||
|
||
# запреты из официальных даташитов
|
||
FORBIDDEN = [
|
||
{"device": "UVC86", "port": "HDMI", "host_contains": "mvc",
|
||
"reason": "HDMI-выход UVC86 совместим с VCS, но НЕ с MVC (даташит)"},
|
||
]
|
||
|
||
def device_ports(self, name):
|
||
"""Порты: проверенные -> извлечённые -> по роли. Возвращает (in, out, source)."""
|
||
k = norm(name)
|
||
if k in self.iface_map:
|
||
v = self.iface_map[k]
|
||
return (v.get("in") or ["—"], v.get("out") or ["—"], "verified")
|
||
if k in self.iface_auto_map:
|
||
v = self.iface_auto_map[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")
|
||
ins, outs = self.ports(name)
|
||
return (ins, outs, "role")
|
||
|
||
def link_plan(self, host_key, items):
|
||
"""План связей: каждый аксессуар -> хост, по совместимости разъёмов."""
|
||
hk = norm(host_key)
|
||
host = self.devices.get(hk, {}).get("name", host_key)
|
||
h_in, h_out, h_src = self.device_ports(host)
|
||
links = []
|
||
for row in items:
|
||
model = row[0] if isinstance(row, (list, tuple)) else row
|
||
acc_in, acc_out, src = self.device_ports(model)
|
||
link = {"device": model, "host": host, "ok": False,
|
||
"from_port": None, "to_port": None, "type": None,
|
||
"source": src, "reason": None}
|
||
# ищем пару: выход аксессуара -> вход хоста (и наоборот)
|
||
pairs = []
|
||
for a in acc_out:
|
||
for b in h_in:
|
||
if (a, b) in self.LINKABLE:
|
||
pairs.append((a, b, self.LINKABLE[(a, b)]))
|
||
elif (b, a) in self.LINKABLE:
|
||
pairs.append((a, b, self.LINKABLE[(b, a)]))
|
||
for a in h_out:
|
||
for b in acc_in:
|
||
if (a, b) in self.LINKABLE:
|
||
pairs.append((a, b, self.LINKABLE[(a, b)]))
|
||
if pairs:
|
||
p = pairs[0]
|
||
link.update({"ok": True, "from_port": p[0], "to_port": p[1],
|
||
"type": p[2]})
|
||
else:
|
||
link["reason"] = ("нет совместимого разъёма: %s in=%s out=%s / хост in=%s out=%s"
|
||
% (model, ",".join(acc_in) or "-", ",".join(acc_out) or "-",
|
||
",".join(h_in) or "-", ",".join(h_out) or "-"))
|
||
# запреты
|
||
for fb in self.FORBIDDEN:
|
||
if norm(fb["device"]) == norm(model) and \
|
||
fb["host_contains"] in norm(host) and \
|
||
(link.get("from_port") == fb["port"] or link.get("to_port") == fb["port"]):
|
||
link.update({"ok": False, "forbidden": True, "reason": fb["reason"]})
|
||
links.append(link)
|
||
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 [])}
|
||
hk = norm(host_key)
|
||
if hk not in self.devices:
|
||
return {"error": "хост не найден"}
|
||
out = []
|
||
used = set()
|
||
for g in self.GROUP_DEFS:
|
||
items = []
|
||
if g["id"] == "infra":
|
||
for x in (self.infra.get("devices") or []):
|
||
items.append({"model": x["device"], "role": "infrastructure",
|
||
"max_qty": 4, "condition": x.get("why") or "",
|
||
"pickup_m": None, "zoom": None,
|
||
"power_w": None, "ports_vch": None,
|
||
"specs": x.get("specs") or {}})
|
||
out.append({"id": g["id"], "name": g["name"], "hint":
|
||
"PoE-коммутаторы и хабы для роста системы", "items": items})
|
||
continue
|
||
for e in self.edges.get(hk, []):
|
||
t = e["to"]
|
||
k = norm(t)
|
||
if k in used:
|
||
continue
|
||
r = self.devices.get(k, {}).get("role")
|
||
if r not in g["roles"]:
|
||
continue
|
||
if not e.get("supported") or not e.get("usable", True):
|
||
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
|
||
a = self.attrs.get(k, {})
|
||
f = {norm(x) for x in self.feats.get(k, set())}
|
||
if need_n and not need_n <= f:
|
||
continue
|
||
used.add(k)
|
||
items.append({"model": t, "role": r,
|
||
"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 self.mounts_map.get(hk, []):
|
||
if m in have:
|
||
continue
|
||
items.append({"model": m, "role": "mount", "max_qty": 1,
|
||
"condition": "лист Mounts & Bracket",
|
||
"power_w": None, "pickup_m": None, "zoom": None,
|
||
"ports_vch": None})
|
||
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,
|
||
"completeness": self.data_completeness(hk)}
|
||
|
||
# ── проверка одной пары: хост + устройство ──
|
||
def check_pair(self, host_key, accessory):
|
||
hk = norm(host_key)
|
||
ak = norm(accessory)
|
||
host = self.devices.get(hk, {}).get("name")
|
||
acc_name = self.devices.get(ak, {}).get("name") or accessory
|
||
if not host:
|
||
return {"error": "хост не найден"}
|
||
found = None
|
||
for e in self.edges.get(hk, []):
|
||
if norm(e["to"]) == ak:
|
||
found = e
|
||
break
|
||
if not found:
|
||
return {"host": host, "device": acc_name, "known": False,
|
||
"supported": False, "verdict": "нет в матрице для этого хоста",
|
||
"note": "устройство не описано как аксессуар этого хоста"}
|
||
supported = bool(found.get("supported"))
|
||
usable = found.get("usable", True)
|
||
if not usable:
|
||
verdict = "исключено: источники расходятся — требуется проверка у вендора"
|
||
elif supported:
|
||
q = found.get("max_qty")
|
||
verdict = "совместимо" + (" (до %s шт)" % q if q else "")
|
||
else:
|
||
verdict = "несовместимо"
|
||
cond = re.sub(r"^[\u221a\u2713\u2714\u00d7\u2717\u2718\u2022\s]+", "",
|
||
(found.get("condition") or "")).strip() # cond_clean
|
||
return {"host": host, "device": acc_name, "known": True,
|
||
"supported": supported, "usable": usable,
|
||
"max_qty": found.get("max_qty"),
|
||
"condition": cond,
|
||
"source": found.get("source") or "матрица",
|
||
"verdict": verdict}
|
||
|
||
# ── матрица: хосты × аксессуары + порты ──
|
||
def matrix(self):
|
||
hosts = [h for h in self.hosts()]
|
||
accs = {}
|
||
for hk in [h["key"] for h in hosts]:
|
||
for e in self.edges.get(hk, []):
|
||
if not e.get("supported") or not e.get("usable", True):
|
||
continue
|
||
accs[norm(e["to"])] = e["to"]
|
||
acc_list = sorted(accs.values())
|
||
rows = []
|
||
for h in hosts:
|
||
hk = h["key"]
|
||
cells = {}
|
||
for e in self.edges.get(hk, []):
|
||
if not e.get("supported") or not e.get("usable", True):
|
||
continue
|
||
k = norm(e["to"])
|
||
q = e.get("max_qty")
|
||
cells[k] = q if q else 1
|
||
ins, outs, src = self.device_ports(h["name"])
|
||
rows.append({"host": h["name"], "cells": cells,
|
||
"ports": {"in": ins, "out": outs, "source": src}})
|
||
return {"hosts": [r["host"] for r in rows],
|
||
"rows": rows,
|
||
"accessories": acc_list}
|
||
|
||
# ── порты всех устройств ──
|
||
def ports_table(self):
|
||
out = []
|
||
for k, v in sorted(self.devices.items(), key=lambda x: x[1]["name"]):
|
||
name = v["name"]
|
||
ins, outs, src = self.device_ports(name)
|
||
pkg = []
|
||
for x in (self.pkg.get("devices") or []):
|
||
if norm(x["device"]) == k:
|
||
pkg = x.get("items") or []
|
||
break
|
||
lim = []
|
||
for x in (self.limits.get("devices") or []):
|
||
if norm(x["device"]) == k:
|
||
lim = x.get("limits") or []
|
||
break
|
||
out.append({"device": name, "role": v["role"],
|
||
"in": ins, "out": outs, "source": src,
|
||
"package": pkg, "limits": lim})
|
||
return out
|
||
|
||
# ── предложения: как закрыть проблему ──
|
||
def suggest_fixes(self, host_key, items, issues, missing_power):
|
||
hk = norm(host_key)
|
||
ha = self.attrs.get(hk, {})
|
||
vch_ports = ha.get("ports.vch")
|
||
qtys = {}
|
||
for row in items:
|
||
qtys[row[0]] = qtys.get(row[0], 0) + int(row[1])
|
||
|
||
def compat(role):
|
||
out = []
|
||
for e in self.edges.get(hk, []):
|
||
if not e.get("supported") or not e.get("usable", True):
|
||
continue
|
||
if self.devices.get(norm(e["to"]), {}).get("role") != role:
|
||
continue
|
||
a = self.attrs.get(norm(e["to"]), {})
|
||
out.append({"model": e["to"], "max_qty": e.get("max_qty"),
|
||
"vch": a.get("ports.vch"), "wifi": a.get("network.wifi"),
|
||
"poe": a.get("network.poe"),
|
||
"power_w": a.get("power.consumption_w")})
|
||
return out
|
||
|
||
variants = []
|
||
need_vch = any("VCH" in i for i in issues)
|
||
|
||
# инфраструктура: RCH40 E2 даёт 4 PoE-порта
|
||
infra_items = []
|
||
for x in (self.infra.get("devices") or []):
|
||
sp = x.get("specs") or {}
|
||
infra_items.append({
|
||
"title": "Добавить %s" % x["device"],
|
||
"why": "%s PoE+ портов, бюджет %s Вт (%s Вт на порт), uplink 1G"
|
||
% (sp.get("poe_ports"), sp.get("poe_budget_w"),
|
||
sp.get("poe_per_port_w")),
|
||
"add": [[x["device"], 1]], "kind": "infra"})
|
||
variants.extend(infra_items)
|
||
|
||
if need_vch:
|
||
# вариант 1: добавить хаб с VCH-портами
|
||
# hub_filter: только реальные VCH-хабы (VCH51/VCH51 Pro), не донглы
|
||
hubs = []
|
||
for h in compat("sharing_or_hub"):
|
||
if not re.match(r"^VCH", h["model"], re.I):
|
||
iv = self.iface_map.get(norm(h["model"])) or {}
|
||
if "VCH" not in (iv.get("in") or []) + (iv.get("out") or []):
|
||
continue
|
||
hubs.append(h)
|
||
for h in hubs[:3]:
|
||
variants.append({
|
||
"title": "Добавить %s" % h["model"],
|
||
"why": "даёт %s VCH-порт(а) для цепочки" % (h["vch"] or 1),
|
||
"add": [[h["model"], 1]],
|
||
"kind": "hub"})
|
||
if not hubs:
|
||
for h in compat("sharing_or_hub")[:2]:
|
||
variants.append({
|
||
"title": "Добавить %s" % h["model"],
|
||
"why": "расширяет подключение (VCH-порты не указаны в данных — проверить)",
|
||
"add": [[h["model"], 1]], "kind": "hub_unknown"})
|
||
# вариант 2: беспроводные микрофоны
|
||
wifi = [a for a in compat("audio") if a.get("wifi")]
|
||
for a in wifi[:2]:
|
||
variants.append({
|
||
"title": "Заменить проводные на %s" % a["model"],
|
||
"why": "беспроводной микрофон — не занимает VCH-порт",
|
||
"replace_role": "audio", "add": [[a["model"], 1]],
|
||
"kind": "wireless"})
|
||
# вариант 3: уменьшить количество
|
||
variants.append({
|
||
"title": "Сократить количество на VCH",
|
||
"why": "у хоста %s VCH-порт(а) — распределить устройства или снизить число"
|
||
% (int(vch_ports) if vch_ports else "?"),
|
||
"kind": "reduce"})
|
||
|
||
if missing_power:
|
||
variants.append({
|
||
"title": "Уточнить питание",
|
||
"why": "нет данных о потреблении: %s — запросить у вендора"
|
||
% ", ".join(missing_power[:5]),
|
||
"kind": "data"})
|
||
|
||
# PoE-бюджет: если есть устройства без PoE, но с питанием
|
||
no_poe = [m for m in qtys if not (self.attrs.get(norm(m), {}) or {}).get("network.poe")]
|
||
if no_poe:
|
||
variants.append({
|
||
"title": "Проверить питание %s" % ", ".join(no_poe[:3]),
|
||
"why": "у этих устройств нет данных о PoE — возможно, нужен блок питания",
|
||
"kind": "data"})
|
||
return variants
|
||
|
||
# ── проверка ёмкости хоста ──
|
||
def capacity(self, host_key, items):
|
||
"""items: [[model, qty], ...]. Проверяет порты VCH, лимиты, питание."""
|
||
hk = norm(host_key)
|
||
if hk not in self.devices:
|
||
return {"error": "хост не найден"}
|
||
host = self.devices[hk]["name"]
|
||
ha = self.attrs.get(hk, {})
|
||
vch_ports = ha.get("ports.vch")
|
||
issues, notes = [], []
|
||
total_w, missing_w = 0.0, []
|
||
vch_users = 0
|
||
qtys = {}
|
||
for row in items:
|
||
model, qty = row[0], int(row[1])
|
||
qtys[model] = qtys.get(model, 0) + qty
|
||
# лимиты из матрицы
|
||
limits = {}
|
||
for e in self.edges.get(hk, []):
|
||
if e.get("supported"):
|
||
limits[norm(e["to"])] = (e.get("max_qty"), e["to"])
|
||
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
|
||
if vch_ports is not None and vch_users > 0:
|
||
notes.append("портов VCH у хоста: %s · устройств на VCH: %d"
|
||
% (int(vch_ports), vch_users))
|
||
if vch_users > vch_ports:
|
||
issues.append(
|
||
"VCH: %d устройств на %s порт(а) — требуется цепочка/расширитель; "
|
||
"ёмкость цепочки в данных отсутствует — ПРОВЕРИТЬ У ВЕНДОРА"
|
||
% (vch_users, int(vch_ports)))
|
||
notes.append("суммарное потребление: %.1f Вт (по данным)" % total_w)
|
||
if missing_w:
|
||
notes.append("нет данных о потреблении: %s" % ", ".join(sorted(set(missing_w))[:8]))
|
||
suggestions = self.suggest_fixes(host_key, items, issues, sorted(set(missing_w)))
|
||
return {"host": host, "vch_ports": vch_ports, "vch_users": vch_users,
|
||
"suggestions": suggestions,
|
||
"total_power_w": round(total_w, 1),
|
||
"missing_power": sorted(set(missing_w)),
|
||
"issues": issues, "notes": notes}
|
||
|
||
# ── варианты для ручной сборки (только совместимые!) ──
|
||
FEATURE_ROLE = {
|
||
"aec": "audio", "anc": "audio", "dante": "audio", "aes67": "audio",
|
||
"autoarchframing": "camera", "autoframing": "camera",
|
||
"speakertracking": "camera", "presentertracking": "camera", "4k": "camera",
|
||
"airplay": "sharing_or_hub", "miracast": "sharing_or_hub", "usbc": "sharing_or_hub",
|
||
"poe": "network", "wifi": "network", "bluetooth": "network",
|
||
"teams": "codec", "zoom": "codec", "h323": "codec", "sip": "codec",
|
||
}
|
||
|
||
ROLE_LABELS = [
|
||
("audio", "Аудио / микрофоны"),
|
||
("camera", "Камеры"),
|
||
("touch", "Панели управления"),
|
||
("sharing_or_hub", "Презентация / хабы"),
|
||
("display", "Дисплеи"),
|
||
("speaker", "Громкоговорители"),
|
||
("mount", "Кронштейны"),
|
||
("remote", "Пульты"),
|
||
("headset", "Гарнитуры"),
|
||
]
|
||
|
||
def options(self, host_key, need=None):
|
||
"""need — требования: фильтруют позиции внутри групп по ролям.""" # VENDOR_LAYER
|
||
need_n = {norm(x) for x in (need or [])}
|
||
hk = norm(host_key)
|
||
if hk not in self.devices:
|
||
return {"error": "хост не найден"}
|
||
groups, blocked_count = [], {}
|
||
for role, label in self.ROLE_LABELS:
|
||
items = []
|
||
blocked = 0
|
||
for e in self.edges.get(hk, []):
|
||
target = e["to"]
|
||
r = self.devices.get(norm(target), {}).get("role")
|
||
if r != role:
|
||
continue
|
||
# несовместимые по матрице НЕ показываем
|
||
if not e.get("supported") or not e.get("usable", True):
|
||
blocked += 1
|
||
continue
|
||
a = self.attrs.get(norm(target), {})
|
||
acc_feats = {norm(f) for f in self.feats.get(norm(target), set())}
|
||
# требование применяется к своей роли
|
||
role_needs = {n for n in need_n
|
||
if self.FEATURE_ROLE.get(n) in (role, None)}
|
||
if role_needs and not role_needs <= acc_feats:
|
||
blocked += 1
|
||
continue
|
||
items.append({
|
||
"model": target,
|
||
"max_qty": e.get("max_qty"),
|
||
"condition": (e.get("condition") or "").strip(),
|
||
"features": sorted(self.feats.get(norm(target), []))[:8],
|
||
"pickup_m": a.get("audio.pickup_m"),
|
||
"zoom": a.get("camera.zoom_optical") or a.get("camera.zoom_hybrid"),
|
||
})
|
||
# mount_merge: кронштейны из обоих источников
|
||
if role == "mount":
|
||
have = {i["model"] for i in items}
|
||
for m in self.mounts_map.get(hk, []):
|
||
if m in have:
|
||
continue
|
||
items.append({"model": m, "max_qty": 1,
|
||
"condition": "лист Mounts & Bracket",
|
||
"features": [], "pickup_m": None, "zoom": None})
|
||
have.add(m)
|
||
if items:
|
||
items.sort(key=lambda x: x["model"])
|
||
groups.append({"role": role, "label": label, "items": items})
|
||
if blocked:
|
||
blocked_count[role] = blocked
|
||
return {"host": self.devices[hk]["name"], "groups": groups,
|
||
"blocked": blocked_count}
|
||
|
||
# ── подбор ──
|
||
def bom(self, host_key, seats=8, need=None, add=None):
|
||
need = need or []
|
||
need_n = {norm(x) for x in need}
|
||
add = add or []
|
||
hk = norm(host_key)
|
||
if hk not in self.devices:
|
||
return {"error": "хост не найден"}
|
||
host = self.devices[hk]["name"]
|
||
need_m = 3 if seats <= 6 else 6 if seats <= 12 else 8 if seats <= 16 else 10
|
||
bom, warn, cross = [], [], []
|
||
|
||
def by_role(role):
|
||
return [e for e in self.edges.get(hk, [])
|
||
if e.get("supported") and e.get("usable", True)
|
||
and self.devices.get(norm(e["to"]), {}).get("role") == role]
|
||
|
||
bom.append({"role": "Хост", "model": host, "qty": 1, "why": "основа системы"})
|
||
|
||
def mark_included():
|
||
"""Помечает позиции, чьи кабели/крепёж уже в комплекте."""
|
||
for b in bom:
|
||
k = norm(b["model"])
|
||
pk = self.pkg_map.get(k) or {}
|
||
items = pk.get("items") or (getattr(self, "pkg_map_extra", {}) or {}).get(k) or []
|
||
if items:
|
||
b["included"] = items
|
||
ha = {norm(f) for f in self.feats.get(hk, [])}
|
||
for n in need:
|
||
if norm(n) not in ha:
|
||
warn.append("хост не имеет функции «%s»" % n)
|
||
|
||
built = self.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(((self.attrs.get(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]
|
||
q = max(1, -(-need_m // max(int(p), 1))) if p else 1
|
||
bom.append({"role": "Микрофон", "model": e["to"], "qty": q,
|
||
"why": "нужно %s м, у %s %s м (до %s шт)"
|
||
% (need_m, e["to"], p or "—", e.get("max_qty") or "—")})
|
||
|
||
cams = by_role("camera")
|
||
if cams:
|
||
def sc(e):
|
||
a = self.attrs.get(norm(e["to"]), {})
|
||
z = (a.get("camera.zoom_optical") or 0) + (a.get("camera.zoom_hybrid") or 0)
|
||
return z - (100 if "content camera" in (e.get("condition") or "").lower() else 0)
|
||
cams.sort(key=sc, 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": (it[0].get("condition") or "совместимо")[:70]})
|
||
disps = by_role("display")
|
||
bom.append({"role": "Дисплей", "model": disps[0]["to"] if disps else "внешний ТВ",
|
||
"qty": 1, "why": "совместим" if disps else "у Yealink нет дисплея"})
|
||
mnts = self.mounts_map.get(hk) or [e["to"] for e in by_role("mount")]
|
||
if mnts:
|
||
bom.append({"role": "Кронштейн", "model": mnts[0], "qty": 1,
|
||
"why": "вариантов: %d" % len(mnts)})
|
||
for n in add:
|
||
bom.append({"role": "Якорь", "model": n, "qty": 1, "why": "задано вручную"})
|
||
if any(norm(x) == "dante" for x in need):
|
||
bom.append({"role": "Dante", "model": "CM50+CS10-D+AP08", "qty": 1,
|
||
"why": "нативный Dante-комплект"})
|
||
|
||
chosen = {norm(b["model"]) for b in bom}
|
||
for e in self.edges.get(hk, []):
|
||
if norm(e["to"]) not in chosen:
|
||
continue
|
||
c = e.get("condition") or ""
|
||
for known, info in self.devices.items():
|
||
if len(known) > 3 and known in norm(c) and known not in chosen:
|
||
cross.append("%s требует %s" % (e["to"], info["name"]))
|
||
|
||
mark_included()
|
||
# что входит в комплект (не покупать отдельно)
|
||
included, kits = [], []
|
||
for b in bom:
|
||
if b["model"].startswith("встроенный") or b["model"].startswith("внешний"):
|
||
continue
|
||
k = norm(b["model"])
|
||
p = self.pkg_map.get(k)
|
||
if p:
|
||
included.append({"device": b["model"],
|
||
"items": p.get("items") or [],
|
||
"kits": p.get("optional_kits") or []})
|
||
for kk in (self.kits.get("kits") or []):
|
||
if norm(kk.get("base")) == hk:
|
||
kits.append(kk)
|
||
|
||
# схема: узлы с портами и связи
|
||
nodes = []
|
||
for b in bom:
|
||
if b["role"] in ("Кронштейн",) or b["model"].startswith("встроенный"):
|
||
continue
|
||
ins, outs = self.ports(b["model"])
|
||
nodes.append({"model": b["model"], "role": b["role"], "qty": b["qty"],
|
||
"ins": ins[:6], "outs": outs[:6],
|
||
"central": b["role"] == "Хост"})
|
||
links = []
|
||
center = next((n for n in nodes if n["central"]), None)
|
||
if center:
|
||
for n in nodes:
|
||
if n["central"]:
|
||
continue
|
||
links.append({"from": center["model"], "to": n["model"],
|
||
"type": (n["outs"] or ["-"])[0]})
|
||
return {"host": host, "seats": seats, "need_pickup": need_m,
|
||
"bom": bom, "warnings": warn, "cross": cross,
|
||
"included": included, "kits": kits,
|
||
"scheme": {"nodes": nodes, "links": links}}
|
||
|
||
|
||
D = Data()
|
||
|
||
ARCHIVE_FILE = os.path.join(BASE, "archive.yaml")
|
||
ARCHIVE_LOG = "/var/log/prism-archive.jsonl"
|
||
|
||
|
||
def _akey(d):
|
||
return str(d.get("id") or norm(_dev_name(d)))
|
||
|
||
|
||
def load_archive():
|
||
try:
|
||
import yaml
|
||
d = yaml.safe_load(open(ARCHIVE_FILE, encoding="utf-8")) or {}
|
||
return d.get("devices") or {}
|
||
except Exception:
|
||
return {}
|
||
|
||
|
||
ARCHIVE = load_archive()
|
||
|
||
|
||
def archive_info(d):
|
||
return ARCHIVE.get(_akey(d))
|
||
|
||
|
||
def is_archived(d):
|
||
return bool(archive_info(d))
|
||
|
||
|
||
def save_archive():
|
||
import yaml
|
||
os.makedirs(os.path.dirname(ARCHIVE_FILE), exist_ok=True)
|
||
tmp = ARCHIVE_FILE + ".tmp"
|
||
yaml.safe_dump({"devices": ARCHIVE}, open(tmp, "w", encoding="utf-8"), allow_unicode=True, sort_keys=True)
|
||
os.replace(tmp, ARCHIVE_FILE)
|
||
|
||
|
||
def set_archive(d, action, reason=""):
|
||
global ARCHIVE
|
||
k = _akey(d)
|
||
if action == "restore":
|
||
ARCHIVE.pop(k, None)
|
||
save_archive()
|
||
return {"ok": True, "archived": False, "key": k, "name": _dev_name(d)}
|
||
ARCHIVE[k] = {"name": _dev_name(d), "vendor": d.get("vendor"),
|
||
"archived_at": time.strftime("%Y-%m-%dT%H:%M:%S"),
|
||
"reason": reason or "устарело/снято с актуальности"}
|
||
save_archive()
|
||
try:
|
||
with open(ARCHIVE_LOG, "a", encoding="utf-8") as f:
|
||
f.write(json.dumps({"ts": ARCHIVE[k]["archived_at"], "key": k,
|
||
"name": _dev_name(d), "reason": ARCHIVE[k]["reason"]},
|
||
ensure_ascii=False) + "\n")
|
||
except Exception:
|
||
pass
|
||
return {"ok": True, "archived": True, "key": k, "name": _dev_name(d)}
|
||
|
||
|
||
def archived_items():
|
||
out = []
|
||
for k, v in ARCHIVE.items():
|
||
out.append(dict(v, key=k))
|
||
return sorted(out, key=lambda x: x.get("archived_at") or "", reverse=True)
|
||
|
||
|
||
def _dev_name(d):
|
||
return d.get("name") or d.get("model") or ""
|
||
|
||
|
||
def analog_search(query, domain="vcs"):
|
||
"""Подбор аналогов: строго domain + solution_class.
|
||
|
||
SIP — протокол, не домен: VCS-бар с SIP не становится телефонией.
|
||
"""
|
||
q = (query or "").strip()
|
||
domain = (domain or "vcs").strip().lower()
|
||
devices = D.analog_devices
|
||
target = None
|
||
if q:
|
||
for d in devices:
|
||
names = [_dev_name(d)] + [str(a) for a in (d.get("aliases") or [])]
|
||
if any(q.lower() == n.lower() for n in names):
|
||
target = d
|
||
break
|
||
if target is None:
|
||
for d in devices:
|
||
names = [_dev_name(d)] + [str(a) for a in (d.get("aliases") or [])]
|
||
if any(q.lower() in n.lower() for n in names):
|
||
target = d
|
||
break
|
||
parsed = {"class": "", "protocols": [], "features": [], "note": ""}
|
||
if target is not None:
|
||
domain = target.get("domain") or domain
|
||
cls = target.get("solution_class") or ""
|
||
parsed["class"] = cls
|
||
else:
|
||
low = q.lower()
|
||
cls = ""
|
||
if domain == "telephony":
|
||
if "dect" in low:
|
||
cls = "telephony.dect"
|
||
elif "гарнитур" in low or "headset" in low:
|
||
cls = "telephony.headset"
|
||
elif "конференц" in low:
|
||
cls = "telephony.sip.conference"
|
||
else:
|
||
cls = "telephony.sip.desk"
|
||
else:
|
||
if "бар" in low or "bar" in low:
|
||
cls = "vcs.bar.compact" if "компакт" in low else "vcs.bar.room"
|
||
elif "панел" in low or "board" in low:
|
||
cls = "vcs.board"
|
||
elif "терминал" in low or "кодек" in low or "codec" in low:
|
||
cls = "vcs.terminal.room"
|
||
elif "камер" in low:
|
||
cls = "vcs.camera.usb"
|
||
elif "аудио" in low or "микрофон" in low:
|
||
cls = "vcs.audio"
|
||
elif "панель управления" in low or "touch" in low:
|
||
cls = "vcs.control.touch"
|
||
parsed["class"] = cls
|
||
if "sip" in low:
|
||
parsed["protocols"].append("SIP")
|
||
if "h.323" in low or "h323" in low:
|
||
parsed["protocols"].append("H.323")
|
||
if "4k" in low:
|
||
parsed["features"].append("4K")
|
||
|
||
def val(d, k):
|
||
return d.get(k) or ""
|
||
|
||
cand = []
|
||
tspec = specs(target) if target is not None else {}
|
||
for d in devices:
|
||
if target is not None and d is target:
|
||
continue
|
||
if d.get("domain") != domain:
|
||
continue
|
||
if parsed["class"] and d.get("solution_class") != parsed["class"]:
|
||
continue
|
||
if target is not None and d.get("vendor") == target.get("vendor"):
|
||
continue
|
||
if domain == "vcs" and d.get("sales_scope") == "reference":
|
||
continue
|
||
if domain == "telephony" and d.get("sales_scope") != "reference":
|
||
continue
|
||
cs = specs(d)
|
||
# жёсткие характеристики: если у цели подтверждено, у кандидата не должно быть «нет»
|
||
if target is not None:
|
||
if tspec.get("4k") is True and cs.get("4k") is False:
|
||
continue
|
||
if tspec.get("sip") is True and cs.get("sip") is False:
|
||
continue
|
||
if tspec.get("pickup_m") and cs.get("pickup_m") and cs["pickup_m"] < tspec["pickup_m"] * 0.8:
|
||
continue
|
||
s, why = 0, []
|
||
if parsed["class"]:
|
||
s += 50
|
||
why.append("same solution_class")
|
||
prot = {str(x).upper() for x in (d.get("protocols") or [])}
|
||
if parsed["protocols"] and prot & set(parsed["protocols"]):
|
||
s += 15
|
||
why.append("protocol match")
|
||
feats = {str(x).lower() for x in (d.get("features") or [])}
|
||
if parsed["features"] and all(f.lower() in feats for f in parsed["features"]):
|
||
s += 10
|
||
why.append("feature match")
|
||
if d.get("form_factor") == (target or {}).get("form_factor"):
|
||
s += 10
|
||
why.append("same form_factor")
|
||
if d.get("sales_scope") == "alternative":
|
||
s += 5
|
||
why.append("alternative vendor")
|
||
# близость числовых характеристик
|
||
for k, label in (("zoom_optical", "зум"), ("pickup_m", "захват"), ("fov_h", "FOV")):
|
||
tv, cv = tspec.get(k), cs.get(k)
|
||
if tv and cv:
|
||
diff = abs(float(tv) - float(cv)) / max(float(tv), 1)
|
||
s += max(0, 10 - int(diff * 10))
|
||
why.append("%s ~ %s" % (label, cv))
|
||
gaps = []
|
||
if is_archived(d):
|
||
gaps.append("снято с продажи — нельзя купить, только замена/существующий парк")
|
||
else:
|
||
s += 3
|
||
why.append("active")
|
||
if target is not None:
|
||
if cs.get("4k") is None:
|
||
gaps.append("4K не подтверждён")
|
||
if cs.get("sip") is None and tspec.get("sip") is True:
|
||
gaps.append("SIP не подтверждён")
|
||
if tspec.get("pickup_m") and cs.get("pickup_m") and cs["pickup_m"] < tspec["pickup_m"]:
|
||
gaps.append("захват меньше: %s < %s м" % (cs["pickup_m"], tspec["pickup_m"]))
|
||
if tspec.get("zoom_optical") and cs.get("zoom_optical") and cs["zoom_optical"] < tspec["zoom_optical"]:
|
||
gaps.append("зум меньше")
|
||
if target.get("form_factor") and d.get("form_factor") != target.get("form_factor"):
|
||
gaps.append("другой форм-фактор")
|
||
if cs.get("room_size") is None:
|
||
gaps.append("вместимость комнаты не подтверждена")
|
||
cand.append({"name": _dev_name(d), "vendor": d.get("vendor"),
|
||
"domain": d.get("domain"), "domain_label": domain_label(d.get("domain")),
|
||
"solution_class": d.get("solution_class"), "class_label": class_label(d.get("solution_class")),
|
||
"sales_scope": d.get("sales_scope"),
|
||
"protocols": d.get("protocols") or [], "specs": cs,
|
||
"archived": is_archived(d),
|
||
"score": s, "why": why, "gaps": gaps})
|
||
cand.sort(key=lambda x: (-x["score"], x["vendor"] or "", x["name"]))
|
||
# если фильтр по протоколу/фиче дал 0 — не врём, а сообщаем о нехватке данных
|
||
if parsed["protocols"] and not any("protocol match" in x["why"] for x in cand):
|
||
parsed["note"] = "в каталоге нет подтверждённых protocols для этого класса — фильтр не применён"
|
||
if parsed["features"] and not any("feature match" in x["why"] for x in cand):
|
||
parsed["note"] = (parsed["note"] + "; " if parsed["note"] else "") + "нет подтверждённых features 4K"
|
||
return {"query": q, "domain": domain,
|
||
"target": ({"name": _dev_name(target), "vendor": target.get("vendor"),
|
||
"solution_class": target.get("solution_class"),
|
||
"deployment": target.get("deployment"),
|
||
"components": target.get("components") or []} if target else None),
|
||
"parsed": parsed,
|
||
"alternatives": cand[:6],
|
||
"note": "Только same domain + solution_class; телефония не предлагается для VCS."}
|
||
|
||
|
||
|
||
def specs(d):
|
||
"""Канонические характеристики для сравнения. None = нет подтверждённых данных."""
|
||
name = _dev_name(d)
|
||
a = D.attrs.get(norm(name), {})
|
||
fs = {str(x).lower() for x in _features(d)}
|
||
prot = {str(x).upper() for x in (d.get("protocols") or [])}
|
||
|
||
def num(k):
|
||
v = a.get(k)
|
||
try:
|
||
return float(v)
|
||
except Exception:
|
||
return None
|
||
|
||
maxres = str(a.get("camera.max_resolution") or "").lower()
|
||
fourk = ("4k" in fs or "3840" in maxres or "4k" in maxres)
|
||
return {
|
||
"4k": True if fourk else (False if fs or maxres else None),
|
||
"sip": True if "SIP" in prot else (False if prot else None),
|
||
"h323": True if any("H.323" in p or "H323" in p for p in prot) else (False if prot else None),
|
||
"zoom_optical": num("camera.zoom_optical"),
|
||
"fov_h": num("camera.fov_h"),
|
||
"pickup_m": num("audio.pickup_m"),
|
||
"mic_count": num("audio.mic_count"),
|
||
"room_size": d.get("room_size") or a.get("room.max_participants"),
|
||
"display_inch": d.get("display_inch"),
|
||
"form_factor": d.get("form_factor"),
|
||
"native_vcs": d.get("native_vcs"),
|
||
"deployment": d.get("deployment"),
|
||
"verified": bool((d.get("source") or {}).get("verified")),
|
||
"sources": (d.get("source") or {}).get("files") or [],
|
||
}
|
||
|
||
|
||
def compare_devices(keys):
|
||
ds = []
|
||
for k in keys:
|
||
d = find_device(k)
|
||
if d and d not in ds:
|
||
ds.append(d)
|
||
if not ds:
|
||
return {"error": "not_found", "keys": keys}
|
||
fields = [
|
||
("vendor", "Вендор"), ("solution_class", "Класс"), ("form_factor", "Форм-фактор"),
|
||
("4k", "4K"), ("sip", "SIP"), ("h323", "H.323"), ("zoom_optical", "Оптический зум"),
|
||
("fov_h", "FOV"), ("pickup_m", "Захват, м"), ("mic_count", "Микрофоны"),
|
||
("room_size", "Комната"), ("native_vcs", "Native VCS"), ("deployment", "Deployment"),
|
||
]
|
||
cols, rows = [], []
|
||
for d in ds:
|
||
s = specs(d)
|
||
cols.append({"key": _key(d), "name": _dev_name(d), "vendor": d.get("vendor")})
|
||
for f, label in fields:
|
||
vals = []
|
||
for d in ds:
|
||
v = specs(d).get(f) if f in specs(d) else d.get(f)
|
||
if v is None or v == "":
|
||
v = None
|
||
elif isinstance(v, bool):
|
||
v = "да" if v else "нет"
|
||
vals.append(v)
|
||
rows.append({"field": f, "label": label, "values": vals})
|
||
return {"columns": cols, "rows": rows, "note": "— = нет подтверждённых данных; не выдумываем."}
|
||
|
||
|
||
def _key(d):
|
||
return d.get("id") or norm(_dev_name(d))
|
||
|
||
|
||
def _features(d):
|
||
"""features из записи + глобального индекса (для Yealink)."""
|
||
fs = set(str(x) for x in (d.get("features") or []))
|
||
fs.update(D.feats.get(norm(_dev_name(d)), set()))
|
||
return sorted(fs)
|
||
|
||
|
||
def search_catalog(params):
|
||
q = (params.get("q", [""])[0] or "").strip()
|
||
vendor = (params.get("vendor", [""])[0] or "all").lower()
|
||
domain = (params.get("domain", [""])[0] or "all").lower()
|
||
cls = (params.get("class", [""])[0] or "").strip()
|
||
role = (params.get("role", [""])[0] or "").strip()
|
||
protocol = (params.get("protocol", [""])[0] or "").strip().upper()
|
||
feature = (params.get("feature", [""])[0] or "").strip()
|
||
arch_mode = (params.get("archived", ["all"])[0] or "all").lower()
|
||
market = (params.get("market", ["all"])[0] or "all").lower()
|
||
low = q.lower()
|
||
interpreted = []
|
||
if not cls:
|
||
if "бар" in low or "bar" in low:
|
||
cls = "vcs.bar.room" if "компакт" not in low else "vcs.bar.compact"
|
||
interpreted.append("класс: бар")
|
||
elif "камер" in low:
|
||
cls = "vcs.camera.usb"
|
||
interpreted.append("класс: камера")
|
||
elif "терминал" in low or "кодек" in low:
|
||
cls = "vcs.terminal.room"
|
||
interpreted.append("класс: терминал")
|
||
elif "byod" in low:
|
||
interpreted.append("контекст: BYOD")
|
||
if not protocol and "sip" in low:
|
||
protocol = "SIP"
|
||
interpreted.append("протокол: SIP")
|
||
if "h.323" in low or "h323" in low:
|
||
protocol = "H.323"
|
||
interpreted.append("протокол: H.323")
|
||
if not feature and "4k" in low:
|
||
feature = "4K"
|
||
interpreted.append("4K")
|
||
|
||
items = []
|
||
target_hit = find_device(q) if q else None
|
||
apply_text = bool(low) and (target_hit is not None or not interpreted)
|
||
for d in D.analog_devices:
|
||
if arch_mode == "only" and not is_archived(d):
|
||
continue
|
||
if arch_mode not in ("only", "all") and is_archived(d):
|
||
continue
|
||
if market not in ("", "all"):
|
||
mv = d.get("market") or "both"
|
||
mvs = d.get("markets") or [mv]
|
||
if market not in mvs and mv not in (market, "both"):
|
||
continue
|
||
if vendor not in ("", "all") and d.get("vendor") != vendor:
|
||
continue
|
||
if domain not in ("", "all") and d.get("domain") != domain:
|
||
continue
|
||
if cls and d.get("solution_class") != cls:
|
||
continue
|
||
if role and d.get("role") != role:
|
||
continue
|
||
prot = [str(x).upper() for x in (d.get("protocols") or [])]
|
||
fs = _features(d)
|
||
text = " ".join([_dev_name(d), str(d.get("vendor")), str(d.get("solution_class")),
|
||
str(d.get("role")), " ".join(prot), " ".join(fs),
|
||
" ".join(str(x) for x in (d.get("aliases") or []))]).lower()
|
||
if apply_text and low not in text:
|
||
continue
|
||
items.append(d)
|
||
|
||
note = ""
|
||
# протокол/4K — мягкие фильтры: если подтверждённых данных нет,
|
||
# не обнуляем выдачу, а показываем кандидатов и предупреждение
|
||
if protocol:
|
||
strict = [d for d in items if protocol in [str(x).upper() for x in (d.get("protocols") or [])]]
|
||
if strict:
|
||
items = strict
|
||
else:
|
||
note = "нет подтверждённых %s — фильтр не применён" % protocol
|
||
if feature:
|
||
strict = [d for d in items if any(feature.lower() in str(x).lower() for x in _features(d))]
|
||
if strict:
|
||
items = strict
|
||
else:
|
||
note = (note + "; " if note else "") + "нет подтверждённых %s — фильтр не применён" % feature
|
||
|
||
fv, fd, fc, fp = {}, {}, {}, {}
|
||
for d in items:
|
||
fv[d.get("vendor")] = fv.get(d.get("vendor"), 0) + 1
|
||
fd[d.get("domain")] = fd.get(d.get("domain"), 0) + 1
|
||
fc[d.get("solution_class")] = fc.get(d.get("solution_class"), 0) + 1
|
||
for p in (d.get("protocols") or []):
|
||
fp[str(p).upper()] = fp.get(str(p).upper(), 0) + 1
|
||
|
||
items.sort(key=lambda d: ((d.get("vendor") or ""), (d.get("solution_class") or ""), _dev_name(d)))
|
||
out = [{"key": _key(d), "name": _dev_name(d), "vendor": d.get("vendor"),
|
||
"domain": d.get("domain"), "domain_label": domain_label(d.get("domain")),
|
||
"market": d.get("market"), "markets": d.get("markets") or [],
|
||
"market_label": market_label(d.get("market")),
|
||
"solution_class": d.get("solution_class"), "class_label": class_label(d.get("solution_class")),
|
||
"role": d.get("role"), "role_label": role_label(d.get("role")),
|
||
"form_factor": d.get("form_factor"),
|
||
"protocols": d.get("protocols") or [], "sales_scope": d.get("sales_scope"),
|
||
"deployment": d.get("deployment"), "features": _features(d)[:8],
|
||
"archived": is_archived(d), "specs": specs(d)}
|
||
for d in items[:100]]
|
||
return {"query": q, "vendor": vendor, "domain": domain,
|
||
"interpreted": interpreted, "total": len(items), "items": out,
|
||
"facets": {"vendors": fv, "domains": fd, "classes": fc, "protocols": fp},
|
||
"note": note}
|
||
|
||
|
||
def find_device(key):
|
||
k = (key or "").strip().lower()
|
||
for d in D.analog_devices:
|
||
if k in (_dev_name(d).lower(), str(d.get("id") or "").lower()):
|
||
return d
|
||
if any(k == str(a).lower() for a in (d.get("aliases") or [])):
|
||
return d
|
||
for d in D.analog_devices:
|
||
if k and k in _dev_name(d).lower():
|
||
return d
|
||
return None
|
||
|
||
|
||
def product_info(key):
|
||
d = find_device(key)
|
||
if not d:
|
||
return {"error": "not_found", "key": key}
|
||
return {"product": {"key": _key(d), "name": _dev_name(d), "vendor": d.get("vendor"),
|
||
"domain": d.get("domain"), "domain_label": domain_label(d.get("domain")),
|
||
"market": d.get("market"), "markets": d.get("markets") or [],
|
||
"market_label": market_label(d.get("market")),
|
||
"solution_class": d.get("solution_class"), "class_label": class_label(d.get("solution_class")),
|
||
"role": d.get("role"), "role_label": role_label(d.get("role")),
|
||
"form_factor": d.get("form_factor"),
|
||
"protocols": d.get("protocols") or [], "sales_scope": d.get("sales_scope"),
|
||
"deployment": d.get("deployment"), "components": d.get("components") or [],
|
||
"features": _features(d), "archived": is_archived(d),
|
||
"specs": specs(d),
|
||
"attributes": D.attrs.get(norm(_dev_name(d)), {})},
|
||
"analogs": analog_search(_dev_name(d), d.get("domain") or "vcs")}
|
||
|
||
|
||
def coverage_report():
|
||
mats = load_yaml("materials.yaml").get("materials") or []
|
||
mat_by_vendor = {}
|
||
for m in mats:
|
||
mat_by_vendor[m.get("vendor")] = mat_by_vendor.get(m.get("vendor"), 0) + 1
|
||
by = {}
|
||
for d in D.analog_devices:
|
||
v = d.get("vendor") or "unknown"
|
||
dom = d.get("domain") or "unknown"
|
||
x = by.setdefault((v, dom), {"vendor": v, "domain": dom, "total": 0, "protocols": 0, "4k": 0,
|
||
"room_size": 0, "compatibility": 0, "archived": 0})
|
||
x["total"] += 1
|
||
s = specs(d)
|
||
if s.get("sip") is not None or s.get("h323") is not None:
|
||
x["protocols"] += 1
|
||
if s.get("4k") is not None:
|
||
x["4k"] += 1
|
||
if s.get("room_size") is not None:
|
||
x["room_size"] += 1
|
||
if D.edges.get(norm(_dev_name(d))):
|
||
x["compatibility"] += 1
|
||
if is_archived(d):
|
||
x["archived"] += 1
|
||
x["materials"] = mat_by_vendor.get(v, 0)
|
||
out = []
|
||
for key, x in by.items():
|
||
t = max(1, x["total"])
|
||
x["coverage_pct"] = round(100 * sum(min(1, x[k] / t) for k in ("protocols", "4k", "room_size", "compatibility")) / 4)
|
||
out.append(x)
|
||
return {"vendors": sorted(out, key=lambda z: (-z["total"], z["vendor"], z["domain"])),
|
||
"totals": {"devices": len(D.analog_devices), "materials": len(mats),
|
||
"archived": sum(1 for d in D.analog_devices if is_archived(d))},
|
||
"note": "Coverage — доля моделей с подтверждёнными protocols, 4K, room size и compatibility. Материалы — L2-контекст."}
|
||
|
||
|
||
def room_roles():
|
||
return {"roles": [
|
||
{"id": "terminal", "name": "Терминал / ПК", "roles": ["codec", "pc", "kit"], "required": True},
|
||
{"id": "camera", "name": "Камера", "roles": ["camera"], "required": False},
|
||
{"id": "audio", "name": "Аудио", "roles": ["audio", "speaker"], "required": False},
|
||
{"id": "touch", "name": "Панель", "roles": ["touch"], "required": False},
|
||
{"id": "display", "name": "Дисплей", "roles": ["display"], "required": False},
|
||
{"id": "mount", "name": "Крепление", "roles": ["mount"], "required": False},
|
||
]}
|
||
|
||
|
||
def room_needs(host):
|
||
d = find_device(host)
|
||
if not d:
|
||
return {"error": "not_found", "host": host}
|
||
groups = []
|
||
if norm(_dev_name(d)) in D.devices:
|
||
try:
|
||
groups = D.groups(_dev_name(d), []).get("groups") or []
|
||
except Exception:
|
||
groups = []
|
||
# дополнительные BYOD/презентационные аксессуары, если их нет в графе
|
||
if not any(g.get("id") == "sharing" for g in groups):
|
||
sharing = []
|
||
for x in D.analog_devices:
|
||
if x.get("vendor") != d.get("vendor") or x.get("domain") != "vcs":
|
||
continue
|
||
if x.get("solution_class") == "vcs.sharing":
|
||
sharing.append({"model": _dev_name(x), "role": x.get("role") or "sharing_hub",
|
||
"max_qty": 1, "condition": "проверить совместимость"})
|
||
if sharing:
|
||
groups.append({"id": "sharing", "name": "Презентация / BYOD", "items": sharing[:10]})
|
||
return {"host": _dev_name(d), "vendor": d.get("vendor"),
|
||
"archived": is_archived(d), "groups": groups}
|
||
|
||
|
||
def compose_room(payload):
|
||
seats = int(payload.get("seats") or 8)
|
||
roles = payload.get("roles") or {}
|
||
vendor = (payload.get("vendor") or "").strip().lower()
|
||
if vendor == "all":
|
||
vendor = ""
|
||
expected = {"terminal": ("codec", "pc", "kit"), "camera": ("camera",),
|
||
"audio": ("audio", "speaker"), "touch": ("touch",),
|
||
"display": ("display",), "mount": ("mount",)}
|
||
items, warnings, seen = [], [], {}
|
||
|
||
def add_item(rid, model, qty=1):
|
||
if not model:
|
||
return
|
||
try:
|
||
qty = max(1, min(99, int(qty or 1)))
|
||
except Exception:
|
||
qty = 1
|
||
d = find_device(model)
|
||
if not d:
|
||
warnings.append({"level": "warning", "text": "не найдено: %s" % model})
|
||
return
|
||
if d.get("domain") != "vcs":
|
||
warnings.append({"level": "blocker", "text": "%s не из VCS — нельзя в комнату" % _dev_name(d)})
|
||
return
|
||
if rid in expected and d.get("role") not in expected[rid]:
|
||
warnings.append({"level": "warning", "text": "%s не подходит на роль %s" % (_dev_name(d), rid)})
|
||
k = _key(d)
|
||
if k in seen:
|
||
seen[k]["qty"] += qty
|
||
return
|
||
item = {"role": rid, "key": k, "name": _dev_name(d), "vendor": d.get("vendor"),
|
||
"solution_class": d.get("solution_class"), "class_label": class_label(d.get("solution_class")),
|
||
"role_label": role_label(rid), "form_factor": d.get("form_factor"),
|
||
"qty": qty, "archived": is_archived(d), "purchasable": not is_archived(d)}
|
||
seen[k] = item
|
||
items.append(item)
|
||
if is_archived(d):
|
||
warnings.append({"level": "warning",
|
||
"text": "%s снято с продажи — в проект можно, купить нельзя" % _dev_name(d)})
|
||
|
||
for rid, val in roles.items():
|
||
if isinstance(val, dict):
|
||
add_item(rid, val.get("model"), val.get("qty") or 1)
|
||
else:
|
||
add_item(rid, val, 1)
|
||
for e in (payload.get("extras") or []):
|
||
if isinstance(e, dict):
|
||
add_item(e.get("role") or "extra", e.get("model"), e.get("qty") or 1)
|
||
terminal = next((x for x in items if x["role"] == "terminal"), None)
|
||
if not terminal:
|
||
warnings.append({"level": "blocker", "text": "нет терминала/ПК"})
|
||
if not vendor and terminal:
|
||
vendor = terminal.get("vendor") or ""
|
||
vendors = sorted({x.get("vendor") for x in items if x.get("vendor")})
|
||
if vendor:
|
||
bad = [x for x in items if x.get("vendor") != vendor]
|
||
if bad:
|
||
warnings.append({"level": "blocker",
|
||
"text": "Вендор комнаты — %s. Нельзя смешивать: %s" % (
|
||
vendor, ", ".join("%s (%s)" % (x["name"], x["vendor"]) for x in bad))})
|
||
elif len(vendors) > 1:
|
||
warnings.append({"level": "blocker",
|
||
"text": "Разные вендоры в одной комнате: " + ", ".join(vendors)})
|
||
deployment = "native_vcs"
|
||
if terminal:
|
||
d = find_device(terminal["key"])
|
||
if d and (d.get("role") == "pc" or d.get("solution_class") == "vcs.byod.kit" or d.get("deployment") == "byod"):
|
||
deployment = "byod"
|
||
return {"seats": seats, "vendor": vendor, "deployment": deployment, "items": items,
|
||
"total_qty": sum(x.get("qty", 1) for x in items),
|
||
"purchasable": all(x.get("purchasable", True) for x in items),
|
||
"warnings": warnings, "ready": not any(w["level"] == "blocker" for w in warnings),
|
||
"note": "Вендор — жёсткая граница: аксессуары и компоненты только этого вендора. Порты — в классическом конструкторе."}
|
||
|
||
|
||
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()
|
||
self.send_response(code)
|
||
self.send_header("Content-Type", ctype)
|
||
self.send_header("Content-Length", str(len(body)))
|
||
self.end_headers()
|
||
self.wfile.write(body)
|
||
|
||
def log_message(self, *a):
|
||
pass
|
||
|
||
def do_GET(self):
|
||
u = urllib.parse.urlparse(self.path)
|
||
q = urllib.parse.parse_qs(u.query)
|
||
p = u.path
|
||
if p in ("/", "/studio"):
|
||
f = os.path.join(os.path.dirname(__file__), "studio.html")
|
||
if not os.path.exists(f):
|
||
f = os.path.join(os.path.dirname(__file__), "index.html")
|
||
return self._out(open(f, encoding="utf-8").read().encode(), ctype="text/html; charset=utf-8")
|
||
if p == "/classic":
|
||
f = os.path.join(os.path.dirname(__file__), "index.html")
|
||
return self._out(open(f, encoding="utf-8").read().encode(), ctype="text/html; charset=utf-8")
|
||
if p in ("/health", "/api/health"):
|
||
return self._out({"ok": True, "service": "combine-web", "devices": len(D.devices)})
|
||
if p == "/api/stats":
|
||
return self._out({"devices": len(D.devices),
|
||
"edges": sum(len(v) for v in D.edges.values()),
|
||
"hosts": len(D.hosts()),
|
||
"mounts": len(D.mounts.get("mounts") or []),
|
||
"attrs": len(D.attrs)})
|
||
if p == "/api/coverage":
|
||
return self._out(coverage_report())
|
||
if p == "/api/directions":
|
||
return self._out(DIRECTIONS)
|
||
if p == "/api/telephony":
|
||
return self._out(load_yaml("telephony.yaml"))
|
||
if p == "/api/materials":
|
||
v = (q.get("vendor", [""])[0] or "").lower()
|
||
m = (q.get("model", [""])[0] or "").lower()
|
||
t = (q.get("type", [""])[0] or "").lower()
|
||
data = load_yaml("materials.yaml").get("materials") or []
|
||
out = []
|
||
for x in data:
|
||
if v and str(x.get("vendor") or "").lower() != v:
|
||
continue
|
||
if m and m not in str(x.get("model") or "").lower():
|
||
continue
|
||
if t and str(x.get("type") or "").lower() != t:
|
||
continue
|
||
out.append(x)
|
||
return self._out({"materials": out})
|
||
if p == "/api/analogs":
|
||
return self._out(analog_search(q.get("q", [""])[0], q.get("domain", ["vcs"])[0]))
|
||
if p == "/api/vendor-catalog":
|
||
v = (q.get("vendor", ["yealink"])[0] or "yealink").lower()
|
||
domain = (q.get("domain", ["vcs"])[0] or "vcs").lower()
|
||
data = D.cat if v == "yealink" else load_yaml("catalog-%s.yaml" % v)
|
||
out = dict(data)
|
||
if domain not in ("", "all"):
|
||
out["devices"] = [x for x in (data.get("devices") or []) if x.get("domain") == domain]
|
||
return self._out(out)
|
||
if p == "/api/search":
|
||
return self._out(search_catalog(q))
|
||
if p == "/api/product":
|
||
return self._out(product_info(q.get("key", [""])[0]))
|
||
if p == "/api/compare":
|
||
keys = [x for x in (q.get("keys", [""])[0] or "").split(",") if x]
|
||
return self._out(compare_devices(keys))
|
||
if p == "/api/archive":
|
||
return self._out({"items": archived_items()})
|
||
if p == "/api/room-roles":
|
||
return self._out(room_roles())
|
||
if p == "/api/room-needs":
|
||
return self._out(room_needs(q.get("host", [""])[0]))
|
||
if p == "/api/hosts":
|
||
return self._out(D.hosts())
|
||
if p == "/api/requirements":
|
||
return self._out(D.requirements())
|
||
if p == "/api/device":
|
||
k = norm(q.get("key", [""])[0])
|
||
if k not in D.devices:
|
||
return self._out({"error": "not found"}, 404)
|
||
return self._out(D.device_row(k))
|
||
if p == "/api/groups":
|
||
return self._out(D.groups(q.get("host", [""])[0],
|
||
[x for x in q.get("need", []) if x]))
|
||
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":
|
||
return self._out(D.kits)
|
||
if p == "/api/check":
|
||
return self._out(D.check_pair(q.get("host", [""])[0],
|
||
q.get("device", [""])[0]))
|
||
if p == "/api/matrix":
|
||
return self._out(D.matrix())
|
||
if p == "/api/ports":
|
||
return self._out(D.ports_table())
|
||
if p == "/api/links":
|
||
items = [x for x in q.get("item", []) if x]
|
||
return self._out(D.link_plan(q.get("host", [""])[0], items))
|
||
if p == "/api/capacity":
|
||
items = []
|
||
for raw in q.get("item", []):
|
||
if ":" in raw:
|
||
m, n = raw.rsplit(":", 1)
|
||
try:
|
||
items.append([m, int(n)])
|
||
except ValueError:
|
||
pass
|
||
return self._out(D.capacity(q.get("host", [""])[0], items))
|
||
if p == "/api/vendors":
|
||
return self._out(VENDORS)
|
||
if p == "/api/options":
|
||
return self._out(D.options(q.get("host", [""])[0],
|
||
[x for x in q.get("need", []) if x]))
|
||
if p == "/api/bom":
|
||
need = [x for x in q.get("need", []) if x]
|
||
add = [x for x in q.get("add", []) if x]
|
||
return self._out(D.bom(q.get("host", [""])[0],
|
||
int(q.get("seats", ["8"])[0]), need, add))
|
||
return self._out({"error": "not found"}, 404)
|
||
|
||
|
||
def do_POST(self):
|
||
u = urllib.parse.urlparse(self.path)
|
||
if u.path == "/api/archive":
|
||
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)
|
||
d = find_device(payload.get("key") or payload.get("name") or "")
|
||
if not d:
|
||
return self._out({"error": "not_found"}, 404)
|
||
return self._out(set_archive(d, payload.get("action") or "archive", payload.get("reason") or ""))
|
||
if u.path == "/api/room":
|
||
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(compose_room(payload))
|
||
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
|
||
|
||
|
||
if __name__ == "__main__":
|
||
import sys
|
||
port = int(sys.argv[1]) if len(sys.argv) > 1 else 8095
|
||
print("combine v2 on :%d" % port, flush=True)
|
||
S(("0.0.0.0", port), H).serve_forever()
|