feat: 계절 각 — 각마다 제철 달(months), 제철 각에 지금 계절 표시·철 지난 각은 순위 밖 맨 끝, 새 각 12개(꽃구경·이불빨래·빙수·실내건조·한강밤바람·단풍·억새·군고구마·해돋이·눈사람·붕어빵·귤까먹기), 해 뜰 무렵 시간대·일출 점수·눈 조건
This commit is contained in:
1 parent
43e1925d70
commit
5c05824ce0
14 files changed
+1130
-66
No files matched your search
@@ -97,7 +97,10 @@
|
||||
| [x] | **[결정 필요]** 히어로 시안 A/B/C 중 선택 — 지금은 이전 히어로로 롤백 → 10/12 D4-2로 결정(해 안 점수 + 문장 두 줄은 서버 값 그대로 + 상태 한 줄 + 하루 흐름 칸, 높이는 지금 그대로 약 400px) | 히어로 다듬기 | `frontend/src/b/TodayPage.tsx`, `frontend/src/b/b.css` |
|
||||
| [x] | **[결정 필요]** 히어로 D4-2 상태 한 줄 — ① 습도는 서버가 %만 줘서 단계 기준을 새로 정해야 함 ② 불쾌지수 '불쾌'처럼 판정 이름을 그대로 쓸지 ③ 미세먼지·자외선은 늘 보일지, 조심할 때만 보일지 → 10/12 결정: 습도 건조(30% 미만)·보통(60% 이하)·습함, 불쾌지수 단계 이름 그대로, 늘 4개(밤엔 자외선 빼기) | 히어로 D4-2 시안 | `backend/services/hero_stats.py`, `backend/services/feed_service.py`, `frontend/src/b/TodayPage.tsx` |
|
||||
| [ ] | **[결정 필요]** 각 목록 '지금 아님' 문구 — 계절이 아니라 각 시간대(등산 7~12시·피크닉 11~16시)가 지났다는 뜻인데 '가을' 표시 옆에 있어 비활성처럼 읽힘. 그 각의 시간('오전에 좋아요' 등)으로 바꿀지 | 사용자 지적 | `frontend/src/b/GakPage.tsx`, `frontend/src/b/TodayPage.tsx` |
|
||||
| [ ] | **[결정 필요]** 계절별 각 늘리기 — 지금 '가을' 표시는 `is_core` 4개(피크닉·등산·캠핑·별보기)에 글자로 박혀 있고 계절 전환이 없음. 계절마다 각 후보 목록을 만들어 검토받고, 계절 필드로 바꾸기 | 사용자 요청 | `backend/seed/index_definition.json`, `frontend/src/b/GakPage.tsx` |
|
||||
| [x] | **[결정 필요]** 계절별 각 늘리기 — 지금 '가을' 표시는 `is_core` 4개(피크닉·등산·캠핑·별보기)에 글자로 박혀 있고 계절 전환이 없음. 계절마다 각 후보 목록을 만들어 검토받고, 계절 필드로 바꾸기 → 10/12 `months` 칸 + 새 각 12개, 계절 표시는 서버 `season` | 사용자 요청 | `backend/seed/index_definition.json`, `frontend/src/b/GakPage.tsx` |
|
||||
| [ ] | 운영 DB에 `index_definition.months` 칸 추가 — `deploy.sh` 가 배포 때 `init.sql`(`ALTER TABLE public.index_definition ADD COLUMN IF NOT EXISTS months JSONB NOT NULL DEFAULT '[]';`)과 `load_seed.py` 를 돌려서 자동으로 들어감. 배포 뒤 각 탭에 계절 표시가 나오는지만 확인 | 계절 각 | `backend/postgres-init/init.sql`, `deploy.sh` |
|
||||
| [ ] | **[검토 필요]** 새 각 12개 문구 — 설명·한 줄 문장(0/30/60/80)·한계 문구, '제철 아님' 표시 문구 | 계절 각 | `backend/seed/index_definition.json`, `frontend/src/b/GakPage.tsx` |
|
||||
| [ ] | 새 각 전용 아이콘 — 꽃구경(화분)·이불빨래/실내건조(빨래)·빙수(아이스커피)·한강밤바람(야장)·억새(볏단)·해돋이(노을)·붕어빵/군고구마(고구마)는 있는 그림 재사용 중 | 계절 각 | `frontend/public/icons/` |
|
||||
| [x] | 댓글 좋아요 실패 시 알림 없음 (연결·서버 오류면 줄에 안내, 지워진 댓글이면 목록 새로고침) (화면은 되돌아감) | 댓글 대기 표시 작업 중 발견 | `frontend/src/b/Sheets.tsx` (`CommentRow`) |
|
||||
| [x] | **[결정 필요]** 노을 탭 재정리에서 정한 것 — ① 노을 등급 '흐림' → '잿빛'(피드 노을 포스트 문구도 같이 바뀜) ② 히어로에 '가장 붉을 때' 시각 하나는 결론('몇 시에')으로 남기고 나머지 시각은 시간표 한 곳에만 ③ '나가 볼 만해요/애매해요/쉬어요' 기준 60·40점, 내일·모레는 10점 넘게 높을 때만 '더 나아요' ④ '쉬어요'면 명소 추천 안 함 ⑤ 블루아워 시각은 시민박명 끝(-6°), 골든아워는 해 고도 6° → 10/7 노을 탭 다시 기획으로 대체: 점수 대신 하늘 상황 5가지, 결론은 상황 기준 | 노을 탭 재정리 | `backend/services/calc/sky_score.py`, `backend/services/sky_service.py`, `frontend/src/b/SkyPage.tsx` |
|
||||
| [x] | 노을 히어로 맨 윗줄("오늘 노을 · 구")이 보라 배경 위 흰 13px라 대비 약 3.9:1 (AA 4.5 미달) — 결론·근거·시각·점수는 어두운 상자 안으로 옮김, → 어두운 바탕을 깔아 6.7:1 | 노을 탭 재정리 중 발견 | `frontend/src/b/SkyPage.tsx` |
|
||||
|
||||
@@ -185,6 +185,7 @@ class IndexDefinition(Base):
|
||||
sentences: Mapped[dict] = mapped_column(JSONB)
|
||||
sort_order: Mapped[int] = mapped_column(SmallInteger)
|
||||
priority: Mapped[int] = mapped_column(SmallInteger, default=2, server_default="2")
|
||||
months: Mapped[list] = mapped_column(JSONB, default=list, server_default="[]") # 제철 달. 비면 일 년 내내
|
||||
|
||||
|
||||
class IndexScore(Base):
|
||||
|
||||
@@ -292,12 +292,14 @@ CREATE TABLE IF NOT EXISTS public.index_definition (
|
||||
limit_description VARCHAR(200) NULL, -- 반영 못 한 것
|
||||
sentences JSONB NOT NULL DEFAULT '{}', -- 문장 틀 {summary, headline, rabbit, bear, notes}
|
||||
sort_order SMALLINT NOT NULL DEFAULT 0,
|
||||
priority SMALLINT NOT NULL DEFAULT 2 -- 중요도: 1=상 2=중 3=하. 순위는 점수 × 가중치로 정한다
|
||||
priority SMALLINT NOT NULL DEFAULT 2, -- 중요도: 1=상 2=중 3=하. 순위는 점수 × 가중치로 정한다
|
||||
months JSONB NOT NULL DEFAULT '[]' -- 제철 달 [9, 10, 11]. 비어 있으면 일 년 내내. 제철이 아니면 순위·피드에서 빠진다
|
||||
);
|
||||
ALTER TABLE public.index_definition ADD COLUMN IF NOT EXISTS weight_uv SMALLINT NOT NULL DEFAULT 0;
|
||||
ALTER TABLE public.index_definition ADD COLUMN IF NOT EXISTS weight_sun SMALLINT NOT NULL DEFAULT 0;
|
||||
ALTER TABLE public.index_definition ADD COLUMN IF NOT EXISTS weight_view SMALLINT NOT NULL DEFAULT 0;
|
||||
ALTER TABLE public.index_definition ADD COLUMN IF NOT EXISTS priority SMALLINT NOT NULL DEFAULT 2;
|
||||
ALTER TABLE public.index_definition ADD COLUMN IF NOT EXISTS months JSONB NOT NULL DEFAULT '[]';
|
||||
|
||||
-- 노을 명소.
|
||||
CREATE TABLE IF NOT EXISTS public.sunset_spot (
|
||||
|
||||
@@ -17,7 +17,7 @@ def _summary(i: IndexItem, today: date) -> IndexSummary:
|
||||
d = i.definition
|
||||
return IndexSummary(
|
||||
index_id=d.index_id, code=d.code, name=d.name, icon=d.icon, category=IndexCategory(d.category), is_fun=d.is_fun,
|
||||
is_core=d.is_core, score=i.score.score, rank=i.rank, summary=i.score.summary,
|
||||
is_core=d.is_core, season=i.season, in_season=i.in_season, score=i.score.score, rank=i.rank, summary=i.score.summary,
|
||||
trend=[TrendPoint(day=t.score_date, label=slot_label(t.score_date, today), score=t.score, estimated=t.estimated) for t in i.trend],
|
||||
active=i.active, slot=i.slot, slots=[SlotPoint(slot=k, label=SLOT_LABEL[k], score=v) for k, v in i.slots.items()],
|
||||
)
|
||||
@@ -27,7 +27,7 @@ def _summary(i: IndexItem, today: date) -> IndexSummary:
|
||||
async def list_indices(
|
||||
region: str = Query(..., description="구 행정코드"),
|
||||
category: Optional[IndexCategory] = Query(None),
|
||||
core: bool = Query(False, description="이번 계절 핵심 지수만"),
|
||||
core: bool = Query(False, description="지금 제철인 각만"),
|
||||
service: IndexService = Depends(),
|
||||
) -> Res_IndexList:
|
||||
err, board = await service.board(region)
|
||||
@@ -35,7 +35,7 @@ async def list_indices(
|
||||
return Res_IndexList(result=error_info(err))
|
||||
items = [_summary(i, board.day) for i in board.items]
|
||||
top3 = [_summary(i, board.day) for i in board.ranked[:3]]
|
||||
filtered = [x for x in items if (category is None or x.category is category) and (not core or x.is_core)]
|
||||
filtered = [x for x in items if (category is None or x.category is category) and (not core or x.season)]
|
||||
return Res_IndexList(region_code=board.region.code, day=board.day, weather_score=board.weather_score, top3=top3, items=filtered)
|
||||
|
||||
|
||||
|
||||
@@ -28,6 +28,8 @@ class IndexSummary(WebPacketProtocol):
|
||||
category: IndexCategory
|
||||
is_fun: bool
|
||||
is_core: bool
|
||||
season: Optional[str] = Field(default=None, description="지금 제철이면 계절 이름(봄·여름·가을·겨울). 일 년 내내인 각은 없음")
|
||||
in_season: bool = Field(default=True, description="false 면 제철이 아니라 순위 밖, 목록 맨 끝")
|
||||
score: int
|
||||
rank: int
|
||||
summary: str
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -55,6 +55,7 @@ class Context:
|
||||
wind_warning: bool
|
||||
lookahead_rain_prob: int
|
||||
moon_note: str = "" # 별보기각 근거 문구: 그날 밤 달 모양·보이는 시간
|
||||
sunrise_score: Optional[int] = None # 그날 아침 일출 하늘 점수 (해돋이각)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -203,13 +204,17 @@ def time_score(rule: dict, ctx: Context) -> tuple[int, str]:
|
||||
return (ctx.sunset_score if ctx.sunset_score is not None else _UNKNOWN), (
|
||||
f"노을 점수 {ctx.sunset_score}" if ctx.sunset_score is not None else f"노을 점수 계산 전이라 {_UNKNOWN}점으로 둬요"
|
||||
)
|
||||
if kind == "sunrise_score":
|
||||
return (ctx.sunrise_score if ctx.sunrise_score is not None else _UNKNOWN), (
|
||||
f"일출 하늘 점수 {ctx.sunrise_score}" if ctx.sunrise_score is not None else f"일출 하늘 점수 계산 전이라 {_UNKNOWN}점으로 둬요"
|
||||
)
|
||||
return _clamp(rule["value"]), f"날짜와 상관없이 이 시간대 기본 점수 {_clamp(rule['value'])}점"
|
||||
|
||||
|
||||
_TEMP_LABEL = {"range": "기온 알맞음", "away": "덥거나 추움", "lower": "추움", "higher": "더움"}
|
||||
_WIND_LABEL = {"calm": "바람 잔잔", "moderate": "바람 적당", "strong": "바람 셈", "ignore": "바람 무관"}
|
||||
_HUMIDITY_LABEL = {"range": "습도 알맞음", "higher": "습도 높음", "lower": "습도 낮음", "ignore": "습도 무관"}
|
||||
_TIME_LABEL = {"weekday": "요일 알맞음", "moon": "달 어두움", "sunset_score": "노을 예쁨", "fixed": "시간대 알맞음"}
|
||||
_TIME_LABEL = {"weekday": "요일 알맞음", "moon": "달 어두움", "sunset_score": "노을 예쁨", "sunrise_score": "일출 하늘 예쁨", "fixed": "시간대 알맞음"}
|
||||
# Open-Meteo 보조 축. 비중이 있는 지수에만 나온다.
|
||||
_OM_LABEL = {"uv": "자외선 약함", "sun": "햇빛", "view": "가시거리"}
|
||||
|
||||
@@ -253,6 +258,8 @@ def _cond(r: dict) -> tuple[str, str, str]:
|
||||
"""조건 하나를 (이유, '…이거나', '…이면') 꼴로."""
|
||||
if r["field"] == "warning":
|
||||
return "강풍 특보가 있어", "강풍 특보가 있거나", "강풍 특보가 있으면"
|
||||
if r["field"] == "snow":
|
||||
return "눈 소식이 없어", "눈 소식이 없거나", "눈 소식이 없으면"
|
||||
base = f"{_FIELD_TEXT[r['field']]} {r['value']}{_UNIT[r['field']]} {'이상' if r['op'] == '>=' else '미만'}"
|
||||
return f"{base}이라", f"{base}이거나", f"{base}이면"
|
||||
|
||||
@@ -333,6 +340,7 @@ def evaluate(definition, windows: list[list[Hour]], ctx: Context) -> Optional[Re
|
||||
"cloudy_ratio": round(100 * sum(h.sky is Sky.CLOUDY for h in hours) / len(hours)),
|
||||
"warning": "wind" if ctx.wind_warning else None,
|
||||
"gust_ms": max(gusts, default=None), "ground_c": max(grounds, default=None),
|
||||
"snow": "yes" if any(h.rain_type in (RainType.SNOW, RainType.SLEET) for h in hours) else "no",
|
||||
}
|
||||
reason, cap = _zero(definition.zero_rules, agg)
|
||||
if reason is not None:
|
||||
@@ -351,7 +359,7 @@ def hour_temp(lo: float, hi: float, hour: int) -> float:
|
||||
|
||||
|
||||
def estimate(definition, fc: DayForecast, windows: list[list[int]], ctx: Context, next_fc: Optional[DayForecast] = None) -> Optional[Result]:
|
||||
"""중기예보로 내는 예상 점수. 기온·비는 정의 규칙 그대로, 바람·습도·미세먼지·자외선·햇빛·가시거리는 정보 없음으로 둔다. 0점 조건은 비 확률만 본다."""
|
||||
"""중기예보로 내는 예상 점수. 기온·비는 정의 규칙 그대로, 바람·습도·미세먼지·자외선·햇빛·가시거리는 정보 없음으로 둔다. 0점 조건은 비 확률과 눈(늘 없음으로 봄)만 본다."""
|
||||
if fc.temp_min_c is None or fc.temp_max_c is None:
|
||||
return None
|
||||
best: Optional[Result] = None
|
||||
@@ -381,7 +389,9 @@ def estimate(definition, fc: DayForecast, windows: list[list[int]], ctx: Context
|
||||
factors = {a: v for a, (v, _) in scored.items()}
|
||||
notes = {a: n for a, (_, n) in scored.items()}
|
||||
score = _weighted(factors, weights)
|
||||
reason, cap = _zero([r for r in definition.zero_rules if r["field"] == "rain_prob"], {"rain_prob": max_prob})
|
||||
# 중기예보엔 눈 여부가 없어서, 눈이 와야 하는 각은 0점으로 둔다
|
||||
known = {"rain_prob": max_prob, "snow": "no"}
|
||||
reason, cap = _zero([r for r in definition.zero_rules if r["field"] in known], known)
|
||||
if reason is not None:
|
||||
score = min(score, cap)
|
||||
mid = hours[len(hours) // 2]
|
||||
|
||||
@@ -371,7 +371,8 @@ class FeedService:
|
||||
for p, item in zip(gak_posts, gak):
|
||||
cards.append(self._gak(p, item))
|
||||
has_warning = bool(now_w and now_w.warnings)
|
||||
items = board.items if board else []
|
||||
# 오늘 이야기 줄엔 제철인 각만 (철 지난 각은 각 탭 목록 끝에만)
|
||||
items = [i for i in board.items if i.in_season] if board else []
|
||||
feed = Res_Feed(
|
||||
region_code=region.code, region_name=region.name, slot=slot,
|
||||
hero=self._hero(now, slot, hourly[0] if hourly else None, now_w, board, today, await self._uv(region.code, hour), _moon_view(region, now, hourly or [])),
|
||||
|
||||
@@ -42,6 +42,26 @@ WEATHER_SCORE_DEF = SimpleNamespace(
|
||||
)
|
||||
|
||||
|
||||
SEASONS = ("겨울", "봄", "여름", "가을")
|
||||
|
||||
|
||||
def season_of(month: int) -> str:
|
||||
"""봄 3–5 · 여름 6–8 · 가을 9–11 · 겨울 12–2."""
|
||||
return SEASONS[month % 12 // 3]
|
||||
|
||||
|
||||
def in_season(defn, month: int) -> bool:
|
||||
"""제철 달이 없으면 일 년 내내."""
|
||||
months = getattr(defn, "months", None)
|
||||
return not months or month in months
|
||||
|
||||
|
||||
def season_badge(defn, month: int) -> Optional[str]:
|
||||
"""제철이 정해진 각이 지금 제철이면 그 계절 이름. 일 년 내내인 각은 없음."""
|
||||
months = getattr(defn, "months", None)
|
||||
return season_of(month) if months and month in months else None
|
||||
|
||||
|
||||
@dataclass
|
||||
class IndexItem:
|
||||
definition: IndexDefinition
|
||||
@@ -52,6 +72,8 @@ class IndexItem:
|
||||
slots: dict[str, int] = field(default_factory=dict)
|
||||
slot_ranks: dict[str, int] = field(default_factory=dict) # 구간별 순위. 그 구간과 안 겹치는 각은 없음
|
||||
active: bool = True # 지금 구간이 이 각의 시간대와 겹치는지. 아니면 순위·피드에서 빼고 목록 끝에 하루 점수로 둔다
|
||||
season: Optional[str] = None # 지금 제철이면 계절 이름 (화면 표시)
|
||||
in_season: bool = True # 제철이 아니면 순위·피드에서 빼고 목록 맨 끝에 둔다
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -92,11 +114,12 @@ def slot_label(day: date, today: date) -> str:
|
||||
|
||||
|
||||
def window_hours(defn, day: date, region: Region) -> list[list[int]]:
|
||||
"""시간대 정의를 그날 기준 시각 목록으로. 24 이상은 다음 날 시각."""
|
||||
"""시간대 정의를 그날 기준 시각 목록으로. 24 이상은 다음 날 시각. around 는 일몰·일출 시각 ±hours."""
|
||||
out = []
|
||||
for w in defn.windows:
|
||||
if w.get("around") == "sunset":
|
||||
h = sun_times(day, float(region.lat), float(region.lon)).sunset_at.astimezone(KST).hour
|
||||
if w.get("around") in ("sunset", "sunrise"):
|
||||
sun = sun_times(day, float(region.lat), float(region.lon))
|
||||
h = (sun.sunset_at if w["around"] == "sunset" else sun.sunrise_at).astimezone(KST).hour
|
||||
out.append(list(range(h - w.get("hours", 1), h + w.get("hours", 1) + 1)))
|
||||
else:
|
||||
out.append(list(range(w["from"], w["to"])))
|
||||
@@ -272,6 +295,9 @@ class IndexService:
|
||||
if ErrorType.DB_ERROR in (err, err2):
|
||||
return ErrorType.DB_ERROR, None
|
||||
by_key = {(x.index_id, x.score_date): x for x in scores}
|
||||
month = today.month
|
||||
out_season = [d for d in defs if not in_season(d, month)]
|
||||
defs = [d for d in defs if in_season(d, month)]
|
||||
# 오늘 점수는 지금 구간 점수. 구간 점수가 없는 행(예전 계산분)은 하루 점수 그대로, 지금 구간과 안 겹치는 각은 뺀다
|
||||
now_score: dict[int, IndexScore] = {}
|
||||
for d in defs:
|
||||
@@ -290,7 +316,7 @@ class IndexService:
|
||||
items.append(IndexItem(
|
||||
definition=d, score=now_score[d.index_id], rank=i + 1,
|
||||
trend=[now_score[d.index_id] if day == today else by_key[(d.index_id, day)] for day in slots if (d.index_id, day) in by_key],
|
||||
slot=shown_slot(cur), slots=parts,
|
||||
slot=shown_slot(cur), slots=parts, season=season_badge(d, month),
|
||||
))
|
||||
off = sorted(
|
||||
(d for d in defs if d.index_id not in now_score and (d.index_id, today) in by_key),
|
||||
@@ -301,12 +327,19 @@ class IndexService:
|
||||
items.append(IndexItem(
|
||||
definition=d, score=row, rank=len(items) + 1,
|
||||
trend=[by_key[(d.index_id, day)] for day in slots if (d.index_id, day) in by_key],
|
||||
slots=_shown_parts({k: v["score"] for k, v in row.slots.items()}, cur), active=False,
|
||||
slots=_shown_parts({k: v["score"] for k, v in row.slots.items()}, cur), active=False, season=season_badge(d, month),
|
||||
))
|
||||
for k in SLOTS:
|
||||
in_slot = sorted((i for i in items if k in i.slots), key=lambda i: rank_score(i.slots[k], i.definition.priority), reverse=True)
|
||||
for n, i in enumerate(in_slot):
|
||||
i.slot_ranks[k] = n + 1
|
||||
# 제철이 아닌 각은 구간 순위 없이 맨 끝에
|
||||
for d in sorted((d for d in out_season if (d.index_id, today) in by_key), key=lambda d: d.sort_order):
|
||||
row = by_key[(d.index_id, today)]
|
||||
items.append(IndexItem(
|
||||
definition=d, score=row, rank=len(items) + 1,
|
||||
trend=[by_key[(d.index_id, day)] for day in slots if (d.index_id, day) in by_key], active=False, in_season=False,
|
||||
))
|
||||
return ErrorType.SUCCESS, IndexBoard(
|
||||
region=region, day=today, weather_score=weather_parts.get(cur), items=items, weather_slots=_shown_parts(weather_parts, cur),
|
||||
)
|
||||
@@ -359,6 +392,7 @@ class IndexService:
|
||||
_, holidays = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.holidays(s, today, days[-1]))
|
||||
_, sky_scores = await DB_SESSION_MNG.execute_lambda(lambda s: self.sky.scores(s, [region.code], today))
|
||||
sunset = {x.score_date: x.score for x in sky_scores or [] if x.sky_type == SkyType.SUNSET.value}
|
||||
sunrise = {x.score_date: x.score for x in sky_scores or [] if x.sky_type == SkyType.SUNRISE.value}
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return err, None
|
||||
out = []
|
||||
@@ -366,7 +400,7 @@ class IndexService:
|
||||
m = night(day, float(region.lat), float(region.lon))
|
||||
ctx = Context(
|
||||
day=day, is_holiday=day in (holidays or set()), moon=m.lit * up_ratio(m, _STARS_HOURS), moon_note=f"{m.name}, {view_line(m, None)}",
|
||||
sunset_score=sunset.get(day), lookahead_rain_prob=0, **base_ctx,
|
||||
sunset_score=sunset.get(day), sunrise_score=sunrise.get(day), lookahead_rain_prob=0, **base_ctx,
|
||||
)
|
||||
for d in defs:
|
||||
result = day_result(d, day, region, by_at, daily, ctx, short=day < today + timedelta(days=DAYS), by_om=by_om)
|
||||
|
||||
@@ -15,7 +15,7 @@ from crud.region_crud import RegionCRUD
|
||||
from crud.weather_crud import WeatherCRUD
|
||||
from router.router import app
|
||||
from services.calc.index_calc import rank_score
|
||||
from services.index_service import IndexService, _nearest_slot_end_hour, _slot_end_hour, slot_days, slot_label, windows_for
|
||||
from services.index_service import IndexService, _nearest_slot_end_hour, _slot_end_hour, season_of, slot_days, slot_label, windows_for
|
||||
|
||||
REGION = "1141000000"
|
||||
|
||||
@@ -54,17 +54,19 @@ def fakes(monkeypatch):
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_index_list_ranks_all_34_with_today_tomorrow_weekend_trend(fakes):
|
||||
async def test_index_list_ranks_every_gak_with_today_tomorrow_weekend_trend(fakes):
|
||||
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
|
||||
body = (await client.get("/v1/index/list", params={"region": REGION})).json()
|
||||
assert body["result"]["success"] is True
|
||||
assert len(body["items"]) == 34 and len(body["top3"]) == 3
|
||||
assert len(body["items"]) == len(_seed()) and len(body["top3"]) == 3
|
||||
priority = {d["code"]: d["priority"] for d in _seed()}
|
||||
# 지금 구간에 해당하는 각이 먼저(순위), 해당 없는 각은 그 뒤. 각 묶음 안에서는 점수 × 중요도 순
|
||||
# 지금 구간에 해당하는 각이 먼저(순위), 해당 없는 각은 그 뒤, 제철 아닌 각은 맨 끝. 앞 두 묶음 안에서는 점수 × 중요도 순
|
||||
actives = [i["active"] for i in body["items"]]
|
||||
assert actives == sorted(actives, reverse=True) and all(i["active"] for i in body["top3"])
|
||||
seasons = [i["in_season"] for i in body["items"]]
|
||||
assert seasons == sorted(seasons, reverse=True) and all(i["active"] is False for i in body["items"] if not i["in_season"])
|
||||
for group in (True, False):
|
||||
weighted = [rank_score(i["score"], priority[i["code"]]) for i in body["items"] if i["active"] is group]
|
||||
weighted = [rank_score(i["score"], priority[i["code"]]) for i in body["items"] if i["active"] is group and i["in_season"]]
|
||||
assert weighted == sorted(weighted, reverse=True)
|
||||
today = now_kst().date()
|
||||
for i in body["items"]:
|
||||
@@ -75,10 +77,12 @@ async def test_index_list_ranks_all_34_with_today_tomorrow_weekend_trend(fakes):
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_index_list_filters_core(fakes):
|
||||
async def test_index_list_filters_core_to_gak_in_season_now(fakes):
|
||||
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
|
||||
body = (await client.get("/v1/index/list", params={"region": REGION, "core": True})).json()
|
||||
assert {i["code"] for i in body["items"]} == {"picnic", "hiking", "camping", "stars"}
|
||||
month = now_kst().month
|
||||
assert {i["code"] for i in body["items"]} == {d["code"] for d in _seed() if month in d["months"]}
|
||||
assert all(i["season"] == season_of(month) for i in body["items"])
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
@@ -119,6 +123,33 @@ def test_every_index_has_priority():
|
||||
assert all(d["priority"] in (1, 2, 3) for d in _seed())
|
||||
|
||||
|
||||
def test_every_index_has_valid_months_and_weights():
|
||||
for d in _seed():
|
||||
assert isinstance(d["months"], list) and all(1 <= m <= 12 for m in d["months"]), d["code"]
|
||||
assert sum(d[f"weight_{a}"] for a in ("temp", "rain", "wind", "humidity", "air", "uv", "sun", "view", "time")) == 100, d["code"]
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_board_puts_out_of_season_gak_last_without_rank_or_badge(monkeypatch):
|
||||
today = now_kst().date()
|
||||
other = [m for m in range(1, 13) if m != today.month]
|
||||
defs = [
|
||||
SimpleNamespace(index_id=1, code="always", priority=2, months=[], sort_order=1),
|
||||
SimpleNamespace(index_id=2, code="now", priority=2, months=[today.month], sort_order=2),
|
||||
SimpleNamespace(index_id=3, code="off", priority=1, months=other[:3], sort_order=3),
|
||||
]
|
||||
scores = [SimpleNamespace(index_id=x, score_date=today, score=v, slots={}) for x, v in ((1, 50), (2, 60), (3, 99))]
|
||||
crud = SimpleNamespace(definitions=lambda s: _async(defs), scores=lambda s, *a: _async(scores))
|
||||
service = IndexService(RegionCRUD(), crud, None, None, None, None, None, None)
|
||||
monkeypatch.setattr(service, "ensure", lambda *a: _async((ErrorType.SUCCESS, {"morning": 50, "day": 50, "evening": 50, "night": 50, "early": 50})))
|
||||
_, board = await service.board(REGION)
|
||||
view = [(i.definition.code, i.active, i.in_season, i.season) for i in board.items]
|
||||
# 점수가 가장 높아도 제철이 아니면 순위 밖 맨 끝. 계절 표시는 제철 달이 정해진 각에만
|
||||
assert view == [("now", True, True, season_of(today.month)), ("always", True, True, None), ("off", False, False, None)]
|
||||
assert [i.definition.code for i in board.ranked] == ["now", "always"]
|
||||
assert all(not i.slot_ranks for i in board.items if not i.in_season)
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_board_ranks_by_score_times_priority_weight(monkeypatch):
|
||||
today = now_kst().date()
|
||||
|
||||
@@ -259,6 +259,22 @@ def test_new_gak_good_day_high_bad_day_low(code, good, bad):
|
||||
assert _seed_score(code, **bad) <= 30
|
||||
|
||||
|
||||
@pytest.mark.parametrize("code, good, bad", [
|
||||
("flower", dict(feels=19.0, wind=2.0, sunshine_ratio=0.8, visibility_km=20.0), dict(feels=8.0, prob=80, rain=RainType.RAIN, sunshine_ratio=0.1, visibility_km=4.0)),
|
||||
("blanket", dict(feels=22.0, wind=3.0, hum=35, sunshine_ratio=0.9), dict(feels=10.0, prob=70, rain=RainType.RAIN, hum=90, sunshine_ratio=0.1)),
|
||||
("bingsu", dict(feels=33.0, hum=75), dict(feels=18.0, hum=40)),
|
||||
("indoordry", dict(feels=27.0, prob=90, rain=RainType.RAIN, hum=55), dict(feels=14.0, hum=90)),
|
||||
("riverwind", dict(feels=24.0, wind=3.0, hum=55), dict(feels=20.0, prob=80, rain=RainType.RAIN, wind=0.5, hum=90)),
|
||||
("foliage", dict(feels=16.0, wind=2.0, sunshine_ratio=0.8, visibility_km=20.0), dict(feels=8.0, prob=80, rain=RainType.RAIN, sunshine_ratio=0.1, visibility_km=4.0)),
|
||||
("sweetpotato", dict(feels=2.0, wind=6.0), dict(feels=20.0, wind=1.0)),
|
||||
("bungeoppang", dict(feels=-5.0, wind=6.0), dict(feels=15.0, wind=1.0)),
|
||||
("tangerine", dict(feels=-5.0, wind=7.0, prob=80, rain=RainType.SNOW), dict(feels=15.0, wind=1.0)),
|
||||
])
|
||||
def test_seasonal_gak_good_day_high_bad_day_low(code, good, bad):
|
||||
assert _seed_score(code, **good) >= 80
|
||||
assert _seed_score(code, **bad) <= 30
|
||||
|
||||
|
||||
def test_new_gak_100_only_when_every_factor_is_perfect():
|
||||
perfect = dict(feels=19.5, wind=1.0, hum=35)
|
||||
assert _seed_score("golf", **perfect) == 100
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
from datetime import date
|
||||
from types import SimpleNamespace
|
||||
|
||||
from common.enums import RainType, Sky
|
||||
from common.utils.kma_time import KST
|
||||
from services.calc.index_calc import Context, DayForecast, Hour, estimate, evaluate, time_score, zero_rules_text
|
||||
from services.calc.sun import sun_times
|
||||
from services.index_service import in_season, season_badge, season_of, window_hours
|
||||
|
||||
CTX = Context(day=date(2027, 1, 9), is_holiday=False, pm25=10, air_label="좋음", moon=0.5, sunset_score=None, wind_warning=False, lookahead_rain_prob=0)
|
||||
SNOWMAN = SimpleNamespace(
|
||||
weight_temp=50, weight_rain=10, weight_wind=20, weight_humidity=0, weight_air=0, weight_time=20,
|
||||
factor_rules={"temp": {"type": "range", "lo": -5, "hi": 2, "best": -1}, "rain": {"dir": "wet"}, "wind": {"type": "calm", "ok": 3, "limit": 10},
|
||||
"humidity": {"type": "ignore"}, "time": {"type": "fixed", "value": 100}},
|
||||
zero_rules=[{"field": "snow", "op": "==", "value": "no"}], windows=[{"from": 9, "to": 16}],
|
||||
)
|
||||
|
||||
|
||||
def _h(hour, rain=RainType.NONE, feels=-1.0):
|
||||
return Hour(hour=hour, feels_c=feels, rain_type=rain, rain_prob=80 if rain is not RainType.NONE else 0, wind_ms=1.0, humidity=70, sky=Sky.CLOUDY)
|
||||
|
||||
|
||||
def test_season_names_and_in_season():
|
||||
assert [season_of(m) for m in (1, 3, 6, 9, 12)] == ["겨울", "봄", "여름", "가을", "겨울"]
|
||||
always, winter = SimpleNamespace(months=[]), SimpleNamespace(months=[12, 1, 2])
|
||||
assert in_season(always, 7) and in_season(winter, 1) and not in_season(winter, 7)
|
||||
# 일 년 내내인 각엔 계절 표시가 없다
|
||||
assert season_badge(always, 1) is None and season_badge(winter, 1) == "겨울" and season_badge(winter, 7) is None
|
||||
assert in_season(SimpleNamespace(), 5)
|
||||
|
||||
|
||||
def test_snowman_is_zero_without_snow_and_high_when_snowing_near_zero():
|
||||
dry = evaluate(SNOWMAN, [[_h(h) for h in range(9, 16)]], CTX)
|
||||
assert dry.score == 0 and dry.zero_reason == "눈 소식이 없어 0점"
|
||||
snowy = evaluate(SNOWMAN, [[_h(h, RainType.SNOW) for h in range(9, 16)]], CTX)
|
||||
assert snowy.score >= 80 and snowy.zero_reason is None
|
||||
assert zero_rules_text(SNOWMAN.zero_rules) == "눈 소식이 없으면 0점"
|
||||
|
||||
|
||||
def test_snowman_estimate_from_mid_forecast_is_zero():
|
||||
fc = DayForecast(temp_min_c=-4, temp_max_c=1, rain_prob_am=70, rain_prob_pm=70, sky=Sky.CLOUDY)
|
||||
assert estimate(SNOWMAN, fc, [list(range(9, 16))], CTX).score == 0
|
||||
|
||||
|
||||
def test_sunrise_score_time_rule():
|
||||
assert time_score({"type": "sunrise_score"}, Context(**{**CTX.__dict__, "sunrise_score": 72})) == (72, "일출 하늘 점수 72")
|
||||
assert time_score({"type": "sunrise_score"}, CTX)[0] == 70
|
||||
|
||||
|
||||
def test_window_around_sunrise_covers_sunrise_hour():
|
||||
region = SimpleNamespace(lat=37.56, lon=126.97)
|
||||
day = date(2027, 1, 1)
|
||||
h = sun_times(day, region.lat, region.lon).sunrise_at.astimezone(KST).hour
|
||||
assert window_hours(SimpleNamespace(windows=[{"around": "sunrise", "hours": 1}]), day, region) == [[h - 1, h, h + 1]]
|
||||
|
||||
@@ -629,7 +629,7 @@ export type Hero = {
|
||||
/**
|
||||
* Status
|
||||
*
|
||||
* 히어로 상태 한 줄: 습도·불쾌지수·자외선(낮에만)·미세먼지 단계 이름. tone=warn 이면 조심(앱이 주황 글자로)
|
||||
* 히어로 상태 한 줄: 습도·불쾌지수·자외선(밤 구간 빼고)·미세먼지 단계 이름. tone=warn 이면 조심(앱이 주황 글자로)
|
||||
*/
|
||||
status?: Array<HeroStat>;
|
||||
};
|
||||
@@ -755,6 +755,18 @@ export type IndexSummary = {
|
||||
* Is Core
|
||||
*/
|
||||
is_core: boolean;
|
||||
/**
|
||||
* Season
|
||||
*
|
||||
* 지금 제철이면 계절 이름(봄·여름·가을·겨울). 일 년 내내인 각은 없음
|
||||
*/
|
||||
season?: string | null;
|
||||
/**
|
||||
* In Season
|
||||
*
|
||||
* false 면 제철이 아니라 순위 밖, 목록 맨 끝
|
||||
*/
|
||||
in_season?: boolean;
|
||||
/**
|
||||
* Score
|
||||
*/
|
||||
@@ -3077,7 +3089,7 @@ export type ListIndicesData = {
|
||||
/**
|
||||
* Core
|
||||
*
|
||||
* 이번 계절 핵심 지수만
|
||||
* 지금 제철인 각만
|
||||
*/
|
||||
core?: boolean;
|
||||
};
|
||||
|
||||
@@ -3,21 +3,22 @@ import { useQuery } from '@tanstack/react-query'
|
||||
import { listArticlesOptions, listIndicesOptions } from '../api/client/@tanstack/react-query.gen'
|
||||
import { ArticleCategory, IndexCategory } from '../api/client/types.gen'
|
||||
import { cx } from '../lib/utils'
|
||||
import { loadOf, MEDALS } from './lib'
|
||||
import { kst, loadOf, MEDALS, seasonOf } from './lib'
|
||||
import { useRegion } from './regionContext'
|
||||
import { useSheet } from './sheetContext'
|
||||
import { Chips, Ic, Sec, Skel, StateBox } from './ui'
|
||||
|
||||
type Cat = 'all' | 'out' | 'food' | 'home' | 'life' | 'core'
|
||||
|
||||
const CATS = [
|
||||
// 마지막 칩은 지금 계절의 제철 각 (예: 가을 각)
|
||||
const CATS: readonly (readonly [Cat, string])[] = [
|
||||
['all', '전체'],
|
||||
['out', '밖에서 놀기'],
|
||||
['food', '먹고 마시기'],
|
||||
['home', '집안일'],
|
||||
['life', '생활 고민'],
|
||||
['core', '가을 각'],
|
||||
] as const
|
||||
['core', `${seasonOf(kst(new Date()).mo)[0]} 각`],
|
||||
]
|
||||
|
||||
const CAT_PARAM: Partial<Record<Cat, IndexCategory>> = { out: IndexCategory.OUTSIDE, food: IndexCategory.FOOD, home: IndexCategory.HOME, life: IndexCategory.LIFE }
|
||||
|
||||
@@ -124,15 +125,15 @@ export function GakPage() {
|
||||
<div className={cx('grid grid-cols-3 gap-2 p-3 transition-opacity', q.isPlaceholderData && 'opacity-60')}>
|
||||
{items.map((g) => {
|
||||
return (
|
||||
<button key={g.index_id} type="button" onClick={() => open({ type: 'gak', indexId: g.index_id })} aria-label={g.active ? `${g.rank}위 ${g.name} ${g.score}점` : `${g.name}, 지금 시간대 아님`} className={cx('relative flex cursor-pointer flex-col items-center rounded-[22px] bg-white px-1.5 pt-3 pb-2.5 shadow-[inset_0_-5px_0_var(--shade)]', !g.active && 'opacity-55')}>
|
||||
<button key={g.index_id} type="button" onClick={() => open({ type: 'gak', indexId: g.index_id })} aria-label={g.active ? `${g.rank}위 ${g.name} ${g.score}점` : `${g.name}, ${g.in_season === false ? '제철 아님' : '지금 시간대 아님'}`} className={cx('relative flex cursor-pointer flex-col items-center rounded-[22px] bg-white px-1.5 pt-3 pb-2.5 shadow-[inset_0_-5px_0_var(--shade)]', !g.active && 'opacity-55')}>
|
||||
{g.active && <span className="absolute top-[7px] left-[9px] font-jua text-[13px] text-(--ink3)">{g.rank}</span>}
|
||||
{g.is_core && <span className="absolute top-2 right-2 text-[10.5px] font-extrabold text-[#1f9d62]">가을</span>}
|
||||
{g.season && <span className="absolute top-2 right-2 text-[10.5px] font-extrabold text-[#1f9d62]">{g.season}</span>}
|
||||
<Ic name={g.icon} className="w-[50px]" />
|
||||
<b className="mt-1 font-jua text-[15px] font-normal">{g.name}</b>
|
||||
{g.active ? (
|
||||
<em className={cx('font-bagel text-[22px] leading-[1.1] not-italic', g.score < 50 ? 'text-(--ink3)' : 'text-(--orange)')}>{g.score}</em>
|
||||
) : (
|
||||
<small className="py-1 text-[12px] leading-[1.1] font-extrabold text-(--ink3)">지금 아님</small>
|
||||
<small className="py-1 text-[12px] leading-[1.1] font-extrabold text-(--ink3)">{g.in_season === false ? '제철 아님' : '지금 아님'}</small>
|
||||
)}
|
||||
</button>
|
||||
)
|
||||
|
||||
Reference in new issue
Block a user