Files
buryan-infra/ops/work/web/services/svc_engine.py
T

676 lines
30 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python3
"""Сервис ДВИЖОК (8102): совместимость, группы, ёмкость, порты, кабели, BOM."""
import io as _io_top
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()}
def ask(q, body):
"""Advisor: ответ на вопрос по данным модели. Сначала поиск по каталогу,
затем (если доступен) локальный LLM объясняет."""
import json as _json
import urllib.request
question = (q.get("q") or [""])[0].strip()
if not question:
return {"error": "пустой вопрос"}
# 1) ищем упомянутые устройства/хосты
words = [w for w in re.split(r"[^A-Za-z0-9\-]+", question) if len(w) > 1]
hits, pairs = [], []
for w in words:
k = cc.norm(w)
if k in C.devices:
hits.append(C.devices[k]["name"])
for h in list(C.devices.keys()):
if len(h) > 4 and h in cc.norm(question):
if C.devices[h]["name"] not in hits:
hits.append(C.devices[h]["name"])
# 2) если названы два устройства — проверяем пару
if len(hits) >= 2:
cand_hosts = [x for x in hits if C.devices[cc.norm(x)]["role"] == "codec"]
cand_devs = [x for x in hits if x not in cand_hosts]
if cand_hosts and cand_devs:
r = C.check_pair(cand_hosts[0], cand_devs[0])
pairs.append(r)
# 3) строим контекст
ctx = {"devices_named": hits}
if pairs:
ctx["pairs"] = pairs
if hits:
first = C.devices.get(cc.norm(hits[0]))
if first:
ctx["ports"] = dict(zip(("in", "out", "source"), C.ports(first["name"])))
ctx["attributes"] = C.attrs.get(cc.norm(hits[0]), {})
if first["role"] == "codec":
ctx["groups"] = [{"name": g["name"],
"items": [i["model"] for i in g["items"]][:8]}
for g in groups({"host": [cc.norm(hits[0])]}, None).get("groups", [])]
answer = None
try:
body_req = _json.dumps({
"model": "qwen2.5:7b", "stream": False, "options": {"temperature": 0},
"prompt": ("Ты помощник по проектированию ВКС Yealink. Отвечай кратко, "
"только по данным ниже, не выдумывай. Если данных нет — скажи.\n"
"ДАННЫЕ: " + _json.dumps(ctx, ensure_ascii=False) +
"\nВОПРОС: " + question + "\nОТВЕТ:"),
}).encode()
req = urllib.request.Request("http://192.168.1.229:11434/api/generate",
data=body_req,
headers={"Content-Type": "application/json"})
with urllib.request.urlopen(req, timeout=20) as r:
answer = _json.loads(r.read().decode()).get("response", "").strip()
except Exception:
answer = None
if not answer:
if pairs:
answer = pairs[0].get("verdict")
elif hits:
answer = "Найдено: " + ", ".join(hits) + ". Уточните вопрос."
else:
answer = "Не нашёл упоминаний устройств в вопросе."
return {"question": question, "answer": answer, "context": ctx,
"llm": bool(answer and "qwen" )}
def spec(q, body):
"""Спецификация проекта без цен: состав, кабели, проверки, комплектация."""
host = (q.get("host") or [""])[0]
seats = int((q.get("seats") or ["8"])[0])
items = _items(q)
if not items:
b = bom(q, body)
if b.get("error"):
return b
items = [[x["model"], x["qty"]] for x in b["bom"]
if not x["model"].startswith(("встроенный", "внешний"))]
hostname = C.devices.get(cc.norm(host), {}).get("name") or host
cab = C.cable_schedule(host, items)
cap = C.capacity(host, items, q.get("infra") or [])
sig = C.signal_chains(host, items)
rev = review({"host": [host], "item": ["%s:%d" % (i[0], i[1]) for i in items]}, None)
def row(*cells):
return "<tr>" + "".join("<td>%s</td>" % c for c in cells) + "</tr>"
h = ["<html><head><meta charset='utf-8'><title>Спецификация</title>",
"<style>body{font:13px Arial;margin:24px}h2{margin:18px 0 8px}"
"table{border-collapse:collapse;width:100%;margin-bottom:14px}"
"td,th{border:1px solid #999;padding:5px 7px;text-align:left;font-size:12px}"
"th{background:#eee}.warn{color:#a15c00}.bad{color:#a11}</style></head><body>",
"<h1>Спецификация оборудования</h1>",
"<p>Комплекс: %s · мест: %d · режим: без цен</p>" % (hostname, seats),
"<h2>1. Состав</h2><table><tr><th>№</th><th>Модель</th><th>Кол</th></tr>"]
for i, r in enumerate(items, 1):
h.append(row(str(i), r[0], str(r[1])))
h.append("</table><h2>2. Кабельный журнал</h2><table>"
"<tr><th>От</th><th>Порт</th><th>К</th><th>Порт</th><th>Тип</th><th>Примечание</th></tr>")
for c in cab["cables"]:
h.append(row(c["from"], c["from_port"], c["to"], c["to_port"], c["type"],
c.get("note") or ""))
h.append("</table><h2>3. Проверки</h2><table><tr><th>Проверка</th><th>Результат</th></tr>")
h.append(row("порты VCH", "%s у хоста, %s устройств" % (cap["vch_ports"], cap["vch_users"])))
h.append(row("порты коммутаторов", "%s (каскад, коммутаторов %s)"
% (cap["extra_ports"], cap["n_switches"])))
h.append(row("питание", "%.1f Вт потребление · %.1f Вт доп. бюджет"
% (cap["total_power_w"], cap["extra_budget_w"])))
h.append(row("сигнальные цепочки", "%s из %s корректны" % (sig["ok"], sig["total"])))
for i in cap["issues"]:
h.append(row("проблема", "<span class='bad'>%s</span>" % i))
h.append("</table><h2>4. Комплектация</h2><table><tr><th>Устройство</th><th>В комплекте</th></tr>")
for r in items:
p = C.package(r[0])
if p["items"]:
h.append(row(r[0], " · ".join(p["items"])))
h.append("</table><h2>5. Ревью</h2><table><tr><th>Готовность</th><th>Значение</th></tr>")
h.append(row("блокеров", str(rev["blockers"])))
h.append(row("предупреждений", str(rev["warnings"])))
h.append(row("готов к закупке", "да" if rev["ready"] else "нет"))
h.append("</table></body></html>")
html = "".join(h)
return {"__file__": html.encode(), "filename": "spec-%s.html" % cc.norm(hostname)[:18],
"content_type": "text/html; charset=utf-8"}
def override(q, body):
body = body or {}
return C.set_override(body.get("device") or (q.get("device") or [""])[0],
body.get("attr") or (q.get("attr") or [""])[0],
body.get("value") if "value" in body else (q.get("value") or [""])[0])
def pack(q, body):
"""Пакет документов: спецификация, BOM, кабели, IP-план, стойка, FAT-протокол."""
import io as _io
import zipfile
host = (q.get("host") or [""])[0]
seats = int((q.get("seats") or ["8"])[0])
items = _items(q)
if not items:
b = bom(q, body)
if b.get("error"):
return b
items = [[x["model"], x["qty"]] for x in b["bom"]
if not x["model"].startswith(("встроенный", "внешний"))]
hostname = C.devices.get(cc.norm(host), {}).get("name") or host
slug = cc.norm(hostname)[:18]
buf = _io.BytesIO()
z = zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED)
# 1) спецификация (HTML)
sp = spec({"host": [host], "seats": [str(seats)],
"item": ["%s:%d" % (i[0], i[1]) for i in items]}, None)
if isinstance(sp, dict) and sp.get("__file__"):
z.writestr("spec.html", sp["__file__"])
# 2) BOM (XLSX)
xl = xlsx({"host": [host], "seats": [str(seats)],
"item": ["%s:%d" % (i[0], i[1]) for i in items]}, None)
if isinstance(xl, dict) and xl.get("__file__"):
z.writestr("bom.xlsx", xl["__file__"])
# 3) кабельный журнал (CSV)
cab = C.cable_schedule(host, items)
lines = ["from,from_port,to,to_port,type,qty,note"]
for c in cab["cables"]:
lines.append(",".join([c["from"], c["from_port"], c["to"], c["to_port"],
c["type"], str(c["qty"]), (c.get("note") or "")]))
z.writestr("cables.csv", "\n".join(lines).encode("utf-8"))
# 4) IP-план (CSV)
ip_rows, n = [], 10
for r in items:
ins, outs, _ = C.ports(r[0])
if "LAN" not in (ins + outs):
continue
for _ in range(r[1]):
ip_rows.append("%s,10.10.20.%d,VLAN20" % (r[0], n))
n += 1
z.writestr("ipplan.csv", ("device,ip,vlan\n" + "\n".join(ip_rows)).encode("utf-8"))
# 5) стойка (SVG)
try:
import services.svc_draw as _d # noqa
except Exception:
pass
# 5b) PDF-спецификация
try:
pd = pdf({"host": [host], "seats": [str(seats)],
"item": ["%s:%d" % (i[0], i[1]) for i in items]}, None)
if isinstance(pd, dict) and pd.get("__file__"):
z.writestr("spec.pdf", pd["__file__"])
except Exception:
pass
# 6) FAT/SAT протокол (HTML)
cap = C.capacity(host, items, q.get("infra") or [])
sig = C.signal_chains(host, items)
checks = [
("Визуальный осмотр монтажа", ""),
("Питание PoE на всех устройствах", "портов VCH: %s, доп. портов: %s"
% (cap["vch_ports"], cap["extra_ports"])),
("Сигнальные цепочки", "%s из %s корректны" % (sig["ok"], sig["total"])),
("Кабельный журнал сверен", "%s кабелей" % cab["count"]),
("Проверка микрофонов (захват)", "по плану покрытия"),
("Проверка камеры (FOV, фокус)", ""),
("Проверка звука (SPL)", ""),
("Проверка презентации (BYOD)", ""),
("Проверка панели управления", ""),
("Сдача документации (as-built)", "пакет документов"),
]
fat = ["<html><head><meta charset='utf-8'><title>FAT/SAT</title>",
"<style>body{font:13px Arial;margin:24px}table{border-collapse:collapse;width:100%}"
"td,th{border:1px solid #999;padding:6px}th{background:#eee}</style></head><body>",
"<h1>Протокол приёмочных испытаний (FAT/SAT)</h1>",
"<p>Объект: %s · мест: %d</p>" % (hostname, seats),
"<table><tr><th>№</th><th>Проверка</th><th>Данные</th><th>Результат</th><th>Подпись</th></tr>"]
for i, (name, data) in enumerate(checks, 1):
fat.append("<tr><td>%d</td><td>%s</td><td>%s</td><td></td><td></td></tr>"
% (i, name, data))
fat.append("</table><p>Исполнитель: ____________ Заказчик: ____________ Дата: __________</p>")
fat.append("</body></html>")
z.writestr("fat-sat.html", "".join(fat).encode("utf-8"))
# 7) O&M заметка
om = ["# Эксплуатация (O&M)", "",
"Комплекс: %s" % hostname, "Мест: %d" % seats, "",
"## Состав", ""]
for r in items:
om.append("- %s × %d" % (r[0], r[1]))
om += ["", "## Комплектация (что в коробке)", ""]
for r in items:
p = C.package(r[0])
if p["items"]:
om.append("- **%s**: %s" % (r[0], "; ".join(p["items"])))
om += ["", "## Проверки", "",
"- портов VCH у хоста: %s" % cap["vch_ports"],
"- устройств на VCH: %s" % cap["vch_users"],
"- потребление: %.1f Вт" % cap["total_power_w"]]
for i in cap["issues"]:
om.append("- ПРОБЛЕМА: %s" % i)
z.writestr("om.md", "\n".join(om).encode("utf-8"))
z.close()
return {"__file__": buf.getvalue(), "filename": "project-%s.zip" % slug,
"content_type": "application/zip"}
def _fresh():
C.reload_if_changed()
def pdf(q, body):
"""PDF-спецификация: состав, кабели, проверки, комплектация."""
try:
from reportlab.lib.pagesizes import A4
from reportlab.lib.units import mm
from reportlab.pdfgen import canvas
except Exception as e:
return {"error": "нет reportlab: %s" % e}
host = (q.get("host") or [""])[0]
seats = int((q.get("seats") or ["8"])[0])
items = _items(q)
if not items:
b = bom(q, body)
if b.get("error"):
return b
items = [[x["model"], x["qty"]] for x in b["bom"]
if not x["model"].startswith(("встроенный", "внешний"))]
hostname = C.devices.get(cc.norm(host), {}).get("name") or host
cab = C.cable_schedule(host, items)
cap = C.capacity(host, items, q.get("infra") or [])
sig = C.signal_chains(host, items)
buf = _io_top.BytesIO()
c = canvas.Canvas(buf, pagesize=A4)
W, H = A4
y = H - 20 * mm
def line(txt, size=10, bold=False, gap=5):
nonlocal y
if y < 25 * mm:
c.showPage()
y = H - 20 * mm
c.setFont("Helvetica-Bold" if bold else "Helvetica", size)
c.drawString(18 * mm, y, str(txt)[:110])
y -= gap * mm
line("Спецификация оборудования", 15, True, 8)
line("Комплекс: %s мест: %d режим: без цен" % (hostname, seats), 9, False, 8)
line("1. Состав", 12, True, 5)
for i, r in enumerate(items, 1):
line("%2d. %-40s %3d шт" % (i, str(r[0])[:40], r[1]), 9)
y -= 3 * mm
line("2. Кабельный журнал", 12, True, 5)
for cbl in cab["cables"]:
line("%-14s %-8s -> %-14s %-7s %s" % (str(cbl["from"])[:14], cbl["from_port"],
str(cbl["to"])[:14], cbl["to_port"],
cbl.get("note") or ""), 8.5)
y -= 3 * mm
line("3. Проверки", 12, True, 5)
line("портов VCH у хоста: %s, устройств на VCH: %s" % (cap["vch_ports"], cap["vch_users"]))
line("портов коммутаторов: %s (коммутаторов %s)" % (cap["extra_ports"], cap["n_switches"]))
line("потребление: %.1f Вт, доп. бюджет: %.1f Вт"
% (cap["total_power_w"], cap["extra_budget_w"]))
line("сигнальные цепочки: %s из %s корректны" % (sig["ok"], sig["total"]))
for i in cap["issues"]:
line("ПРОБЛЕМА: %s" % i, 8.5)
y -= 3 * mm
line("4. Комплектация", 12, True, 5)
for r in items:
p = C.package(r[0])
if p["items"]:
line("%s: %s" % (str(r[0])[:22], "; ".join(p["items"])[:80]), 8.5)
c.save()
return {"__file__": buf.getvalue(),
"filename": "spec-%s.pdf" % cc.norm(hostname)[:18],
"content_type": "application/pdf"}
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,
"/ask": ask,
"/spec": spec,
"/override": override,
"/pack": pack,
"/pdf": pdf,
"/xlsx": xlsx,
}, int(sys.argv[1]) if len(sys.argv) > 1 else 8102, "engine", before=C.reload_if_changed)