в базу записывается статистика игроков по матчу

This commit is contained in:
2026-09-29 10:14:25 +03:00
parent b5f36bb6c1
commit 203ce44b6d
4 changed files with 61743 additions and 45086 deletions

File diff suppressed because it is too large Load Diff

View File

@@ -22,6 +22,7 @@ from .models import (
Game,
GameControlState,
GameTeamStatistic,
GamePlayerStatistic,
GameOfficial,
GameRoster,
OperatorSession,
@@ -213,6 +214,7 @@ class HockeyDatabase:
TeamSeasonStatistic,
PlayerSeasonStatistic,
GameTeamStatistic,
GamePlayerStatistic,
UserPreference,
VmixDevice,
VmixAssignment,

View File

@@ -706,6 +706,69 @@ class GameTeamStatistic(Base):
)
class GamePlayerStatistic(Base):
"""Normalized per-player statistics for one game."""
__tablename__ = "hockey_game_player_statistics"
id: Mapped[int] = mapped_column(Integer, primary_key=True)
game_external_id: Mapped[str] = mapped_column(
String(96), ForeignKey("hockey_games.external_id", ondelete="CASCADE"), nullable=False
)
tournament_external_id: Mapped[str] = mapped_column(String(64), nullable=False)
team_external_id: Mapped[str] = mapped_column(String(96), nullable=False, default="")
player_id: Mapped[Optional[int]] = mapped_column(
Integer, ForeignKey("hockey_players.id", ondelete="SET NULL"), nullable=True
)
player_external_id: Mapped[str] = mapped_column(String(64), nullable=False)
jersey_number: Mapped[str] = mapped_column(String(16), nullable=False, default="")
side: Mapped[str] = mapped_column(String(16), nullable=False, default="")
role: Mapped[str] = mapped_column(String(32), nullable=False, default="")
played: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False)
goals: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
assists: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
points: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
shots: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
hits: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
blocked_shots: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
takeaways: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
giveaways: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
interceptions: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
penalty_minutes: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
penalties: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
faceoffs: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
faceoffs_won: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
faceoff_pct: Mapped[float] = mapped_column(Float, nullable=False, default=0.0)
time_on_ice: Mapped[str] = mapped_column(String(64), nullable=False, default="")
even_strength_time: Mapped[str] = mapped_column(String(64), nullable=False, default="")
power_play_time: Mapped[str] = mapped_column(String(64), nullable=False, default="")
short_handed_time: Mapped[str] = mapped_column(String(64), nullable=False, default="")
empty_net_time: Mapped[str] = mapped_column(String(64), nullable=False, default="")
shifts: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
shots_against: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
goals_against: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
saves: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
save_pct: Mapped[float] = mapped_column(Float, nullable=False, default=0.0)
raw_payload: Mapped[str] = mapped_column(Text, nullable=False, default="")
synced_at: Mapped[datetime] = mapped_column(DateTime, nullable=False, default=datetime.utcnow)
__table_args__ = (
UniqueConstraint(
"game_external_id",
"team_external_id",
"player_external_id",
name="uq_hockey_game_player_stat",
),
Index("ix_hockey_game_player_stats_game", "game_external_id"),
Index("ix_hockey_game_player_stats_tournament", "tournament_external_id"),
Index("ix_hockey_game_player_stats_player", "player_external_id"),
Index("ix_hockey_game_player_stats_player_id", "player_id"),
)
class GameRoster(Base):
__tablename__ = "hockey_game_rosters"

View File

@@ -63,6 +63,7 @@ from .models import (
GameControlState,
GameOfficial,
GameTeamStatistic,
GamePlayerStatistic,
GameRoster,
OperatorSession,
PenaltyType,
@@ -3762,6 +3763,112 @@ class HockeyDataService:
created += 1
return created
def _store_game_player_statistics(
self,
session: Session,
*,
game: Game,
rosters: list[Any],
now: datetime,
) -> int:
"""Replace normalized per-player statistics for one game.
Match roster payloads contain the player stat row for the current game.
Store the common skater/goalkeeper fields as real columns and keep the
original bilingual payload alongside them so newly introduced Stat2TV
fields are not lost.
"""
session.execute(
delete(GamePlayerStatistic).where(
GamePlayerStatistic.game_external_id == game.external_id
)
)
roster_player_external_ids = {
str(getattr(roster, "player_external_id", "") or "")
for roster in rosters
if str(getattr(roster, "player_external_id", "") or "")
}
# Profiles may have been inserted earlier in the same match refresh.
# Flush once so their database IDs are available for direct SQL joins.
session.flush()
player_db_ids = {
str(external_id): int(player_id)
for player_id, external_id in session.execute(
select(Player.id, Player.external_id).where(
Player.external_id.in_(roster_player_external_ids)
)
).all()
} if roster_player_external_ids else {}
created = 0
for roster in rosters:
raw_payload = str(getattr(roster, "raw_payload", "") or "")
raw = self._details_json_object(raw_payload)
raw_ru = raw.get("ru") if isinstance(raw.get("ru"), dict) else {}
raw_en = raw.get("en") if isinstance(raw.get("en"), dict) else {}
source: dict[str, Any] = dict(raw_en)
source.update(raw_ru)
if not source and raw:
source = raw
role = str(getattr(roster, "role", "") or "")
values = self._normalise_player_statistics(source, role=role)
side = str(getattr(roster, "side", "") or "")
team_id = str(getattr(roster, "team_external_id", "") or "")
if not team_id:
team_id = (
game.home_team_external_id
if side == "home"
else game.away_team_external_id
)
player_external_id = str(getattr(roster, "player_external_id", "") or "")
row = GamePlayerStatistic(
game_external_id=game.external_id,
tournament_external_id=game.tournament_external_id,
team_external_id=team_id,
player_id=player_db_ids.get(player_external_id),
player_external_id=player_external_id,
jersey_number=str(
getattr(roster, "number", "")
or source.get("jn")
or source.get("number")
or ""
),
side=side,
role=role,
played=bool(values.get("played")),
goals=self._stat_int(values.get("goals")),
assists=self._stat_int(values.get("assists")),
points=self._stat_int(values.get("points")),
shots=self._stat_int(values.get("shots")),
hits=self._stat_int(values.get("hits")),
blocked_shots=self._stat_int(values.get("blocked_shots")),
takeaways=self._stat_int(values.get("takeaways")),
giveaways=self._stat_int(source.get("gva")),
interceptions=self._stat_int(source.get("p_intc")),
penalty_minutes=self._stat_int(values.get("penalty_minutes")),
penalties=self._stat_int(values.get("penalties")),
faceoffs=self._stat_int(values.get("faceoffs")),
faceoffs_won=self._stat_int(values.get("faceoffs_won")),
faceoff_pct=self._stat_float(values.get("faceoff_pct")),
time_on_ice=str(values.get("time_on_ice") or ""),
even_strength_time=str(values.get("even_strength_time") or ""),
power_play_time=str(values.get("power_play_time") or ""),
short_handed_time=str(values.get("short_handed_time") or ""),
empty_net_time=str(values.get("empty_net_time") or ""),
shifts=self._stat_int(values.get("shifts")),
shots_against=self._stat_int(values.get("shots_against")),
goals_against=self._stat_int(values.get("goals_against")),
saves=self._stat_int(values.get("saves")),
save_pct=self._stat_float(values.get("save_pct")),
raw_payload=raw_payload,
synced_at=now,
)
session.add(row)
created += 1
return created
def _store_normalized_standings(
self,
session: Session,
@@ -4122,7 +4229,7 @@ class HockeyDataService:
def _backfill_normalized_statistics(self, session: Session) -> dict[str, int]:
now = datetime.utcnow()
result = {"game_team_statistics": 0, "player_season_statistics": 0, "standing_rows": 0, "statistic_rows": 0, "team_season_statistics": 0}
result = {"game_team_statistics": 0, "game_player_statistics": 0, "player_season_statistics": 0, "standing_rows": 0, "statistic_rows": 0, "team_season_statistics": 0}
if (session.scalar(select(func.count(GameTeamStatistic.id))) or 0) == 0:
games = list(session.scalars(select(Game).where(Game.details_raw_payload_ru != "")))
@@ -4132,6 +4239,25 @@ class HockeyDataService:
periods = raw.get("teams_periods") if isinstance(raw.get("teams_periods"), dict) else {}
result["game_team_statistics"] += self._store_game_team_statistics(session, game=game, raw_teams=teams, raw_periods=periods, now=now)
if (session.scalar(select(func.count(GamePlayerStatistic.id))) or 0) == 0:
roster_rows = list(session.scalars(select(GameRoster)))
rosters_by_game: dict[str, list[GameRoster]] = {}
for roster in roster_rows:
rosters_by_game.setdefault(str(roster.game_external_id), []).append(roster)
if rosters_by_game:
games = list(
session.scalars(
select(Game).where(Game.external_id.in_(list(rosters_by_game)))
)
)
for game in games:
result["game_player_statistics"] += self._store_game_player_statistics(
session,
game=game,
rosters=rosters_by_game.get(str(game.external_id), []),
now=now,
)
if (session.scalar(select(func.count(PlayerSeasonStatistic.id))) or 0) == 0:
memberships = session.execute(
select(Player, PlayerTournament).join(PlayerTournament, PlayerTournament.player_id == Player.id)
@@ -4178,6 +4304,7 @@ class HockeyDataService:
models = {
"schedule_games": Game,
"game_team_statistics": GameTeamStatistic,
"game_player_statistics": GamePlayerStatistic,
"player_season_statistics": PlayerSeasonStatistic,
"team_season_statistics": TeamSeasonStatistic,
"standings_rows": TournamentStandingRow,
@@ -4446,6 +4573,10 @@ class HockeyDataService:
if key not in seen_rosters:
session.delete(roster)
self._store_game_player_statistics(
session, game=game, rosters=list(details.rosters), now=now
)
existing_officials = list(
session.scalars(
select(GameOfficial).where(