토너먼트 대진 추가

This commit is contained in:
JinwooKim committed 2026-06-29 09:11:58 +09:00
1 parent 59db1c4e9a
commit 6815540ae6
6 files changed
+161 -50

No files matched your search

+33 -7
View File
@@ -23,6 +23,17 @@ from ..teams_data import code_for_tla
log = logging.getLogger("triplepick.schedule")
KST = timezone(timedelta(hours=9))
# football-data stage → 녹아웃 라운드 라벨(한글). 조별리그는 group 으로 따로 처리.
# 2026 포맷(48개국)은 32강(LAST_32)부터 토너먼트가 시작된다.
KO_STAGE_LABEL = {
"LAST_32": "32강",
"LAST_16": "16강",
"QUARTER_FINALS": "8강",
"SEMI_FINALS": "4강",
"THIRD_PLACE": "3·4위전",
"FINAL": "결승",
}
# "13:00 UTC-6" / "20:00 UTC+2" 형태 파싱
_TIME_RE = re.compile(r"(\d{1,2}):(\d{2})\s*UTC\s*([+-]\d{1,2})")
@@ -97,9 +108,12 @@ async def _fetch_football_data() -> list[dict]:
async def _fetch_all_groups_football_data() -> list[dict]:
"""football-data 에서 전체 조별리그(12개조 72경기) 수집.
"""football-data 에서 전체 조별리그 + 녹아웃 토너먼트 일정 수집.
반환: [{teamA, teamB, group('A'..'L'), kickoffKst, venue}] (tla→코드)
반환: [{teamA, teamB, group('A'..'L' 또는 ''), roundLabel('' 또는 '32강'..), kickoffKst, venue}]
조별리그는 group 으로, 32강 이후 토너먼트는 roundLabel 로 구분한다(tla→코드).
녹아웃 경기는 대진이 확정되기 전엔 팀이 TBD 라 소스가 tla 를 주지 않아 자동 제외되고,
조별리그 종료로 대진이 확정되면 다음 동기화에서 자동 등장한다.
"""
if not settings.football_data_token:
log.warning("schedule(all): football-data 토큰 미설정 — 수집 생략")
@@ -117,13 +131,19 @@ async def _fetch_all_groups_football_data() -> list[dict]:
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'
stage = m.get("stage")
if stage == "GROUP_STAGE":
g = (m.get("group") or "").replace("GROUP_", "") # 'A'..'L'
round_label = ""
elif stage in KO_STAGE_LABEL:
g = "" # 녹아웃은 조 없음 — roundLabel 로 구분
round_label = KO_STAGE_LABEL[stage]
else:
continue # 예선/플레이오프 등은 제외
ht = (m.get("homeTeam") or {}).get("tla")
at = (m.get("awayTeam") or {}).get("tla")
if not ht or not at:
continue
continue # 대진 미확정(TBD) — 확정 후 다음 동기화에서 등장
utc = m.get("utcDate")
if not utc:
continue
@@ -135,6 +155,7 @@ async def _fetch_all_groups_football_data() -> list[dict]:
"teamA": code_for_tla(ht),
"teamB": code_for_tla(at),
"group": g,
"roundLabel": round_label,
"kickoffKst": kickoff,
"venue": m.get("venue") or "",
}
@@ -232,7 +253,12 @@ async def _results_football_data() -> list[dict]:
ft = ((m.get("score") or {}).get("fullTime") or {})
if ft.get("home") is None or ft.get("away") is None:
continue
out.append({"teamA": a, "teamB": b, "scoreA": int(ft["home"]), "scoreB": int(ft["away"])})
# 라운드 표기 — 같은 두 팀이 조별리그·토너먼트에서 만나도 정산을 구분(없으면 "").
round_label = KO_STAGE_LABEL.get(m.get("stage") or "", "")
out.append({
"teamA": a, "teamB": b, "scoreA": int(ft["home"]), "scoreB": int(ft["away"]),
"roundLabel": round_label,
})
return out
+23 -9
View File
@@ -21,24 +21,38 @@ from ..teams_data import team_info
log = logging.getLogger("triplepick.schedule")
KST = timezone(timedelta(hours=9))
# 녹아웃 라운드 라벨 → match_id 접두어(조가 없는 토너먼트 경기 식별용)
KO_PREFIX = {"32강": "R32", "16강": "R16", "8강": "QF", "4강": "SF", "3·4위전": "P3", "결승": "F"}
def _stage_prefix(group: str, round_label: str) -> str:
"""경기 식별 접두어 — 조별리그는 조 문자, 녹아웃은 라운드 코드.
같은 두 팀이 조별리그와 결승에서 다시 만나도 서로 다른 경기로 구분된다."""
return group or KO_PREFIX.get(round_label, "KO")
async def sync_schedule(db: AsyncSession, records: list[dict]) -> dict:
if not records:
return {"updated": 0, "inserted": 0, "skipped": 0}
existing = (await db.execute(select(Match))).scalars().all()
# 순서 무관 매칭 — 소스의 홈/원정 순서가 우리와 달라도 기존 경기를 찾음(중복 방지)
# 순서 무관 매칭 — 소스의 홈/원정 순서가 우리와 달라도 기존 경기를 찾음(중복 방지).
# 단계(조/라운드)도 키에 포함 — 같은 두 팀의 조별리그 경기와 토너먼트 경기를 구분.
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
p = _stage_prefix(m.group, m.round_label)
by_pair[(p, m.team_a_code, m.team_b_code)] = m
by_pair[(p, 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)
round_label = rec.get("roundLabel", "")
# 조별리그는 조 문자, 녹아웃은 조 없음(""). roundLabel 이 있으면 토너먼트 경기.
group = "" if round_label else rec.get("group", settings.featured_group)
prefix = _stage_prefix(group, round_label)
kickoff = parse_kickoff(rec["kickoffKst"])
m = by_pair.get((a, b))
m = by_pair.get((prefix, a, b))
if m is not None:
if m.result_outcome is not None:
skipped += 1
@@ -52,10 +66,10 @@ async def sync_schedule(db: AsyncSession, records: list[dict]) -> dict:
else:
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}"
match_id = f"{prefix}_{a}_{b}_{kst_date}"
new = Match(
match_id=match_id,
round_label="",
round_label=round_label,
group=group,
team_a_name=ta["name"], team_a_short=ta["shortName"],
team_a_code=ta["code"], team_a_flag=ta["flag"],
@@ -70,8 +84,8 @@ async def sync_schedule(db: AsyncSession, records: list[dict]) -> dict:
)
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
by_pair[(prefix, a, b)] = new
by_pair[(prefix, b, a)] = new
inserted += 1
await db.commit()
+17 -4
View File
@@ -202,10 +202,23 @@ async def settle_matches() -> None:
if due or recheck_ids:
results = await fetch_results()
# 정방향/역방향 키 모두 등록 — 소스의 홈/원정 순서가 우리와 달라도 매칭.
# 라운드(round_label)를 키에 포함해 같은 두 팀의 조별리그·토너먼트 경기를 구분.
# round_label 없는 소스(openfootball) 대비 라운드 무시 키도 함께 등록(폴백).
by_pair: dict[tuple, tuple[int, int]] = {}
for r in results:
by_pair[(r["teamA"], r["teamB"])] = (r["scoreA"], r["scoreB"])
by_pair[(r["teamB"], r["teamA"])] = (r["scoreB"], r["scoreA"]) # 뒤집어 저장
rl = r.get("roundLabel", "")
a2, b2, sa, sb = r["teamA"], r["teamB"], r["scoreA"], r["scoreB"]
for key in ((rl, a2, b2), (a2, b2)):
by_pair[key] = (sa, sb)
for key in ((rl, b2, a2), (b2, a2)): # 뒤집어 저장
by_pair[key] = (sb, sa)
def _lookup(m: Match) -> tuple[int, int] | None:
# 라운드까지 일치하는 결과 우선, 없으면 팀쌍만으로 폴백.
return by_pair.get((m.round_label, m.team_a_code, m.team_b_code)) or by_pair.get(
(m.team_a_code, m.team_b_code)
)
settled = corrected = 0
async with SessionLocal() as db:
# 1) 신규 정산 — 미정산 경기에 FINISHED 스코어 반영
@@ -213,7 +226,7 @@ async def settle_matches() -> None:
m = await db.get(Match, mid)
if m is None or m.result_outcome is not None:
continue
sc = by_pair.get((m.team_a_code, m.team_b_code))
sc = _lookup(m)
if not sc:
continue
await apply_result(db, m, sc[0], sc[1]) # 우리 팀A/팀B 기준으로 채점+집계+commit
@@ -224,7 +237,7 @@ async def settle_matches() -> None:
m = await db.get(Match, mid)
if m is None or m.result_outcome is None:
continue
sc = by_pair.get((m.team_a_code, m.team_b_code))
sc = _lookup(m)
if not sc:
continue # 소스에 아직 없으면 기존값 유지
if (m.result_score_a, m.result_score_b) == (sc[0], sc[1]):