diff --git a/app.py b/app.py
index 16aa766..61f9004 100644
--- a/app.py
+++ b/app.py
@@ -2,6 +2,7 @@ from __future__ import annotations
import os
from pathlib import Path
+from datetime import date
from typing import Any
import httpx
@@ -29,7 +30,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.18.7"
+BUILD_VERSION = "2026.09.18.8"
# compatibility: BUILD_VERSION = "2026.08.26.1"
# compatibility: BUILD_VERSION = "2026.08.25.1"
# compatibility: BUILD_VERSION = "2026.08.24.15"
@@ -379,6 +380,35 @@ app.include_router(
)
+@app.post(
+ "/api/hockey/tournaments/{external_id}/games/online-sync",
+ dependencies=[Depends(hockey_auth.require_user)],
+ tags=["Hockey"],
+)
+async def refresh_tournament_schedule_online(
+ external_id: str,
+ on_date: date = Query(...),
+ language: str = Query("ru", pattern="^(ru|en)$"),
+) -> dict[str, Any]:
+ """Refresh score/status for every game on one schedule date from match JSON.
+
+ RU explicitly reads ``json/{game_id}.json`` and EN explicitly reads
+ ``json_en/{game_id}.json``. No schedule XML is fetched by this button.
+ """
+ if hockey_service.tournament(external_id, language=language) is None:
+ raise HTTPException(status_code=404, detail="Турнир не найден")
+ try:
+ return await hockey_service.refresh_schedule_from_match_json(
+ tournament_external_id=external_id,
+ on_date=on_date,
+ language=language,
+ )
+ except ValueError as error:
+ raise HTTPException(status_code=400, detail=str(error)) from error
+ except Exception as error:
+ raise HTTPException(status_code=502, detail=str(error)) from error
+
+
@app.post(
"/api/hockey/tournaments/{external_id}/standings/force-sync",
dependencies=[Depends(hockey_auth.require_user)],
diff --git a/hockey_data/service.py b/hockey_data/service.py
index 97daa0d..89ccff7 100644
--- a/hockey_data/service.py
+++ b/hockey_data/service.py
@@ -472,6 +472,135 @@ class HockeyDataService:
"errors": errors[:12],
}
+ async def refresh_schedule_from_match_json(
+ self,
+ *,
+ tournament_external_id: str,
+ on_date: date,
+ language: str = "ru",
+ ) -> dict[str, Any]:
+ """Operator-triggered schedule refresh directly from per-game JSON.
+
+ This intentionally does not touch schedule XML. Every game already stored
+ for ``on_date`` in the selected tournament is fetched from the language
+ selected by the operator: RU -> json, EN -> json_en. Only the schedule
+ fields that need to be live (score/status and their canonical flags) are
+ reconciled into PostgreSQL.
+ """
+ tournament_id = str(tournament_external_id or "").strip()
+ if not tournament_id:
+ raise ValueError("Турнир не выбран")
+ lang = "en" if str(language or "ru").lower() == "en" else "ru"
+
+ with self.database.session() as session:
+ game_ids = [
+ str(row.external_id).strip()
+ for row in session.scalars(
+ select(Game)
+ .where(Game.tournament_external_id == tournament_id)
+ .where(Game.game_date == on_date)
+ .order_by(Game.start_time, Game.id)
+ )
+ if str(row.external_id or "").strip()
+ ]
+
+ settings = self.settings.public()
+ if lang == "en":
+ template = str(
+ settings.get("match_json_en_endpoint_template")
+ or "{tournament_id}/json_en/{game_id}.json"
+ ).strip()
+ source_folder = "json_en"
+ else:
+ template = str(
+ settings.get("match_json_endpoint_template")
+ or "{tournament_id}/json/{game_id}.json"
+ ).strip()
+ source_folder = "json"
+
+ semaphore = asyncio.Semaphore(4)
+ errors: list[str] = []
+
+ async def refresh_one(game_id: str) -> dict[str, Any] | None:
+ endpoint = self._resolve_match_resource_endpoint(
+ template,
+ tournament_external_id=tournament_id,
+ game_external_id=game_id,
+ )
+ async with semaphore:
+ response = await self._fetch_cached_resource(
+ endpoint,
+ cache_seconds=0.0,
+ force=True,
+ )
+ # The JSON schemas are the same in json/json_en; for this targeted
+ # update the selected language payload can be parsed as the primary
+ # card because only score/status fields are persisted below.
+ details = parse_match_details_json(
+ response.content,
+ response.content if lang == "en" else None,
+ expected_game_id=game_id,
+ )
+ raw_payload = response.content.decode("utf-8-sig", errors="replace")
+ now = datetime.utcnow()
+ with self.database.session() as session:
+ game = session.scalar(select(Game).where(Game.external_id == game_id))
+ if game is None or str(game.tournament_external_id) != tournament_id:
+ return None
+ before_score = (game.home_score, game.away_score, game.score_raw, game.overtime_type)
+ before_status = (game.status, bool(game.approved))
+ self._apply_details_game_fields(game, details, now=now)
+ game.details_source_endpoint = endpoint
+ game.details_synced_at = now
+ if lang == "en":
+ game.details_raw_payload_en = raw_payload
+ else:
+ game.details_raw_payload_ru = raw_payload
+ after_score = (game.home_score, game.away_score, game.score_raw, game.overtime_type)
+ after_status = (game.status, bool(game.approved))
+ return {
+ "game_id": game_id,
+ "score_changed": before_score != after_score,
+ "status_changed": before_status != after_status,
+ "status": str(game.status or ""),
+ }
+
+ async def guarded(game_id: str) -> dict[str, Any] | None:
+ try:
+ return await refresh_one(game_id)
+ except Exception as error:
+ errors.append(f"{game_id}: {str(error)[:180]}")
+ return None
+
+ results: list[dict[str, Any]] = []
+ # Keep temporary task/result allocations bounded, as in BUILD148.
+ for offset in range(0, len(game_ids), 16):
+ batch = game_ids[offset:offset + 16]
+ batch_results = await asyncio.gather(*(guarded(game_id) for game_id in batch))
+ results.extend(item for item in batch_results if item is not None)
+
+ score_updated = sum(1 for item in results if item.get("score_changed"))
+ status_updated = sum(1 for item in results if item.get("status_changed"))
+ live_count = sum(1 for item in results if item.get("status") == "live")
+ finished_count = sum(1 for item in results if item.get("status") == "finished")
+ scheduled_count = sum(1 for item in results if item.get("status") == "scheduled")
+ return {
+ "ok": True,
+ "tournament_external_id": tournament_id,
+ "date": on_date.isoformat(),
+ "language": lang,
+ "source_folder": source_folder,
+ "checked": len(game_ids),
+ "updated": sum(1 for item in results if item.get("score_changed") or item.get("status_changed")),
+ "score_updated": score_updated,
+ "status_updated": status_updated,
+ "scheduled": scheduled_count,
+ "live": live_count,
+ "finished": finished_count,
+ "failed": len(errors),
+ "errors": errors[:20],
+ }
+
async def refresh_schedule_catalog(self, *, deep: bool = False) -> dict[str, Any]:
"""Refresh schedules, standings and authoritative per-game scores/statuses."""
status = self.settings.status()
diff --git a/hockey_data/static/tournament-menu.js b/hockey_data/static/tournament-menu.js
index d5423f2..02a6dd0 100644
--- a/hockey_data/static/tournament-menu.js
+++ b/hockey_data/static/tournament-menu.js
@@ -45,6 +45,7 @@
settingsModal: null,
gamesAutoSyncAttempted: new Set(),
scheduleSyncBusy: false,
+ scheduleOnlineBusy: false,
gameOpenBusy: false,
gameOpenGeneration: 0,
gamePollTimer: null,
@@ -113,6 +114,9 @@
noGames: "На выбранную дату матчей нет",
noGamesLoaded: "Календарь матчей ещё не загружен",
updateGames: "Обновить матчи",
+ onlineRefresh: "ОНЛАЙН",
+ onlineRefreshing: "ОБНОВЛЯЕМ…",
+ onlineUpdated: "Расписание обновлено из JSON матчей",
discovering: "Ищем XML матчей…",
loadingGames: "Загружаем календарь…",
gamesLoaded: "Матчи загружены",
@@ -221,6 +225,9 @@
noGames: "No games on the selected date",
noGamesLoaded: "The game calendar has not been loaded yet",
updateGames: "Update games",
+ onlineRefresh: "ONLINE",
+ onlineRefreshing: "UPDATING…",
+ onlineUpdated: "Schedule updated from match JSON",
discovering: "Discovering games XML…",
loadingGames: "Loading schedule…",
gamesLoaded: "Games loaded",
@@ -1661,6 +1668,42 @@ function gameCard(game) {
`;
}
+ async function refreshScheduleOnline({ onDate = state.gameDate, language = state.language } = {}) {
+ if (!state.selectedId) {
+ throw new Error(state.language === "en" ? "Tournament is not selected" : "Турнир не выбран");
+ }
+ if (state.scheduleOnlineBusy) return null;
+ state.scheduleOnlineBusy = true;
+ const selectedDate = String(onDate || state.gameDate || localDateIso());
+ const selectedLanguage = language === "en" ? "en" : "ru";
+ try {
+ const result = await request(
+ `/api/hockey/tournaments/${encodeURIComponent(state.selectedId)}/games/online-sync`
+ + `?on_date=${encodeURIComponent(selectedDate)}`
+ + `&language=${encodeURIComponent(selectedLanguage)}`,
+ { method: "POST", timeoutMs: 45000 }
+ );
+
+ // Re-read PostgreSQL only after every match JSON has been processed.
+ state.games = await request(gamesUrl());
+ applyGamesData();
+ renderGames();
+ await loadTeamSchedule({ force: true });
+
+ const changed = [];
+ if (Number(result.score_updated || 0)) changed.push(`${state.language === "en" ? "score" : "счёт"}: ${Number(result.score_updated || 0)}`);
+ if (Number(result.status_updated || 0)) changed.push(`${state.language === "en" ? "status" : "статус"}: ${Number(result.status_updated || 0)}`);
+ const changedLabel = changed.length ? ` · ${changed.join(", ")}` : "";
+ notify(`${t("onlineUpdated")} · ${Number(result.checked || 0) - Number(result.failed || 0)}/${Number(result.checked || 0)}${changedLabel}`);
+ return result;
+ } catch (error) {
+ notify(error.message, true);
+ throw error;
+ } finally {
+ state.scheduleOnlineBusy = false;
+ }
+ }
+
async function syncGames(forceDiscovery, { silentSuccess = false } = {}) {
if (!state.selectedId || state.scheduleSyncBusy) return;
state.scheduleSyncBusy = true;
@@ -2710,6 +2753,7 @@ document.addEventListener("visibilitychange", () => {
selectTournament: openTournament,
selectGame: openGame,
reloadGames: () => loadGames({ autoSync: false }),
+ refreshScheduleOnline,
refreshStandings: refreshTournamentStandings,
};
diff --git a/ui_builder/static/app.js b/ui_builder/static/app.js
index fd3a04c..6bf0f08 100644
--- a/ui_builder/static/app.js
+++ b/ui_builder/static/app.js
@@ -1,3 +1,4 @@
+// BUILD150: Schedule ONLINE button refreshes score/status from language-specific per-game JSON.
// BUILD146: schedule tab remains permanent; score/status refresh is driven by tournament-menu.js.
(() => {
"use strict";
@@ -13251,9 +13252,28 @@ function renderHockeyPenaltyDashboard(node, component, runtime) {
` : "";
node.innerHTML = `