diff --git a/app.py b/app.py index 586edc6..46751ed 100644 --- a/app.py +++ b/app.py @@ -29,7 +29,7 @@ from ui_builder import install_ui_builder from khl_site.khl_data_center import APP as khl_site_app BASE_DIR = Path(__file__).resolve().parent -BUILD_VERSION = "2026.09.15.2" +BUILD_VERSION = "2026.09.15.3" # compatibility: BUILD_VERSION = "2026.08.26.1" # compatibility: BUILD_VERSION = "2026.08.25.1" # compatibility: BUILD_VERSION = "2026.08.24.15" diff --git a/hockey_data/models.py b/hockey_data/models.py index 7946d7f..c2cb126 100644 --- a/hockey_data/models.py +++ b/hockey_data/models.py @@ -264,7 +264,11 @@ class Team(Base): color_3_enabled: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False) color_4_hex: Mapped[str] = mapped_column(String(9), nullable=False, default="") color_4_enabled: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False) + # BUILD135: three operator-editable logo locations. ``logo_url`` remains + # logo #1 for backwards compatibility with existing SQL/mappings. logo_url: Mapped[str] = mapped_column(Text, nullable=False, default="") + logo_2_url: Mapped[str] = mapped_column(Text, nullable=False, default="") + logo_3_url: Mapped[str] = mapped_column(Text, nullable=False, default="") raw_payload: Mapped[str] = mapped_column(Text, nullable=False, default="") synced_at: Mapped[datetime] = mapped_column( DateTime, nullable=False, default=datetime.utcnow diff --git a/hockey_data/router.py b/hockey_data/router.py index 7a6e618..341961f 100644 --- a/hockey_data/router.py +++ b/hockey_data/router.py @@ -1,7 +1,9 @@ from __future__ import annotations import asyncio +import os from datetime import date +from pathlib import Path from time import perf_counter from typing import Any, Callable @@ -174,6 +176,8 @@ class TeamDirectoryPayload(BaseModel): color_4_hex: str = Field(default="", max_length=9) color_4_enabled: bool = False logo_url: str = Field(default="", max_length=2000) + logo_2_url: str = Field(default="", max_length=2000) + logo_3_url: str = Field(default="", max_length=2000) active: bool = True @@ -561,6 +565,73 @@ def create_hockey_router( include_inactive=include_inactive, ) + + @router.post("/directories/teams/select-logo-file", dependencies=admin) + def select_team_logo_file( + initial_path: str = Query("", max_length=2000), + ) -> dict[str, Any]: + """Open a native image chooser on the machine running FastAPI. + + Browsers intentionally hide absolute local file paths, so a normal + ```` cannot provide the Windows path needed by vMix. + When the control server is running on the operator workstation this + native chooser returns the real path. Manual paste remains available + when the server has no desktop session. + """ + try: + import tkinter as tk + from tkinter import filedialog + except Exception as error: + raise HTTPException( + status_code=501, + detail="На этом сервере недоступен системный выбор файла. Вставьте полный путь вручную.", + ) from error + + initial = str(initial_path or "").strip().strip('"').strip("'") + initial_dir = "" + initial_file = "" + if initial: + candidate = Path(initial) + if candidate.is_dir(): + initial_dir = str(candidate) + else: + initial_file = candidate.name + if candidate.parent and str(candidate.parent) not in {"", "."}: + initial_dir = str(candidate.parent) + + root = None + try: + root = tk.Tk() + root.withdraw() + try: + root.attributes("-topmost", True) + except Exception: + pass + selected = filedialog.askopenfilename( + parent=root, + title="Выберите логотип команды", + initialdir=initial_dir or None, + initialfile=initial_file or None, + filetypes=[ + ("Изображения", "*.png *.jpg *.jpeg *.webp *.bmp *.gif *.svg"), + ("Все файлы", "*.*"), + ], + ) + except Exception as error: + raise HTTPException( + status_code=501, + detail="Не удалось открыть системный выбор файла. Вставьте полный путь вручную.", + ) from error + finally: + if root is not None: + try: + root.destroy() + except Exception: + pass + + selected = str(selected or "").strip() + return {"ok": True, "cancelled": not bool(selected), "path": selected} + @router.post("/directories/teams/sync", dependencies=admin) async def sync_directory_teams( tournament_external_id: str = Query("", max_length=64), diff --git a/hockey_data/service.py b/hockey_data/service.py index 9f2ac6e..a0d7484 100644 --- a/hockey_data/service.py +++ b/hockey_data/service.py @@ -100,6 +100,19 @@ def normalise_team_color_hex(value: Any) -> str: return raw_color +def normalise_team_media_path(value: Any) -> str: + """Trim a copied URL/path and remove matching outer quotes. + + Windows Explorer's ``Copy as path`` intentionally puts the full path in + double quotes. Operators paste those values into the directory frequently, + so store the useful path rather than the shell quoting. + """ + result = str(value or "").strip() + while len(result) >= 2 and result[0] == result[-1] and result[0] in {"\"", "'"}: + result = result[1:-1].strip() + return result + + DEFAULT_PENALTY_TYPES: tuple[tuple[str, str, str, str], ...] = ( ("TRIP", "Подножка", "Tripping", "2"), ("HOOK", "Задержка клюшкой", "Hooking", "2"), @@ -824,6 +837,9 @@ class HockeyDataService: {"index": 4, "hex": team.color_4_hex, "enabled": bool(team.color_4_enabled)}, ], "logo_url": team.logo_url, + "logo_2_url": team.logo_2_url, + "logo_3_url": team.logo_3_url, + "logo_paths": [team.logo_url, team.logo_2_url, team.logo_3_url], "source": membership.source, "active": bool(membership.active), "synced_at": ( @@ -965,11 +981,14 @@ class HockeyDataService: "short_name_en", "city_ru", "city_en", - "logo_url", ): if field in payload and payload[field] is not None: setattr(team, field, str(payload[field]).strip()) + for field in ("logo_url", "logo_2_url", "logo_3_url"): + if field in payload and payload[field] is not None: + setattr(team, field, normalise_team_media_path(payload[field])) + color_fields = ( ("color_hex", "color_enabled"), ("color_2_hex", "color_2_enabled"), diff --git a/hockey_data/static/admin-directories.css b/hockey_data/static/admin-directories.css index f5af4f8..8d67f15 100644 --- a/hockey_data/static/admin-directories.css +++ b/hockey_data/static/admin-directories.css @@ -2158,3 +2158,213 @@ body.hockey-admin-settings-open { overflow: hidden; } .hockey-map-grid-result{flex:0 0 auto}.hockey-map-grid-matrix-wrap{max-height:330px;overflow:auto}.hockey-map-grid-matrix{border-collapse:collapse;min-width:100%;width:max-content}.hockey-map-grid-matrix th,.hockey-map-grid-matrix td{border-right:1px solid #26384a;border-bottom:1px solid #26384a;padding:5px;vertical-align:top}.hockey-map-grid-matrix thead th{position:sticky;top:0;z-index:2;background:#111f2d;text-align:left;min-width:145px}.hockey-map-grid-matrix thead th:first-child{left:0;z-index:3}.hockey-map-grid-matrix thead strong{display:block;color:#d9e7f3;font-size:9px}.hockey-map-grid-matrix thead small{display:block;color:#6e859b;font-size:7px;margin-top:2px}.hockey-map-grid-matrix tbody th{position:sticky;left:0;z-index:1;background:#0f1b28;min-width:130px;text-align:left}.hockey-map-grid-matrix tbody th b{display:block;color:#74d5c1;font-size:9px}.hockey-map-grid-matrix tbody th span{display:block;color:#7e94aa;font-size:8px;max-width:140px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.hockey-map-grid-matrix-cell{min-width:145px;display:grid;grid-template-columns:minmax(0,1fr) auto;gap:2px 5px;align-items:center}.hockey-map-grid-matrix-cell strong{font-size:8px;color:#dce9f5;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.hockey-map-grid-matrix-cell span{grid-column:1/2;font-size:8px;color:#8299ae;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.hockey-map-grid-matrix-cell small{font-size:7px;font-weight:900}.hockey-map-grid-matrix-cell button{grid-column:2;grid-row:1/4;width:26px;height:26px;border:1px solid #38516a;border-radius:7px;background:#132337;color:#b7c8d8;cursor:pointer}.hockey-map-grid-matrix td.is-auto small{color:#5fd7bd}.hockey-map-grid-matrix td.is-template small{color:#6ec8f2}.hockey-map-grid-matrix td.is-override{background:#2a2112}.hockey-map-grid-matrix td.is-override small{color:#f2c66d}.hockey-map-grid-matrix td.is-empty small{color:#6e8092}.hockey-map-grid-limit{display:block;padding:7px 10px;color:#73899e;font-size:8px}.hockey-map-grid-empty{display:grid;place-content:center;justify-items:center;gap:6px;text-align:center;color:#7f95aa;padding:18px}.hockey-map-grid-empty.is-large{min-height:300px}.hockey-map-grid-empty strong{color:#e0ebf5;font-size:14px}.hockey-map-grid-empty span{max-width:620px;line-height:1.45}.hockey-map-grid-limit{color:#74899c} @media(max-width:1250px){.hockey-map-grid-builder{grid-template-columns:minmax(0,1fr) minmax(310px,.8fr)}.hockey-map-grid-toolbar{grid-template-columns:1fr 1fr}.hockey-map-grid-toolbar .is-small{grid-column:1/-1}} @media(max-width:980px){.hockey-map-grid-toolbar{grid-template-columns:1fr}.hockey-map-grid-toolbar .is-small{grid-column:auto}.hockey-map-grid-builder{grid-template-columns:1fr}.hockey-map-grid-data-scroll,.hockey-map-grid-target-scroll{height:330px}.hockey-map-grid-apply{align-items:stretch;flex-direction:column}.hockey-map-grid-apply button{width:100%}} + +/* BUILD135 — denser Teams directory + three logo paths */ +.hockey-teams-directory-grid { + grid-template-columns: minmax(620px, 1fr) minmax(360px, 420px); + align-items: stretch; + height: calc(100dvh - 208px); + min-height: 520px; + max-height: calc(100dvh - 208px); +} + +.hockey-teams-table-wrap { + height: 100%; + max-height: none; + min-height: 0; +} + +.hockey-teams-directory-grid > .hockey-directory-form { + min-height: 0; + max-height: 100%; + overflow: auto; + align-content: start; +} + +.hockey-teams-table { + table-layout: auto; +} + +.hockey-teams-table th { + padding: 7px 7px; +} + +.hockey-teams-table td { + padding: 4px 7px; + line-height: 1.15; +} + +.hockey-teams-table td strong { + overflow: hidden; + max-width: 220px; + font-size: 9px; + line-height: 1.15; + text-overflow: ellipsis; + white-space: nowrap; +} + +.hockey-teams-table td small { + margin-top: 1px; + font-size: 7px; + line-height: 1.1; +} + +.hockey-teams-table td code { + font-size: 8px; +} + +.hockey-teams-table tr.is-editing td { + background: rgba(72, 223, 189, .055); +} + +.hockey-teams-table tr.is-editing td:first-child { + box-shadow: inset 3px 0 0 #48dfbd; +} + +.hockey-teams-table .hockey-directory-edit { + min-height: 25px; + padding: 0 7px; + font-size: 8px; +} + +/* The directory only needs a compact visual summary of team colours. Full + HEX values stay in the editor and in tooltips, which keeps each team row low. */ +.hockey-teams-table .hockey-team-colors-cell { + display: flex; + align-items: center; + gap: 4px; + min-width: 78px; +} + +.hockey-teams-table .hockey-team-color-chip { + display: grid; + grid-template-columns: 12px 14px; + align-items: center; + gap: 2px; + min-height: 16px; +} + +.hockey-teams-table .hockey-team-color-chip > b { + width: 12px; + height: 12px; + font-size: 6px; +} + +.hockey-teams-table .hockey-team-color-chip > i { + width: 13px; + height: 13px; +} + +.hockey-team-logo-paths { + display: grid; + gap: 8px; + padding: 10px; + border: 1px solid #2b4057; + border-radius: 10px; + background: #0b1725; +} + +.hockey-team-logo-paths-head { + display: flex; + align-items: flex-end; + justify-content: space-between; + gap: 10px; +} + +.hockey-team-logo-paths-head > span { + color: #c8d7e6; + font-size: 10px; + font-weight: 900; +} + +.hockey-team-logo-paths-head > small { + max-width: 260px; + color: #71869a; + font-size: 7px; + line-height: 1.35; + text-align: right; +} + +.hockey-team-logo-field { + display: grid !important; + gap: 4px !important; +} + +.hockey-team-logo-control { + display: grid; + grid-template-columns: minmax(0, 1fr) auto 34px; + gap: 6px; + align-items: center; +} + +.hockey-team-logo-control > input { + min-width: 0; + font-family: Consolas, "SFMono-Regular", monospace; + font-size: 9px; +} + +.hockey-team-logo-control > button { + min-height: 35px; + padding: 0 10px; + color: #cbd8e8; + border: 1px solid #304863; + border-radius: 8px; + background: #142338; + font-size: 9px; + font-weight: 850; + white-space: nowrap; +} + +.hockey-team-logo-control > button:hover { + border-color: #48dfbd; +} + +.hockey-team-logo-control > button:disabled { + opacity: .5; + cursor: wait; +} + +.hockey-team-logo-control > button.hockey-team-logo-clear { + padding: 0; + color: #93a8bd; + font-size: 17px; +} + +@media (max-width: 1180px) { + .hockey-teams-directory-grid { + grid-template-columns: minmax(520px, 1fr) minmax(330px, 390px); + } + .hockey-team-logo-paths-head { + align-items: flex-start; + flex-direction: column; + } + .hockey-team-logo-paths-head > small { + max-width: none; + text-align: left; + } +} + +@media (max-width: 900px) { + .hockey-teams-directory-grid { + grid-template-columns: 1fr; + height: auto; + max-height: none; + } + .hockey-teams-table-wrap { + height: min(54vh, 620px); + min-height: 360px; + } + .hockey-teams-directory-grid > .hockey-directory-form { + max-height: none; + overflow: visible; + } +} + +@media (max-width: 620px) { + .hockey-team-logo-control { + grid-template-columns: minmax(0, 1fr) auto; + } + .hockey-team-logo-control > .hockey-team-logo-clear { + grid-column: 2; + } +} diff --git a/hockey_data/static/admin-directories.js b/hockey_data/static/admin-directories.js index a8b971d..f374157 100644 --- a/hockey_data/static/admin-directories.js +++ b/hockey_data/static/admin-directories.js @@ -58,6 +58,8 @@ referees: null, coaches: null, teamLeague: "", + teamTableScrollTop: 0, + teamContentScrollTop: 0, directorySearch: "", editingTeam: null, editingPenalty: null, @@ -81,6 +83,34 @@ return /^#[0-9A-F]{6}$/.test(color) ? color : ""; }; + const normalizeTeamMediaPath = (value) => { + let result = String(value ?? "").trim(); + while (result.length >= 2) { + const first = result[0]; + const last = result[result.length - 1]; + if (!((first === '"' && last === '"') || (first === "'" && last === "'"))) break; + result = result.slice(1, -1).trim(); + } + return result; + }; + + const teamLogoFieldName = (index) => index === 1 ? "logo_url" : `logo_${index}_url`; + + const teamLogoPathMarkup = (editing, index) => { + const field = teamLogoFieldName(index); + const value = normalizeTeamMediaPath(editing?.[field] || ""); + return ` + + `; + }; + const teamColorPreview = (value) => { const color = normalizeTeamColorHex(value); return color || "#FFFFFF"; @@ -120,7 +150,8 @@ const enabledField = teamColorEnabledName(index); const value = normalizeTeamColorHex(item?.[field]); const enabled = Boolean(item?.[enabledField]) && Boolean(value); - return `${index}${escapeHtml(value || "—")}`; + const title = `Цвет ${index}: ${enabled ? "включён" : "выключен"}${value ? ` · ${value}` : ""}`; + return `${index}`; }).join(""); const countryFlagMarkup = (item) => { @@ -390,17 +421,16 @@ const rows = data.items.length ? data.items.map((item) => ` - + ${escapeHtml(item.external_id)} ${escapeHtml(item.name_ru || "—")}${escapeHtml(item.short_name_ru || "")} ${escapeHtml(item.name_en || "—")}${escapeHtml(item.short_name_en || "")} ${escapeHtml(item.city_ru || item.city_en || "—")}
${teamColorsCellMarkup(item)}
- ${escapeHtml(item.source === "manual" ? "изменено" : "Stat2TV")} `).join("") - : `Для этой лиги команды ещё не загружены. Нажмите «Обновить из API».`; + : `Для этой лиги команды ещё не загружены. Нажмите «Обновить из API».`; const content = `
@@ -412,10 +442,10 @@

Команды формируются из матчей Stat2TV и разделяются по лигам. При выбранном матче показывается только его лига.

${statusMarkup()} -
-
- - +
+
+
ID APIРусскийEnglishГородЦветаИсточник
+ ${rows}
ID APIРусскийEnglishГородЦвета
@@ -433,7 +463,15 @@
- +
+
+ Логотипы команды + Можно вставить URL или полный путь. Кавычки из Windows «Копировать как путь» удаляются автоматически. +
+ ${teamLogoPathMarkup(editing, 1)} + ${teamLogoPathMarkup(editing, 2)} + ${teamLogoPathMarkup(editing, 3)} +
Цвета команды @@ -3508,9 +3546,63 @@ function bindTeams() { const modal = ensureModal(); + const tableWrap = modal.querySelector("[data-team-table-wrap]"); + if (tableWrap) { + tableWrap.scrollTop = Number(state.teamTableScrollTop || 0); + tableWrap.addEventListener("scroll", () => { + state.teamTableScrollTop = tableWrap.scrollTop; + }, { passive: true }); + } + const contentWrap = modal.querySelector(".hockey-directory-content"); + if (contentWrap) { + contentWrap.scrollTop = Number(state.teamContentScrollTop || 0); + contentWrap.addEventListener("scroll", () => { + state.teamContentScrollTop = contentWrap.scrollTop; + }, { passive: true }); + } + + const bindTeamLogoPath = (index) => { + const input = modal.querySelector(`[data-team-logo-path="${index}"]`); + const pick = modal.querySelector(`[data-team-logo-pick="${index}"]`); + const clear = modal.querySelector(`[data-team-logo-clear="${index}"]`); + const normalizeInput = () => { + if (!input) return ""; + const normalized = normalizeTeamMediaPath(input.value); + if (input.value !== normalized) input.value = normalized; + return normalized; + }; + input?.addEventListener("input", normalizeInput); + input?.addEventListener("blur", normalizeInput); + input?.addEventListener("paste", () => setTimeout(normalizeInput, 0)); + clear?.addEventListener("click", () => { + if (!input) return; + input.value = ""; + input.focus(); + }); + pick?.addEventListener("click", async () => { + if (!input) return; + pick.disabled = true; + try { + const params = new URLSearchParams(); + const current = normalizeInput(); + if (current) params.set("initial_path", current); + const result = await request(`/api/hockey/directories/teams/select-logo-file?${params}`, { method: "POST" }); + if (!result?.cancelled && result?.path) { + input.value = normalizeTeamMediaPath(result.path); + setStatus(`Логотип ${index}: файл выбран.`); + } + } catch (error) { + setStatus(error.message, true); + } finally { + pick.disabled = false; + } + }); + }; + [1, 2, 3].forEach(bindTeamLogoPath); modal.querySelector("[data-team-league-filter]")?.addEventListener("change", async (event) => { state.teamLeague = event.target.value; state.editingTeam = null; + state.teamTableScrollTop = 0; try { await loadTeams(); setStatus(""); @@ -3646,7 +3738,9 @@ color_3_enabled: normalizedColors.color_3_enabled, color_4_hex: normalizedColors.color_4_hex, color_4_enabled: normalizedColors.color_4_enabled, - logo_url: values.get("logo_url") || "", + logo_url: normalizeTeamMediaPath(values.get("logo_url") || ""), + logo_2_url: normalizeTeamMediaPath(values.get("logo_2_url") || ""), + logo_3_url: normalizeTeamMediaPath(values.get("logo_3_url") || ""), active: values.has("active"), }; const editingId = state.editingTeam?.id;