diff --git a/backend/crud/index_crud.py b/backend/crud/index_crud.py index ce43105..298f23e 100644 --- a/backend/crud/index_crud.py +++ b/backend/crud/index_crud.py @@ -35,9 +35,10 @@ class IndexCRUD: return await s.scalar(stmt) async def has_unslotted(self, s: AsyncSession, region_code: str, day: date) -> bool: - """그날 행 중 구간 점수가 비어 있는 행(구간 계산 전 행)이 있는지.""" + """현재 방식으로 모든 구간을 계산하지 않은 행이 있는지.""" stmt = select(IndexScore.index_id).where( - IndexScore.region_code == region_code, IndexScore.score_date == day, text("index_score.slots = '{}'::jsonb") + IndexScore.region_code == region_code, IndexScore.score_date == day, + text("NOT (index_score.slots ?& ARRAY['morning', 'day', 'evening', 'night', 'early'])") ).limit(1) return (await s.scalar(stmt)) is not None diff --git a/backend/services/calc/index_calc.py b/backend/services/calc/index_calc.py index 87ec931..a776c3d 100644 --- a/backend/services/calc/index_calc.py +++ b/backend/services/calc/index_calc.py @@ -57,6 +57,7 @@ class Context: moon_note: str = "" # 별보기각 근거 문구: 그날 밤 달 모양·보이는 시간 sunrise_score: Optional[int] = None # 그날 아침 일출 하늘 점수 (해돋이각) rain_hours: frozenset[int] = frozenset() # 그날 비 오는 시각(0~23). 우산분실각의 '앞서 비가 왔는지' + time_matches: bool = True # 평가하는 시간대가 각의 활동 시간대에 해당하는지 @dataclass(frozen=True) @@ -209,7 +210,7 @@ def time_score(rule: dict, ctx: Context) -> tuple[int, str]: 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'])}점" + return (100, "활동 시간대에 해당해요") if ctx.time_matches else (0, "활동 시간대가 아니에요") _TEMP_LABEL = {"range": "기온 알맞음", "away": "덥거나 추움", "lower": "추움", "higher": "더움"} @@ -296,12 +297,13 @@ def _summary(hours: list[Hour]) -> str: return f"{hour_label(mid.hour % 24)} {round(mid.feels_c)}°, {tag}" -def _weighted(factors: dict[str, int], weights: dict[str, int], worst_pull: bool = True) -> int: +def _weighted(factors: dict[str, int], weights: dict[str, int], worst_pull: bool = True, time_is_binary: bool = False) -> int: """비중대로 섞고, worst_pull 이면 가장 낮은 요소로 최대 25% 깎는다 (지금 날씨 점수는 깎지 않는다).""" mixed = sum(factors[a] * weights[a] for a in AXES) / 100 if not worst_pull: return round(mixed) - worst = min((factors[a] for a in AXES if weights[a]), default=100) + # 시간대 불일치는 해당 가중치만 잃으며, 최저 요소에 따른 추가 감점에는 넣지 않는다. + worst = min((factors[a] for a in AXES if weights[a] and not (time_is_binary and a == "time")), default=100) return round(mixed * (1 - _WORST_PULL + _WORST_PULL * worst / 100)) @@ -342,7 +344,7 @@ def evaluate(definition, windows: list[list[Hour]], ctx: Context) -> Optional[Re } factors = {a: v for a, (v, _) in scored.items()} notes = {a: n for a, (_, n) in scored.items()} - score = _weighted(factors, weights, getattr(definition, "worst_pull", True)) + score = _weighted(factors, weights, getattr(definition, "worst_pull", True), rules["time"]["type"] == "fixed") agg = { "rain_prob": max_prob, "wind_ms": max(winds) if winds else None, "pm25": ctx.pm25, "feels_c": (min(h.feels_c for h in hours), max(h.feels_c for h in hours)), @@ -399,7 +401,7 @@ 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, getattr(definition, "worst_pull", True)) + score = _weighted(factors, weights, getattr(definition, "worst_pull", True), rules["time"]["type"] == "fixed") # 중기예보엔 눈 여부가 없어서, 눈이 와야 하는 각은 0점으로 둔다 # 하루 예보로는 비가 언제 그치는지 몰라 '앞서 비 옴'은 없는 것으로 본다 known = {"rain_prob": max_prob, "snow": "no", "rain_before": "no"} diff --git a/backend/services/feed_service.py b/backend/services/feed_service.py index 6f4d209..23f48f8 100644 --- a/backend/services/feed_service.py +++ b/backend/services/feed_service.py @@ -311,7 +311,7 @@ class FeedService: now = now_kst() sunset_at = sun_times(now.date(), float(region.lat), float(region.lon)).sunset_at slot = slot_of(now, sunset_at) - key = f"feed:{region.code}:{slot}" + key = f"feed:{region.code}:time-weight-v2:{slot}" try: cached = await REDIS.conn.get(key) if cached: diff --git a/backend/services/index_service.py b/backend/services/index_service.py index c9b427c..165e5a1 100644 --- a/backend/services/index_service.py +++ b/backend/services/index_service.py @@ -77,8 +77,8 @@ class IndexItem: trend: list[IndexScore] slot: Optional[str] = None slots: dict[str, int] = field(default_factory=dict) - slot_ranks: dict[str, int] = field(default_factory=dict) # 구간별 순위. 그 구간과 안 겹치는 각은 없음 - active: bool = True # 지금 구간이 이 각의 시간대와 겹치는지. 아니면 순위·피드에서 빼고 목록 끝에 하루 점수로 둔다 + slot_ranks: dict[str, int] = field(default_factory=dict) # 각 구간의 날씨·시간대 적합도로 계산한 순위 + active: bool = True # 시간대와 관계없이 활성화. 제철이 아닌 각만 제외 season: Optional[str] = None # 지금 제철이면 계절 이름 (화면 표시) in_season: bool = True # 제철이 아니면 순위·피드에서 빼고 목록 맨 끝에 둔다 @@ -93,7 +93,7 @@ class IndexBoard: @property def ranked(self) -> list[IndexItem]: - """지금 구간에 해당하는 각만 (순위·피드용).""" + """활성화된 각 (순위·피드용).""" return [i for i in self.items if i.active] @@ -183,7 +183,6 @@ def windows_for( EARLY = "early" # 0~5시: 전날 밤 구간 -MIN_SLOT_HOURS = 2 # 각 시간대가 구간과 이만큼은 겹쳐야 그 구간 점수를 낸다 (한 시간짜리 각은 한 시간) def current_slot(now: datetime, sunset_at: datetime) -> str: @@ -220,16 +219,21 @@ def slot_results( defn, day: date, region: Region, by_at: dict[datetime, WeatherHourly], by_om: dict[datetime, OpenMeteoHourly], ctx: Context, sunset_at: datetime, now: Optional[datetime] = None, ) -> dict[str, Result]: - """그날 아침·낮·저녁·밤과 0~5시(전날 밤) 점수. 각 시간대와 겹치지 않는 구간은 빠진다. now 를 주면 지금 구간은 지금 시각부터만 본다.""" + """각 구간의 날씨로 평가한다. 활동 시간대와 안 겹쳐도 계산하되 시간 요소는 0점. now 가 있으면 현재 구간은 남은 시각만 본다.""" hours_by_slot = slot_hours(day, sunset_at) - cur = _trim_passed(hours_by_slot, day, sunset_at, now) if now else None - parts = {k: windows_for(defn, day, region, by_at, by_om, only=hours) for k, hours in hours_by_slot.items()} - parts[EARLY] = windows_for(defn, day - timedelta(days=1), region, by_at, by_om, only=set(range(24, 24 + NIGHT_END_HOUR))) - need = min(MIN_SLOT_HOURS, max((len(h) for h in window_hours(defn, day, region)), default=0)) + hours_by_slot[EARLY] = set(range(NIGHT_END_HOUR)) + if now: + _trim_passed(hours_by_slot, day, sunset_at, now) + activity = [{h % 24 for h in w} for w in window_hours(defn, day, region)] out = {} - for key, windows in parts.items(): - k_need = min(need, len(hours_by_slot[key])) if key == cur else need - result = evaluate(defn, [w for w in windows if len(w) >= k_need], ctx) + for key, hours in hours_by_slot.items(): + if not hours: + continue + matches = any(any(h % 24 in w for h in hours) for w in activity) + # 시간대 일치 여부와 날씨 평가를 분리해 하루 점수로 대체하지 않는다. + window = SimpleNamespace(windows=[{"from": min(hours), "to": max(hours) + 1}]) + windows = windows_for(window, day, region, by_at, by_om, only=hours) + result = evaluate(defn, windows, replace(ctx, time_matches=matches)) if result is not None: out[key] = result return out @@ -336,16 +340,13 @@ class IndexService: 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: row = by_key.get((d.index_id, today)) - if row is None: + if row is None or cur not in row.slots: continue - if not row.slots: - now_score[d.index_id] = row - elif cur in row.slots: - now_score[d.index_id] = _with_slot(row, row.slots[cur]) + now_score[d.index_id] = _with_slot(row, row.slots[cur]) ranked = sorted((d for d in defs if d.index_id in now_score), key=lambda d: rank_score(now_score[d.index_id].score, d.priority), reverse=True) items = [] for i, d in enumerate(ranked): @@ -356,17 +357,6 @@ class IndexService: 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, 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), - key=lambda d: rank_score(by_key[(d.index_id, today)].score, d.priority), reverse=True, - ) - for d in off: - 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], - 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): diff --git a/backend/tests/test_day_slot.py b/backend/tests/test_day_slot.py index b34f7bb..f503959 100644 --- a/backend/tests/test_day_slot.py +++ b/backend/tests/test_day_slot.py @@ -48,11 +48,10 @@ def test_current_slot_before_5_is_previous_night(): assert current_slot(datetime(2026, 10, 8, 16, 30, tzinfo=KST), SUNSET) == "evening" -def test_gak_hidden_in_slots_outside_its_window(): +def test_gak_scores_every_slot_and_time_match_is_binary(): parts = slot_results(_defn([{"from": 17, "to": 24}]), DAY, REGION, _rows(), {}, CTX, SUNSET) - assert set(parts) == {"evening", "night"} - # 18시 한 시간만 저녁 구간(16~18시)과 겹치면 저녁 점수는 내지 않는다 - assert set(slot_results(_defn([{"from": 18, "to": 24}]), DAY, REGION, _rows(), {}, CTX, SUNSET)) == {"night"} + assert set(parts) == {"morning", "day", "evening", "night", EARLY} + assert {k: r.factors["time"] for k, r in parts.items()} == {"morning": 0, "day": 0, "evening": 100, "night": 100, EARLY: 0} def test_rain_in_evening_lowers_only_later_slots(): @@ -102,12 +101,25 @@ def test_ultra_rain_lowers_slot_score(): assert wet < dry -def test_slot_needs_two_overlapping_hours(): - """10~17시 각은 아침 구간(5~11시)과 10시 한 시간만 겹쳐서 아침 점수를 내지 않는다. 한 시간짜리 각은 한 시간이면 된다.""" +def test_time_match_includes_one_overlapping_hour(): by_at = _rows() - assert "morning" not in slot_results(_defn([{"from": 10, "to": 17}]), DAY, REGION, by_at, {}, CTX, SUNSET) - assert "morning" in slot_results(_defn([{"from": 9, "to": 17}]), DAY, REGION, by_at, {}, CTX, SUNSET) - assert "morning" in slot_results(_defn([{"from": 10, "to": 11}]), DAY, REGION, by_at, {}, CTX, SUNSET) + for start, end in ((10, 17), (9, 17), (10, 11)): + assert slot_results(_defn([{"from": start, "to": end}]), DAY, REGION, by_at, {}, CTX, SUNSET)["morning"].factors["time"] == 100 + + +def test_outside_window_uses_current_weather_instead_of_daily_weather(): + parts = slot_results(_defn([{"from": 7, "to": 11}]), DAY, REGION, _rows(rain_from=16), {}, CTX, SUNSET) + assert parts["morning"].score == 100 + assert parts["night"].score < parts["morning"].score + assert parts["night"].factors["rain"] == 0 and parts["night"].factors["time"] == 0 + + +def test_early_hours_match_windows_crossing_midnight(): + parts = slot_results(_defn([{"from": 21, "to": 26}]), DAY, REGION, _rows(), {}, CTX, SUNSET) + assert parts[EARLY].factors["time"] == 100 + now = datetime(2026, 10, 8, 2, 0, tzinfo=KST) + parts = slot_results(_defn([{"from": 21, "to": 26}]), DAY, REGION, _rows(), {}, CTX, SUNSET, now) + assert parts[EARLY].factors["time"] == 0 def test_current_slot_skips_passed_hours(): diff --git a/backend/tests/test_feed.py b/backend/tests/test_feed.py index bfba8ae..d8303e3 100644 --- a/backend/tests/test_feed.py +++ b/backend/tests/test_feed.py @@ -8,10 +8,12 @@ from common.database.db_session_manager import DB_SESSION_MNG from common.enums import PostType from common.utils.kma_time import now_kst from crud.feed_crud import FeedCRUD +from crud.index_crud import IndexCRUD from crud.region_crud import RegionCRUD from crud.season_crud import SeasonCRUD from router.router import app from services.feed_service import build_feed_day +from services.index_service import in_season from services.week_service import collect_events REGION = "1114000000" @@ -61,7 +63,10 @@ async def test_feed_assembles_hero_stories_posts_and_bands(offline): body = (await client.get("/v1/feed", params={"region": REGION})).json() assert body["result"]["success"] is True assert body["hero"]["temp_c"] == 20 and body["hero"]["top1"]["rank"] == 1 and "top3" not in body["hero"] - assert len(body["stories"]) == 40 + _, definitions = await DB_SESSION_MNG.execute_lambda(lambda s: IndexCRUD().definitions(s)) + expected = {d.code for d in definitions if in_season(d, now_kst().month)} + assert {g["code"] for g in body["stories"]} == expected + assert all(g["active"] for g in body["stories"]) assert body["hero"]["weather_score"] == body["hero"]["weather_slots"][body["slot"]] assert all(g["slots"][body["slot"]] == g["score"] and g["slot_ranks"][body["slot"]] == g["rank"] for g in body["stories"] if g["active"]) weather = next(p for p in body["posts"] if p["post_type"] == PostType.WEATHER.value) diff --git a/backend/tests/test_index_api.py b/backend/tests/test_index_api.py index 936788d..483c145 100644 --- a/backend/tests/test_index_api.py +++ b/backend/tests/test_index_api.py @@ -8,7 +8,7 @@ import services.air_service as air_service import services.warning_service as warning_service import services.weather_service as weather_service from common.database.db_session_manager import DB_SESSION_MNG -from common.database.model.models import OpenMeteoHourly, WeatherHourly +from common.database.model.models import IndexScore, OpenMeteoHourly, WeatherHourly from common.enums import ErrorType from common.utils.kma_time import kst_midnight, now_kst from crud.region_crud import RegionCRUD @@ -24,6 +24,14 @@ async def _async(v): return v +def _board_score(index_id, day, score, slot_score=None): + value = score if slot_score is None else slot_score + return IndexScore(index_id=index_id, score_date=day, score=score, slots={ + k: {"score": value, "summary": "", "factors": {}, "zero_reason": None, "notes": {}} + for k in ("morning", "day", "evening", "night", "early") + }) + + def _vilage(*_): start = kst_midnight(now_kst().date()) items = [] @@ -61,7 +69,8 @@ async def test_index_list_ranks_every_gak_with_today_tomorrow_weekend_trend(fake assert body["result"]["success"] is True assert len(body["items"]) == len(_seed()) and len(body["top3"]) == 3 priority = {d["code"]: d["priority"] for d in _seed()} - # 지금 구간에 해당하는 각이 먼저(순위), 해당 없는 각은 그 뒤, 제철 아닌 각은 맨 끝. 앞 두 묶음 안에서는 점수 × 중요도 순 + # 시간대와 관계없이 제철인 각은 모두 활성화하고, 제철 아닌 각은 맨 끝. + assert all(i["active"] for i in body["items"] if i["in_season"]) 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"]] @@ -139,7 +148,7 @@ async def test_board_puts_out_of_season_gak_last_without_rank_or_badge(monkeypat 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))] + scores = [_board_score(x, today, v) 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}))) @@ -159,7 +168,7 @@ async def test_board_ranks_by_score_times_priority_weight(monkeypatch): SimpleNamespace(index_id=2, code="mid", priority=2), SimpleNamespace(index_id=3, code="high", priority=1), ] - scores = [SimpleNamespace(index_id=x, score_date=today, score=v, slots={}) for x, v in ((1, 90), (2, 80), (3, 70))] + scores = [_board_score(x, today, v) for x, v in ((1, 90), (2, 80), (3, 70))] 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}))) @@ -175,7 +184,7 @@ async def test_board_ranks_each_slot_with_priority_weight(monkeypatch): defs = [SimpleNamespace(index_id=1, code="low", priority=3), SimpleNamespace(index_id=2, code="high", priority=1)] every = ("morning", "day", "evening", "night", "early") slots = {1: {k: {"score": 90, "summary": "", "factors": {}, "zero_reason": None, "notes": []} for k in every}, - 2: {k: {"score": 20 if k == "morning" else 70, "summary": "", "factors": {}, "zero_reason": None, "notes": []} for k in every if k not in ("night", "early")}} + 2: {k: {"score": 20 if k == "morning" else 70, "summary": "", "factors": {}, "zero_reason": None, "notes": []} for k in every}} scores = [SimpleNamespace(index_id=x, score_date=today, score=80, slots=slots[x]) for x in (1, 2)] crud = SimpleNamespace(definitions=lambda s: _async(defs), scores=lambda s, *a: _async(scores)) service = IndexService(RegionCRUD(), crud, None, None, None, None, None, None) @@ -183,10 +192,32 @@ async def test_board_ranks_each_slot_with_priority_weight(monkeypatch): monkeypatch.setattr("services.index_service._with_slot", lambda row, data: SimpleNamespace(score=data["score"])) _, board = await service.board(REGION) ranks = {i.definition.code: i.slot_ranks for i in board.items} - # 아침: 하 90(63) > 상 20(20). 낮: 상 70(70) > 하 90(63). 상은 밤 구간이 없어 밤 순위도 없다 + # 아침: 하 90(63) > 상 20(20). 낮·밤: 상 70(70) > 하 90(63). assert ranks["low"]["morning"] == 1 and ranks["high"]["morning"] == 2 assert ranks["high"]["day"] == 1 and ranks["low"]["day"] == 2 - assert "night" not in ranks["high"] + assert ranks["high"]["night"] == 1 and ranks["low"]["night"] == 2 + + +@pytest.mark.anyio +@pytest.mark.parametrize("cur", ["morning", "day", "evening", "night", "early"]) +async def test_board_activates_gak_outside_its_time_window(monkeypatch, cur): + today = now_kst().date() + defs = [SimpleNamespace(index_id=1, code="outside", priority=1)] + row = _board_score(1, today, 85, slot_score=65) + crud = SimpleNamespace(definitions=lambda s: _async(defs), scores=lambda s, *a: _async([row])) + service = IndexService(RegionCRUD(), crud, None, None, None, None, None, None) + monkeypatch.setattr(service, "ensure", lambda *a: _async((ErrorType.SUCCESS, {cur: 50}))) + monkeypatch.setattr("services.index_service.current_slot", lambda *a: cur) + + err, board = await service.board(REGION) + + assert err is ErrorType.SUCCESS + assert len(board.ranked) == 1 + item = board.ranked[0] + assert item.active and item.score.score == 65 and item.rank == 1 + assert item.trend == [item.score] and item.slot == ("night" if cur == "early" else cur) + assert item.slots == {k: 65 for k in ("morning", "day", "evening", "night")} + assert item.slot_ranks == {k: 1 for k in item.slots} def _om_row(at, **over): diff --git a/backend/tests/test_index_calc.py b/backend/tests/test_index_calc.py index 3ea3c38..6f6f267 100644 --- a/backend/tests/test_index_calc.py +++ b/backend/tests/test_index_calc.py @@ -38,6 +38,22 @@ def test_perfect_evening_scores_100(): assert r.notes["temp"] == "체감 21°, 편한 범위 18~24° 안" +@pytest.mark.parametrize("weight", [5, 10, 20]) +def test_time_match_adds_only_its_weight_without_extra_penalty(weight): + rules = _defn().factor_rules | {"time": {"type": "fixed", "value": 55}} + defn = _defn(weight_temp=100 - weight, weight_rain=0, weight_wind=0, weight_humidity=0, weight_air=0, + weight_time=weight, factor_rules=rules) + hours = [[_h(12)]] + matched = evaluate(defn, hours, replace(CTX, time_matches=True)) + unmatched = evaluate(defn, hours, replace(CTX, time_matches=False)) + assert matched.factors["time"] == 100 and unmatched.factors["time"] == 0 + assert matched.score == 100 and unmatched.score == 100 - weight + + +def test_time_matching_does_not_replace_weekday_score(): + assert evaluate(_defn(), [[_h(12)]], replace(CTX, time_matches=False)).factors["time"] == 100 + + def test_good_but_not_perfect_stays_below_100(): assert evaluate(_defn(), [[_h(19, feels=23, hum=58, wind=1.8)]], CTX).score < 95 diff --git a/docs/서비스_동작_안내.md b/docs/서비스_동작_안내.md index 036b5fe..d86633d 100644 --- a/docs/서비스_동작_안내.md +++ b/docs/서비스_동작_안내.md @@ -175,16 +175,16 @@ ### 2-7. 각 점수 (오늘의 각 34개) - **식은 2-2~2-4와 같습니다.** 각마다 요소별 비중, 방식(2-3), 조건, 하기 좋은 시간대가 다릅니다. 34개 각의 시간대와 주요 비중은 [부록](#부록-각-34개-한눈에-보기)에 있습니다. -- **오늘 점수 = 지금 구간 점수.** 각의 시간대 중 지금 구간에 드는 시간만 골라 계산합니다. 예: 오후 5시(저녁 구간)의 야장각(18~24시)은 18시대만 봅니다. -- 각의 시간대가 지금 구간과 겹치지 않으면(예: 아침의 야장각) 순위, 피드 카드, 맨 위 1위에서 빠집니다. 각 탭 전체 목록에는 맨 뒤에 '지금 아님'으로, 하루 점수와 함께 남습니다. -- **하루 점수**(내일·토·일 칸, '지금 아님' 각): 각의 시간대 전체로 계산한 점수입니다. +- **오늘 점수 = 지금 구간 점수.** 지금 구간의 날씨로 계산하며, 현재 구간은 이미 지난 시각을 제외합니다. +- 각의 시간대가 지금 구간과 겹치지 않아도 현재 구간의 날씨 점수로 활성화하고 순위, 피드 카드, 맨 위 1위 후보에 포함합니다. 시간대 미리보기도 각 구간의 날씨로 계산합니다. 제철이 아닌 각의 비활성화는 유지합니다. +- **하루 점수**(내일·토·일 칸): 각의 시간대 전체로 계산한 점수입니다. - **햇빛·자외선·가시거리:** 10개 각(피크닉, 등산, 세차, 별보기, 빨래, 자전거, 가드닝, 사진산책, 드라이브, 물놀이)은 이 요소도 봅니다. 모두 2-3의 ② 방식입니다. - **'시간' 요소**는 날씨가 아닌 것을 넣는 칸입니다. | 종류 | 식 | 쓰는 각 | |---|---|---| | 요일 | 요일·공휴일마다 정한 점수 | 19개 | -| 고정 | 정한 점수 하나 | 13개 | +| 시간대 알맞음 | 활동 시간대와 겹치면 100점, 아니면 0점. 가중치 10%라면 10점 또는 0점 반영(불일치 추가 감점 없음) | fixed 유형 | | 달 | 20 + 80 × (1 − 달이 비추는 정도). 달이 비추는 정도 = 달의 빛나는 면 × 21~26시 중 달이 떠 있는 비율 | 별보기각 | | 노을 | 그날 노을 점수 (2-9) | 사진산책각 | diff --git a/docs/점수_계산식.md b/docs/점수_계산식.md index 0c54fb9..fe2b072 100644 --- a/docs/점수_계산식.md +++ b/docs/점수_계산식.md @@ -86,9 +86,10 @@ ## 4. 각 점수 - 1의 방식. 요소·비중·시간대·0점 조건은 각마다 다르며 [각_계산기준.md](각_계산기준.md)에 있습니다. -- **오늘 점수 = 지금 구간 점수.** 각의 시간대 중 지금 구간에 드는 시각만으로 계산합니다(시간대가 여러 개면 그중 가장 좋은 쪽). 비가 오면 그 뒤 구간 점수가 내려갑니다. -- 각의 시간대가 지금 구간과 겹치지 않으면(예: 아침의 야장각) **순위·피드 카드·히어로 1위에서 빠집니다.** 스토리·각 탭 '전체'에는 맨 뒤에 '지금 아님'으로 남고, 점수는 하루 점수(가장 좋은 시간대)입니다. -- 각 상세 창에 오늘 아침·낮·저녁·밤 점수를 보여 줍니다. 안 겹치는 구간은 '–'. +- **오늘 점수 = 지금 구간 점수.** 지금 구간의 날씨로 계산하며, 현재 구간은 이미 지난 시각을 제외합니다. 비가 오면 그 뒤 구간 점수가 내려갑니다. +- 각의 시간대가 지금 구간과 겹치지 않아도 **현재 구간의 날씨 점수로 활성화하고 순위·피드 카드·히어로 1위 후보에 포함합니다.** 제철이 아닌 각의 비활성화는 유지합니다. +- **시간대 알맞음:** 활동 시간대와 겹치면 요소 점수 100점, 아니면 0점입니다. 가중치가 10%라면 10점 또는 0점을 반영하고, 불일치에 따른 추가 최저 요소 감점은 없습니다. 요일·달·노을·일출 요소는 기존 계산을 유지합니다. +- 각 상세 창과 시간대 미리보기의 아침·낮·저녁·밤 점수도 각 구간의 날씨로 계산하며 하루 점수로 대체하지 않습니다. - 내일·토·일 칸은 하루 점수(가장 좋은 시간대)입니다. - 순위는 점수 × 중요도(상 1.0 · 중 0.85 · 하 0.7). 화면 숫자는 점수 그대로입니다. - 단기예보가 닿지 않는 날(토·일 등)은 중기예보의 최저·최고 기온으로 시각별 기온을 어림하고(새벽 6시 최저, 오후 3시 최고, 코사인 곡선), 바람·습도·미세먼지는 정보 없음으로 둔 '예상 점수'입니다. diff --git a/docs/피드_동작방식.md b/docs/피드_동작방식.md index 1a752ed..f2c6a80 100644 --- a/docs/피드_동작방식.md +++ b/docs/피드_동작방식.md @@ -107,13 +107,13 @@ - 각 점수와 순위 자체는 새 예보·미세먼지가 들어올 때 다시 계산되므로(하루 8번 예보 + 매시 미세먼지), 그때 캐시가 끝나면 1·2·3위가 바뀔 수 있다. **히어로·띠의 순서** -- 오늘의 각 줄(34개): 지금 구간(아침·낮·저녁·밤) 점수 높은 순. 각 시간대가 지금 구간과 안 겹치는 각은 맨 뒤에 '지금 아님'으로. -- 띠의 각 순위(5개)·피드 각 카드 1~3위·히어로 1위 각: 지금 구간에 해당하는 각만, 지금 구간 점수 순. +- 오늘의 각 줄(34개): 지금 구간(아침·낮·저녁·밤)의 날씨 점수로 순위를 매깁니다. 시간대 알맞음은 활동 시간대와 겹치면 가중치만큼, 아니면 0점을 반영합니다. 제철이 아닌 각은 비활성화합니다. +- 띠의 각 순위(5개)·피드 각 카드 1~3위·히어로 1위 각: 제철인 각을 시간대와 관계없이 포함하고, 지금 구간 점수로 순위를 매깁니다. - 띠의 행사: 30km 안 행사 중 시작일이 오늘과 가까운 순(같으면 가까운 거리 순) 4개. 계절 소식: 이번 주 글. ### 같이 만드는 것 - 히어로: 지금 날씨 점수, 아래 네 칸(지금 기온·습도·불쾌지수·챙길 것 한 칸), 1위 각, 말풍선, 오늘 밤 달 모양·잘 보이는지 -- 오늘의 각 줄: 34개 이름·점수·순위 (지금 구간에 안 맞는 각은 '지금 아님') +- 오늘의 각 줄: 34개 이름·점수·순위 (시간대와 관계없이 활성화, 각 구간의 날씨·시간대 적합도로 계산) - 띠: 행사 4개, 각 순위 5개, 계절 소식 ## 3. 저장과 갱신 diff --git a/frontend/src/b/Sheets.tsx b/frontend/src/b/Sheets.tsx index 4a93525..8044ecb 100644 --- a/frontend/src/b/Sheets.tsx +++ b/frontend/src/b/Sheets.tsx @@ -354,7 +354,7 @@ function GakSheet({ indexId, onTitle }: { indexId: number; onTitle: (t: string) {g.score} - {!g.active &&

지금 시간대엔 해당 없어요. 점수는 오늘 가장 좋은 시간대 기준이에요.

} + {!g.active &&

지금은 제철이 아니에요. 점수는 오늘 가장 좋은 시간대 기준이에요.

} {now && (

{now.low}~{now.high}점 diff --git a/frontend/src/b/TodayPage.tsx b/frontend/src/b/TodayPage.tsx index 3be96ae..f1f3352 100644 --- a/frontend/src/b/TodayPage.tsx +++ b/frontend/src/b/TodayPage.tsx @@ -67,7 +67,7 @@ const failed = (load: Load) => load === 'error' || load === 'retrying' // 미리보기 탭과 서버 구간 이름. 저녁 탭(노을 하늘)은 서버의 evening 구간 const SLOT_KEY: Record = { morning: 'morning', day: 'day', sunset: 'evening', night: 'night' } -/** 미리보기 시간대면 이미 받은 구간 점수·순위로 다시 줄 세운다. 그 구간과 안 겹치는 각은 흐리게 끝으로. 구간 값이 없으면(예전 캐시) 그대로 */ +/** 미리보기 시간대면 서버가 해당 구간의 날씨·시간대 적합도로 계산한 점수·순위로 다시 줄 세운다. 구간 값이 없으면(예전 캐시) 그대로 */ function atSlot(items: TopIndex[], kind: TimeKind | null): TopIndex[] { const k = kind && SLOT_KEY[kind] if (!k || !items.some((g) => Object.keys(g.slot_ranks ?? {}).length)) return items