Refactor: Next.js+Firebase → React(Vite) + FastAPI + PostgreSQL

- 백엔드: FastAPI + SQLAlchemy(async) + PostgreSQL, 별도 워커(APScheduler)
- 프론트: React 19 + Vite + TS + Tailwind v4 (기존 UI 이식, API 연동)
- docker-compose: db · api · worker · frontend 일괄 실행
- 경기 일정: openfootball 매일 09:00 크롤링 → DB upsert (신규 경기 자동 삽입+예측 생성)
- AI 예측: GPT·Claude·Gemini 실 API 매일 생성 → DB 저장 → 조회 (목데이터 제거)
- 투표창: 오픈 킥오프 D-2 / 마감 킥오프 1시간 전, lockAt 백엔드 전달→프론트 카운트다운
- 채점/리더보드: docs/SCORING.md 기준 누적 포인트
- crowd: 0 시작, 실제 제출로만 증분
- 구 Next.js/Firebase 파일 제거, README/AGENTS 갱신

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
HyeongBaeYangandClaude Opus 4.8 committed 2026-06-10 13:04:35 +09:00
1 parent 35414a8d47
commit 6ffe0dfca3
95 files changed
+5266 -8856

No files matched your search

+112
View File
@@ -0,0 +1,112 @@
"""경기 일정 외부 수집 — 매일 워커가 호출(크롤링).
소스(SCHEDULE_SOURCE):
openfootball raw GitHub JSON (키 불필요, 기본). 2026 Group A = 본 서비스 6경기.
football-data football-data.org /v4/competitions/WC/matches (FOOTBALL_DATA_TOKEN 필요)
fallback 외부 호출 없이 빈 결과 → 기존(시드) 일정 유지
반환 표준 레코드:
{teamA: code, teamB: code, kickoffKst: ISO(+09:00), venue: str}
team 코드로 매핑되지 않는 경기(다른 그룹/팀)는 제외.
시각은 절대 시점(UTC)으로 환산 후 KST(+09:00) 고정 오프셋으로 표기.
"""
from __future__ import annotations
import logging
import re
from datetime import datetime, timedelta, timezone
from ..config import settings
from ..schedule_data import code_for
log = logging.getLogger("triplepick.schedule")
KST = timezone(timedelta(hours=9))
# "13:00 UTC-6" / "20:00 UTC+2" 형태 파싱
_TIME_RE = re.compile(r"(\d{1,2}):(\d{2})\s*UTC\s*([+-]\d{1,2})")
def _to_kst_iso(date_str: str, time_str: str) -> str | None:
m = _TIME_RE.search(time_str or "")
if not m:
return None
hh, mm, off = int(m.group(1)), int(m.group(2)), int(m.group(3))
try:
y, mo, d = (int(x) for x in date_str.split("-"))
except ValueError:
return None
local = datetime(y, mo, d, hh, mm, tzinfo=timezone(timedelta(hours=off)))
return local.astimezone(KST).isoformat()
async def _fetch_openfootball() -> list[dict]:
import httpx
async with httpx.AsyncClient(timeout=20) as c:
r = await c.get(settings.schedule_url)
r.raise_for_status()
data = r.json()
out: list[dict] = []
for m in data.get("matches", []):
if (m.get("group") or "").strip() != settings.schedule_group:
continue
a, b = code_for(m.get("team1", "")), code_for(m.get("team2", ""))
if not a or not b:
continue
kickoff = _to_kst_iso(m.get("date", ""), m.get("time", ""))
if not kickoff:
continue
out.append({"teamA": a, "teamB": b, "kickoffKst": kickoff, "venue": m.get("ground", "")})
return out
async def _fetch_football_data() -> list[dict]:
if not settings.football_data_token:
log.warning("schedule: 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("group") or "").replace("GROUP_", "Group ") != settings.schedule_group:
continue
a = code_for((m.get("homeTeam") or {}).get("name", "") or "")
b = code_for((m.get("awayTeam") or {}).get("name", "") or "")
if not a or not b:
continue
utc = m.get("utcDate") # ISO Z
if not utc:
continue
kickoff = (
datetime.fromisoformat(utc.replace("Z", "+00:00")).astimezone(KST).isoformat()
)
venue = m.get("venue") or ""
out.append({"teamA": a, "teamB": b, "kickoffKst": kickoff, "venue": venue})
return out
async def fetch_schedule() -> list[dict]:
"""소스에 따라 일정 수집. 실패 시 빈 리스트(기존 일정 유지)."""
src = settings.schedule_source.lower()
try:
if src == "openfootball":
records = await _fetch_openfootball()
elif src == "football-data":
records = await _fetch_football_data()
else:
return []
log.info("schedule: %s 에서 %d경기 수집", src, len(records))
return records
except Exception as e: # noqa: BLE001
log.error("schedule fetch 실패(%s): %s — 기존 일정 유지", src, e)
return []