Files
o2o-weather/backend/services/weekend_plan.py
minaChoi 1fa0695c84 fix: 출시 전 QA 버그 3건 — 주말 플랜 500, 광주·전남 행사 0건, 미세먼지 갱신 멈춤
- 주말 플랜: '14시~' 같은 시간 라벨에서 정렬이 멈춰 피드 전체가 500 (광산구·울릉군)
- 광주·전남: 구 코드는 12인데 행사는 29·46으로 저장돼 27개 구에서 행사를 못 찾음
- 미세먼지: 에어코리아 전국 조회가 15~20초 걸려 8초 한도에 매번 걸림 → 45초
2026-10-08 13:58:06 +09:00

168 lines
8.1 KiB
Python

import re
from dataclasses import dataclass
from datetime import date, datetime
from typing import Optional
from common.enums import EventKind
from common.utils.kma_time import KST
from common.utils.text import day_range, short_day
from services.week_service import DayPlan, EventItem, image_credit
_HOT = 28
_COLD = 10
_BIG_GAP = 10
_MAX_EVENTS = 2
# 주말 동선은 축제를 먼저, 전시는 마지막. 가깝다고 미술관만 이어지지 않게
_KIND_RANK = {EventKind.FESTIVAL: 0, EventKind.CONCERT: 1, EventKind.POPUP: 2, EventKind.EXHIBITION: 3}
@dataclass
class Step:
time: str
icon: str
title: str
sub: str
image: Optional[str] = None
image_credit: Optional[str] = None
@dataclass
class WeekendForecast:
line: str
tip: Optional[str]
caption: str
@dataclass
class DayPlanCard:
eyebrow: str
line: str
steps: list[Step]
caption: str
def _gap(d: DayPlan) -> Optional[float]:
return d.temp_max_c - d.temp_min_c if d.temp_max_c is not None and d.temp_min_c is not None else None
def _deg(v: Optional[float]) -> str:
return f"{round(v)}°" if v is not None else "-"
def forecast(days: list[DayPlan]) -> WeekendForecast:
"""주말 예보 카드의 큰 줄·팁·캡션. 비 > 더위 > 추위 > 일교차 순으로 하나만 짚는다."""
rainy = [d for d in days if d.is_rainy]
clear = [d for d in days if not d.is_rainy]
names = "·".join(d.weekday for d in days)
if not rainy and all(d.icon == "sun" for d in days):
line = f"{names} {'둘 다 ' if len(days) > 1 else ''}맑음!\n나들이 확정각"
elif not rainy:
line = f"{names} 비 소식 없음!\n{'흐려도' if any(d.icon == 'cloud' for d in days) else '구름 좀 껴도'} 나들이각"
elif not clear:
line = f"{names} {'내내 ' if len(days) > 1 else ''}비 소식\n실내 일정 각"
else:
line = f"{clear[0].weekday}요일이 정답!\n{rainy[0].weekday}요일은 비 와요"
lows = [d.temp_min_c for d in days if d.temp_min_c is not None]
highs = [d.temp_max_c for d in days if d.temp_max_c is not None]
gaps = [g for g in (_gap(d) for d in days) if g is not None]
if rainy:
tip = f"{rainy[0].weekday}요일은 비 {rainy[0].rain_prob}%, 우산 꼭 챙겨요!"
elif highs and max(highs) >= _HOT:
tip = f"낮 최고 {_deg(max(highs))}, 물이랑 모자 챙기기!"
elif lows and min(lows) <= _COLD:
tip = f"아침 {_deg(min(lows))}까지 떨어져요. 두꺼운 겉옷 필수!"
elif gaps and max(gaps) >= _BIG_GAP:
tip = f"아침저녁 {_deg(min(lows))}라 반팔만 입으면 큰일 나요. 겉옷 하나 꼭!"
else:
tip = None
carry = "우산" if rainy else "겉옷" if tip else "가벼운 옷"
caption = f"이번 주말은 {carry}만 챙기면 돼요. 토·일 플랜은 피드에 따로 올려둘게요."
return WeekendForecast(line=line, tip=tip, caption=caption)
def pick_events(d: date, events: list[EventItem], exclude: frozenset[int] = frozenset()) -> list[EventItem]:
"""그날 열리는 행사를 축제→공연→팝업→전시 순으로 종류마다 하나씩, 같은 종류는 가까운 순. 일요일은 같은 종류 안에서 그날 끝나는 것을 먼저 (마지막 날 찬스)."""
sunday = d.weekday() == 6
open_ = [e for e in events if e.event.start_date <= d <= e.event.end_date and e.event.event_id not in exclude]
open_.sort(key=lambda e: (_KIND_RANK.get(e.event.kind, len(_KIND_RANK)), sunday and e.event.end_date != d,
e.distance_km if e.distance_km is not None else 9999))
first, rest, kinds = [], [], set()
for e in open_:
(rest if e.event.kind in kinds else first).append(e)
kinds.add(e.event.kind)
return (first + rest)[:_MAX_EVENTS]
def _place(e: EventItem) -> str:
parts = e.event.place_name.split()
return " ".join(parts[1:3]) if len(parts) >= 3 else e.event.place_name
def _event_step(time: str, e: EventItem, d: date) -> Step:
if e.event.end_date == d:
parts = ["오늘이 마지막 날", _place(e)]
elif e.event.start_date == d:
parts = ["오늘 시작", _place(e)]
else:
parts = [_place(e), day_range(e.event.start_date, e.event.end_date)]
sub = " · ".join(x for x in parts if x)
return Step(time=time, icon=e.event.icon, title=e.event.name, sub=sub, image=e.event.image_url, image_credit=image_credit(e.event))
def day_plan(d: DayPlan, sunset_at: Optional[datetime], picks: list[EventItem], next_min: Optional[float]) -> DayPlanCard:
"""그날 시간대별 동선. picks 는 pick_events 로 고른 행사. 일요일은 내일 출근을 생각해 일찍 들어오는 걸로 끝낸다."""
ending = [e for e in picks if e.event.end_date == d.day] if d.day.weekday() == 6 else []
gap = _gap(d)
steps: list[Step] = []
if d.rain_hours is not None:
start, end = d.rain_hours
steps.append(Step(time=f"{start}~{end}시", icon="umbrella", title="이 시간엔 실내로", sub=f"비 {d.rain_prob}% · 전시·카페 추천"))
if start >= 13:
steps.insert(0, Step(time=f"~{start}시", icon="sun", title="비 오기 전에 바깥", sub=f"최고 {_deg(d.temp_max_c)}"))
elif end <= 16:
steps.append(Step(time=f"{end}시~", icon="sun", title="비 그치면 바깥", sub=f"최고 {_deg(d.temp_max_c)}"))
elif d.is_rainy:
steps.append(Step(time="종일", icon="umbrella", title="실내로 알차게", sub=f"비 {d.rain_prob}% · 전시·카페·영화"))
else:
if gap is not None and gap >= _BIG_GAP:
steps.append(Step(time="오전", icon="coldwind", title="겉옷 입고 출발", sub=f"아침 {_deg(d.temp_min_c)}, 쌀쌀해요"))
hot = d.temp_max_c is not None and d.temp_max_c >= _HOT
steps.append(Step(time="12~16시", icon=d.icon, title="그늘 찾아 바깥" if hot else "바깥 골든타임", sub=f"최고 {_deg(d.temp_max_c)}" + (", 물 챙기기" if hot else ", 걷기 딱 좋아요")))
for t, e in zip(["오전", "오후"] if len(picks) > 1 else ["오후"], picks):
steps.append(_event_step(t, e, d.day))
if d.day.weekday() == 6:
steps.append(Step(time="저녁", icon="moon", title="일찍 귀가 추천", sub=f"월요일 아침 {_deg(next_min)}" if next_min is not None else "내일은 월요일"))
elif sunset_at is not None:
steps.append(Step(time=f"{sunset_at.astimezone(KST):%H:%M}", icon="sunset", title="노을 보고 저녁", sub="해 지면 금방 쌀쌀해져요" if gap is not None and gap >= _BIG_GAP else "바깥 자리에서 저녁"))
steps = _sort(steps)
if ending:
line = f"오늘 끝나는 축제\n{len(ending)}개나 있어요!" if len(ending) > 1 else f"{ending[0].event.name}\n오늘이 마지막 날!"
caption = f"{d.weekday}요일엔 끝나는 축제부터 챙기기. 놓치면 내년이에요 🥲"
elif d.is_rainy:
line = f"비 오는 {d.weekday}요일,\n실내로 알차게"
caption = f"{d.weekday}요일은 우산 필수. 비 피해서 알차게 놀아요!"
elif d.icon == "sun":
line = "해 좋은 낮 4시간,\n밖에서 꽉 채우기"
caption = f"{d.weekday}요일은 낮이 제일 예뻐요. 12시부터 16시까지는 무조건 밖으로!"
else:
line = f"{'흐려도' if d.icon == 'cloud' else '구름 좀 껴도'} 비는 없어요,\n낮엔 밖으로"
caption = f"{d.weekday}요일은 비 소식 없어요. 12시부터 16시까지 바깥 일정 잡기 좋아요!"
eyebrow = f"{d.weekday}요일 {short_day(d.day)} · " + ("마지막 날 찬스" if ending else "이렇게 놀아요")
return DayPlanCard(eyebrow=eyebrow, line=line, steps=steps, caption=caption)
_ORDER = {"오전": 1, "종일": 2, "오후": 4, "저녁": 6}
def _sort(steps: list[Step]) -> list[Step]:
"""시간 라벨 순서대로. 숫자 시각은 오전·한낮·노을(17시 이후, 저녁 칸 앞) 자리로."""
def key(s: Step) -> float:
t = s.time
if t[0].isdigit():
h = int(re.match(r"\d+", t).group())
return 5.5 if h >= 17 else 1.5 if h < 12 else 3
if t.startswith("~"):
return 0
return _ORDER.get(t, 4)
return sorted(steps, key=key)