From 8abb809e245bc483f78cdf230b84a4a1d72f63e5 Mon Sep 17 00:00:00 2001 From: Roman Buryan Date: Fri, 6 Nov 2026 18:44:13 +0300 Subject: [PATCH] =?UTF-8?q?[WORK]=20=D0=9F=D0=BE=D0=BA=D1=80=D1=8B=D1=82?= =?UTF-8?q?=D0=B8=D0=B5=20=D0=BF=D0=BE=20=D0=B7=D0=BE=D0=BD=D0=B0=D0=BC=20?= =?UTF-8?q?(=D1=81=D0=B5=D1=82=D0=BA=D0=B0,=20%=20=D0=BF=D0=BB=D0=BE=D1=89?= =?UTF-8?q?=D0=B0=D0=B4=D0=B8),=20=D1=80=D0=BE=D0=BB=D0=B8=20=D0=B8=20?= =?UTF-8?q?=D1=82=D0=BE=D0=BA=D0=B5=D0=BD=D1=8B=20=D0=B7=D0=B0=D0=BF=D0=B8?= =?UTF-8?q?=D1=81=D0=B8=20(viewer/editor/admin),=20=D0=B0=D1=83=D0=B4?= =?UTF-8?q?=D0=B8=D1=82=20=D0=B8=D0=B7=D0=BC=D0=B5=D0=BD=D0=B5=D0=BD=D0=B8?= =?UTF-8?q?=D0=B9,=20=D0=B8=D0=BC=D0=BF=D0=BE=D1=80=D1=82=20=D0=BF=D1=80?= =?UTF-8?q?=D0=BE=D0=B5=D0=BA=D1=82=D0=B0=20=D0=B8=D0=B7=20CSV?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ops/work/compat/access.yaml | 14 +++++++++ ops/work/web/combine_core.py | 46 ++++++++++++++++++++++++++++ ops/work/web/services/svc_draw.py | 40 ++++++++++++++++++++++++ ops/work/web/services/svc_project.py | 30 ++++++++++++++++++ ops/work/web/svc_base.py | 39 +++++++++++++++++++++++ 5 files changed, 169 insertions(+) create mode 100644 ops/work/compat/access.yaml diff --git a/ops/work/compat/access.yaml b/ops/work/compat/access.yaml new file mode 100644 index 0000000..44e9fb6 --- /dev/null +++ b/ops/work/compat/access.yaml @@ -0,0 +1,14 @@ +note: 'роли: viewer (чтение) · editor (изменение) · admin (всё)' +roles: + admin: + token: adm-a06ef28b7100 + can_write: true + editor: + token: ed-e23aca07414f + can_write: true +default: viewer +protected: +- /save +- /delete +- /override +- /import diff --git a/ops/work/web/combine_core.py b/ops/work/web/combine_core.py index 9936e13..4ebeaf8 100644 --- a/ops/work/web/combine_core.py +++ b/ops/work/web/combine_core.py @@ -339,6 +339,52 @@ class Core: "fov_h": a.get("camera.fov_h"), "zoom": a.get("camera.zoom_optical") or a.get("camera.zoom_hybrid")} + # ── покрытие по зонам (сетка) ── + def coverage_grid(self, host_key, items, w=8.0, l=10.0, cell=0.5): + """Считает покрытие микрофонами по сетке комнаты. + + Возвращает матрицу «сколько микрофонов достаёт до точки» и процент + площади с покрытием хотя бы одним микрофоном. + """ + mics = [] + for r in items: + model, qty = r[0], int(r[1]) + p = self.attrs.get(norm(model), {}).get("audio.pickup_m") + if p: + mics.append({"model": model, "qty": qty, "radius": float(p)}) + built = self.attrs.get(norm(host_key), {}).get("audio.pickup_m") + if built: + mics.append({"model": "встроенный", "qty": 1, "radius": float(built)}) + if not mics: + return {"ok": False, "reason": "нет данных о дальности микрофонов", + "grid": [], "covered_pct": 0} + nx, ny = max(1, int(w / cell)), max(1, int(l / cell)) + # считаем, что микрофоны распределены по потолку равномерно + total_units = sum(m["radius"] and m["qty"] for m in mics) or 1 + positions = [] + idx = 0 + for m in mics: + for _ in range(m["qty"]): + frac = (idx + 1) / (total_units + 1) + positions.append({"x": w * frac, "y": l * 0.5, "r": m["radius"], + "model": m["model"]}) + idx += 1 + grid, covered = [], 0 + for j in range(ny): + row = [] + for i in range(nx): + cx, cy = (i + 0.5) * cell, (j + 0.5) * cell + n = sum(1 for p in positions + if (p["x"] - cx) ** 2 + (p["y"] - cy) ** 2 <= p["r"] ** 2) + row.append(n) + if n: + covered += 1 + grid.append(row) + return {"ok": True, "grid": grid, "nx": nx, "ny": ny, "cell": cell, + "w": w, "l": l, "positions": positions, + "covered_pct": round(100.0 * covered / (nx * ny), 1), + "mics": len(positions)} + # ── комплектация ── def package(self, name): k = norm(name) diff --git a/ops/work/web/services/svc_draw.py b/ops/work/web/services/svc_draw.py index f3eb0d0..0653838 100644 --- a/ops/work/web/services/svc_draw.py +++ b/ops/work/web/services/svc_draw.py @@ -283,6 +283,45 @@ def _fresh(): C.reload_if_changed() +def zones(q, body): + w, l = _room(q) + items = _items(q) + g = C.coverage_grid((q.get("host") or [""])[0], items, w, l, 0.5) + if not g.get("ok"): + return {"ok": False, "reason": g.get("reason"), + "svg": '' + '' + 'нет данных о дальности микрофонов', + "covered_pct": 0} + scale = 40 + pad = 40 + W = g["nx"] * scale + pad * 2 + H = g["ny"] * scale + pad * 2 + parts = [f'', + f''] + for j in range(g["ny"]): + for i in range(g["nx"]): + n = g["grid"][j][i] + if n >= 2: + col = "#1f7a3f" + elif n == 1: + col = "#2e7d4f" + else: + col = "#4a1d1d" + parts.append(f'') + for p in g["positions"]: + cx = pad + p["x"] / g["cell"] * scale + cy = pad + p["y"] / g["cell"] * scale + parts.append(f'') + parts.append(f'' + f'покрытие {g["covered_pct"]}% · микрофонов {g["mics"]} · ' + f'комната {g["w"]}×{g["l"]} м, шаг {g["cell"]} м') + parts.append("") + return {"ok": True, "svg": "".join(parts), "covered_pct": g["covered_pct"], + "mics": g["mics"], "grid_size": [g["nx"], g["ny"]]} + + serve({ "/diagram": diagram, "/cables": cables, @@ -290,5 +329,6 @@ serve({ "/ipplan": ipplan, "/layout": layout, "/plan": plan, + "/zones": zones, "/heatmap": heatmap, }, int(sys.argv[1]) if len(sys.argv) > 1 else 8104, "draw", before=C.reload_if_changed) diff --git a/ops/work/web/services/svc_project.py b/ops/work/web/services/svc_project.py index aaa4050..8060160 100644 --- a/ops/work/web/services/svc_project.py +++ b/ops/work/web/services/svc_project.py @@ -123,9 +123,39 @@ def remove(q, body): return {"error": "not found"} +def import_project(q, body): + """Импорт проекта: CSV-текст 'model,qty' или список models.""" + body = body or {} + text = body.get("csv") or "" + rows = [] + if text: + for line in text.splitlines(): + line = line.strip() + if not line or line.lower().startswith(("model", "модель")): + continue + parts = [p.strip() for p in line.replace(";", ",").split(",")] + if len(parts) < 2: + continue + try: + rows.append([parts[0], int(float(parts[1]))]) + except ValueError: + continue + for m in body.get("models") or []: + rows.append([m.get("model"), int(m.get("qty") or 1)]) + if not rows: + return {"error": "нечего импортировать"} + payload = {"name": body.get("name") or "Импортированный проект", + "host": body.get("host") or "meetingbara50", + "items": [{"model": r[0], "qty": r[1]} for r in rows]} + res = save(None, payload) + res["imported"] = len(rows) + return res + + serve({ "/list": lst, "/get": get, "/save": save, "/delete": remove, + "/import": import_project, }, int(sys.argv[1]) if len(sys.argv) > 1 else 8103, "project") diff --git a/ops/work/web/svc_base.py b/ops/work/web/svc_base.py index fdb6d76..7a106ae 100644 --- a/ops/work/web/svc_base.py +++ b/ops/work/web/svc_base.py @@ -6,6 +6,37 @@ import sys import urllib.parse from http.server import BaseHTTPRequestHandler +PROTECTED = ("/save", "/delete", "/override", "/import") +AUDIT = "/opt/work-hub/compat/audit.jsonl" +AUTH_FILE = "/opt/work-hub/compat/access.yaml" + + +def _tokens(): + """Читает токены и роли из access.yaml.""" + try: + import yaml + d = yaml.safe_load(open(AUTH_FILE, encoding="utf-8")) or {} + except Exception: + return {} + out = {} + for role, info in (d.get("roles") or {}).items(): + tok = (info or {}).get("token") + if tok: + out[tok] = {"role": role, "write": bool(info.get("can_write"))} + return out + + +def _audit(path, role, body): + import time + try: + with open(AUDIT, "a", encoding="utf-8") as f: + f.write(json.dumps({"at": time.strftime("%Y-%m-%dT%H:%M:%S"), + "path": path, "role": role, + "body": str(body)[:400]}, ensure_ascii=False) + "\n") + except Exception: + pass + + CORS = { "Access-Control-Allow-Origin": "*", "Access-Control-Allow-Methods": "GET, POST, OPTIONS", @@ -47,6 +78,14 @@ def serve(routes, port, name, before=None): self._send({}, 204) def _handle(self, body=None): + u = urllib.parse.urlparse(self.path) + if u.path in PROTECTED and self.command == "POST": + tok = self.headers.get("X-Token") or "" + info = _tokens().get(tok) + if not info or not info.get("write"): + return self._send({"error": "нужен токен editor/admin", + "hint": "заголовок X-Token"}, 403) + _audit(u.path, info.get("role"), body) if before is not None: try: before()