Load all 12 groups' schedule (72 matches) + Naver-style schedule UI

Backend
- teams_data.py: 48-team data (ko/short/en), TLA→FIFA code remap
- config: schedule_all_groups, featured_group("A") — only featured group is votable/AI-predicted
- schedule_fetch: fetch all GROUP_STAGE matches from football-data, KST serialize
- schedule_sync: ingest all groups, unordered-pair match to avoid Group A dup, derive votable from group
- worker: AI generation limited to featured group; settle still covers all
- domain/predictions: is_votable() + MatchOut.votable; reject non-votable submits with 403 MATCH_NOT_VOTABLE

Frontend
- types: Match.votable
- ScheduleBoard: Naver-style date/group tabs + chips; votable(A) cards link to detail with AI split + 참여수, others display-only

Verified: 72 matches (12×6), Group A not duplicated, votable A=6/others=66; A submit 200, B submit 403

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
HyeongBaeYangandClaude Opus 4.8 committed 2026-06-12 14:56:24 +09:00
1 parent c9244bc42d
commit deb1332440
10 files changed
+366 -99

No files matched your search

+57 -1
View File
@@ -18,6 +18,7 @@ from datetime import datetime, timedelta, timezone
from ..config import settings
from ..schedule_data import code_for
from ..teams_data import code_for_tla
log = logging.getLogger("triplepick.schedule")
@@ -95,8 +96,63 @@ async def _fetch_football_data() -> list[dict]:
return out
async def _fetch_all_groups_football_data() -> list[dict]:
"""football-data 에서 전체 조별리그(12개조 72경기) 수집.
반환: [{teamA, teamB, group('A'..'L'), kickoffKst, venue}] (tla→코드)
"""
if not settings.football_data_token:
log.warning("schedule(all): football-data 토큰 미설정 — 수집 생략")
return []
import httpx
url = (
f"https://api.football-data.org/v4/competitions/"
f"{settings.football_data_competition}/matches"
)
async with httpx.AsyncClient(timeout=20) as c:
r = await c.get(url, headers={"X-Auth-Token": settings.football_data_token})
r.raise_for_status()
data = r.json()
out: list[dict] = []
for m in data.get("matches", []):
if m.get("stage") != "GROUP_STAGE":
continue
g = (m.get("group") or "").replace("GROUP_", "") # 'A'..'L'
ht = (m.get("homeTeam") or {}).get("tla")
at = (m.get("awayTeam") or {}).get("tla")
if not ht or not at:
continue
utc = m.get("utcDate")
if not utc:
continue
kickoff = (
datetime.fromisoformat(utc.replace("Z", "+00:00")).astimezone(KST).isoformat()
)
out.append(
{
"teamA": code_for_tla(ht),
"teamB": code_for_tla(at),
"group": g,
"kickoffKst": kickoff,
"venue": m.get("venue") or "",
}
)
return out
async def fetch_schedule() -> list[dict]:
"""소스에 따라 일정 수집. 실패 시 빈 리스트(기존 일정 유지)."""
"""일정 수집. 전체 조 모드면 football-data 전 조별리그, 아니면 단일 조."""
if settings.schedule_all_groups:
try:
records = await _fetch_all_groups_football_data()
log.info("schedule: 전체 조별리그 %d경기 수집", len(records))
if records:
return records
except Exception as e: # noqa: BLE001
log.error("schedule(all) 실패: %s — 단일 조 폴백", e)
src = settings.schedule_source.lower()
try:
if src == "openfootball":
+34 -26
View File
@@ -1,21 +1,25 @@
"""수집한 일정을 DB에 반영 — 워커(스케줄링 서버)가 매일 호출.
매칭 키 = (teamA_code, teamB_code) 순서쌍 (그룹 라운드로빈에서 유일).
- 기존 경기: 킥오프/venue/투표시간(opens·lock) 갱신. 결과·예측·crowd·라운드/후킹은 보존.
- 신규 경기: matchId 생성 + crowd 초기화하여 삽입(예측은 워커 AI 생성이 채움).
전체 조별리그 모드: 12개조 72경기를 적재. 결과/스코어는 전 경기 표시.
- 기존 경기: (팀쌍, 순서 무관) 매칭 → 킥오프/venue/투표시간만 갱신. 결과·예측·crowd·팀명·라운드 보존.
- 신규 경기: teams_data(48개국)로 팀 구성 + matchId 생성 + crowd 초기화하여 삽입.
종료(result) 경기는 시각 변경하지 않음.
"""
from __future__ import annotations
import logging
from datetime import timedelta, timezone
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from ..config import settings
from ..models import CrowdStats, Match
from ..schedule_data import TEAMS, lock_at, opens_at, parse_kickoff
from ..schedule_data import lock_at, opens_at, parse_kickoff
from ..teams_data import team_info
log = logging.getLogger("triplepick.schedule")
KST = timezone(timedelta(hours=9))
async def sync_schedule(db: AsyncSession, records: list[dict]) -> dict:
@@ -23,11 +27,16 @@ async def sync_schedule(db: AsyncSession, records: list[dict]) -> dict:
return {"updated": 0, "inserted": 0, "skipped": 0}
existing = (await db.execute(select(Match))).scalars().all()
by_pair = {(m.team_a_code, m.team_b_code): m for m in existing}
# 순서 무관 매칭 — 소스의 홈/원정 순서가 우리와 달라도 기존 경기를 찾음(중복 방지)
by_pair: dict[tuple, Match] = {}
for m in existing:
by_pair[(m.team_a_code, m.team_b_code)] = m
by_pair[(m.team_b_code, m.team_a_code)] = m
updated = inserted = skipped = 0
for rec in records:
a, b = rec["teamA"], rec["teamB"]
group = rec.get("group", settings.featured_group)
kickoff = parse_kickoff(rec["kickoffKst"])
m = by_pair.get((a, b))
if m is not None:
@@ -41,29 +50,28 @@ async def sync_schedule(db: AsyncSession, records: list[dict]) -> dict:
m.venue = rec["venue"]
updated += 1
else:
ta, tb = TEAMS.get(a), TEAMS.get(b)
if not ta or not tb:
skipped += 1
continue
match_id = f"A_{a}_{b}_{kickoff.astimezone().strftime('%Y%m%d')}"
db.add(
Match(
match_id=match_id,
round_label="Match",
group="A",
team_a_name=ta["name"], team_a_short=ta["shortName"],
team_a_code=ta["code"], team_a_flag=ta["flag"],
team_b_name=tb["name"], team_b_short=tb["shortName"],
team_b_code=tb["code"], team_b_flag=tb["flag"],
venue=rec.get("venue", ""),
hook_text=f"{ta['shortName']} vs {tb['shortName']}, AI의 예측은",
kickoff_at=kickoff,
opens_at=opens_at(kickoff),
lock_at=lock_at(kickoff),
status="scheduled",
)
ta, tb = team_info(a), team_info(b)
kst_date = kickoff.astimezone(KST).strftime("%Y%m%d")
match_id = f"{group}_{a}_{b}_{kst_date}"
new = Match(
match_id=match_id,
round_label="",
group=group,
team_a_name=ta["name"], team_a_short=ta["shortName"],
team_a_code=ta["code"], team_a_flag=ta["flag"],
team_b_name=tb["name"], team_b_short=tb["shortName"],
team_b_code=tb["code"], team_b_flag=tb["flag"],
venue=rec.get("venue", ""),
hook_text=f"{ta['shortName']} vs {tb['shortName']}",
kickoff_at=kickoff,
opens_at=opens_at(kickoff),
lock_at=lock_at(kickoff),
status="scheduled",
)
db.add(new)
db.add(CrowdStats(match_id=match_id, total=0, team_a_win=0, draw=0, team_b_win=0))
by_pair[(a, b)] = new
by_pair[(b, a)] = new
inserted += 1
await db.commit()