diff --git a/README_UPDATE180_RU.txt b/README_UPDATE180_RU.txt new file mode 100644 index 0000000..62af24e --- /dev/null +++ b/README_UPDATE180_RU.txt @@ -0,0 +1,30 @@ +BUILD180 — 2026.10.02.1 +Обновление поверх BUILD179. В архиве только 7 изменённых файлов программы и эта инструкция. + +ЧТО ИЗМЕНИЛОСЬ +1. Настройки → Удаления → «Штраф по умолчанию»: список берётся из правил длительности удалений, настроенных во вкладке «Игра». Ваше правило «2+10» и другие пользовательские правила теперь доступны для выбора и сохраняются. Повторы убираются. Если ранее сохранённое правило удалено из панели, его значение остаётся доступным при редактировании записи. +2. «Свои плюсы»: ОДНА общая ссылка в шапке, над обеими таблицами. Введите адрес и нажмите «Открыть ↗» — ссылка откроется в новой вкладке браузера. Адрес сохраняется автоматически для выбранного матча, общий для RUS и ENG и обеих таблиц. Поле не добавляется в отдельные строки. +3. Ссылка сохраняется в PostgreSQL в отдельном поле состояния матча, без сокращения до лимита динамических строк. Повторное открытие матча восстанавливает ссылку. Очистка поля удаляет сохранённый адрес. Зритель может открыть ссылку; редактирует управляющий оператор. +4. Обновление данных онлайн-матча не пересоздаёт поле во время ввода. Изменение ссылки при незавершённом сохранении сохраняет последнее введённое значение. + +КАК УСТАНОВИТЬ +1. Остановите приложение. +2. Распакуйте файлы в корень существующего проекта с заменой, сохраняя пути: + app.py + hockey_data/models.py + hockey_data/router.py + hockey_data/service.py + hockey_data/static/admin-directories.js + ui_builder/static/app.js + ui_builder/static/styles.css +3. Запустите приложение обычной командой. При запуске существующий механизм обновления схемы автоматически добавит поле hockey_game_control_states.custom_pluses_link_url. Существующие строки, таймеры и настройки сохраняются. Ручной SQL не нужен. +4. Обновите страницу браузера с очисткой кеша (Ctrl+F5). В шапке должна отображаться сборка 2026.10.02.1. +5. Откройте нужный матч → «Свои плюсы», вставьте общую ссылку и дождитесь «Сохранено». + +Настройки проекта, конфигурационные JSON, .env, база данных и пользовательские файлы в архив не включены. Дополнительные зависимости не требуются. Правила удаления создавайте в своей конфигурации панели «Игра»; обновление не добавляет и не заменяет пользовательские правила. + +ПРОВЕРКА +38 автоматических тестов на изолированной тестовой базе: сохранение/чтение ссылки, RUS/ENG, отдельные матчи, совместимость старого клиента, защита прав, добавление нового поля и сохранность таймеров/строк. +Браузерные проверки: одна ссылка в шапке, открытие в новой вкладке, автосохранение, повторная загрузка, быстрые изменения, стабильность ввода, ширина 1600/1000 px, выбор и сохранение «2+10», пользовательские правила и сохранение старого значения. +Повторно прошли браузерные проверки BUILD179: кнопки общего Input, обновление SQL при нажатии и очередь действий с независимым управлением таймерами. +Проверки выполнялись локально с изолированной базой и имитацией API/vMix. Производственная база и ваш vMix не использовались. diff --git a/app.py b/app.py index 9d5427d..c41bcb9 100644 --- a/app.py +++ b/app.py @@ -35,7 +35,7 @@ from khl_site.khl_data_center import APP as khl_site_app, configure_storage, syn from hockey_data.khl_career import KhlCareerService BASE_DIR = Path(__file__).resolve().parent -BUILD_VERSION = "2026.09.30.2" +BUILD_VERSION = "2026.10.02.1" # compatibility: BUILD_VERSION = "2026.09.24.2" # compatibility: BUILD_VERSION = "2026.09.23.8" # compatibility: BUILD_VERSION = "2026.09.23.7" diff --git a/hockey_data/models.py b/hockey_data/models.py index 3af9003..c99fbd5 100644 --- a/hockey_data/models.py +++ b/hockey_data/models.py @@ -955,6 +955,10 @@ class GameControlState(Base): runtime_values_json: Mapped[str] = mapped_column( Text, nullable=False, default="{}" ) + # One shared reference link above both custom-plus tables, scoped to the match. + custom_pluses_link_url: Mapped[str] = mapped_column( + Text, nullable=False, default="" + ) updated_by: Mapped[str] = mapped_column(String(128), nullable=False, default="") created_at: Mapped[datetime] = mapped_column( DateTime, nullable=False, default=datetime.utcnow diff --git a/hockey_data/router.py b/hockey_data/router.py index ad6c8b0..04463dc 100644 --- a/hockey_data/router.py +++ b/hockey_data/router.py @@ -167,6 +167,7 @@ class CustomPlusesPayload(BaseModel): model_config = ConfigDict(extra="ignore") rows: list[CustomPlusRowPayload] = Field(default_factory=list) + link_url: str | None = Field(default=None, max_length=2000) language: str = Field(default="ru", pattern="^(ru|en)$") @@ -1346,6 +1347,7 @@ def create_hockey_router( return service.save_custom_pluses( external_id, rows=[item.model_dump(exclude_unset=True) for item in payload.rows], + link_url=payload.link_url, updated_by=user.id, language=payload.language, ) diff --git a/hockey_data/service.py b/hockey_data/service.py index f882a14..63f857d 100644 --- a/hockey_data/service.py +++ b/hockey_data/service.py @@ -8099,6 +8099,10 @@ class HockeyDataService: .where(CustomPlusRow.game_external_id == game.external_id) .order_by(CustomPlusRow.side, CustomPlusRow.sort_order, CustomPlusRow.id) )) + control = session.scalar(select(GameControlState).where( + GameControlState.game_external_id == game.external_id + )) + link_url = str(control.custom_pluses_link_url or "") if control else "" game_payload = self._serialize_game( game, language=language, fallback_language=fallback_language ) @@ -8108,6 +8112,7 @@ class HockeyDataService: grouped[row.side].append(self._custom_plus_row_payload(row, language=language)) return { "game_external_id": str(game_external_id), + "link_url": link_url, "home": grouped["home"], "away": grouped["away"], "teams": { @@ -8121,9 +8126,14 @@ class HockeyDataService: game_external_id: str, *, rows: list[dict[str, Any]], + link_url: str | None = None, updated_by: str = "", language: str = "ru", ) -> dict[str, Any]: + if link_url is not None: + link_url = str(link_url).strip() + if len(link_url) > 2000: + raise ValueError("Ссылка не должна быть длиннее 2000 символов") normalised: dict[tuple[str, int], dict[str, Any]] = {} for index, item in enumerate(rows or []): side = str(item.get("side") or "").strip().lower() @@ -8186,6 +8196,13 @@ class HockeyDataService: row.updated_by = str(updated_by or "")[:128] row.updated_at = now + # Omitted by older clients: preserve the existing header link. + if link_url is not None: + control = self._get_or_create_game_control(session, game.external_id) + control.custom_pluses_link_url = link_url + control.updated_by = str(updated_by or "")[:128] + control.updated_at = now + return self.custom_pluses(game_external_id, language=language) def set_game_period( diff --git a/hockey_data/static/admin-directories.js b/hockey_data/static/admin-directories.js index 440fbac..17f2fc7 100644 --- a/hockey_data/static/admin-directories.js +++ b/hockey_data/static/admin-directories.js @@ -517,8 +517,24 @@ bindTeams(); } + function penaltyDefaultPresetValues(selectedValue = "") { + const values = []; + const add = (value) => { + const label = String(value || "").trim(); + if (label && !values.includes(label)) values.push(label); + }; + const presets = window.UIBuilderRuntime?.getHockeyPenaltyPresets?.() || []; + presets.forEach((preset) => add(preset.id || preset.label)); + if (!values.length) ["2", "2+2", "4", "5", "5+20", "10"].forEach(add); + // Keep an existing directory value selectable when its rule was removed. + add(selectedValue); + return values; + } + function renderPenalties() { const editing = state.editingPenalty; + const presetValues = penaltyDefaultPresetValues(editing?.default_preset); + const selectedPreset = editing?.default_preset || (presetValues.includes("2") ? "2" : presetValues[0]); const items = state.penalties?.items || []; const rows = items.length ? items.map((item) => ` @@ -555,7 +571,7 @@
diff --git a/ui_builder/static/app.js b/ui_builder/static/app.js index 199a3ed..9f98585 100644 --- a/ui_builder/static/app.js +++ b/ui_builder/static/app.js @@ -172,6 +172,7 @@ preparedTitleSnapshotLoading: false, customPluses: { home: [], away: [] }, customPlusesTeams: { home: {}, away: {} }, + customPlusesLinkUrl: "", customPlusesLoading: false, customPlusesSaving: false, customPlusesLoadedKey: "", @@ -6048,6 +6049,9 @@ function applyExternalDataPatch(patch, { render = true } = {}) { getTimer: (actionId) => { const component = componentByActionId(actionId); const timerState = isTimerComponent(component) ? ensureTimerState(component) : null; return timerState ? clone({ ...timerState, formatted: formatTimerValue(component, timerState) }) : null; }, openTimersEditor: (actionId = "") => openTimerQuickEditor(actionId), getHockeyPenaltyBoard: (actionId) => clone(state.hockeyPenaltyBoards[actionId] || {}), + getHockeyPenaltyPresets: () => clone((state.config.components || []) + .filter((component) => component.type === "hockey_penalty_dashboard") + .flatMap((component) => parseHockeyPenaltyPresets(component.props?.presets))), assignHockeyPenalty: (actionId, player, preset = "2") => { const component = componentByActionId(actionId); return component?.type === "hockey_penalty_dashboard" ? assignHockeyPenalty(component, player, preset) : false; }, controlHockeyPenalty: (actionId, penaltyId, command, value = "") => { const component = componentByActionId(actionId); return component?.type === "hockey_penalty_dashboard" ? controlHockeyPenalty(component, penaltyId, command, value) : false; }, getConfig: () => clone(state.config), @@ -11028,10 +11032,22 @@ function hockeyCustomPlusesPayloadRows() { }))); } +function hockeyCustomPlusesLinkHref(value) { + const raw = String(value || "").trim(); + if (!raw) return ""; + try { + const url = new URL(raw.startsWith("//") ? `https:${raw}` + : /^[a-z][a-z\d+.-]*:/i.test(raw) ? raw : `https://${raw}`); + return ["http:", "https:"].includes(url.protocol) && url.hostname ? url.href : ""; + } catch (_) { + return ""; + } +} + async function hockeySaveCustomPluses({ immediate = false } = {}) { if (!hockeyCanControl()) return false; const gameId = hockeyCustomPlusesWorkspaceKey(); - if (!gameId) return false; + if (!gameId || state.customPlusesLoadedKey !== gameId) return false; if (state.customPlusesSaveTimer) { clearTimeout(state.customPlusesSaveTimer); state.customPlusesSaveTimer = null; @@ -11051,7 +11067,7 @@ async function hockeySaveCustomPluses({ immediate = false } = {}) { try { await hockeyGameControlRequest(`/games/${encodeURIComponent(gameId)}/custom-pluses`, { method: "PUT", - body: JSON.stringify({ rows, language: hockeyGameControlLanguage() }), + body: JSON.stringify({ rows, link_url: state.customPlusesLinkUrl, language: hockeyGameControlLanguage() }), }); if (gameId === hockeyCustomPlusesWorkspaceKey() && state.customPlusesRevision === revision) { state.customPlusesDirty = false; @@ -11085,6 +11101,7 @@ async function hockeyLoadCustomPlusesWorkspace({ force = false } = {}) { state.customPlusesLoadedKey = ""; state.customPluses = { home: [], away: [] }; state.customPlusesTeams = { home: {}, away: {} }; + state.customPlusesLinkUrl = ""; if (state.activeTab === "custom_pluses") renderRuntime(); return false; } @@ -11098,6 +11115,7 @@ async function hockeyLoadCustomPlusesWorkspace({ force = false } = {}) { hockeySeedCustomPlusRows("home", payload?.home); hockeySeedCustomPlusRows("away", payload?.away); state.customPlusesTeams = payload?.teams || { home: {}, away: {} }; + state.customPlusesLinkUrl = String(payload?.link_url || ""); state.customPlusesLoadedKey = gameId; state.customPlusesDirty = false; state.customPlusesLastSavedAt = ""; @@ -11143,6 +11161,13 @@ function renderHockeyCustomPlusesWorkspace() { node.innerHTML = `
MATCH NOTESСвои плюсыМатч ${escapeHtml(gameId)} · каждая строка сохраняется в базе
+ ${escapeHtml(hockeyCustomPlusesSaveStateText())}
@@ -11154,6 +11179,30 @@ function renderHockeyCustomPlusesWorkspace() { `).join("")}
`; + const linkInput = node.querySelector("[data-custom-pluses-link]"); + const linkOpen = node.querySelector("[data-custom-pluses-link-open]"); + const updateLink = () => { + const href = hockeyCustomPlusesLinkHref(state.customPlusesLinkUrl); + if (href) linkOpen.setAttribute("href", href); + else linkOpen.removeAttribute("href"); + linkOpen.classList.toggle("is-disabled", !href); + linkOpen.setAttribute("aria-disabled", href ? "false" : "true"); + linkOpen.tabIndex = href ? 0 : -1; + }; + updateLink(); + linkOpen.addEventListener("click", (event) => { + if (!linkOpen.hasAttribute("href")) event.preventDefault(); + }); + linkInput.addEventListener("input", () => { + if (!hockeyCanControl()) return; + state.customPlusesLinkUrl = linkInput.value; + updateLink(); + hockeyScheduleCustomPlusesSave(); + }); + linkInput.addEventListener("blur", () => { + if (state.customPlusesDirty) hockeyScheduleCustomPlusesSave(120); + }); + const rowRef = (raw) => { const [side, indexRaw] = String(raw || "").split(":"); const index = Number(indexRaw); diff --git a/ui_builder/static/styles.css b/ui_builder/static/styles.css index 9a6963c..010665f 100644 --- a/ui_builder/static/styles.css +++ b/ui_builder/static/styles.css @@ -8064,6 +8064,58 @@ body.hockey-navigation-open .runtime-viewport.has-hockey-pbp { gap: 14px !import color: #8fa1b5; font-size: 12px; } +.hcp-header-link { + min-width: 0; + max-width: 580px; + flex: 1; + display: grid; + gap: 6px; + color: #8fa1b5; + font-size: 12px; +} +.hcp-link-control { + min-width: 0; + display: flex; + align-items: center; + gap: 8px; +} +.hcp-link-control input { + min-width: 0; + width: 100%; + flex: 1; + height: 36px; + padding: 0 11px; + border: 1px solid #30445d; + border-radius: 8px; + background: #0b1523; + color: #edf4fc; + font: inherit; +} +.hcp-link-control input:focus { + outline: 2px solid #4d9cff; + outline-offset: 1px; +} +.hcp-link-open { + flex: 0 0 auto; + display: inline-flex; + align-items: center; + justify-content: center; + height: 36px; + padding: 0 12px; + border: 1px solid #365b81; + border-radius: 8px; + background: #17324e; + color: #d7eaff; + font-weight: 700; + text-decoration: none; + white-space: nowrap; +} +.hcp-link-open:hover { background: #204565; } +.hcp-link-open.is-disabled { + opacity: .45; + cursor: default; + pointer-events: none; +} .hcp-save-state { flex: 0 0 auto; min-width: 172px;