#!/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": 8, "condition": (x.get("evidence") or "")[:110], "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: def cam_score(e): a = C.attrs.get(cc.norm(e["to"]), {}) zoom = (a.get("camera.zoom_optical") or 0) + (a.get("camera.zoom_hybrid") or 0) content = 1 if "content camera" in (e.get("condition") or "").lower() else 0 return zoom - content * 100 cams.sort(key=cam_score, 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)} def accessory_hosts(q, body): """Обратный взгляд: какой аксессуар поддерживают какие хосты.""" ak = cc.norm((q.get("device") or [""])[0]) name = C.devices.get(ak, {}).get("name") or (q.get("device") or [""])[0] hosts = [] for hk, edges in C.edges.items(): if C.devices.get(hk, {}).get("role") != "codec": continue for e in edges: if cc.norm(e["to"]) != ak: continue if not e.get("supported") or not e.get("usable", True): continue hosts.append({"host": C.devices[hk]["name"], "max_qty": e.get("max_qty"), "condition": (e.get("condition") or "").strip()[:120]}) break return {"device": name, "hosts": sorted(hosts, key=lambda x: x["host"]), "count": len(hosts)} def autofill(q, body): """Guided default: собрать состав по выбору пользователя.""" host = (q.get("host") or [""])[0] seats = int((q.get("seats") or ["8"])[0]) include = [x for x in (q.get("include") or []) if x] need = [x for x in (q.get("need") or []) if x] return C.autofill(host, seats, include or None, need) def checklist(q, body): """Полнота проекта: чего не хватает по ролям и предупреждения.""" hk = cc.norm((q.get("host") or [""])[0]) if hk not in C.devices: return {"error": "хост не найден"} items = _items(q) models = {cc.norm(r[0]) for r in items} roles = {C.devices.get(m, {}).get("role") for m in models} role = C.devices[hk]["role"] checks = [] def add(ok, name, hint): checks.append({"ok": bool(ok), "name": name, "hint": hint}) add("codec" in roles or True, "Хост выбран", "основа системы") add(bool(models & {m for m in models if C.devices.get(m, {}).get("role") == "audio"}) or C.attrs.get(hk, {}).get("audio.pickup_m"), "Микрофоны / покрытие", "встроенного захвата нет — добавьте микрофон") add("camera" in roles or C.completeness(hk)["level"] != "none", "Камера", "нет камеры в составе") add("touch" in roles, "Панель управления", "нет панели — управление со смартфона") add("display" in roles, "Дисплей", "нет совместимого дисплея — нужен внешний ТВ") add("mount" in roles, "Крепление", "нет кронштейна") cap = C.capacity(hk, items) add(not cap["issues"], "Ёмкость портов и питания", "; ".join(cap["issues"]) or "пройдено") missing = [m for m in models if not C.package(C.devices.get(m, {}).get("name", m))["items"]] add(True, "Комплектация", "нет данных о комплектации: " + ", ".join( C.devices.get(m, {}).get("name", m) for m in missing[:4]) if missing else "известна") done = sum(1 for c in checks if c["ok"]) return {"host": C.devices[hk]["name"], "checks": checks, "passed": done, "total": len(checks), "ready": done == len(checks), "capacity": cap} def xlsx(q, body): """Экспорт BOM и кабельного журнала в XLSX.""" import openpyxl from openpyxl.styles import Font, PatternFill res = bom(q, body) if res.get("error"): return res wb = openpyxl.Workbook() hdr = Font(color="FFFFFF", bold=True) fill = PatternFill("solid", fgColor="1F4E78") ws = wb.active ws.title = "BOM" ws.append(["Роль", "Модель", "Кол", "Обоснование"]) for b in res["bom"]: ws.append([b["role"], b["model"], b["qty"], b.get("why") or ""]) for c in ws[1]: c.font = hdr c.fill = fill ws.freeze_panes = "A2" for col in ws.columns: ws.column_dimensions[col[0].column_letter].width = 28 ws2 = wb.create_sheet("Кабели") ws2.append(["От", "Порт", "К", "Порт", "Тип", "Кол", "Примечание"]) for c in (res.get("cables") or {}).get("cables") or []: ws2.append([c["from"], c["from_port"], c["to"], c["to_port"], c["type"], c["qty"], c.get("note") or ""]) for c in ws2[1]: c.font = hdr c.fill = fill ws3 = wb.create_sheet("Комплектация") ws3.append(["Устройство", "В комплекте"]) for inc in res.get("included") or []: ws3.append([inc["device"], " · ".join(inc["items"])]) for c in ws3[1]: c.font = hdr c.fill = fill ws4 = wb.create_sheet("Проверки") ws4.append(["Показатель", "Значение"]) cap = res.get("capacity") or {} for k in ("vch_ports", "vch_users", "total_power_w", "extra_ports", "extra_budget_w"): ws4.append([k, cap.get(k)]) for i in cap.get("issues") or []: ws4.append(["проблема", i]) import io as _io buf = _io.BytesIO() wb.save(buf) return {"__file__": buf.getvalue(), "filename": "bom-%s.xlsx" % cc.norm(res["host"])[:20], "content_type": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"} def signals(q, body): return C.signal_chains((q.get("host") or [""])[0], _items(q)) def port_objects(q, body): name = (q.get("device") or [""])[0] return {"device": name, "ports": C.port_objects(name)} def review(q, body): """Ревью проекта: проблемы с серьёзностью, до закупки.""" hk = cc.norm((q.get("host") or [""])[0]) if hk not in C.devices: return {"error": "хост не найден"} items = _items(q) issues = [] cap = C.capacity(hk, items, q.get("infra") or []) for i in cap["issues"]: issues.append({"level": "blocker", "text": i}) sig = C.signal_chains(hk, items) for r in sig["chains"]: if not r["ok"]: issues.append({"level": "blocker", "text": "%s: %s" % (r["device"], r["reason"])}) comp = C.completeness(hk) if comp["level"] != "full": issues.append({"level": "warning", "text": "неполные данные: " + comp["note"]}) if cap["missing_power"]: issues.append({"level": "warning", "text": "нет данных о питании: " + ", ".join(cap["missing_power"][:6])}) # крепления в комплекте for r in items: if C.mount_included(r[0]): issues.append({"level": "info", "text": "%s: крепление уже в комплекте" % r[0]}) blockers = sum(1 for i in issues if i["level"] == "blocker") return {"host": C.devices[hk]["name"], "issues": issues, "blockers": blockers, "warnings": sum(1 for i in issues if i["level"] == "warning"), "ready": blockers == 0, "checks": len("checklist")} def vendors(q, body): return {"vendors": C.vendors()} serve({ "/groups": groups, "/check": check, "/capacity": capacity, "/ports": port_plan, "/cables": cables, "/bom": bom, "/autofill": autofill, "/accessory": accessory_hosts, "/checklist": checklist, "/signals": signals, "/ports-objects": port_objects, "/review": review, "/vendors": vendors, "/xlsx": xlsx, }, int(sys.argv[1]) if len(sys.argv) > 1 else 8102, "engine")