diff --git a/ops/work/web/services/svc_engine.py b/ops/work/web/services/svc_engine.py index dd02761..f1730e8 100644 --- a/ops/work/web/services/svc_engine.py +++ b/ops/work/web/services/svc_engine.py @@ -127,7 +127,12 @@ def bom(q, body): "why": "нужно %s м, у %s %s м" % (need_m, e["to"], p or "—")}) cams = by_role("camera") if cams: - cams.sort(key=lambda e: -((C.attrs.get(cc.norm(e["to"]), {}).get("camera.zoom_optical") or 0)), reverse=True) + 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", "Презентация")): @@ -158,6 +163,114 @@ def bom(q, body): "cables": C.cable_schedule(hk, items)} +def autofill(q, body): + """Guided default: собрать состав по комнате автоматически.""" + res = bom(q, body) + if res.get("error"): + return res + items = [] + for b in res["bom"]: + if b["model"].startswith(("встроенный", "внешний")): + continue + items.append({"model": b["model"], "qty": b["qty"], "role": b["role"], + "why": b.get("why")}) + return {"host": res["host"], "seats": res["seats"], + "items": items, "warnings": res["warnings"], + "capacity": res["capacity"], "completeness": C.completeness(cc.norm(res["host"]))} + + +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"} + + serve({ "/groups": groups, "/check": check, @@ -165,4 +278,7 @@ serve({ "/ports": port_plan, "/cables": cables, "/bom": bom, + "/autofill": autofill, + "/checklist": checklist, + "/xlsx": xlsx, }, int(sys.argv[1]) if len(sys.argv) > 1 else 8102, "engine") diff --git a/ops/work/web/svc_base.py b/ops/work/web/svc_base.py index 88df875..441cda5 100644 --- a/ops/work/web/svc_base.py +++ b/ops/work/web/svc_base.py @@ -17,7 +17,20 @@ def serve(routes, port, name): """routes: {path: callable(q: dict, body: dict|None) -> dict}""" class H(BaseHTTPRequestHandler): + def _send_file(self, data, filename, ctype): + self.send_response(200) + self.send_header("Content-Type", ctype) + self.send_header("Content-Disposition", 'attachment; filename="%s"' % filename) + self.send_header("Content-Length", str(len(data))) + for k, v in CORS.items(): + self.send_header(k, v) + self.end_headers() + self.wfile.write(data) + def _send(self, obj, code=200): + if isinstance(obj, dict) and obj.get("__file__"): + return self._send_file(obj["__file__"], obj.get("filename", "file"), + obj.get("content_type", "application/octet-stream")) body = json.dumps(obj, ensure_ascii=False).encode() self.send_response(code) self.send_header("Content-Type", "application/json; charset=utf-8") diff --git a/ops/work/web/webui.html b/ops/work/web/webui.html new file mode 100644 index 0000000..9972a35 --- /dev/null +++ b/ops/work/web/webui.html @@ -0,0 +1,330 @@ + + +
+ +