ros_control: централизованное управление парком MikroTik RouterOS

Control Server (FastAPI) с WEB UI (Jinja2 + HTMX) и JSON API для группового
администрирования устройств RouterOS 7 через REST.

- Устройства: список, статус (модель, канал, версии ROS/FW, uptime, доступные
  обновления), примечания, пароли шифруются (Fernet); фоновый опрос каждые 30 с
  и быстрое обнаружение недоступности (таймаут соединения 4 с).
- Группы устройств и фильтры (устройства, резервные копии).
- Резервные копии: .backup и .rsc (show-sensitive) создаются через REST,
  скачиваются сервером и загружаются в S3 (Yandex Object Storage).
- Обновление ROS/FW и выбор канала, групповые операции задачами.
- Интерфейс по утверждённому макету: светлая/тёмная темы, окна, шрифты IBM Plex
  локально. Docker Compose, SQLite в томе, минимальный набор тестов.
- Планы и итоги каждого изменения — в docs/changes/.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
ayurishchevandClaude Sonnet 5 committed 2026-09-19 13:13:29 +03:00
commit 4c1841b61b
85 files changed
+3579

No files matched your search

View File
Whitespace-only changes.
+15
View File
@@ -0,0 +1,15 @@
"""Иконки интерфейса: inline SVG (stroke), общий набор с макетом."""
ICONS = {
"search": '<circle cx="11" cy="11" r="7"/><path d="m20 20-3.5-3.5"/>',
"chev": '<path d="m6 9 6 6 6-6"/>',
"plus": '<path d="M12 5v14M5 12h14"/>',
"refresh": '<path d="M20 12a8 8 0 1 1-2.3-5.7M20 4v5h-5"/>',
"more": '<circle cx="5" cy="12" r="1.3"/><circle cx="12" cy="12" r="1.3"/><circle cx="19" cy="12" r="1.3"/>',
"check": '<path d="m5 12 5 5L20 7"/>',
"up": '<path d="M12 19V5M6 11l6-6 6 6"/>',
"x": '<path d="M6 6l12 12M18 6 6 18"/>',
"archive": '<rect x="3" y="4" width="18" height="5" rx="1"/><path d="M5 9v10h14V9M10 13h4"/>',
"download": '<path d="M12 4v11M7 11l5 5 5-5M5 20h14"/>',
"router": '<rect x="3" y="14" width="18" height="6" rx="2"/><path d="M7 17h.01M11 17h.01M8 14l-2-6M16 14l2-6"/>',
"arrow": '<path d="M5 12h14M13 6l6 6-6 6"/>',
}
+379
View File
@@ -0,0 +1,379 @@
"""WEB UI: Jinja2 + HTMX. Использует те же сервисы, что и JSON API."""
from datetime import date
from pathlib import Path
from urllib.parse import urlencode
from fastapi import APIRouter, Depends, Form, Request, Response
from fastapi.responses import HTMLResponse, RedirectResponse
from fastapi.templating import Jinja2Templates
from app import s3, security
from app.config import get_settings
from app.ros.operations import CHANNELS
from app.services import backups, devices, groups, jobs, ops
from app.ui.icons import ICONS
def plural(n, one: str, few: str, many: str) -> str:
"""Русское склонение по числу: 1 файл, 2 файла, 5 файлов."""
n = abs(int(n))
if n % 10 == 1 and n % 100 != 11:
return one
if 2 <= n % 10 <= 4 and not 12 <= n % 100 <= 14:
return few
return many
templates = Jinja2Templates(directory=Path(__file__).parent / "templates")
templates.env.filters["dt"] = lambda v: v.strftime("%Y-%m-%d %H:%M") if v else "—"
templates.env.filters["size"] = lambda n: f"{n / 1024 / 1024:.1f} МБ" if n >= 1024 * 1024 else f"{n / 1024:.0f} КБ"
templates.env.filters["plural"] = plural
templates.env.globals["ICONS"] = ICONS
class LoginRequired(Exception):
pass
def require_login(request: Request) -> None:
if not request.session.get("user"):
raise LoginRequired()
router = APIRouter(include_in_schema=False)
def _render(request: Request, name: str, **ctx):
return templates.TemplateResponse(request, name, ctx)
def _is_htmx(request: Request) -> bool:
return request.headers.get("HX-Request") == "true"
def _done(request: Request, fallback: str = "/"):
"""Успех формы: из окна (HTMX) — обновить страницу, обычной формой — редирект."""
if _is_htmx(request):
return Response(headers={"HX-Refresh": "true"})
return RedirectResponse(fallback, status_code=303)
def _opt_int(value: str) -> int | None:
return int(value) if str(value).strip().isdigit() else None
FILTER_FIELDS = ("group", "q", "status", "updates", "channel") # в форме и URL — с префиксом f_
FILTER_VALUES = {"status": ("online", "offline"), "updates": ("ros", "fw", "any", "none")}
def _flt(params) -> dict:
"""Фильтр списка устройств из query/формы (поля f_*)."""
flt = {k: str(params.get(f"f_{k}") or "").strip() for k in FILTER_FIELDS}
for k, allowed in FILTER_VALUES.items():
if flt[k] not in allowed:
flt[k] = ""
return flt
def _page_url(flt: dict, **override) -> str:
"""Адрес страницы устройств с фильтром (только непустые поля)."""
merged = {**flt, **override}
query = urlencode({f"f_{k}": v for k, v in merged.items() if v})
return "/?" + query if query else "/"
def _visible(flt: dict):
return devices.filter_devices(devices.list_devices(), **flt)
def _devices_ctx(flt: dict) -> dict:
everyone = devices.list_devices()
stats = {"total": len(everyone), "online": sum(d.online is True for d in everyone),
"offline": sum(d.online is False for d in everyone)}
return {"devices": devices.filter_devices(everyone, **flt), "channels": CHANNELS, "filtered": any(flt.values()),
"total": len(everyone), "stats": stats,
"group_names": {g["id"]: g["name"] for g in groups.list_groups()}}
def _tabs(flt: dict) -> list[dict]:
"""Вкладки групп: «Все», «Без группы» и каждая группа со счётчиком устройств."""
all_devices = devices.list_devices()
glist = groups.list_groups()
items = [("Все", "", len(all_devices)),
("Без группы", "none", sum(1 for d in all_devices if d.group_id is None))]
items += [(g["name"], str(g["id"]), g["device_count"]) for g in glist]
return [{"label": label, "count": n, "href": _page_url(flt, group=value), "active": flt["group"] == value}
for label, value, n in items]
# --- вход / выход ---
@router.get("/login", response_class=HTMLResponse)
async def login_form(request: Request):
return _render(request, "login.html", error=None)
@router.post("/login")
async def login(request: Request, username: str = Form(), password: str = Form()):
if not security.check_admin(username, password):
return _render(request, "login.html", error="Неверный логин или пароль")
request.session["user"] = username
return RedirectResponse("/", status_code=303)
@router.post("/logout")
async def logout(request: Request):
request.session.clear()
return RedirectResponse("/login", status_code=303)
# --- дашборд ---
@router.get("/", response_class=HTMLResponse, dependencies=[Depends(require_login)])
async def dashboard(request: Request):
flt = _flt(request.query_params)
return _render(request, "dashboard.html", section="devices", jobs=jobs.list_jobs(15), flt=flt, tabs=_tabs(flt),
groups=groups.list_groups(), page_url=_page_url(flt),
flt_active=sum(1 for k in ("q", "status", "updates", "channel") if flt[k]), **_devices_ctx(flt))
@router.get("/ui/devices", response_class=HTMLResponse, dependencies=[Depends(require_login)])
async def devices_table(request: Request):
flt = _flt(request.query_params)
resp = _render(request, "_devices.html", oob=True, **_devices_ctx(flt))
if request.query_params.get("poll") != "1": # автообновление не должно засорять историю браузера
resp.headers["HX-Push-Url"] = _page_url(flt) # фильтр переживает перезагрузку страницы
return resp
@router.get("/ui/jobs", response_class=HTMLResponse, dependencies=[Depends(require_login)])
async def jobs_table(request: Request):
return _render(request, "_jobs.html", jobs=jobs.list_jobs(15))
@router.post("/ui/refresh", response_class=HTMLResponse, dependencies=[Depends(require_login)])
async def refresh(request: Request, device_ids: list[int] = Form(default=[])):
flt = _flt(await request.form())
# без выбора обновляем все устройства текущего представления (группа + фильтры)
await ops.refresh_many(device_ids or [d.id for d in _visible(flt)])
return _render(request, "_devices.html", oob=True, **_devices_ctx(flt))
@router.post("/ui/batch/{action}", response_class=HTMLResponse, dependencies=[Depends(require_login)])
async def batch(request: Request, action: str, device_ids: list[int] = Form(default=[]),
channel: str = Form(default="")):
if not device_ids:
return _render(request, "_jobs.html", jobs=jobs.list_jobs(15), flash="Выберите устройства")
if action == "channel":
for i in device_ids:
await ops.set_channel(i, channel)
return _render(request, "_devices.html", oob=True, **_devices_ctx(_flt(await request.form())))
jobs.start_jobs(action, device_ids)
return _render(request, "_jobs.html", jobs=jobs.list_jobs(15))
@router.post("/ui/devices/{device_id}/{action}", response_class=HTMLResponse,
dependencies=[Depends(require_login)])
async def device_action(request: Request, device_id: int, action: str, channel: str = Form(default="")):
"""Действие над одним устройством (пункты меню «⋯» в строке таблицы)."""
if action == "refresh":
await ops.refresh_status(device_id)
elif action == "channel":
await ops.set_channel(device_id, channel)
else:
jobs.start_jobs(action, [device_id])
return _render(request, "_jobs.html", jobs=jobs.list_jobs(15))
return _render(request, "_devices.html", oob=True, **_devices_ctx(_flt(await request.form())))
@router.post("/ui/move", dependencies=[Depends(require_login)])
async def move(device_ids: list[int] = Form(default=[]), group_id: str = Form(""), next: str = Form("/")):
"""Перенос отмеченных устройств в группу (обычный POST + редирект: счётчики вкладок обновляются)."""
if device_ids:
groups.move_devices(device_ids, _opt_int(group_id))
return RedirectResponse(next if next.startswith("/") and not next.startswith("//") else "/", status_code=303)
# --- окна (dialog) и формы: одна разметка для окна и запасной страницы ---
def _device_values(device=None, **form) -> dict:
"""Значения полей формы устройства: из отправленной формы (при ошибке), из устройства или значения по умолчанию."""
if form:
return form
if device is not None:
return dict(name=device.name, host=device.host, port=device.port, username=device.username,
group_id=str(device.group_id or ""), new_group="", use_tls=device.use_tls,
verify_tls=device.verify_tls, note=device.note or "")
return dict(name="", host="", port=443, username="", group_id="", new_group="", use_tls=True, verify_tls=False, note="")
def _device_form(request: Request, device, v: dict, error: str | None = None):
ctx = dict(device=device, v=v, error=error, groups=groups.list_groups(), section="devices")
if _is_htmx(request):
return _render(request, "_device_form.html", in_modal=True, **ctx)
return _render(request, "device_form.html", in_modal=False, **ctx)
def _group_form(request: Request, group, name: str, error: str | None = None):
ctx = dict(group=group, gname=name, error=error)
return _render(request, "_group_form.html", in_modal=_is_htmx(request), **ctx)
@router.get("/ui/dialog/device", response_class=HTMLResponse, dependencies=[Depends(require_login)])
async def dialog_device_new(request: Request, group: str = ""):
v = _device_values()
v["group_id"] = group if group.isdigit() else ""
return _render(request, "_device_form.html", in_modal=True, device=None, v=v, error=None, groups=groups.list_groups())
@router.get("/ui/dialog/device/{device_id}", response_class=HTMLResponse, dependencies=[Depends(require_login)])
async def dialog_device_edit(request: Request, device_id: int):
d = devices.get_device(device_id)
return _render(request, "_device_form.html", in_modal=True, device=d, v=_device_values(d), error=None,
groups=groups.list_groups())
@router.get("/ui/dialog/group", response_class=HTMLResponse, dependencies=[Depends(require_login)])
async def dialog_group_new(request: Request):
return _render(request, "_group_form.html", in_modal=True, group=None, gname="", error=None)
@router.get("/ui/dialog/group/{group_id}", response_class=HTMLResponse, dependencies=[Depends(require_login)])
async def dialog_group_edit(request: Request, group_id: int):
g = groups.get_group(group_id)
return _render(request, "_group_form.html", in_modal=True, group=g, gname=g.name, error=None)
# --- группы ---
@router.get("/groups", response_class=HTMLResponse, dependencies=[Depends(require_login)])
async def groups_page(request: Request, error: str = ""):
everyone = devices.list_devices()
return _render(request, "groups.html", section="groups", groups=groups.list_groups(), error=error,
total=len(everyone), ungrouped=sum(1 for d in everyone if d.group_id is None))
def _group_action(request: Request, fn, *args, name: str = "", group=None):
try:
fn(*args)
except ValueError as e:
if _is_htmx(request): # ошибка показывается в окне
return _group_form(request, group, name, str(e))
return RedirectResponse("/groups?" + urlencode({"error": str(e)}), status_code=303)
return _done(request, "/groups")
@router.post("/groups/new", dependencies=[Depends(require_login)])
async def group_create(request: Request, name: str = Form()):
return _group_action(request, groups.create_group, name, name=name)
@router.post("/groups/{group_id}/rename", dependencies=[Depends(require_login)])
async def group_rename(request: Request, group_id: int, name: str = Form()):
return _group_action(request, groups.rename_group, group_id, name, name=name, group=groups.get_group(group_id))
@router.post("/groups/{group_id}/delete", dependencies=[Depends(require_login)])
async def group_delete(request: Request, group_id: int):
return _group_action(request, groups.delete_group, group_id)
# --- управление списком устройств ---
def _group_choice(group_id: str, new_group: str) -> tuple[int | None, str | None]:
"""Выбор в списке «Группа»: id, «без группы» или «Новая группа…» (тогда нужно название)."""
if group_id == "__new__":
if not new_group.strip():
raise ValueError("Введите название новой группы")
return None, new_group.strip()
return _opt_int(group_id), None
@router.get("/devices/new", response_class=HTMLResponse, dependencies=[Depends(require_login)])
async def device_new(request: Request, group: str = ""):
v = _device_values()
v["group_id"] = group if group.isdigit() else ""
return _device_form(request, None, v)
@router.post("/devices/new", dependencies=[Depends(require_login)])
async def device_create(request: Request, name: str = Form(), host: str = Form(),
port: int = Form(443), username: str = Form(), password: str = Form(),
verify_tls: bool = Form(False), use_tls: bool = Form(False),
group_id: str = Form(""), new_group: str = Form(""), note: str = Form("")):
v = dict(name=name, host=host, port=port, username=username, group_id=group_id, new_group=new_group,
use_tls=use_tls, verify_tls=verify_tls, note=note)
try:
gid, ng = _group_choice(group_id, new_group)
d = devices.create_device(name, host, port, username, password, verify_tls, use_tls, gid, ng, note)
except ValueError as e:
return _device_form(request, None, v, str(e))
await ops.refresh_status(d.id)
return _done(request)
@router.get("/devices/{device_id}/edit", response_class=HTMLResponse, dependencies=[Depends(require_login)])
async def device_edit(request: Request, device_id: int):
d = devices.get_device(device_id)
return _device_form(request, d, _device_values(d))
@router.post("/devices/{device_id}/edit", dependencies=[Depends(require_login)])
async def device_update(request: Request, device_id: int, name: str = Form(), host: str = Form(),
port: int = Form(443), username: str = Form(), password: str = Form(""),
verify_tls: bool = Form(False), use_tls: bool = Form(False),
group_id: str = Form(""), new_group: str = Form(""), note: str = Form("")):
v = dict(name=name, host=host, port=port, username=username, group_id=group_id, new_group=new_group,
use_tls=use_tls, verify_tls=verify_tls, note=note)
try:
gid, ng = _group_choice(group_id, new_group)
devices.update_device(device_id, name=name, host=host, port=port, username=username, password=password,
verify_tls=verify_tls, use_tls=use_tls, group_id=gid, new_group=ng, note=note)
except ValueError as e:
return _device_form(request, devices.get_device(device_id), v, str(e))
return _done(request)
@router.post("/devices/{device_id}/delete", dependencies=[Depends(require_login)])
async def device_delete(request: Request, device_id: int):
devices.delete_device(device_id)
return _done(request)
# --- резервные копии в бакете ---
def _opt_date(value: str) -> date | None:
try:
return date.fromisoformat(value)
except ValueError:
return None
@router.get("/backups", response_class=HTMLResponse, dependencies=[Depends(require_login)])
async def backups_page(request: Request, device: str = "", group: str = "", kind: str = "",
date_from: str = "", date_to: str = "", q: str = ""):
kind = kind if kind in ("backup", "rsc") else ""
items, stats, error = [], {"total": 0, "size": 0}, None
try:
items, stats = await backups.search(device, group, kind, _opt_date(date_from), _opt_date(date_to), q)
except Exception as e: # noqa: BLE001 — показываем ошибку S3 на странице
error = str(e)
flt = dict(device=device, group=group, kind=kind, date_from=date_from, date_to=date_to, q=q)
return _render(request, "backups.html", section="backups", items=items, stats=stats, error=error, flt=flt,
flt_active=sum(1 for v in flt.values() if v), bucket=get_settings().s3_bucket,
devices=devices.list_devices(), groups=groups.list_groups())
@router.get("/backups/download", dependencies=[Depends(require_login)])
async def backup_download(key: str):
if not s3.key_allowed(key):
raise ValueError("Недопустимый ключ")
return RedirectResponse(s3.presign_get(key))
@router.post("/backups/delete", dependencies=[Depends(require_login)])
async def backup_delete(key: str = Form()):
if not s3.key_allowed(key):
raise ValueError("Недопустимый ключ")
await s3.delete_object(key)
return RedirectResponse("/backups", status_code=303)
+105
View File
@@ -0,0 +1,105 @@
// ros_control UI: выбор строк, меню, окна, состояние фильтров. Без внешних библиотек (кроме htmx).
(() => {
const $ = (s, r = document) => r.querySelector(s);
const $$ = (s, r = document) => [...r.querySelectorAll(s)];
// --- выбор строк: панель фильтров ⇄ панель действий над выбранными ---
function syncSelection() {
const boxes = $$("input[name=device_ids]");
const n = boxes.filter((b) => b.checked).length;
boxes.forEach((b) => b.closest("tr")?.classList.toggle("sel", b.checked));
const all = $("#check-all");
if (all) { all.checked = boxes.length > 0 && n === boxes.length; all.indeterminate = n > 0 && n < boxes.length; }
const bulk = $("#tools-bulk"), filters = $("#tools-filters");
if (bulk && filters) { bulk.hidden = n === 0; filters.hidden = n > 0; }
const cnt = $("#sel-count"); if (cnt) cnt.textContent = n;
}
// --- фильтры устройств: подсветка включённых полей и кнопка «Сбросить (N)» ---
function syncFilters() {
const form = $("#dev-filters"); if (!form) return;
let active = 0;
$$("select.field", form).forEach((s) => { const on = s.value !== ""; s.classList.toggle("on", on); active += on; });
if ($("input[name=f_q]", form)?.value.trim()) active += 1;
const reset = $("#filters-reset", form);
if (reset) { reset.hidden = active === 0; reset.textContent = `Сбросить (${active})`; }
}
// Выпадающие списки позиционируются от кнопки в координатах окна: их не обрезает прокручиваемая
// таблица, а внизу экрана список раскрывается вверх.
function placeMenu(menu) {
const panel = $(".menu-panel", menu), btn = $("summary", menu);
if (!panel || !btn) return;
panel.style.position = "fixed"; panel.style.top = "0"; panel.style.left = "0"; panel.style.right = "auto";
const b = btn.getBoundingClientRect(), w = panel.offsetWidth, h = panel.offsetHeight, gap = 4, edge = 8;
let left = menu.classList.contains("right") ? b.right - w : b.left;
left = Math.max(edge, Math.min(left, window.innerWidth - w - edge));
const below = b.bottom + gap, above = b.top - gap - h;
panel.style.left = `${left}px`;
panel.style.top = `${below + h > window.innerHeight - edge && above >= edge ? above : below}px`;
}
document.addEventListener("toggle", (e) => { if (e.target.matches?.("details.menu[open]")) placeMenu(e.target); }, true);
// при прокрутке/изменении размера список следует за кнопкой; если кнопка ушла за пределы окна — закрывается
function reflowMenu(e) {
if (e?.target?.closest?.(".menu-panel")) return;
const menu = $("details.menu[open]"); if (!menu) return;
const r = $("summary", menu).getBoundingClientRect();
if (r.bottom < 0 || r.top > window.innerHeight || r.right < 0 || r.left > window.innerWidth) menu.removeAttribute("open");
else placeMenu(menu);
}
window.addEventListener("scroll", reflowMenu, true);
window.addEventListener("resize", reflowMenu);
const closeMenus = (keep) => $$("details.menu[open]").forEach((m) => { if (m !== keep) m.removeAttribute("open"); });
document.addEventListener("change", (e) => {
const t = e.target;
if (t.matches("input[name=device_ids]")) syncSelection();
if (t.id === "check-all") { $$("input[name=device_ids]").forEach((b) => (b.checked = t.checked)); syncSelection(); }
if (t.closest("#dev-filters")) syncFilters();
// «Новая группа…» в списке групп окна устройства
if (t.matches("select[name=group_id][data-newgroup]")) $("#new-group-field").hidden = t.value !== "__new__";
// предупреждение о HTTP
if (t.matches("input[name=use_tls]")) $("#http-note").hidden = t.checked;
});
document.addEventListener("input", (e) => { if (e.target.closest("#dev-filters")) syncFilters(); });
document.addEventListener("click", (e) => {
const t = e.target;
if (t.closest("#clear-sel")) { $$("input[name=device_ids]").forEach((b) => (b.checked = false)); syncSelection(); }
// меню: закрывается по клику вне и после выбора пункта; открыто не более одного
if (t.closest("details.sub > summary")) return; // раскрытие подменю («Сменить канал…») меню не закрывает
const menu = t.closest("details.menu");
closeMenus(t.closest(".menu-panel") ? null : menu);
// окно: закрытие по кнопке и по клику на подложку
const modal = $("#modal");
if (modal && (t.closest("[data-close]") || t === modal)) modal.close();
});
document.addEventListener("keydown", (e) => { if (e.key === "Escape") closeMenus(null); });
// окно открывается, когда HTMX положил в него содержимое
document.addEventListener("htmx:afterSwap", (e) => {
const modal = $("#modal");
if (e.detail.target.id === "modal-body") {
if (modal && !modal.open) modal.showModal();
$("#modal-body [autofocus], #modal-body input:not([type=hidden])")?.focus();
const sel = $("select[name=group_id][data-newgroup]"); if (sel) $("#new-group-field").hidden = sel.value !== "__new__";
}
syncSelection(); syncFilters();
});
// --- автообновление статусов: сервер опрашивает устройства сам, страница подтягивает результат ---
const REFRESH_MS = 15000;
function autoRefresh() {
const form = $("#dev-filters"), target = $("#devices");
if (!form || !target || document.hidden) return;
const busy = $$("input[name=device_ids]:checked").length || $("details[open]") || $("#modal")?.open || $("#dev-card .htmx-request");
if (busy || form.contains(document.activeElement)) return; // не мешаем работе пользователя
const params = new URLSearchParams(new FormData(form)); params.set("poll", "1");
htmx.ajax("GET", `/ui/devices?${params}`, { target: "#devices", swap: "innerHTML" });
}
setInterval(autoRefresh, REFRESH_MS);
const init = () => { syncSelection(); syncFilters(); };
document.readyState === "loading" ? document.addEventListener("DOMContentLoaded", init) : init();
})();
+93
View File
@@ -0,0 +1,93 @@
Copyright © 2017 IBM Corp. with Reserved Font Name "Plex"
This Font Software is licensed under the SIL Open Font License, Version 1.1.
This license is copied below, and is also available with a FAQ at: http://scripts.sil.org/OFL
-----------------------------------------------------------
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
-----------------------------------------------------------
PREAMBLE
The goals of the Open Font License (OFL) are to stimulate worldwide
development of collaborative font projects, to support the font creation
efforts of academic and linguistic communities, and to provide a free and
open framework in which fonts may be shared and improved in partnership
with others.
The OFL allows the licensed fonts to be used, studied, modified and
redistributed freely as long as they are not sold by themselves. The
fonts, including any derivative works, can be bundled, embedded,
redistributed and/or sold with any software provided that any reserved
names are not used by derivative works. The fonts and derivatives,
however, cannot be released under any other type of license. The
requirement for fonts to remain under this license does not apply
to any document created using the fonts or their derivatives.
DEFINITIONS
"Font Software" refers to the set of files released by the Copyright
Holder(s) under this license and clearly marked as such. This may
include source files, build scripts and documentation.
"Reserved Font Name" refers to any names specified as such after the
copyright statement(s).
"Original Version" refers to the collection of Font Software components as
distributed by the Copyright Holder(s).
"Modified Version" refers to any derivative made by adding to, deleting,
or substituting -- in part or in whole -- any of the components of the
Original Version, by changing formats or by porting the Font Software to a
new environment.
"Author" refers to any designer, engineer, programmer, technical
writer or other person who contributed to the Font Software.
PERMISSION & CONDITIONS
Permission is hereby granted, free of charge, to any person obtaining
a copy of the Font Software, to use, study, copy, merge, embed, modify,
redistribute, and sell modified and unmodified copies of the Font
Software, subject to the following conditions:
1) Neither the Font Software nor any of its individual components,
in Original or Modified Versions, may be sold by itself.
2) Original or Modified Versions of the Font Software may be bundled,
redistributed and/or sold with any software, provided that each copy
contains the above copyright notice and this license. These can be
included either as stand-alone text files, human-readable headers or
in the appropriate machine-readable metadata fields within text or
binary files as long as those fields can be easily viewed by the user.
3) No Modified Version of the Font Software may use the Reserved Font
Name(s) unless explicit written permission is granted by the corresponding
Copyright Holder. This restriction only applies to the primary font name as
presented to the users.
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
Software shall not be used to promote, endorse or advertise any
Modified Version, except to acknowledge the contribution(s) of the
Copyright Holder(s) and the Author(s) or with their explicit written
permission.
5) The Font Software, modified or unmodified, in part or in whole,
must be distributed entirely under this license, and must not be
distributed under any other license. The requirement for fonts to
remain under this license does not apply to any document created
using the Font Software.
TERMINATION
This license becomes null and void if any of the above conditions are
not met.
DISCLAIMER
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
OTHER DEALINGS IN THE FONT SOFTWARE.
+1
View File
@@ -0,0 +1 @@
var htmx=function(){"use strict";const Q={onLoad:null,process:null,on:null,off:null,trigger:null,ajax:null,find:null,findAll:null,closest:null,values:function(e,t){const n=cn(e,t||"post");return n.values},remove:null,addClass:null,removeClass:null,toggleClass:null,takeClass:null,swap:null,defineExtension:null,removeExtension:null,logAll:null,logNone:null,logger:null,config:{historyEnabled:true,historyCacheSize:10,refreshOnHistoryMiss:false,defaultSwapStyle:"innerHTML",defaultSwapDelay:0,defaultSettleDelay:20,includeIndicatorStyles:true,indicatorClass:"htmx-indicator",requestClass:"htmx-request",addedClass:"htmx-added",settlingClass:"htmx-settling",swappingClass:"htmx-swapping",allowEval:true,allowScriptTags:true,inlineScriptNonce:"",inlineStyleNonce:"",attributesToSettle:["class","style","width","height"],withCredentials:false,timeout:0,wsReconnectDelay:"full-jitter",wsBinaryType:"blob",disableSelector:"[hx-disable], [data-hx-disable]",scrollBehavior:"instant",defaultFocusScroll:false,getCacheBusterParam:false,globalViewTransitions:false,methodsThatUseUrlParams:["get","delete"],selfRequestsOnly:true,ignoreTitle:false,scrollIntoViewOnBoost:true,triggerSpecsCache:null,disableInheritance:false,responseHandling:[{code:"204",swap:false},{code:"[23]..",swap:true},{code:"[45]..",swap:false,error:true}],allowNestedOobSwaps:true},parseInterval:null,_:null,version:"2.0.4"};Q.onLoad=j;Q.process=kt;Q.on=ye;Q.off=be;Q.trigger=he;Q.ajax=Rn;Q.find=u;Q.findAll=x;Q.closest=g;Q.remove=z;Q.addClass=K;Q.removeClass=G;Q.toggleClass=W;Q.takeClass=Z;Q.swap=$e;Q.defineExtension=Fn;Q.removeExtension=Bn;Q.logAll=V;Q.logNone=_;Q.parseInterval=d;Q._=e;const n={addTriggerHandler:St,bodyContains:le,canAccessLocalStorage:B,findThisElement:Se,filterValues:hn,swap:$e,hasAttribute:s,getAttributeValue:te,getClosestAttributeValue:re,getClosestMatch:o,getExpressionVars:En,getHeaders:fn,getInputValues:cn,getInternalData:ie,getSwapSpecification:gn,getTriggerSpecs:st,getTarget:Ee,makeFragment:P,mergeObjects:ce,makeSettleInfo:xn,oobSwap:He,querySelectorExt:ae,settleImmediately:Kt,shouldCancel:ht,triggerEvent:he,triggerErrorEvent:fe,withExtensions:Ft};const r=["get","post","put","delete","patch"];const H=r.map(function(e){return"[hx-"+e+"], [data-hx-"+e+"]"}).join(", ");function d(e){if(e==undefined){return undefined}let t=NaN;if(e.slice(-2)=="ms"){t=parseFloat(e.slice(0,-2))}else if(e.slice(-1)=="s"){t=parseFloat(e.slice(0,-1))*1e3}else if(e.slice(-1)=="m"){t=parseFloat(e.slice(0,-1))*1e3*60}else{t=parseFloat(e)}return isNaN(t)?undefined:t}function ee(e,t){return e instanceof Element&&e.getAttribute(t)}function s(e,t){return!!e.hasAttribute&&(e.hasAttribute(t)||e.hasAttribute("data-"+t))}function te(e,t){return ee(e,t)||ee(e,"data-"+t)}function c(e){const t=e.parentElement;if(!t&&e.parentNode instanceof ShadowRoot)return e.parentNode;return t}function ne(){return document}function m(e,t){return e.getRootNode?e.getRootNode({composed:t}):ne()}function o(e,t){while(e&&!t(e)){e=c(e)}return e||null}function i(e,t,n){const r=te(t,n);const o=te(t,"hx-disinherit");var i=te(t,"hx-inherit");if(e!==t){if(Q.config.disableInheritance){if(i&&(i==="*"||i.split(" ").indexOf(n)>=0)){return r}else{return null}}if(o&&(o==="*"||o.split(" ").indexOf(n)>=0)){return"unset"}}return r}function re(t,n){let r=null;o(t,function(e){return!!(r=i(t,ue(e),n))});if(r!=="unset"){return r}}function h(e,t){const n=e instanceof Element&&(e.matches||e.matchesSelector||e.msMatchesSelector||e.mozMatchesSelector||e.webkitMatchesSelector||e.oMatchesSelector);return!!n&&n.call(e,t)}function T(e){const t=/<([a-z][^\/\0>\x20\t\r\n\f]*)/i;const n=t.exec(e);if(n){return n[1].toLowerCase()}else{return""}}function q(e){const t=new DOMParser;return t.parseFromString(e,"text/html")}function L(e,t){while(t.childNodes.length>0){e.append(t.childNodes[0])}}function A(e){const t=ne().createElement("script");se(e.attributes,function(e){t.setAttribute(e.name,e.value)});t.textContent=e.textContent;t.async=false;if(Q.config.inlineScriptNonce){t.nonce=Q.config.inlineScriptNonce}return t}function N(e){return e.matches("script")&&(e.type==="text/javascript"||e.type==="module"||e.type==="")}function I(e){Array.from(e.querySelectorAll("script")).forEach(e=>{if(N(e)){const t=A(e);const n=e.parentNode;try{n.insertBefore(t,e)}catch(e){O(e)}finally{e.remove()}}})}function P(e){const t=e.replace(/<head(\s[^>]*)?>[\s\S]*?<\/head>/i,"");const n=T(t);let r;if(n==="html"){r=new DocumentFragment;const i=q(e);L(r,i.body);r.title=i.title}else if(n==="body"){r=new DocumentFragment;const i=q(t);L(r,i.body);r.title=i.title}else{const i=q('<body><template class="internal-htmx-wrapper">'+t+"</template></body>");r=i.querySelector("template").content;r.title=i.title;var o=r.querySelector("title");if(o&&o.parentNode===r){o.remove();r.title=o.innerText}}if(r){if(Q.config.allowScriptTags){I(r)}else{r.querySelectorAll("script").forEach(e=>e.remove())}}return r}function oe(e){if(e){e()}}function t(e,t){return Object.prototype.toStrinLine truncated
+202
View File
@@ -0,0 +1,202 @@
/* ros_control UI — перенос утверждённого макета. Значения (размеры, радиусы, цвета) взяты из макета 1:1.
Формы: контролы h36 r8 · метки h22 r6 · панели/карточки r12. Шрифты — IBM Plex (локально, OFL). */
@font-face { font-family: "IBM Plex Sans"; font-weight: 400; font-display: swap; src: url(fonts/ibm-plex-sans-cyrillic-400-normal.woff2) format("woff2"); unicode-range: U+0301, U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116; }
@font-face { font-family: "IBM Plex Sans"; font-weight: 400; font-display: swap; src: url(fonts/ibm-plex-sans-latin-400-normal.woff2) format("woff2"); unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD; }
@font-face { font-family: "IBM Plex Sans"; font-weight: 500; font-display: swap; src: url(fonts/ibm-plex-sans-cyrillic-500-normal.woff2) format("woff2"); unicode-range: U+0301, U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116; }
@font-face { font-family: "IBM Plex Sans"; font-weight: 500; font-display: swap; src: url(fonts/ibm-plex-sans-latin-500-normal.woff2) format("woff2"); unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD; }
@font-face { font-family: "IBM Plex Sans"; font-weight: 600; font-display: swap; src: url(fonts/ibm-plex-sans-cyrillic-600-normal.woff2) format("woff2"); unicode-range: U+0301, U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116; }
@font-face { font-family: "IBM Plex Sans"; font-weight: 600; font-display: swap; src: url(fonts/ibm-plex-sans-latin-600-normal.woff2) format("woff2"); unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD; }
@font-face { font-family: "IBM Plex Mono"; font-weight: 400; font-display: swap; src: url(fonts/ibm-plex-mono-cyrillic-400-normal.woff2) format("woff2"); unicode-range: U+0301, U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116; }
@font-face { font-family: "IBM Plex Mono"; font-weight: 400; font-display: swap; src: url(fonts/ibm-plex-mono-latin-400-normal.woff2) format("woff2"); unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD; }
@font-face { font-family: "IBM Plex Mono"; font-weight: 500; font-display: swap; src: url(fonts/ibm-plex-mono-cyrillic-500-normal.woff2) format("woff2"); unicode-range: U+0301, U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116; }
@font-face { font-family: "IBM Plex Mono"; font-weight: 500; font-display: swap; src: url(fonts/ibm-plex-mono-latin-500-normal.woff2) format("woff2"); unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD; }
:root {
--font: "IBM Plex Sans", system-ui, sans-serif;
--mono: "IBM Plex Mono", ui-monospace, monospace;
--bg: #f4f6f9; --surf: #ffffff; --head: #f8fafc; --sel: #f3f7ff;
--line: #dde3ea; --line2: #c5ced9;
--text: #18212f; --muted: #58657a; --faint: #8a95a5;
--acc: #2450c8; --acc-solid: #2450c8; --acc50: #eaf0ff; --acc100: #d5e2ff; --accd: #1e449e;
--ok-t: #14683a; --ok-b: #e3f4ea; --warn-t: #7c4a00; --warn-b: #fdf0d5; --bad-t: #a32020; --bad-b: #fbe6e6;
--neu-t: #3c4859; --neu-b: #eef1f5;
--dot-on: #1f8a4c; --dot-off: #c62828; --dot-unk: #8a95a5;
--shadow-menu: 0 8px 24px rgba(20, 33, 60, .14); --shadow-modal: 0 16px 48px rgba(20, 33, 60, .25);
--backdrop: rgba(24, 33, 47, .45); --disabled-bg: #f4f6f9; --disabled-t: #8a95a5;
color-scheme: light;
}
@media (prefers-color-scheme: dark) {
:root {
--bg: #0f141b; --surf: #171e27; --head: #1b2430; --sel: #1a2540;
--line: #2a3441; --line2: #3a4759;
--text: #e6ebf2; --muted: #97a3b6; --faint: #7a8699;
--acc: #7ea1ff; --acc-solid: #3d68de; --acc50: #1c2a4a; --acc100: #26385f; --accd: #a9c1ff;
--ok-t: #6fd39a; --ok-b: #12301f; --warn-t: #f0b04a; --warn-b: #3a2a0c; --bad-t: #ff8f8f; --bad-b: #3b1616;
--neu-t: #b6c0cf; --neu-b: #232c39;
--dot-on: #3fbf78; --dot-off: #ff6b6b; --dot-unk: #7a8699;
--shadow-menu: 0 8px 24px rgba(0, 0, 0, .5); --shadow-modal: 0 16px 48px rgba(0, 0, 0, .6);
--backdrop: rgba(0, 0, 0, .6); --disabled-bg: #1b2430; --disabled-t: #6b7789;
color-scheme: dark;
}
}
* { box-sizing: border-box; }
body { margin: 0; background: var(--bg); color: var(--text); font: 400 14px/1.4 var(--font); }
a { color: var(--acc); text-decoration: none; }
h1, h2 { margin: 0; }
[hidden] { display: none !important; }
:focus-visible { outline: 2px solid var(--acc); outline-offset: 2px; }
.grow { flex: 1; }
.muted { color: var(--muted); }
.mono { font: 400 13px/1.2 var(--mono); }
.sr-only { position: absolute; width: 1px; height: 1px; overflow: hidden; clip: rect(0 0 0 0); white-space: nowrap; }
.ico { flex: none; }
/* ---------- 1 · Приложение ---------- */
.app-header { height: 56px; display: flex; align-items: center; gap: 32px; padding: 0 24px; background: var(--surf); border-bottom: 1px solid var(--line); }
.brand { display: flex; align-items: center; gap: 10px; font: 600 16px/1 var(--font); color: var(--text); }
.brand-logo { width: 28px; height: 28px; border-radius: 8px; background: var(--acc-solid); color: #fff; display: flex; align-items: center; justify-content: center; }
.nav { display: flex; height: 100%; gap: 4px; }
.nav a { display: flex; align-items: center; height: 100%; padding: 0 14px; font: 500 14px/1 var(--font); color: var(--muted); border-bottom: 2px solid transparent; }
.nav a.on { color: var(--text); border-bottom-color: var(--acc); }
.user { color: var(--muted); }
.container { max-width: 1600px; margin: 0 auto; padding: 0 24px 48px; }
/* ---------- 2 · Страница ---------- */
.page-head { display: flex; align-items: flex-end; justify-content: space-between; margin: 24px 0 16px; gap: 16px; }
.page-head h1 { font: 600 24px/1.2 var(--font); }
.page-head .sub { margin-top: 4px; color: var(--muted); }
.page-head .actions { display: flex; gap: 8px; }
/* ---------- Кнопки: h36 · r8 · 14/500 ---------- */
.btn { display: inline-flex; align-items: center; justify-content: center; gap: 8px; height: 36px; margin: 0; padding: 0 14px; border-radius: 8px;
border: 1px solid var(--line2); background: var(--surf); color: var(--text); font: 500 14px/1 var(--font); white-space: nowrap; cursor: pointer; }
.btn:hover { border-color: var(--acc); }
.btn.primary { background: var(--acc-solid); border-color: var(--acc-solid); color: #fff; }
.btn.primary:hover { filter: brightness(1.08); }
.btn.ghost { background: transparent; border-color: transparent; color: var(--acc); padding: 0 10px; }
.btn.ghost-n { background: transparent; border-color: transparent; color: var(--muted); padding: 0 10px; }
.btn.ghost:hover, .btn.ghost-n:hover { background: var(--acc50); border-color: transparent; }
.btn.icon { width: 36px; padding: 0; }
.btn.danger { color: var(--bad-t); }
.btn:disabled { background: var(--disabled-bg); color: var(--disabled-t); border-color: var(--line); cursor: not-allowed; }
summary.btn { list-style: none; }
summary.btn::-webkit-details-marker { display: none; }
/* ---------- Поля: та же форма, что у кнопок ---------- */
.field, .input { height: 36px; margin: 0; border-radius: 8px; border: 1px solid var(--line2); background-color: var(--surf); color: var(--text); font: 400 14px/1 var(--font); }
.input { width: 100%; padding: 0 12px; }
textarea.input { height: 72px; padding: 10px 12px; font-family: var(--font); line-height: 1.4; resize: vertical; }
select.field { appearance: none; -webkit-appearance: none; padding: 0 36px 0 14px; font-weight: 500; cursor: pointer;
background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='14' height='14' viewBox='0 0 24 24' fill='none' stroke='%2358657a' stroke-width='1.8' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='m6 9 6 6 6-6'/%3E%3C/svg%3E");
background-repeat: no-repeat; background-position: right 12px center; }
select.field.on { background-color: var(--acc50); border-color: var(--acc); color: var(--accd); }
select.field option { color: var(--text); background: var(--surf); font-weight: 400; }
.search { position: relative; display: inline-flex; align-items: center; flex: none; }
.search .ico { position: absolute; left: 12px; color: var(--muted); pointer-events: none; }
.search input { height: 36px; width: 280px; padding: 0 12px 0 36px; border-radius: 8px; border: 1px solid var(--line2); background: var(--surf); color: var(--text); font: 400 14px/1 var(--font); }
.search input::placeholder { color: var(--faint); }
.datefield { display: inline-flex; align-items: center; gap: 8px; height: 36px; width: 170px; padding: 0 12px; border-radius: 8px; border: 1px solid var(--line2); background: var(--surf); color: var(--muted); font: 400 14px/1 var(--font); }
.datefield input { flex: 1; min-width: 0; border: 0; background: transparent; color: var(--text); font: 400 13px/1 var(--mono); padding: 0; }
.datefield input::-webkit-calendar-picker-indicator { opacity: .55; cursor: pointer; }
/* ---------- Метки: h22 · r6 ---------- */
.badge { display: inline-flex; align-items: center; gap: 4px; height: 22px; padding: 0 8px; border-radius: 6px; background: var(--neu-b); color: var(--neu-t); font: 500 12px/1 var(--font); white-space: nowrap; }
.badge.warn { background: var(--warn-b); color: var(--warn-t); }
.badge.ok { background: var(--ok-b); color: var(--ok-t); }
.badge.bad { background: var(--bad-b); color: var(--bad-t); }
.badge.run { background: var(--acc50); color: var(--accd); }
.okmark { display: inline-flex; align-items: center; gap: 4px; color: var(--ok-t); font: 500 13px/1 var(--font); }
.dash { color: var(--faint); }
.dot { display: inline-block; width: 8px; height: 8px; border-radius: 50%; flex: none; background: var(--dot-unk); }
.dot.on { background: var(--dot-on); } .dot.off { background: var(--dot-off); }
/* ---------- 3 · Область: вкладки-подчёркивание ---------- */
.tabs { display: flex; align-items: center; gap: 24px; margin-bottom: 16px; border-bottom: 1px solid var(--line); }
.tab { padding: 10px 2px 12px; margin-bottom: -1px; font: 500 14px/1 var(--font); color: var(--muted); border-bottom: 2px solid transparent; }
.tab:hover { color: var(--text); }
.tab.on { font-weight: 600; color: var(--text); border-bottom-color: var(--acc); }
.tab .count { margin-left: 2px; font-weight: 400; color: var(--muted); }
.tab-link { display: inline-flex; align-items: center; gap: 6px; padding-bottom: 10px; font: 500 14px/1 var(--font); color: var(--acc); }
/* ---------- Карточка, 4 · инструменты таблицы ---------- */
.card { background: var(--surf); border: 1px solid var(--line); border-radius: 12px; }
.tools { display: flex; align-items: center; gap: 8px; height: 64px; padding: 0 16px; }
.tools.bulk { background: var(--acc50); border-radius: 12px 12px 0 0; }
.tools form { display: contents; }
.sel-count { display: inline-flex; align-items: center; gap: 4px; margin-right: 8px; font: 600 14px/1 var(--font); color: var(--accd); }
.busy { opacity: 0; color: var(--muted); } .htmx-request .busy, .busy.htmx-request { opacity: 1; }
/* ---------- 5 · Данные: таблица ---------- */
table.grid { width: 100%; border-collapse: collapse; table-layout: fixed; }
.grid th { height: 40px; padding: 0 6px; text-align: left; font: 600 12px/1 var(--font); color: var(--muted); background: var(--head); border-top: 1px solid var(--line); border-bottom: 1px solid var(--line); }
.grid td { height: 60px; padding: 0 6px; border-bottom: 1px solid var(--line); vertical-align: middle; font: 400 14px/1.3 var(--font); }
.grid th:first-child, .grid td:first-child { padding-left: 16px; }
.grid th:last-child, .grid td:last-child { padding-right: 16px; }
.grid tr.sel td { background: var(--sel); }
.grid input[type=checkbox], .modal input[type=checkbox] { width: 16px; height: 16px; margin: 0; accent-color: var(--acc-solid); }
.dev { display: flex; align-items: center; gap: 10px; min-width: 0; }
.dev-name { font-weight: 600; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.dev-link { color: inherit; }
.dev-link:hover { color: var(--acc); text-decoration: underline; }
.dev-sub { margin-top: 2px; font-size: 12px; color: var(--muted); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.dev-sub.bad { color: var(--bad-t); }
.c-mono { font: 400 13px/1.2 var(--mono); }
.c-small { font-size: 13px; color: var(--muted); }
.c-menu { text-align: right; }
.tfoot { display: flex; align-items: center; height: 44px; padding: 0 16px; font: 400 13px/1 var(--font); color: var(--muted); }
.empty { height: 88px; text-align: center; color: var(--muted); }
.table-wrap { overflow-x: auto; }
@media (min-width: 1360px) { .table-wrap { overflow: visible; } }
.grid.jobs td { height: 48px; }
.grid.files td { height: 52px; }
.grid.groups td { height: 56px; }
.section-head { display: flex; align-items: center; gap: 12px; margin: 32px 0 12px; }
.section-head h2 { font: 600 16px/1.2 var(--font); }
.msg { color: var(--muted); font-size: 13px; overflow-wrap: anywhere; }
.err { color: var(--bad-t); }
/* ---------- Меню «⋯» и выпадающие списки ---------- */
.menu { position: relative; display: inline-flex; }
.menu-panel { position: absolute; top: 40px; left: 0; z-index: 30; width: 250px; padding: 6px; text-align: left; background: var(--surf);
border: 1px solid var(--line); border-radius: 12px; box-shadow: var(--shadow-menu); }
.menu.right .menu-panel { left: auto; right: 0; }
.w200 { width: 200px; } .w270 { width: 270px; } .w330 { width: 330px; }
.mi { display: flex; flex-direction: column; align-items: flex-start; gap: 2px; width: 100%; margin: 0; padding: 8px 10px; border: 0; border-radius: 8px; background: transparent;
color: var(--text); text-align: left; font: 500 14px/1.3 var(--font); cursor: pointer; }
.mi small { font: 400 12px/1.3 var(--font); color: var(--muted); }
.mi:hover { background: var(--acc50); }
.mi.warn { color: var(--warn-t); } .mi.bad { color: var(--bad-t); }
.mi.on { flex-direction: row; align-items: center; gap: 6px; }
.mi.on::before { content: "✓"; }
summary.mi { list-style: none; } summary.mi::-webkit-details-marker { display: none; }
.menu-panel hr { height: 1px; margin: 6px 0; border: 0; background: var(--line); }
details.sub .sub-list { padding-left: 10px; }
/* ---------- Окна ---------- */
dialog.modal { width: 560px; max-width: calc(100vw - 32px); padding: 0; border: 1px solid var(--line); border-radius: 12px; background: var(--surf); color: var(--text); box-shadow: var(--shadow-modal); }
dialog.modal::backdrop { background: var(--backdrop); }
.modal-head { display: flex; align-items: center; justify-content: space-between; padding: 16px 16px 0 24px; }
.modal-head h2 { font: 600 18px/1.2 var(--font); }
.modal-body { display: flex; flex-direction: column; gap: 16px; padding: 16px 24px 24px; }
.modal-foot { display: flex; align-items: center; justify-content: flex-end; gap: 8px; padding: 16px 24px; border-top: 1px solid var(--line); }
.form-row { display: grid; gap: 12px; grid-template-columns: 1fr 1fr; }
.form-row.host { grid-template-columns: 1fr 110px; }
.lbl { display: flex; flex-direction: column; gap: 6px; font: 500 13px/1.3 var(--font); }
.lbl small { font-size: inherit; font-weight: 400; color: var(--muted); }
.check { display: flex; align-items: flex-start; gap: 10px; font: 500 14px/1.3 var(--font); }
.check small { display: block; font-weight: 400; font-size: 12px; color: var(--muted); }
.note { padding: 10px 12px; border-radius: 8px; background: var(--warn-b); color: var(--warn-t); font: 400 13px/1.4 var(--font); }
.form-err { padding: 10px 12px; border-radius: 8px; background: var(--bad-b); color: var(--bad-t); font: 500 13px/1.4 var(--font); }
.page-card { max-width: 560px; margin: 24px auto; }
/* ---------- Вход ---------- */
.login { max-width: 400px; margin: 96px auto 0; }
.login h1 { font: 600 24px/1.2 var(--font); margin-bottom: 16px; }
/* таблица в карточке без собственной верхней/нижней границы (её даёт карточка) */
.card > table.grid:first-child thead th { border-top: 0; }
.card > table.grid:first-child thead th:first-child { border-top-left-radius: 11px; }
.card > table.grid:first-child thead th:last-child { border-top-right-radius: 11px; }
.card > table.grid:last-child tbody tr:last-child td { border-bottom: 0; }
+1
View File
@@ -0,0 +1 @@
{{ stats.total }} {{ stats.total|plural("устройство", "устройства", "устройств") }} · {{ stats.online }} online · {{ stats.offline }} offline
+51
View File
@@ -0,0 +1,51 @@
{# Форма устройства: одна разметка для окна (in_modal) и запасной страницы. v — значения полей. #}
{% import "_ui.html" as ui %}
{% set edit = device is not none %}
{% set action = ('/devices/' ~ device.id ~ '/edit') if edit else '/devices/new' %}
<form method="post" action="{{ action }}" {% if in_modal %}hx-post="{{ action }}" hx-target="#modal-body"{% endif %}>
<header class="modal-head">
<h2 id="modal-title">{{ "Изменить устройство" if edit else "Новое устройство" }}</h2>
{% if in_modal %}<button type="button" class="btn ghost-n icon" data-close aria-label="Закрыть">{{ ui.icon("x") }}</button>{% endif %}
</header>
<div class="modal-body">
{% if error %}<div class="form-err" role="alert">{{ error }}</div>{% endif %}
<label class="lbl"><span>Название <small>латиница, цифры, «.», «_», «-»; попадает в ключи бэкапов</small></span>
<input class="input" name="name" value="{{ v.name }}" maxlength="64" required autofocus></label>
<label class="lbl"><span>Примечание <small>необязательно</small></span>
<textarea class="input" name="note" rows="3" maxlength="500" placeholder="Например: серверная, 2 этаж; ответственный — дежурный инженер">{{ v.note }}</textarea></label>
<div class="form-row host">
<label class="lbl">Адрес<input class="input" name="host" value="{{ v.host }}" required></label>
<label class="lbl">Порт<input class="input" name="port" type="number" min="1" max="65535" value="{{ v.port }}" required></label>
</div>
<div class="form-row">
<label class="lbl">Пользователь<input class="input" name="username" value="{{ v.username }}" required></label>
<label class="lbl"><span>Пароль {% if edit %}<small>пусто — не менять</small>{% endif %}</span>
<input class="input" name="password" type="password" autocomplete="new-password" {{ "" if edit else "required" }}></label>
</div>
<label class="lbl">Группа
<select class="field" name="group_id" data-newgroup style="width:100%">
<option value="">— без группы —</option>
{% for g in groups %}<option value="{{ g.id }}" {{ "selected" if v.group_id == g.id|string }}>{{ g.name }}</option>{% endfor %}
<option value="__new__" {{ "selected" if v.group_id == "__new__" }}>+ Новая группа…</option>
</select>
</label>
<label class="lbl" id="new-group-field" {{ "" if v.group_id == "__new__" else "hidden" }}>Название новой группы
<input class="input" name="new_group" value="{{ v.new_group }}" maxlength="64"></label>
<label class="check"><input name="use_tls" type="checkbox" {{ "checked" if v.use_tls }}>
<span>HTTPS (сервис www-ssl)<small>Порт обычно 443; без HTTPS — сервис www, порт 80</small></span></label>
<div class="note" id="http-note" {{ "hidden" if v.use_tls }}>Без HTTPS логин и пароль передаются по сети открытым текстом — только для доверенной сети.</div>
<label class="check"><input name="verify_tls" type="checkbox" {{ "checked" if v.verify_tls }}>
<span>Проверять TLS-сертификат<small>Отключите для самоподписанных сертификатов</small></span></label>
</div>
<footer class="modal-foot">
{% if edit %}
{% if in_modal %}<button type="button" class="btn danger" hx-post="/devices/{{ device.id }}/delete"
hx-confirm="Удалить устройство {{ device.name }} из списка? Бэкапы в бакете сохранятся.">Удалить устройство</button>
{% else %}<button class="btn danger" formaction="/devices/{{ device.id }}/delete" formnovalidate
onclick="return confirm('Удалить устройство {{ device.name }} из списка? Бэкапы в бакете сохранятся.')">Удалить устройство</button>{% endif %}
{% endif %}
<span class="grow"></span>
{% if in_modal %}<button type="button" class="btn ghost-n" data-close>Отмена</button>{% else %}<a class="btn ghost-n" href="/">Отмена</a>{% endif %}
<button class="btn primary">{{ "Сохранить" if edit else "Добавить устройство" }}</button>
</footer>
</form>
+75
View File
@@ -0,0 +1,75 @@
{% import "_ui.html" as ui %}
{% if oob %}<div class="sub" id="dev-sub" hx-swap-oob="true">{% include "_dev_sub.html" %}</div>{% endif %}
<div class="table-wrap">
<table class="grid">
<colgroup><col style="width:44px"><col><col style="width:110px"><col style="width:110px"><col style="width:100px"><col style="width:120px"><col style="width:90px"><col style="width:120px"><col style="width:100px"><col style="width:150px"><col style="width:52px"></colgroup>
<thead>
<tr>
<th><input type="checkbox" id="check-all" aria-label="Выбрать все"></th>
<th>Устройство</th><th>Группа</th><th>Канал</th><th>ROS</th><th>Upgrade ROS</th><th>FW</th><th>Upgrade FW</th><th>Uptime</th><th>Запрос бэкапа (UTC)</th><th><span class="sr-only">Действия</span></th>
</tr>
</thead>
<tbody>
{% for d in devices %}
{% set st = d.status %}{% set down = d.online is false %}
{% set ros_new = st.ros_latest and st.ros_installed and st.ros_latest != st.ros_installed %}
{% set fw_new = st.fw_current and st.fw_upgrade and st.fw_upgrade != st.fw_current %}
<tr>
<td><input type="checkbox" name="device_ids" value="{{ d.id }}" form="move-form" aria-label="Выбрать {{ d.name }}"></td>
<td>
<div class="dev">
<span class="dot {{ 'on' if d.online else ('off' if down else '') }}" title="{{ d.last_error or ('online, опрошено ' ~ (d.status_at|dt)) }}"></span>
<div style="min-width:0">
<div class="dev-name"><a class="dev-link" href="/devices/{{ d.id }}/edit" hx-get="/ui/dialog/device/{{ d.id }}" hx-target="#modal-body"
title="{{ d.note or 'Изменить устройство' }}">{{ d.name }}</a></div>
{% if down %}<div class="dev-sub bad" title="{{ d.last_error }}">Нет соединения</div>
{% else %}<div class="dev-sub">{{ d.host }}:{{ d.port }}{% if st.model %} · {{ st.model }}{% endif %}</div>{% endif %}
</div>
</div>
</td>
<td class="muted">{{ group_names.get(d.group_id) or "—" }}</td>
<td>{% if down %}<span class="dash">—</span>{% else %}{{ st.channel or "—" }}{% endif %}</td>
<td class="c-mono">{% if down %}<span class="dash">—</span>{% else %}{{ st.ros_installed or st.ros_version or "—" }}{% endif %}</td>
<td>
{% if down or not (st.ros_latest and st.ros_installed) %}<span class="dash" title="{{ st.ros_check_error or 'Проверка обновлений ещё не выполнялась' }}">—</span>
{% elif ros_new %}<span class="badge warn" title="Доступно обновление ROS до {{ st.ros_latest }}">{{ ui.icon("up", 12, 2.2) }}{{ st.ros_latest }}</span>
{% else %}<span class="okmark">{{ ui.icon("check", 14, 2.2) }}актуально</span>{% endif %}
</td>
<td class="c-mono">{% if down %}<span class="dash">—</span>{% else %}{{ st.fw_current or "—" }}{% endif %}</td>
<td>
{% if down or not (st.fw_current and st.fw_upgrade) %}<span class="dash" title="Нет RouterBOARD firmware (например, CHR) или устройство не опрошено">—</span>
{% elif fw_new %}<span class="badge warn" title="Доступно обновление прошивки до {{ st.fw_upgrade }}">{{ ui.icon("up", 12, 2.2) }}{{ st.fw_upgrade }}</span>
{% else %}<span class="okmark">{{ ui.icon("check", 14, 2.2) }}актуально</span>{% endif %}
</td>
<td class="c-small">{% if down %}<span class="dash">—</span>{% else %}{{ st.uptime or "—" }}{% endif %}</td>
<td class="c-small">{{ d.last_backup_requested_at|dt }}</td>
<td class="c-menu">
<details class="menu right">
<summary class="btn ghost-n icon" aria-label="Действия для {{ d.name }}" title="Действия">{{ ui.icon("more") }}</summary>
<div class="menu-panel w270">
<button type="button" class="mi" hx-post="/ui/devices/{{ d.id }}/refresh" hx-include="#dev-filters" hx-target="#devices">Обновить статус</button>
<button type="button" class="mi" hx-post="/ui/devices/{{ d.id }}/backup" hx-target="#jobs">Создать бэкап</button>
<hr>
<button type="button" class="mi warn" hx-post="/ui/devices/{{ d.id }}/ros_update" hx-target="#jobs"
hx-confirm="Обновить ROS на {{ d.name }}? Устройство перезагрузится после скачивания.">Обновить ROS<small>Перезагрузка после скачивания</small></button>
<button type="button" class="mi warn" hx-post="/ui/devices/{{ d.id }}/fw_update" hx-target="#jobs"
hx-confirm="Обновить прошивку на {{ d.name }}? Устройство перезагрузится сразу после обновления.">Обновить FW<small>Перезагрузка сразу после обновления</small></button>
<hr>
<details class="sub">
<summary class="mi">Сменить канал…</summary>
<div class="sub-list">
{% for c in channels %}<button type="button" class="mi {{ 'on' if c == st.channel }}" hx-post="/ui/devices/{{ d.id }}/channel" hx-vals='{"channel": "{{ c }}"}' hx-include="#dev-filters" hx-target="#devices">{{ c }}</button>{% endfor %}
</div>
</details>
<button type="button" class="mi" hx-get="/ui/dialog/device/{{ d.id }}" hx-target="#modal-body">Изменить устройство</button>
</div>
</details>
</td>
</tr>
{% else %}
<tr><td colspan="11" class="empty">{{ "Нет устройств, подходящих под фильтр." if filtered else "Устройств пока нет. Добавьте первое." }}</td></tr>
{% endfor %}
</tbody>
</table>
</div>
<div class="tfoot">Показано {{ devices|length }} из {{ total }} {{ total|plural("устройства", "устройств", "устройств") }}</div>
+18
View File
@@ -0,0 +1,18 @@
{% import "_ui.html" as ui %}
{% set edit = group is not none %}
{% set action = ('/groups/' ~ group.id ~ '/rename') if edit else '/groups/new' %}
<form method="post" action="{{ action }}" {% if in_modal %}hx-post="{{ action }}" hx-target="#modal-body"{% endif %}>
<header class="modal-head">
<h2 id="modal-title">{{ "Переименовать группу" if edit else "Новая группа" }}</h2>
{% if in_modal %}<button type="button" class="btn ghost-n icon" data-close aria-label="Закрыть">{{ ui.icon("x") }}</button>{% endif %}
</header>
<div class="modal-body">
{% if error %}<div class="form-err" role="alert">{{ error }}</div>{% endif %}
<label class="lbl">Название<input class="input" name="name" value="{{ gname }}" maxlength="64" required autofocus></label>
</div>
<footer class="modal-foot">
<span class="grow"></span>
{% if in_modal %}<button type="button" class="btn ghost-n" data-close>Отмена</button>{% else %}<a class="btn ghost-n" href="/groups">Отмена</a>{% endif %}
<button class="btn primary">{{ "Сохранить" if edit else "Создать группу" }}</button>
</footer>
</form>
+31
View File
@@ -0,0 +1,31 @@
{% import "_ui.html" as ui %}
{% set running = jobs|selectattr("status", "in", ["pending", "running"])|list|length %}
{% set done = jobs|selectattr("status", "equalto", "done")|list|length %}
{% set failed = jobs|selectattr("status", "equalto", "failed")|list|length %}
<div class="section-head">
<h2>Задачи</h2>
{% if running %}<span class="badge run">{{ running }} выполняется</span>{% endif %}
{% if done %}<span class="badge">{{ done }} завершено</span>{% endif %}
{% if failed %}<span class="badge bad">{{ failed }} с ошибкой</span>{% endif %}
</div>
{% if flash %}<p class="err">{{ flash }}</p>{% endif %}
<div class="card">
<table class="grid jobs">
<colgroup><col style="width:56px"><col style="width:16%"><col style="width:16%"><col style="width:130px"><col><col style="width:150px"></colgroup>
<thead><tr><th>#</th><th>Устройство</th><th>Операция</th><th>Статус</th><th>Сообщение</th><th>Создана (UTC)</th></tr></thead>
<tbody>
{% for j in jobs %}
<tr>
<td class="muted">{{ j.id }}</td>
<td style="font-weight:500">{{ j.device_name }}</td>
<td>{{ {"backup": "Бэкап", "ros_update": "Обновление ROS", "fw_update": "Обновление FW"}.get(j.type, j.type) }}</td>
<td><span class="badge {{ {'running': 'run', 'done': 'ok', 'failed': 'bad'}.get(j.status, '') }}">{{ {"pending": "В очереди", "running": "Выполняется", "done": "Готово", "failed": "Ошибка"}.get(j.status, j.status) }}</span></td>
<td class="msg">{{ j.message }}</td>
<td class="c-small">{{ j.created_at|dt }}</td>
</tr>
{% else %}
<tr><td colspan="6" class="empty">Задач пока нет.</td></tr>
{% endfor %}
</tbody>
</table>
</div>
+4
View File
@@ -0,0 +1,4 @@
{# Общие макросы: иконки (inline SVG, stroke) #}
{% macro icon(name, size=16, sw=1.8) -%}
<svg class="ico" width="{{ size }}" height="{{ size }}" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="{{ sw }}" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">{{ ICONS[name]|safe }}</svg>
{%- endmacro %}
+70
View File
@@ -0,0 +1,70 @@
{% extends "base.html" %}
{% import "_ui.html" as ui %}
{% block content %}
<div class="page-head">
<div>
<h1>Резервные копии</h1>
<div class="sub">Бакет {{ bucket }} · {{ stats.total }} {{ stats.total|plural("файл", "файла", "файлов") }} · {{ stats.size|size }}</div>
</div>
<div class="actions"><a class="btn secondary" href="/backups?{{ request.url.query }}">{{ ui.icon("refresh") }}Обновить список</a></div>
</div>
<div class="card">
<div class="tools">
<form method="get" action="/backups">
<select class="field {{ 'on' if flt.group }}" name="group" onchange="this.form.submit()" aria-label="Группа" style="width:170px">
<option value="">Группа: любая</option>
<option value="none" {{ "selected" if flt.group == "none" }}>Группа: без группы</option>
{% for g in groups %}<option value="{{ g.id }}" {{ "selected" if flt.group == g.id|string }}>Группа: {{ g.name }}</option>{% endfor %}
</select>
<select class="field {{ 'on' if flt.device }}" name="device" onchange="this.form.submit()" aria-label="Устройство" style="width:190px">
<option value="">Устройство: любое</option>
{% for d in devices %}<option value="{{ d.name }}" {{ "selected" if d.name == flt.device }}>Устройство: {{ d.name }}</option>{% endfor %}
</select>
<select class="field {{ 'on' if flt.kind }}" name="kind" onchange="this.form.submit()" aria-label="Тип файла" style="width:150px">
<option value="">Тип: любой</option>
<option value="backup" {{ "selected" if flt.kind == "backup" }}>Тип: .backup</option>
<option value="rsc" {{ "selected" if flt.kind == "rsc" }}>Тип: .rsc</option>
</select>
<label class="datefield">с <input type="date" name="date_from" value="{{ flt.date_from }}" onchange="this.form.submit()" aria-label="Дата с"></label>
<label class="datefield">по <input type="date" name="date_to" value="{{ flt.date_to }}" onchange="this.form.submit()" aria-label="Дата по"></label>
<label class="search">{{ ui.icon("search") }}<input type="search" name="q" value="{{ flt.q }}" placeholder="Имя файла" aria-label="Поиск по имени файла" style="width:220px"></label>
<span class="grow"></span>
{% if flt_active %}<a class="btn ghost" href="/backups">Сбросить ({{ flt_active }})</a>{% endif %}
</form>
</div>
{% if error %}<div class="form-err" role="alert" style="margin:0 16px 16px">Ошибка S3: {{ error }}</div>{% endif %}
<div class="table-wrap">
<table class="grid files">
<colgroup><col style="width:20%"><col style="width:140px"><col style="width:100px"><col><col style="width:100px"><col style="width:170px"><col style="width:104px"></colgroup>
<thead><tr><th>Устройство</th><th>Группа</th><th>Тип</th><th>Файл</th><th>Размер</th><th>Изменён (UTC)</th><th><span class="sr-only">Действия</span></th></tr></thead>
<tbody>
{% for i in items %}
<tr>
<td style="font-weight:600">{{ i.device or "—" }}</td>
<td class="muted">{{ i.group or "—" }}</td>
<td><span class="badge">{{ {"backup": ".backup", "rsc": ".rsc"}.get(i.kind, "—") }}</span></td>
<td class="c-mono" title="{{ i.key }}" style="overflow:hidden;text-overflow:ellipsis;white-space:nowrap">{{ i.key.split("/")[-1] }}</td>
<td class="c-small">{{ i.size|size }}</td>
<td class="c-small">{{ i.last_modified|dt }}</td>
<td class="c-menu">
<a class="btn ghost-n icon" href="/backups/download?key={{ i.key|urlencode }}" aria-label="Скачать {{ i.key.split('/')[-1] }}" title="Скачать">{{ ui.icon("download") }}</a>
<details class="menu right">
<summary class="btn ghost-n icon" aria-label="Действия" title="Действия">{{ ui.icon("more") }}</summary>
<div class="menu-panel w200">
<form method="post" action="/backups/delete" onsubmit="return confirm('Удалить файл из бакета?')">
<input type="hidden" name="key" value="{{ i.key }}"><button class="mi bad">Удалить файл</button>
</form>
</div>
</details>
</td>
</tr>
{% else %}
<tr><td colspan="7" class="empty">Файлов не найдено.</td></tr>
{% endfor %}
</tbody>
</table>
</div>
<div class="tfoot">Найдено {{ items|length }} из {{ stats.total }} {{ stats.total|plural("файла", "файлов", "файлов") }}</div>
</div>
{% endblock %}
+28
View File
@@ -0,0 +1,28 @@
{% import "_ui.html" as ui %}
<!doctype html>
<html lang="ru">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>{% block title %}ros_control{% endblock %}</title>
<link rel="stylesheet" href="/static/style.css">
<script src="/static/htmx.min.js"></script>
<script src="/static/app.js" defer></script>
</head>
<body>
{% if request.session.get("user") %}
{% set nav = [("Устройства", "/", "devices"), ("Группы", "/groups", "groups"), ("Резервные копии", "/backups", "backups")] %}
<header class="app-header">
<a class="brand" href="/"><span class="brand-logo">{{ ui.icon("router") }}</span>ros_control</a>
<nav class="nav" aria-label="Разделы">
{% for title, href, key in nav %}<a href="{{ href }}" class="{{ 'on' if section == key }}">{{ title }}</a>{% endfor %}
</nav>
<span class="grow"></span>
<span class="user">{{ request.session.get("user") }}</span>
<form method="post" action="/logout"><button class="btn ghost-n">Выйти</button></form>
</header>
{% endif %}
<main class="container">{% block content %}{% endblock %}</main>
<dialog id="modal" class="modal" aria-labelledby="modal-title"><div id="modal-body"></div></dialog>
</body>
</html>
+85
View File
@@ -0,0 +1,85 @@
{% extends "base.html" %}
{% import "_ui.html" as ui %}
{% block content %}
<div class="page-head">
<div>
<h1>Устройства</h1>
<div class="sub" id="dev-sub">{% include "_dev_sub.html" %}</div>
</div>
<div class="actions">
<button type="button" class="btn secondary" hx-post="/ui/refresh" hx-include="#dev-filters" hx-target="#devices" hx-indicator="#busy">{{ ui.icon("refresh") }}Обновить статус</button>
<button type="button" class="btn primary" hx-get="/ui/dialog/device{{ '?group=' ~ flt.group if flt.group.isdigit() }}" hx-target="#modal-body">{{ ui.icon("plus") }}Добавить устройство</button>
</div>
</div>
<nav class="tabs" aria-label="Группы устройств">
{% for t in tabs %}<a class="tab {{ 'on' if t.active }}" href="{{ t.href }}">{{ t.label }} <span class="count">{{ t.count }}</span></a>{% endfor %}
<span class="grow"></span>
<a class="tab-link" href="/groups">Управление группами {{ ui.icon("arrow", 14) }}</a>
</nav>
<form id="move-form" method="post" action="/ui/move" hidden><input type="hidden" name="next" value="{{ page_url }}"></form>
<div class="card" id="dev-card">
<div class="tools" id="tools-filters">
<form id="dev-filters" hx-get="/ui/devices" hx-target="#devices" hx-trigger="input delay:300ms, change" onsubmit="return false">
<input type="hidden" name="f_group" value="{{ flt.group }}">
<label class="search">{{ ui.icon("search") }}<input type="search" name="f_q" value="{{ flt.q }}" placeholder="Поиск: имя, адрес, модель" aria-label="Поиск: имя, адрес, модель"></label>
<select class="field {{ 'on' if flt.status }}" name="f_status" aria-label="Статус" style="width:150px">
<option value="">Статус: любой</option>
<option value="online" {{ 'selected' if flt.status == 'online' }}>Статус: online</option>
<option value="offline" {{ 'selected' if flt.status == 'offline' }}>Статус: offline</option>
</select>
<select class="field {{ 'on' if flt.updates }}" name="f_updates" aria-label="Обновления" style="width:190px">
<option value="">Обновления: любые</option>
<option value="any" {{ 'selected' if flt.updates == 'any' }}>Есть обновление</option>
<option value="ros" {{ 'selected' if flt.updates == 'ros' }}>Есть обновление ROS</option>
<option value="fw" {{ 'selected' if flt.updates == 'fw' }}>Есть обновление FW</option>
<option value="none" {{ 'selected' if flt.updates == 'none' }}>Всё актуально</option>
</select>
<select class="field {{ 'on' if flt.channel }}" name="f_channel" aria-label="Канал" style="width:150px">
<option value="">Канал: любой</option>
{% for c in channels %}<option value="{{ c }}" {{ 'selected' if flt.channel == c }}>Канал: {{ c }}</option>{% endfor %}
</select>
<span class="grow"></span>
<a id="filters-reset" class="btn ghost" href="{{ '/?f_group=' ~ flt.group if flt.group else '/' }}" {{ 'hidden' if not flt_active }}>Сбросить ({{ flt_active }})</a>
<span id="busy" class="busy htmx-indicator">…</span>
</form>
</div>
<div class="tools bulk" id="tools-bulk" hidden>
<span class="sel-count">Выбрано: <span id="sel-count">0</span></span>
<button type="button" class="btn secondary" hx-post="/ui/batch/backup" hx-include="[name=device_ids]:checked" hx-target="#jobs">{{ ui.icon("archive") }}Создать бэкап</button>
<button type="button" class="btn secondary" hx-post="/ui/refresh" hx-include="[name=device_ids]:checked, #dev-filters" hx-target="#devices">{{ ui.icon("refresh") }}Обновить статус</button>
<details class="menu">
<summary class="btn secondary">Обновление {{ ui.icon("chev", 14) }}</summary>
<div class="menu-panel w330">
<button type="button" class="mi warn" hx-post="/ui/batch/ros_update" hx-include="[name=device_ids]:checked" hx-target="#jobs"
hx-confirm="Обновить ROS на выбранных устройствах? Они перезагрузятся после скачивания.">Обновить ROS до актуальной версии<small>Устройство перезагрузится после скачивания</small></button>
<button type="button" class="mi warn" hx-post="/ui/batch/fw_update" hx-include="[name=device_ids]:checked" hx-target="#jobs"
hx-confirm="Обновить прошивку на выбранных устройствах? Они перезагрузятся сразу после обновления.">Обновить прошивку (FW)<small>Устройство перезагрузится сразу после обновления</small></button>
</div>
</details>
<details class="menu">
<summary class="btn secondary">Канал {{ ui.icon("chev", 14) }}</summary>
<div class="menu-panel w200">
{% for c in channels %}<button type="button" class="mi" hx-post="/ui/batch/channel" hx-vals='{"channel": "{{ c }}"}' hx-include="[name=device_ids]:checked, #dev-filters" hx-target="#devices">{{ c }}</button>{% endfor %}
</div>
</details>
<details class="menu">
<summary class="btn secondary">В группу {{ ui.icon("chev", 14) }}</summary>
<div class="menu-panel w200">
{% for g in groups %}<button type="submit" form="move-form" name="group_id" value="{{ g.id }}" class="mi">{{ g.name }}</button>{% endfor %}
{% if groups %}<hr>{% endif %}
<button type="submit" form="move-form" name="group_id" value="" class="mi">Без группы</button>
</div>
</details>
<span class="grow"></span>
<button type="button" id="clear-sel" class="btn ghost-n">{{ ui.icon("x") }}Снять выбор</button>
</div>
<div id="devices">{% include "_devices.html" %}</div>
</div>
<div id="jobs" hx-get="/ui/jobs" hx-trigger="every 3s" hx-swap="innerHTML">{% include "_jobs.html" %}</div>
{% endblock %}
+4
View File
@@ -0,0 +1,4 @@
{% extends "base.html" %}
{% block content %}
<div class="card page-card">{% include "_device_form.html" %}</div>
{% endblock %}
+45
View File
@@ -0,0 +1,45 @@
{% extends "base.html" %}
{% import "_ui.html" as ui %}
{% block content %}
<div class="page-head">
<div>
<h1>Группы</h1>
<div class="sub">{{ groups|length }} {{ groups|length|plural("группа", "группы", "групп") }} · {{ total }} {{ total|plural("устройство", "устройства", "устройств") }}</div>
</div>
<div class="actions">
<button type="button" class="btn primary" hx-get="/ui/dialog/group" hx-target="#modal-body">{{ ui.icon("plus") }}Создать группу</button>
</div>
</div>
{% if error %}<div class="form-err" role="alert" style="margin-bottom:16px">{{ error }}</div>{% endif %}
<div class="card">
<table class="grid groups">
<colgroup><col><col style="width:200px"><col style="width:120px"></colgroup>
<thead><tr><th>Название</th><th>Устройства</th><th><span class="sr-only">Действия</span></th></tr></thead>
<tbody>
{% for g in groups %}
<tr>
<td style="font-weight:600">{{ g.name }}</td>
<td><a href="/?f_group={{ g.id }}" style="font-weight:500">{{ g.device_count }} {{ g.device_count|plural("устройство", "устройства", "устройств") }}</a></td>
<td class="c-menu">
<details class="menu right">
<summary class="btn ghost-n icon" aria-label="Действия для группы {{ g.name }}" title="Действия">{{ ui.icon("more") }}</summary>
<div class="menu-panel w200">
<button type="button" class="mi" hx-get="/ui/dialog/group/{{ g.id }}" hx-target="#modal-body">Переименовать</button>
<button type="button" class="mi bad" hx-post="/groups/{{ g.id }}/delete"
hx-confirm="Удалить группу «{{ g.name }}»? Устройства останутся и станут «Без группы».">Удалить</button>
</div>
</details>
</td>
</tr>
{% else %}
<tr><td colspan="3" class="empty">Групп пока нет. Создайте первую.</td></tr>
{% endfor %}
<tr>
<td class="muted" style="font-weight:600">Без группы</td>
<td><a href="/?f_group=none" style="font-weight:500">{{ ungrouped }} {{ ungrouped|plural("устройство", "устройства", "устройств") }}</a></td>
<td class="c-menu c-small">системная</td>
</tr>
</tbody>
</table>
</div>
{% endblock %}
+12
View File
@@ -0,0 +1,12 @@
{% extends "base.html" %}
{% block content %}
<form method="post" action="/login" class="card login">
<div class="modal-body">
<h1>Вход</h1>
{% if error %}<div class="form-err">{{ error }}</div>{% endif %}
<label class="lbl">Логин <input class="input" name="username" autofocus required></label>
<label class="lbl">Пароль <input class="input" name="password" type="password" required></label>
<button class="btn primary">Войти</button>
</div>
</form>
{% endblock %}