Files
o2o-weather/backend/services/weekend_plan.py
T
minaChoi ddf05aeb5c feat: 로딩 스켈레톤·행사 사진·전시·주말 예상 점수·노을 탭 재정리 등 화면 전반 개선
- 화면 전체 스켈레톤, 로딩·완료·실패 사이 레이아웃 고정, 값 없음은 '?'
- 행사 사진·출처 표시, 문화정보 API 전시 연결, 행사 30km 거리 기준
- 각 상세 점수 칸 오늘/내일/토/일, 단기예보 밖 주말은 중기예보 예상 점수
- 6각 차트 축 이름을 좋은 방향으로, 계산 근거 문구 정리
- 아이콘 오용·뜻 모를 표시·빈 데이터·포스트 본문 반복 수정
- 미세먼지 별도 포스트, 노을 명소 전국 155곳 거리 기준, 노을 탭 결론 중심 재구성
- 밤 다크 테마·별똥별, 댓글·좋아요 대기·실패 표시
- 주말 전국 랭킹·당일치기 카드, 계절 이야기 사진 수집
- 문서: 포스트 타입별 내용, 각 데이터 정리, TODO 진행 순서
2026-10-06 16:36:11 +09:00

159 lines
7.6 KiB
Python

from dataclasses import dataclass
from datetime import date, datetime
from typing import Optional
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
@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: (sunday and e.event.end_date != d, e.distance_km if e.distance_km is not None else 9999))
return open_[:_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(t.split("~")[0].split(":")[0])
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)