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

View File
Whitespace-only changes.
+72
View File
@@ -0,0 +1,72 @@
"""관리자 API — Bearer 토큰 인증. 경기/AI예측 upsert + 결과 입력(채점)."""
from __future__ import annotations
from fastapi import APIRouter, Depends, Header, HTTPException
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from ..config import settings
from ..database import get_db
from ..domain import now_utc
from ..models import AIPrediction, Match
from ..schemas import AdminAIPredictionIn, AdminSetResultIn, GenericOk
from ..services.grading import apply_result
router = APIRouter(prefix="/api/admin", tags=["admin"])
def require_admin(authorization: str = Header(default="")) -> None:
token = authorization.removeprefix("Bearer ").strip()
if not token or token != settings.admin_api_token:
raise HTTPException(status_code=401, detail="UNAUTHORIZED")
@router.post("/ai-predictions", response_model=GenericOk, dependencies=[Depends(require_admin)])
async def upsert_ai_prediction(
body: AdminAIPredictionIn, db: AsyncSession = Depends(get_db)
) -> GenericOk:
match = (
await db.execute(select(Match).where(Match.match_id == body.matchId))
).scalars().first()
if not match:
raise HTTPException(status_code=404, detail="MATCH_NOT_FOUND")
pred = (
await db.execute(
select(AIPrediction).where(
AIPrediction.match_id == body.matchId, AIPrediction.model == body.model
)
)
).scalars().first()
if pred is None:
pred = AIPrediction(match_id=body.matchId, model=body.model)
db.add(pred)
pred.outcome = body.outcome
pred.score_a = body.scoreA
pred.score_b = body.scoreB
pred.confidence_pct = body.confidencePct
pred.reason_ko = body.reasonKo
pred.reason_en = body.reasonEn
pred.generated_at = now_utc()
pred.source = "admin"
await db.commit()
return GenericOk(ok=True, detail="upserted")
@router.post("/result", response_model=GenericOk, dependencies=[Depends(require_admin)])
async def set_result(
body: AdminSetResultIn, db: AsyncSession = Depends(get_db)
) -> GenericOk:
match = (
await db.execute(select(Match).where(Match.match_id == body.matchId))
).scalars().first()
if not match:
raise HTTPException(status_code=404, detail="MATCH_NOT_FOUND")
graded = await apply_result(db, match, body.scoreA, body.scoreB)
# 결과 메일은 워커가 result_email_delay_minutes 경과 후 발송(@finished_at 기준).
return GenericOk(
ok=True,
detail="result set & graded",
extra={"gradedPicks": graded, "emailsSentBy": "worker"},
)
+80
View File
@@ -0,0 +1,80 @@
"""리더보드 API — 누적 포인트 1위 (docs/SCORING.md §3 랭킹 규칙).
1차 정렬: 누적 포인트. 동점: 정확스코어 횟수 → 적중률 → 참여수 → 최초도달.
주최측/임직원 배제(P1). 이메일은 마스킹하여 노출.
"""
from __future__ import annotations
from collections import defaultdict
from fastapi import APIRouter, Depends, Query
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from ..database import get_db
from ..models import UserPrediction
from ..scoring import SCORE, is_excluded
from ..schemas import LeaderboardOut, StandingOut
router = APIRouter(prefix="/api/leaderboard", tags=["leaderboard"])
def _mask(email: str) -> str:
name, _, domain = email.partition("@")
head = name[:2] if len(name) >= 2 else name
return f"{head}{'*' * max(1, len(name) - 2)}@{domain}"
@router.get("", response_model=LeaderboardOut)
async def leaderboard(
limit: int = Query(50, ge=1, le=200), db: AsyncSession = Depends(get_db)
) -> LeaderboardOut:
rows = (
await db.execute(
select(UserPrediction).where(
UserPrediction.points.is_not(None),
UserPrediction.email.is_not(None),
)
)
).scalars().all()
agg: dict[str, dict] = defaultdict(
lambda: {"points": 0, "exact": 0, "played": 0, "first": None}
)
matches: set[str] = set()
for r in rows:
email = (r.email or "").strip().lower()
if not email or is_excluded(email):
continue
matches.add(r.match_id)
a = agg[email]
a["points"] += r.points or 0
a["played"] += 1
if (r.points or 0) >= SCORE["EXACT"]:
a["exact"] += 1
ts = r.scored_at or r.created_at
if a["first"] is None or (ts and ts < a["first"]):
a["first"] = ts
ranked = sorted(
agg.items(),
key=lambda kv: (
-kv[1]["points"],
-kv[1]["exact"],
-(kv[1]["points"] / kv[1]["played"] if kv[1]["played"] else 0),
-kv[1]["played"],
kv[1]["first"].timestamp() if kv[1]["first"] else 0,
),
)
standings = [
StandingOut(
rank=i + 1,
emailMasked=_mask(email),
totalPoints=v["points"],
exactCount=v["exact"],
matchesPlayed=v["played"],
)
for i, (email, v) in enumerate(ranked[:limit])
]
return LeaderboardOut(standings=standings, scoredMatches=len(matches))
+47
View File
@@ -0,0 +1,47 @@
"""공개 읽기 API — 경기 목록 / 경기 상세 (AI예측 + crowd 포함)."""
from __future__ import annotations
from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.orm import selectinload
from ..database import get_db
from ..domain import match_out
from ..models import Match
from ..schemas import MatchOut
router = APIRouter(prefix="/api/matches", tags=["matches"])
@router.get("", response_model=list[MatchOut])
async def list_matches(
lang: str = Query("ko"),
db: AsyncSession = Depends(get_db),
) -> list[MatchOut]:
rows = (
await db.execute(
select(Match)
.options(selectinload(Match.predictions), selectinload(Match.crowd))
.order_by(Match.kickoff_at)
)
).scalars().all()
return [match_out(m, lang) for m in rows]
@router.get("/{match_id}", response_model=MatchOut)
async def get_match(
match_id: str,
lang: str = Query("ko"),
db: AsyncSession = Depends(get_db),
) -> MatchOut:
m = (
await db.execute(
select(Match)
.where(Match.match_id == match_id)
.options(selectinload(Match.predictions), selectinload(Match.crowd))
)
).scalars().first()
if not m:
raise HTTPException(status_code=404, detail="MATCH_NOT_FOUND")
return match_out(m, lang)
+116
View File
@@ -0,0 +1,116 @@
"""픽 제출 API — 검증 · 중복방지(1회 수정) · crowd 원자적 증분 · 매칭 모델 계산."""
from __future__ import annotations
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy import select, update
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.orm import selectinload
from ..database import get_db
from ..domain import crowd_out, is_open_for_voting
from ..models import AIPrediction, CrowdStats, Match, UserPrediction
from ..scoring import outcome_of
from ..schemas import SubmitPredictionIn, SubmitPredictionOut
router = APIRouter(prefix="/api/predictions", tags=["predictions"])
_COL = {"TEAM_A_WIN": "team_a_win", "DRAW": "draw", "TEAM_B_WIN": "team_b_win"}
async def _adjust_crowd(
db: AsyncSession, match_id: str, *, add: str | None, remove: str | None
) -> None:
"""crowd_stats 원자적 증분/보정 (Postgres UPDATE)."""
values: dict = {}
if add:
col = _COL[add]
values[col] = CrowdStats.__table__.c[col] + 1
if not remove: # 신규 제출이면 total +1
values["total"] = CrowdStats.total + 1
if remove and remove != add:
col = _COL[remove]
values[col] = CrowdStats.__table__.c[col] - 1
if values:
await db.execute(
update(CrowdStats).where(CrowdStats.match_id == match_id).values(**values)
)
@router.post("", response_model=SubmitPredictionOut)
async def submit_prediction(
body: SubmitPredictionIn, db: AsyncSession = Depends(get_db)
) -> SubmitPredictionOut:
match = (
await db.execute(
select(Match)
.where(Match.match_id == body.matchId)
.options(selectinload(Match.predictions))
)
).scalars().first()
if not match:
raise HTTPException(status_code=404, detail="MATCH_NOT_FOUND")
if not is_open_for_voting(match):
# 마감/종료/오픈전 구분
if match.result_outcome is not None:
raise HTTPException(status_code=409, detail="MATCH_FINISHED")
raise HTTPException(status_code=423, detail="MATCH_LOCKED")
# outcome 은 스코어에서 도출 (입력과 불일치해도 스코어 기준으로 정규화)
outcome = outcome_of(body.scoreA, body.scoreB)
existing = (
await db.execute(
select(UserPrediction).where(
UserPrediction.match_id == body.matchId,
UserPrediction.device_id == body.deviceId,
)
)
).scalars().first()
if existing:
# 마감 전 1회 수정: 분포 보정 (이전 outcome 제거, 새 outcome 추가)
await _adjust_crowd(db, body.matchId, add=outcome, remove=existing.outcome)
existing.outcome = outcome
existing.score_a = body.scoreA
existing.score_b = body.scoreB
if body.email:
existing.email = str(body.email)
existing.notify = body.notify
pred = existing
else:
await _adjust_crowd(db, body.matchId, add=outcome, remove=None)
pred = UserPrediction(
match_id=body.matchId,
device_id=body.deviceId,
outcome=outcome,
score_a=body.scoreA,
score_b=body.scoreB,
email=str(body.email) if body.email else None,
notify=body.notify,
)
db.add(pred)
await db.commit()
# 매칭 AI 모델 (같은 outcome) + 정확스코어 일치 여부
matched: list[str] = []
exact = False
for p in match.predictions:
if p.outcome == outcome:
matched.append(p.model)
if p.score_a == body.scoreA and p.score_b == body.scoreB:
exact = True
crowd = (
await db.execute(
select(CrowdStats).where(CrowdStats.match_id == body.matchId)
)
).scalars().first()
return SubmitPredictionOut(
ok=True,
predictionId=f"{body.matchId}_{body.deviceId}",
matchedModels=matched, # type: ignore[arg-type]
exactMatch=exact,
crowd=crowd_out(crowd, body.matchId),
)