diff --git a/app.py b/app.py index afc755c..37d7918 100644 --- a/app.py +++ b/app.py @@ -30,7 +30,8 @@ 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.23.7" +BUILD_VERSION = "2026.09.23.8" +# compatibility: BUILD_VERSION = "2026.09.23.7" # compatibility: BUILD_VERSION = "2026.09.23.6" # compatibility: BUILD_VERSION = "2026.08.26.1" # compatibility: BUILD_VERSION = "2026.08.25.1" diff --git a/hockey_data/models.py b/hockey_data/models.py index e2b2a8e..7e22626 100644 --- a/hockey_data/models.py +++ b/hockey_data/models.py @@ -938,6 +938,37 @@ class ShootoutAttempt(Base): ) +class CustomPlusRow(Base): + """One operator-entered row from the match-scoped "Свои плюсы" workspace.""" + + __tablename__ = "hockey_custom_plus_rows" + + id: Mapped[int] = mapped_column(Integer, primary_key=True) + game_external_id: Mapped[str] = mapped_column( + String(64), ForeignKey("hockey_games.external_id", ondelete="CASCADE"), + nullable=False, + ) + side: Mapped[str] = mapped_column(String(16), nullable=False) + sort_order: Mapped[int] = mapped_column(Integer, nullable=False, default=1) + text_value: Mapped[str] = mapped_column(Text, nullable=False, default="") + status: Mapped[str] = mapped_column(String(16), nullable=False, default="skip") + updated_by: Mapped[str] = mapped_column(String(128), nullable=False, default="") + created_at: Mapped[datetime] = mapped_column( + DateTime, nullable=False, default=datetime.utcnow + ) + updated_at: Mapped[datetime] = mapped_column( + DateTime, nullable=False, default=datetime.utcnow + ) + + __table_args__ = ( + UniqueConstraint( + "game_external_id", "side", "sort_order", + name="uq_hockey_custom_plus_game_side_order", + ), + Index("ix_hockey_custom_plus_game_side", "game_external_id", "side"), + ) + + class OperatorSession(Base): __tablename__ = "hockey_operator_sessions" diff --git a/hockey_data/router.py b/hockey_data/router.py index f1a0041..4497ee9 100644 --- a/hockey_data/router.py +++ b/hockey_data/router.py @@ -142,6 +142,22 @@ class GameLinesPayload(BaseModel): language: str = Field(default="ru", pattern="^(ru|en)$") +class CustomPlusRowPayload(BaseModel): + model_config = ConfigDict(extra="ignore") + + side: str = Field(pattern="^(home|away)$") + sort_order: int = Field(default=1, ge=1, le=999) + text: str = Field(default="", max_length=4000) + status: str = Field(default="skip", pattern="^(skip|check|cross)$") + + +class CustomPlusesPayload(BaseModel): + model_config = ConfigDict(extra="ignore") + + rows: list[CustomPlusRowPayload] = Field(default_factory=list) + language: str = Field(default="ru", pattern="^(ru|en)$") + + class ShootoutSetupPayload(BaseModel): initial_attempts: int = Field(default=3) reset: bool = False @@ -1202,6 +1218,33 @@ def create_hockey_router( except ValueError as error: raise HTTPException(status_code=400, detail=str(error)) from error + @router.get("/games/{external_id}/custom-pluses") + async def get_custom_pluses( + external_id: str, + language: str = Query("ru", pattern="^(ru|en)$"), + user: HockeyUser = Depends(auth_dependency), + ) -> dict[str, Any]: + try: + return service.custom_pluses(external_id, language=language) + except ValueError as error: + raise HTTPException(status_code=404, detail=str(error)) from error + + @router.put("/games/{external_id}/custom-pluses") + async def update_custom_pluses( + external_id: str, + payload: CustomPlusesPayload, + user: HockeyUser = Depends(auth_dependency), + ) -> dict[str, Any]: + try: + return service.save_custom_pluses( + external_id, + rows=[item.model_dump() for item in payload.rows], + updated_by=user.id, + language=payload.language, + ) + except ValueError as error: + raise HTTPException(status_code=400, detail=str(error)) from error + @router.put("/games/{external_id}/control/values") async def update_game_values( external_id: str, diff --git a/hockey_data/service.py b/hockey_data/service.py index dc0bcff..3587981 100644 --- a/hockey_data/service.py +++ b/hockey_data/service.py @@ -55,6 +55,7 @@ from .models import ( Coach, CoachTournament, Country, + CustomPlusRow, EndpointDiscovery, Game, GameControlState, @@ -7661,6 +7662,118 @@ class HockeyDataService: raise ValueError("Матч не найден") return result + @staticmethod + def _custom_plus_row_payload(row: CustomPlusRow) -> dict[str, Any]: + return { + "id": row.id, + "game_external_id": row.game_external_id, + "side": row.side, + "sort_order": int(row.sort_order or 0), + "text": row.text_value or "", + "status": row.status or "skip", + "updated_by": row.updated_by or "", + "created_at": row.created_at.isoformat() if row.created_at else None, + "updated_at": row.updated_at.isoformat() if row.updated_at else None, + } + + def custom_pluses( + self, + game_external_id: str, + *, + language: str = "ru", + ) -> dict[str, Any]: + settings = self.settings.public() + language = normalise_language(language, settings["ui_language"]) + fallback_language = settings["fallback_language"] + with self.database.session() as session: + game = session.scalar(select(Game).where(Game.external_id == str(game_external_id))) + if game is None: + raise ValueError("Матч не найден") + rows = list(session.scalars( + select(CustomPlusRow) + .where(CustomPlusRow.game_external_id == game.external_id) + .order_by(CustomPlusRow.side, CustomPlusRow.sort_order, CustomPlusRow.id) + )) + game_payload = self._serialize_game( + game, language=language, fallback_language=fallback_language + ) + grouped = {"home": [], "away": []} + for row in rows: + if row.side in grouped: + grouped[row.side].append(self._custom_plus_row_payload(row)) + return { + "game_external_id": str(game_external_id), + "home": grouped["home"], + "away": grouped["away"], + "teams": { + "home": game_payload.get("home") or {}, + "away": game_payload.get("away") or {}, + }, + } + + def save_custom_pluses( + self, + game_external_id: str, + *, + rows: list[dict[str, Any]], + updated_by: str = "", + language: str = "ru", + ) -> dict[str, Any]: + normalised: dict[tuple[str, int], dict[str, Any]] = {} + for index, item in enumerate(rows or []): + side = str(item.get("side") or "").strip().lower() + if side not in {"home", "away"}: + raise ValueError("Неизвестная сторона строки") + try: + sort_order = int(item.get("sort_order") or index + 1) + except (TypeError, ValueError): + sort_order = index + 1 + if sort_order < 1 or sort_order > 999: + raise ValueError("Порядок строки должен быть от 1 до 999") + status = str(item.get("status") or "skip").strip().lower() + if status not in {"skip", "check", "cross"}: + raise ValueError("Неизвестный статус строки") + text_value = str(item.get("text") or "").strip() + if len(text_value) > 4000: + raise ValueError("Текст строки не должен быть длиннее 4000 символов") + normalised[(side, sort_order)] = { + "side": side, + "sort_order": sort_order, + "text_value": text_value, + "status": status, + } + + now = datetime.utcnow() + with self.database.session() as session: + game = session.scalar(select(Game).where(Game.external_id == str(game_external_id))) + if game is None: + raise ValueError("Матч не найден") + existing = list(session.scalars( + select(CustomPlusRow).where(CustomPlusRow.game_external_id == game.external_id) + )) + existing_by_key = {(row.side, int(row.sort_order or 0)): row for row in existing} + incoming_keys = set(normalised) + for row in existing: + key = (row.side, int(row.sort_order or 0)) + if key not in incoming_keys: + session.delete(row) + for key, item in normalised.items(): + row = existing_by_key.get(key) + if row is None: + row = CustomPlusRow( + game_external_id=game.external_id, + side=item["side"], + sort_order=item["sort_order"], + created_at=now, + ) + session.add(row) + row.text_value = item["text_value"] + row.status = item["status"] + row.updated_by = str(updated_by or "")[:128] + row.updated_at = now + + return self.custom_pluses(game_external_id, language=language) + def set_game_period( self, game_external_id: str, diff --git a/ui_builder/static/app.js b/ui_builder/static/app.js index 686522d..6e543e9 100644 --- a/ui_builder/static/app.js +++ b/ui_builder/static/app.js @@ -144,6 +144,15 @@ preparedTitlePanelId: "", preparedTitleMappingSources: [], preparedTitleSnapshotLoading: false, + customPluses: { home: [], away: [] }, + customPlusesTeams: { home: {}, away: {} }, + customPlusesLoading: false, + customPlusesSaving: false, + customPlusesLoadedKey: "", + customPlusesSaveTimer: null, + customPlusesDirty: false, + customPlusesLastSavedAt: "", + customPlusesRevision: 0, modalLocked: false, timerQuickEditorInterval: null, timers: {}, @@ -794,7 +803,7 @@ project_name: "Хоккей — назначения удалений", data_source: "vmix_demo", canvas: { ...state.config.canvas, width: 1440, height: 760, background: "#060d17", show_grid: true, snap_enabled: true }, - tabs: [{ id: "main", label: "Игра" }, { id: "lines", label: "Пятёрки" }, { id: "referees", label: "Судьи" }, { id: "statistics", label: "Статистика" }, { id: "standings", label: "Турнирная таблица" }, { id: "schedule", label: "Расписание" }, { id: "shootout", label: "Буллиты" }, { id: "prepared_titles", label: "Заготовки" }], + tabs: [{ id: "main", label: "Игра" }, { id: "lines", label: "Пятёрки" }, { id: "referees", label: "Судьи" }, { id: "statistics", label: "Статистика" }, { id: "standings", label: "Турнирная таблица" }, { id: "schedule", label: "Расписание" }, { id: "shootout", label: "Буллиты" }, { id: "custom_pluses", label: "Свои плюсы" }, { id: "prepared_titles", label: "Заготовки" }], components: [gameTimer, board, shootout, referees, statistics, schedule, standings], triggers: [] }; @@ -2628,6 +2637,7 @@ function startCustomTooltips() { { id: "standings", label: "Турнирная таблица" }, { id: "schedule", label: "Расписание" }, { id: "shootout", label: "Буллиты" }, + { id: "custom_pluses", label: "Свои плюсы" }, { id: "prepared_titles", label: "Заготовки" }, ]; const existingTabsById = new Map(state.config.tabs.map((tab) => [String(tab?.id || ""), tab])); @@ -10215,6 +10225,258 @@ function renderHockeyRuntimeSideWindows() { } +function hockeyCustomPlusesWorkspaceKey() { + return hockeyTimerSelectedGameId(); +} + +function hockeyCustomPlusBlankRow(side, sortOrder) { + return { + id: `new-${side}-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`, + side, + sort_order: sortOrder, + text: "", + status: "skip", + }; +} + +function hockeyCustomPlusRows(side) { + if (!state.customPluses || typeof state.customPluses !== "object") { + state.customPluses = { home: [], away: [] }; + } + if (!Array.isArray(state.customPluses[side])) state.customPluses[side] = []; + return state.customPluses[side]; +} + +function hockeySeedCustomPlusRows(side, rows) { + const normalised = (Array.isArray(rows) ? rows : []).map((row, index) => ({ + id: row?.id || `loaded-${side}-${index + 1}`, + side, + sort_order: Number(row?.sort_order) || index + 1, + text: String(row?.text ?? row?.text_value ?? ""), + status: ["skip", "check", "cross"].includes(String(row?.status || "").toLowerCase()) + ? String(row.status).toLowerCase() + : "skip", + })).sort((a, b) => Number(a.sort_order) - Number(b.sort_order)); + if (!normalised.length) { + for (let index = 0; index < 5; index += 1) normalised.push(hockeyCustomPlusBlankRow(side, index + 1)); + } + normalised.forEach((row, index) => { row.sort_order = index + 1; }); + state.customPluses[side] = normalised; +} + +function hockeyCustomPlusStatusLabel(status) { + if (status === "check") return "✓ Галочка"; + if (status === "cross") return "✕ Крестик"; + return "— Пропуск"; +} + +function hockeyCustomPlusTeamName(side) { + const fromPayload = state.customPlusesTeams?.[side]?.name || state.customPlusesTeams?.[side]?.short_name; + const fromGame = getByPath(state.data, `hockey.selected_game.${side}.name`) + || getByPath(state.data, `hockey.selected_game.${side}.short_name`); + return String(fromPayload || fromGame || (side === "home" ? "Левая таблица" : "Правая таблица")); +} + +function hockeyCustomPlusesSaveStateText() { + if (state.customPlusesSaving) return "Сохраняю…"; + if (state.customPlusesDirty) return "Есть несохранённые изменения"; + if (state.customPlusesLastSavedAt) return "Сохранено"; + return "Автосохранение включено"; +} + +function hockeyUpdateCustomPlusesSaveIndicator() { + const indicator = el.runtimeStage?.querySelector?.("[data-custom-pluses-save-state]"); + if (!indicator) return; + indicator.textContent = hockeyCustomPlusesSaveStateText(); + indicator.classList.toggle("is-saving", Boolean(state.customPlusesSaving)); + indicator.classList.toggle("is-dirty", Boolean(state.customPlusesDirty)); + indicator.classList.toggle("is-saved", !state.customPlusesSaving && !state.customPlusesDirty && Boolean(state.customPlusesLastSavedAt)); +} + +function hockeyCustomPlusesPayloadRows() { + return ["home", "away"].flatMap((side) => hockeyCustomPlusRows(side).map((row, index) => ({ + side, + sort_order: index + 1, + text: String(row.text || ""), + status: ["skip", "check", "cross"].includes(row.status) ? row.status : "skip", + }))); +} + +async function hockeySaveCustomPluses({ immediate = false } = {}) { + const gameId = hockeyCustomPlusesWorkspaceKey(); + if (!gameId) return false; + if (state.customPlusesSaveTimer) { + clearTimeout(state.customPlusesSaveTimer); + state.customPlusesSaveTimer = null; + } + if (state.customPlusesSaving) { + state.customPlusesSaveTimer = setTimeout(() => { + state.customPlusesSaveTimer = null; + hockeySaveCustomPluses({ immediate: true }).catch(() => {}); + }, 160); + return false; + } + if (!state.customPlusesDirty && !immediate) return true; + const revision = state.customPlusesRevision; + state.customPlusesSaving = true; + hockeyUpdateCustomPlusesSaveIndicator(); + const rows = hockeyCustomPlusesPayloadRows(); + try { + await hockeyGameControlRequest(`/games/${encodeURIComponent(gameId)}/custom-pluses`, { + method: "PUT", + body: JSON.stringify({ rows, language: hockeyGameControlLanguage() }), + }); + if (gameId === hockeyCustomPlusesWorkspaceKey() && state.customPlusesRevision === revision) { + state.customPlusesDirty = false; + state.customPlusesLastSavedAt = new Date().toISOString(); + } + return true; + } catch (error) { + toast(`Свои плюсы: ${error.message}`, true); + return false; + } finally { + state.customPlusesSaving = false; + hockeyUpdateCustomPlusesSaveIndicator(); + } +} + +function hockeyScheduleCustomPlusesSave(delay = 500) { + state.customPlusesRevision += 1; + state.customPlusesDirty = true; + hockeyUpdateCustomPlusesSaveIndicator(); + if (state.customPlusesSaveTimer) clearTimeout(state.customPlusesSaveTimer); + state.customPlusesSaveTimer = setTimeout(() => { + state.customPlusesSaveTimer = null; + hockeySaveCustomPluses({ immediate: true }).catch(() => {}); + }, Math.max(0, Number(delay) || 0)); +} + +async function hockeyLoadCustomPlusesWorkspace({ force = false } = {}) { + const gameId = hockeyCustomPlusesWorkspaceKey(); + if (!gameId) { + state.customPlusesLoadedKey = ""; + state.customPluses = { home: [], away: [] }; + state.customPlusesTeams = { home: {}, away: {} }; + if (state.activeTab === "custom_pluses") renderRuntime(); + return false; + } + if (!force && state.customPlusesLoadedKey === gameId) return true; + if (state.customPlusesLoading) return false; + state.customPlusesLoading = true; + try { + const payload = await hockeyGameControlRequest(`/games/${encodeURIComponent(gameId)}/custom-pluses?language=${encodeURIComponent(hockeyGameControlLanguage())}`); + if (gameId !== hockeyCustomPlusesWorkspaceKey()) return false; + state.customPluses = { home: [], away: [] }; + hockeySeedCustomPlusRows("home", payload?.home); + hockeySeedCustomPlusRows("away", payload?.away); + state.customPlusesTeams = payload?.teams || { home: {}, away: {} }; + state.customPlusesLoadedKey = gameId; + state.customPlusesDirty = false; + state.customPlusesLastSavedAt = ""; + state.customPlusesRevision = 0; + return true; + } catch (error) { + toast(`Свои плюсы: ${error.message}`, true); + return false; + } finally { + state.customPlusesLoading = false; + if (state.activeTab === "custom_pluses") renderRuntime(); + } +} + +function hockeyCustomPlusRowMarkup(side, row, index) { + const status = ["skip", "check", "cross"].includes(row.status) ? row.status : "skip"; + return ` +