Compare commits

...
19 Commits
Author SHA1 Message Date
minaChoi e30f41de68 chore: main 병합 — 단풍·띠 좋아요, 밀림 수정, 글 주제·사진 Blob, 애드센스 2026-10-23 15:29:15 +09:00
minaChoi 3cb58b9f0f feat: 작업 중이던 변경 반영 — 글 주제(동네 이야기·하늘·비·단풍·옷차림)와 주제별 묶음을 피드 사이사이에, 이야기 페이지(/talk), 애드센스 코드·ads.txt·개인정보처리방침, 사진 검증을 Blob 주소까지 2026-10-23 15:06:21 +09:00
minaChoi 1393fc465c feat: 글 사진을 Azure Blob에 올리기(접속 문자열 또는 컨테이너 주소+SAS, nalssigak/talk 아래). 설정이 없으면 지금처럼 서버 폴더에 저장 2026-10-23 15:06:21 +09:00
skkim 0edb7059c8 feat: 주말 나들이 점수를 평균 60 정규분포로 보정, 지금 날씨·나들이 점수 100점은 완벽한 날만
- 나들이 점수(주말 전국 순위·당일치기)에 지금 날씨 점수와 같은 방식의 바꾸기 표를 적용: 원래 점수를 1년 치 분포의 순위로 보고 평균 60·표준편차 15 정규분포 점수로 바꿈 (weekend_rank.py, outing_score_table.json, scripts/gen_outing_score_table.py)
- 나들이 점수 만점 조건을 엄격하게: 체감온도 최적 21°±0.5°, 바람 초속 1m 이하일 때만 100점 (같은 예보를 받는 여러 지역이 한꺼번에 100점이 되던 것을 줄임)
- 표 맨 위가 100으로 잘려 비슷한 원래 점수(96·97·99)가 모두 100점이 되던 것을 막기 위해 straighten_top 추가: 표시 점수 83 이하인 마지막 원래 점수에서 100점까지 직선으로 이어, 100점은 구간에서 나올 수 있는 가장 높은 원래 점수(밤은 85)일 때만 나옴. 지금 날씨 점수 표도 다시 만듦 (90점 이상 약 2.4% → 1.5%)
- 당일치기 최소 점수는 원래 50점과 같은 날씨 수준(표시 62점)으로 옮김
- 주말 순위 캐시 키를 weekend_rank:v2:<날짜>로 올려 옛 점수 캐시를 쓰지 않게 함
- 테스트 추가: test_outing_score_table, test_weather_score_table(straighten_top·100점 조건)
- docs/점수_계산식.md의 지금 날씨 점수·나들이 점수 항목을 새 기준과 숫자로 갱신
2026-10-23 15:02:09 +09:00
minaChoi 03e54ad552 feat: 단풍 지도·이번 주 행사 띠·계절 이야기 띠에 좋아요·댓글(서버 포스트 자리 18·19·20), 히어로 아래 글자 칸 높이를 미리 잡아 오늘의 각부터 피드가 밀려 내려가던 문제 수정 2026-10-23 14:53:59 +09:00
minaChoi b2470d80ed chore: main 병합 — 점수 근거 버튼·지금 상태 2026-10-23 11:54:40 +09:00
minaChoi eb84a72c2f feat: 날씨 점수 근거 버튼을 구름에 가리던 해 구석 '?'에서 상태 줄 끝 '점수 근거 ›'로(해를 눌러도 열림), 근거 창에 지금 상태(습도·불쾌지수·자외선·미세먼지) 실제 값과 기준 추가 2026-10-23 11:14:56 +09:00
minaChoi fdd2200ae2 chore: main 병합 — 단풍 지도 페이지·검수 반영 2026-10-23 10:59:41 +09:00
minaChoi 1888dd6cf3 feat: 단풍 지도 디자인 검수 반영 — 카드 2장(지도·순위), 라벨 눌러 고르기, 엑스 없앤 선택 줄, 명소마다 공유 이미지, 시·도 이름, 밤 화면 글자, 확대할수록 이름 2026-10-23 10:44:01 +09:00
minaChoi d75144a6ac feat: 단풍 지도 페이지(/foliage) — 카드는 절정만 잎 아이콘, 누르면 페이지에서 확대·이동·목록, 확대할수록 이름 더, 뒤로 가면 피드 위치 그대로 2026-10-23 09:49:43 +09:00
minaChoi 446af2e9b5 fix: 단풍 지도 점이 빽빽해 보이던 문제 — 절정만 테두리 점으로 띄우고 나머지는 작은 점으로, 지도를 누르면 가장 가까운 명소가 열리게 2026-10-23 09:22:23 +09:00
minaChoi 9a75b02d1a fix: 단풍 지도에서 겹쳐 안 보이고 못 누르던 점 — 겹친 점을 서로 밀어 65곳 모두 보이고 눌리게 2026-10-23 09:16:53 +09:00
skkim d5f8b148b4 fix: 각 점수에 중요도 배율을 반영해 화면 점수와 순위를 일치시킴 2026-10-23 09:14:52 +09:00
minaChoi 199e834227 feat: 단풍 지도 제목을 '지금 절정: 시·도'로, 보여 주는 기간을 명소 절정일에 맞춰(첫 단풍 시작~마지막 절정 7일 뒤) 2026-10-23 09:13:12 +09:00
minaChoi 1306c43740 fix: 단풍 지도 이름표를 눌러도 명소 정보가 나오게 2026-10-23 09:07:51 +09:00
minaChoi 8ca38f1806 feat: 단풍 지도를 점으로 — 단계별 점 색, 절정 단풍은 이름표(겹치면 생략), 지도 색 옅게, 절정 7일 뒤부터는 회색 2026-10-23 08:54:07 +09:00
skkim 621a0cf90d chore: main 병합 — 지금 날씨 점수 보정을 바꾸기 표로 통일
- index_service.py 충돌: main 의 오늘·내일 날씨 점수 계산은 그대로 쓰고, 보정만 strict_weather 에서 구간별 바꾸기 표(weather_slot_scores)로 바꿈
- weather_slot_scores 는 main 의 weather_why 가 쓰는 점수 근거(factors)를 그대로 둔 Result 를 돌려줌
- strict_weather 와 그 테스트(test_weather_score_is_strict_near_top) 삭제 (바꾸기 표로 통일하기로 정함)
- test_board_activates_gak_outside_its_time_window 의 ensure 스텁을 main 의 {날짜: {구간: Result}} 모양으로 맞춤
2026-10-22 13:58:36 +09:00
skkim 799a46f53c fix: 각을 시간대와 관계없이 활성화하고 시간 적합도를 가중치로 반영 2026-10-22 13:38:39 +09:00
skkim 3b5afba8a1 feat: 지금 날씨 점수를 평균 60 정규분포로 (가장 낮은 요소로 깎기 제거, 구간별 바꾸기 표, 90점 이상 약 2.4%)
- 지금 날씨 점수는 '가장 낮은 요소로 깎기'를 하지 않는다 (밤엔 해 난 비율이 늘 0점이라 밤 점수가 62점을 못 넘었음). 각 점수는 그대로
- 원래 점수를 구간(아침·낮·저녁·밤)마다 1년 치 분포의 순위로 보고 평균 60·표준편차 15 정규분포 점수로 바꿔 보여 준다
- 바꾸기 표는 scripts/gen_weather_score_table.py 가 Open-Meteo 과거 예보로 만든다 (weather_score_table.json)
2026-10-22 13:33:50 +09:00
61 changed files with 3036 additions and 344 deletions

No files matched your search

+25
View File
@@ -0,0 +1,25 @@
# Product
<!-- impeccable:product-schema 1 -->
## Platform
web
## Users
휴대폰으로 오늘·내일 뭘 할지 정하려는 2040 일반인. 아침이나 외출 전에 잠깐 열어 봐요.
## Product Purpose
동네(구) 날씨를 '빨래각·소맥각' 같은 활동 점수로 바꿔 보여 줘요. 피드로 훑어보고 친구에게 보내요.
## Positioning
날씨 숫자가 아니라 '지금 ○○하기 좋은지'를 알려 주고, 귀엽고 공유하고 싶은 카드로 보여 줘요.
## Constraints
- 모바일 웹 우선(토스 미니앱, 홈 화면 추가).
- 로그인은 글쓰기에만 요구해요.
- 화면 문구는 반말 없는 '해요'체예요.
+3
View File
@@ -66,6 +66,9 @@
| [ ] | '○○구 내일 날씨' 검색 태깅 — 스위치 뒤 내용은 눌러야 보여 구글이 읽는지 공식 문서로 확인 필요. 구 페이지(SEO)에 내일 기온·습도 넣는 안과 비교 | 10/21 회의 결정 | `backend/router/v1/seo/` |
| [x] | **운영 DB 반영(10/21 배포 때 init.sql로 적용 확인)** — 댓글 표 `user_id` NULL 허용, `ip_hash`·`region_name` 칸, `idx_comment_ip` (init.sql에 추가, 로컬만 적용). 배포 전에 운영에 ALTER 실행 (운영 영향, 확인 받고) | 익명 댓글 | `backend/postgres-init/init.sql` |
| [ ] | **[결정 필요]** 새 화면 문구 검토: '보냈어요. 링크도 복사해 뒀어요', '글쓰기는 로그인한 뒤에 할 수 있어요.', '오늘'/'내일', '내일 낮 날씨 점수', '내일은 ○○각!'/'내일은 쉬어 가요', '최저'/'최고'/'습도', 익명 이름 '마포구 익명', 단풍 지도 '단풍 전'/'첫 단풍'/'절정'/'단풍'/'은행', '가까운 예측 지점 날짜예요', '지금 절정 ○곳: … 외' | 화면 문구 규칙 | `frontend/src/b/TodayPage.tsx`, `frontend/src/b/Sheets.tsx` |
| [ ] | 단풍 지도 페이지(`/foliage`) 검색 등록 — 사이트맵 추가, 미리 그린 HTML(제목·설명), 공식 문서로 확인 후 | 페이지 따로 만든 이유(공유·검색), 사용자 10/23 | `backend/services/seo_service.py`, `frontend/src/b/FoliagePage.tsx` |
| [ ] | 단풍 지도 그림 고해상도로 다시(지금 1024px라 확대하면 흐림) — Codex | 단풍 지도 페이지 확대 | `frontend/public/foliage/korea-map.webp` |
| [ ] | **[결정 필요]** 단풍 지도 페이지 문구: '단풍 절정'/'은행 절정', '지도 크게 보기 ›', '지금 절정'/'곧 절정'/'아직'/'절정 지남', '전체'/'단풍'/'은행', '절정 예상'/'가까운 지점 날짜', '링크를 복사했어요' | 화면 문구 규칙 | `frontend/src/b/FoliagePage.tsx`, `frontend/src/b/foliageMap.tsx` |
| [ ] | 익명 댓글이 링크·하루 제한에 걸려도 '댓글을 올리지 못했어요'만 나옴 — 이유별 안내 | 익명 댓글 작업 중 발견 | `frontend/src/b/Sheets.tsx` |
| [ ] | 매일 대표에게 진행 보고 (미완료 포함) | 10/21 회의 결정 | |
+1
View File
@@ -401,6 +401,7 @@ class Talk(Base):
body: Mapped[str] = mapped_column(String(100))
weather: Mapped[Optional[str]] = mapped_column(String(30), nullable=True)
image: Mapped[Optional[str]] = mapped_column(String(200), nullable=True)
topic: Mapped[int] = mapped_column(SmallInteger, default=1)
like_count: Mapped[int] = mapped_column(Integer, default=0)
report_count: Mapped[int] = mapped_column(Integer, default=0)
hidden: Mapped[bool] = mapped_column(Boolean, default=False)
+13
View File
@@ -115,6 +115,16 @@ class IndexCategory(CodeEnum):
LIFE = 4
class TalkTopic(CodeEnum):
"""사람 글 주제. 안 고르면 동네 이야기. 피드에서 같은 주제 포스트 옆에 묶어 보여 준다"""
LOCAL = 1 # 동네 이야기
SKY = 2 # 하늘·노을
RAIN = 3 # 비·눈
FOLIAGE = 4 # 단풍·꽃
OUTFIT = 5 # 오늘 옷차림
class TalkReport(CodeEnum):
ABUSE = 1 # 욕설·비하
SPAM = 2 # 광고·도배
@@ -147,6 +157,9 @@ class PostType(CodeEnum):
UV = 15 # 오늘 낮 자외선 (아침·낮, '보통' 이상인 날만)
HERO = 16 # 히어로(오늘 날씨)의 좋아요·댓글 자리. 피드 목록엔 안 나온다
TODAY_GAK = 17 # 오늘의 각 카드의 좋아요·댓글 자리. 피드 목록엔 안 나온다
FOLIAGE = 18 # 단풍 지도 카드의 좋아요·댓글 자리. 피드 목록엔 안 나온다
EVENTS_BAND = 19 # 이번 주 가까운 행사 띠의 좋아요·댓글 자리
SEASON_BAND = 20 # 이번 주 계절 이야기 띠의 좋아요·댓글 자리
class EventKind(CodeEnum):
+7
View File
@@ -36,6 +36,13 @@ class Settings(BaseSettings):
# 사람 글 사진을 저장할 폴더 (compose 볼륨)
upload_dir: str = "uploads"
# 사람 글 사진을 올릴 Azure Blob. 접속 문자열이 비면 위 폴더에 저장한다
azure_storage_connection_string: str = ""
azure_storage_container: str = ""
azure_storage_prefix: str = "nalssigak"
# 접속 문자열 대신 컨테이너 주소 + SAS 토큰으로도 올릴 수 있다
azure_blob_base_url: str = ""
azure_blob_sas_token: str = ""
# 구글 로그인 OAuth 클라이언트 ID (공개값). 비면 구글 로그인을 받지 않는다
google_client_id: str = ""
+3 -2
View File
@@ -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
+20 -3
View File
@@ -13,7 +13,8 @@ from crud.reaction_crud import toggle_like_row
class TalkCRUD:
async def page(
self, s: AsyncSession, viewer: Optional[uuid.UUID], sido: Optional[str], boost_sec: int, cursor: Optional[tuple[int, int]], limit: int
self, s: AsyncSession, viewer: Optional[uuid.UUID], sido: Optional[str], boost_sec: int, cursor: Optional[tuple[int, int]], limit: int,
topic: Optional[int] = None,
) -> list[tuple[Talk, User, Optional[str], int]]:
"""최신 글부터. 보는 사람과 같은 시도 글은 boost_sec 만큼 늦게 쓴 것처럼 앞에 둔다. 숨김·지운 글과 내가 안 보기로 한 사람의 글은 뺀다.
cursor 는 앞 페이지 마지막 글의 (정렬 키, talk_id)."""
@@ -28,10 +29,24 @@ class TalkCRUD:
)
if viewer is not None:
stmt = stmt.where(Talk.user_id.not_in(select(UserBlock.blocked_id).where(UserBlock.user_id == viewer)))
if topic is not None:
stmt = stmt.where(Talk.topic == topic)
if cursor is not None:
stmt = stmt.where(tuple_(key, Talk.talk_id) < tuple_(*cursor))
return list((await s.execute(stmt.order_by(key.desc(), Talk.talk_id.desc()).limit(limit))).all())
async def recent(self, s: AsyncSession, viewer: Optional[uuid.UUID], since: datetime, limit: int) -> list[tuple[Talk, User, Optional[str]]]:
"""since 뒤에 쓴 글 최신순 (숨김·지운 글, 내가 안 보기로 한 사람 글 빼고). 피드 묶음을 고를 재료"""
stmt = (
select(Talk, User, Region.short_name)
.join(User, User.user_id == Talk.user_id)
.outerjoin(Region, Region.code == Talk.region_code)
.where(Talk.deleted.is_(False), Talk.hidden.is_(False), User.deleted.is_(False), Talk.created_at >= since)
)
if viewer is not None:
stmt = stmt.where(Talk.user_id.not_in(select(UserBlock.blocked_id).where(UserBlock.user_id == viewer)))
return list((await s.execute(stmt.order_by(Talk.created_at.desc()).limit(limit))).all())
async def mine(self, s: AsyncSession, user_id: uuid.UUID, cursor: Optional[int], limit: int) -> list[tuple[Talk, Optional[str]]]:
"""내가 쓴 글, 최신부터. 신고로 숨겨진 글도 쓴 사람에겐 보인다."""
stmt = select(Talk, Region.short_name).outerjoin(Region, Region.code == Talk.region_code).where(Talk.user_id == user_id, Talk.deleted.is_(False))
@@ -48,8 +63,10 @@ class TalkCRUD:
async def count_since(self, s: AsyncSession, user_id: uuid.UUID, since: datetime) -> int:
return await s.scalar(select(func.count()).select_from(Talk).where(Talk.user_id == user_id, Talk.created_at >= since))
async def add(self, s: AsyncSession, user_id: uuid.UUID, region_code: str, body: str, weather: Optional[str], image: Optional[str] = None) -> Talk:
t = Talk(user_id=user_id, region_code=region_code, body=body, weather=weather, image=image)
async def add(
self, s: AsyncSession, user_id: uuid.UUID, region_code: str, body: str, weather: Optional[str], image: Optional[str] = None, topic: int = 1
) -> Talk:
t = Talk(user_id=user_id, region_code=region_code, body=body, weather=weather, image=image, topic=topic)
s.add(t)
await s.flush()
await s.refresh(t)
+3
View File
@@ -294,6 +294,9 @@ CREATE TABLE IF NOT EXISTS public.talk (
);
CREATE INDEX IF NOT EXISTS idx_talk_list ON public.talk (talk_id DESC) WHERE deleted = FALSE AND hidden = FALSE;
CREATE INDEX IF NOT EXISTS idx_talk_user_day ON public.talk (user_id, created_at);
-- 글 주제 (TalkTopic: 1 동네 이야기, 2 하늘·노을, 3 비·눈, 4 단풍·꽃, 5 오늘 옷차림)
ALTER TABLE public.talk ADD COLUMN IF NOT EXISTS topic SMALLINT NOT NULL DEFAULT 1;
CREATE INDEX IF NOT EXISTS idx_talk_recent ON public.talk (created_at DESC) WHERE deleted = FALSE AND hidden = FALSE;
CREATE TABLE IF NOT EXISTS public.talk_like (
talk_id BIGINT NOT NULL,
+1
View File
@@ -14,3 +14,4 @@ python-jose[cryptography]
bcrypt
python-multipart
Pillow
azure-storage-blob
+1 -1
View File
@@ -22,7 +22,7 @@ async def get_feed(
err, feed = await service.feed(region)
if err is not ErrorType.SUCCESS:
return Res_Feed(result=error_info(err))
pinned = [x for x in (feed.hero_post, feed.gak_post) if x is not None]
pinned = [x for x in (feed.hero_post, feed.gak_post, feed.foliage_post, feed.events_post, feed.season_post) if x is not None]
ids = [p.post_id for p in feed.posts] + [x.post_id for x in pinned]
counts = await reactions.counts(ids)
liked, saved = await reactions.marks(user, ids)
+7 -3
View File
@@ -86,7 +86,7 @@ class WeekDay(WebPacketProtocol):
temp_min_c: Optional[float] = None
temp_max_c: Optional[float] = None
rain_prob: Optional[int] = None
gaks: list[WeekGak] = Field(default_factory=list, description="그날 대표 각 (점수 × 중요도 순 3개). 각 점수가 아직 없는 날은 비어 있음")
gaks: list[WeekGak] = Field(default_factory=list, description="그날 대표 각 (중요도 배율을 반영한 최종 표시 점수 내림차순 3개, 동점이면 중요도 순). 각 점수가 아직 없는 날은 비어 있음")
class WeekSlide(WebPacketProtocol):
@@ -137,7 +137,7 @@ class PostData(WebPacketProtocol):
class PostReaction(WebPacketProtocol):
"""포스트 틀이 아닌 카드(히어로·오늘의 각)에 붙는 좋아요·댓글."""
"""포스트 틀이 아닌 카드(히어로·오늘의 각·단풍 지도·띠)에 붙는 좋아요·댓글."""
post_id: int
like_count: int
comment_count: int
@@ -154,7 +154,7 @@ class TopIndex(WebPacketProtocol):
summary: Optional[str] = None
active: bool = Field(default=True, description="지금 구간이 이 각의 시간대와 겹침. false 면 순위 밖, score 는 하루 점수")
slots: dict[str, int] = Field(default_factory=dict, description="오늘 구간별 점수 {morning·day·evening·night: 점수}. 각 시간대와 안 겹치는 구간은 없음")
slot_ranks: dict[str, int] = Field(default_factory=dict, description="오늘 구간별 순위 (점수 × 중요도 가중치). 각 시간대와 안 겹치는 구간은 없음")
slot_ranks: dict[str, int] = Field(default_factory=dict, description="오늘 구간별 순위 (중요도 배율을 반영한 최종 표시 점수 내림차순, 동점이면 중요도 순)")
class HeroStat(WebPacketProtocol):
@@ -162,6 +162,7 @@ class HeroStat(WebPacketProtocol):
label: str
value: str
tone: Literal["normal", "warn", "rain"] = Field(description="normal=기본, warn=조심(노랑), rain=비(파랑)")
detail: Optional[str] = Field(default=None, description="단계 이름 밑의 실제 값 (예: 68%, 72, 2, 초미세먼지 15㎍/㎥). 상태 줄에만")
class WeatherWhy(WebPacketProtocol):
@@ -234,6 +235,9 @@ class Res_Feed(Res_WebPacketProtocol):
posts: list[PostData] = []
hero_post: Optional[PostReaction] = None
gak_post: Optional[PostReaction] = None
foliage_post: Optional[PostReaction] = None
events_post: Optional[PostReaction] = None
season_post: Optional[PostReaction] = None
bands: Optional[Bands] = None
+12 -1
View File
@@ -3,7 +3,7 @@ from typing import Optional
from pydantic import Field
from common.enums import TalkReport
from common.enums import TalkReport, TalkTopic
from common.models.gmodel import Req_WebPacketProtocol, Res_WebPacketProtocol, WebPacketProtocol
@@ -17,6 +17,7 @@ class TalkData(WebPacketProtocol):
weather: Optional[str] = Field(None, description="쓸 때 그 동네 날씨 (18° 맑음)")
body: str
image: Optional[str] = Field(None, description="올린 사진 주소")
topic: TalkTopic = TalkTopic.LOCAL
like_count: int
liked: bool
mine: bool
@@ -27,6 +28,7 @@ class Req_Talk(Req_WebPacketProtocol):
region_code: str = Field(min_length=10, max_length=10)
body: str = Field(min_length=1, max_length=200, description="공백을 줄인 뒤 100자까지")
image: Optional[str] = Field(None, max_length=200, description="먼저 올린 사진 주소 (POST /v1/talk/image 결과)")
topic: TalkTopic = Field(TalkTopic.LOCAL, description="글 주제. 안 고르면 동네 이야기")
class Req_TalkReport(Req_WebPacketProtocol):
@@ -38,6 +40,15 @@ class Res_TalkList(Res_WebPacketProtocol):
next_cursor: Optional[str] = Field(None, description="다음 페이지를 받을 때 그대로 cursor 로 보낸다")
class TalkGroup(WebPacketProtocol):
topic: int = Field(description="0 이면 '동네 사람들'(모든 주제), 아니면 TalkTopic")
talks: list[TalkData] = []
class Res_TalkGroups(Res_WebPacketProtocol):
groups: list[TalkGroup] = Field([], description="동네 사람들 묶음은 늘 있고(비어 있을 수 있음), 주제 묶음은 3장 이상일 때만")
class Res_Talk(Res_WebPacketProtocol):
talk: Optional[TalkData] = None
+19 -5
View File
@@ -7,12 +7,12 @@ from fastapi.responses import FileResponse
from common.auth import current_user, optional_user
from common.database.model.models import User
from common.enums import ErrorType
from common.enums import ErrorType, TalkTopic
from common.liker import Liker, liker
from common.models.errors import error_info
from common.models.gmodel import Res_WebPacketProtocol
from common.utils.kma_time import KST
from router.v1.talk.protocol import Req_Talk, Req_TalkReport, Res_Talk, Res_TalkImage, Res_TalkLike, Res_TalkList, TalkData
from router.v1.talk.protocol import Req_Talk, Req_TalkReport, Res_Talk, Res_TalkGroups, Res_TalkImage, Res_TalkLike, Res_TalkList, TalkData, TalkGroup
from services.talk_image import MAX_BYTES, URL_PREFIX, file_of, save
from services.talk_service import TalkService, TalkView
@@ -23,19 +23,33 @@ def _data(v: TalkView) -> TalkData:
t, u = v.talk, v.author
return TalkData(
talk_id=t.talk_id, nickname=u.nickname, character=u.character, color=u.color, mood=u.mood, region_name=v.region_name, weather=t.weather,
body=t.body, image=t.image, like_count=t.like_count, liked=v.liked, mine=v.mine, created_at=t.created_at.astimezone(KST),
body=t.body, image=t.image, topic=TalkTopic(t.topic), like_count=t.like_count, liked=v.liked, mine=v.mine, created_at=t.created_at.astimezone(KST),
)
@router.get("/groups", response_model=Res_TalkGroups, response_model_exclude_none=True, summary="오늘 피드 묶음 (동네 사람들 + 주제별, 가까운 동네·덜 지난 글 먼저, 한 사람 한 장)")
async def talk_groups(
region: Optional[str] = Query(None, min_length=10, max_length=10, description="보는 사람의 구 행정코드"),
user: Optional[User] = Depends(optional_user),
who: Liker = Depends(liker),
service: TalkService = Depends(),
) -> Res_TalkGroups:
err, groups = await service.groups(user, who.ip_hash, region)
if err is not ErrorType.SUCCESS:
return Res_TalkGroups(result=error_info(err))
return Res_TalkGroups(groups=[TalkGroup(topic=k, talks=[_data(v) for v in vs]) for k, vs in groups.items()])
@router.get("/list", response_model=Res_TalkList, response_model_exclude_none=True, summary="동네 이야기 (전국 최신순, 보는 동네와 같은 시도 글은 앞으로, 같은 사람 글은 띄움, 로그인 없이 보기)")
async def list_talks(
region: Optional[str] = Query(None, min_length=10, max_length=10, description="보는 사람의 구 행정코드"),
topic: Optional[TalkTopic] = Query(None, description="이 주제 글만. 없으면 전체"),
cursor: Optional[str] = Query(None, max_length=40),
user: Optional[User] = Depends(optional_user),
who: Liker = Depends(liker),
service: TalkService = Depends(),
) -> Res_TalkList:
err, views, nxt = await service.page(user, who.ip_hash, region, cursor)
err, views, nxt = await service.page(user, who.ip_hash, region, cursor, topic.value if topic else None)
if err is not ErrorType.SUCCESS:
return Res_TalkList(result=error_info(err))
return Res_TalkList(talks=[_data(v) for v in views], next_cursor=nxt)
@@ -53,7 +67,7 @@ async def list_my_talks(cursor: Optional[str] = Query(None, max_length=20), user
@router.post("", response_model=Res_Talk, response_model_exclude_none=True, summary="동네 이야기 쓰기 (링크·전화번호 불가, 하루 5개)")
async def add_talk(req: Req_Talk, user: User = Depends(current_user), service: TalkService = Depends()) -> Res_Talk:
err, v = await service.add(user, req.region_code, req.body, req.image)
err, v = await service.add(user, req.region_code, req.body, req.image, req.topic)
return Res_Talk(result=error_info(err)) if err is not ErrorType.SUCCESS or v is None else Res_Talk(talk=_data(v))
+2 -2
View File
@@ -5,7 +5,7 @@ import sys
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, ROOT)
from services.calc.index_calc import PRIORITY_WEIGHT, _cond # noqa: E402
from services.calc.index_calc import _cond # noqa: E402
SEED = os.path.join(ROOT, "seed", "index_definition.json")
OUT = os.path.join(os.path.dirname(ROOT), "docs", "각_계산기준.md")
@@ -109,7 +109,7 @@ def main() -> None:
P("- 시간대가 여러 개면 그중 가장 좋은 시간대 점수를 씁니다.")
P("- 미세먼지는 초미세먼지 15㎍/㎥ 이하 100점 → 75㎍/㎥ 이상 0점입니다. 집콕각처럼 규칙을 따로 적은 각만 거꾸로(탁할수록 좋음) 셉니다.")
P("- 바람·미세먼지·노을 정보가 없으면 70점으로 둡니다.")
P("- 순위는 점수 × 중요도 가중치(" + " · ".join(f"{PRIO[k]} {v}" for k, v in PRIORITY_WEIGHT.items()) + ")로 정합니다. 화면에 보이는 점수는 그대로입니다.\n")
P("- 최종 점수는 원점수 × 중요도 배율(상 1.0 · 중 0.85 · 하 0.7)을 정수로 반올림한 값입니다. 순위와 화면 표시 모두 이 최종 점수를 사용합니다.\n")
P("## 한눈에 보기\n")
P("| 순서 | 각 | 코드 | 분류 | 중요도 | 시간대 | 기온 | 비 | 바람 | 습도 | 미세먼지 | 시간 | 재미 각 | 계절 핵심 |")
P("|---:|---|---|---|:---:|---|---:|---:|---:|---:|---:|---:|:---:|:---:|")
+76
View File
@@ -0,0 +1,76 @@
"""나들이 점수 바꾸기 표(services/calc/outing_score_table.json)를 다시 만든다.
나들이 점수(index_calc.outing: 낮 10~17시, 기온·비·하늘·바람)의 원래 점수를 1년 치 분포의 순위로 보고,
평균 60·표준편차 15 정규분포의 같은 위치 점수로 바꾼다 (지금 날씨 점수와 같은 방식, scripts/gen_weather_score_table.py).
1년 치 날씨는 Open-Meteo 과거 예보로, region.csv 에서 8개마다 1곳(32곳)을 쓴다. 하늘은 구름양 40%·80% 이상을 구름 많음·흐림으로 본다.
나들이 점수 규칙(OUTING_*)이 바뀌면 실행: cd backend && python scripts/gen_outing_score_table.py
"""
import csv
import json
import os
import sys
import time
from datetime import date, timedelta
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from common.enums import RainType, Sky # noqa: E402
from common.logger import LOG # noqa: E402
from scripts.gen_weather_score_table import _WEATHER, DAYS, EVERY, MEAN, SIGMA, fetch, straighten_top, table # noqa: E402
from services.calc.index_calc import OUTING_HOURS, Hour, outing # noqa: E402
BACKEND = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
REGIONS = os.path.join(BACKEND, "seed", "region.csv")
OUT = os.path.join(BACKEND, "services", "calc", "outing_score_table.json")
_HOURLY = "apparent_temperature,precipitation,precipitation_probability,wind_speed_10m,cloud_cover"
def region_scores(lat: float, lon: float, start: date, end: date) -> list[int]:
"""한 지점의 날마다 나들이 점수(원래 점수). 10~17시가 모두 있는 날만."""
base = dict(latitude=lat, longitude=lon, start_date=start.isoformat(), end_date=end.isoformat(), timezone="Asia/Seoul")
w = fetch(_WEATHER, base | dict(hourly=_HOURLY, wind_speed_unit="ms"))["hourly"]
at_index = {t: i for i, t in enumerate(w["time"])}
out = []
day = start
while day <= end:
hours = []
for h in range(*OUTING_HOURS):
i = at_index.get(f"{day.isoformat()}T{h:02d}:00")
if i is None or w["apparent_temperature"][i] is None:
break
cloud = w["cloud_cover"][i] or 0
hours.append(Hour(
hour=h, feels_c=w["apparent_temperature"][i], rain_type=RainType.RAIN if (w["precipitation"][i] or 0) >= 0.1 else RainType.NONE,
rain_prob=int(w["precipitation_probability"][i] or 0), wind_ms=w["wind_speed_10m"][i], humidity=50,
sky=Sky.CLOUDY if cloud >= 80 else Sky.PARTLY if cloud >= 40 else Sky.CLEAR,
))
result = outing(hours) if len(hours) == OUTING_HOURS[1] - OUTING_HOURS[0] else None
if result is not None:
out.append(result.score)
day += timedelta(days=1)
return out
def main() -> None:
end = date.today() - timedelta(days=2)
start = end - timedelta(days=DAYS)
regions = list(csv.DictReader(open(REGIONS, encoding="utf-8")))[::EVERY]
scores: list[int] = []
for r in regions:
scores += region_scores(float(r["lat"]), float(r["lon"]), start, end)
LOG.info(f"[outing-table] {r['name']} 완료")
time.sleep(1)
doc = {
"about": f"나들이 점수 바꾸기 표: 원래 점수 0~100 → 표시 점수. 평균 {MEAN}·표준편차 {SIGMA}. scripts/gen_outing_score_table.py 가 만든다",
"period": [start.isoformat(), end.isoformat()], "regions": len(regions), "samples": len(scores),
"table": straighten_top(table(scores)), # 100점은 원래 점수 100(완벽한 날)일 때만
}
with open(OUT, "w", encoding="utf-8") as f:
json.dump(doc, f, ensure_ascii=False, indent=1)
print(len(regions), "regions", len(scores), "samples")
if __name__ == "__main__":
main()
+148
View File
@@ -0,0 +1,148 @@
"""지금 날씨 점수 바꾸기 표(services/calc/weather_score_table.json)를 다시 만든다.
지금 날씨 점수 공식(WEATHER_SCORE_DEF)으로 나온 원래 점수를 구간(아침·낮·저녁·밤)마다 1년 치 분포의 순위로 바꾼 뒤,
평균 60·표준편차 15 정규분포의 같은 위치 점수로 바꾼다. 90점 이상은 구간마다 약 2.5%가 나온다. 맨 위는 straighten_top 으로 100점이 가장 좋은 원래 점수에서만 나오게 한다.
1년 치 날씨는 Open-Meteo 과거 예보(강수확률 포함)와 대기질(초미세먼지)로, region.csv 에서 8개마다 1곳(32곳)을 쓴다.
WEATHER_SCORE_DEF 가 바뀌면 실행: cd backend && python scripts/gen_weather_score_table.py
"""
import csv
import json
import os
import sys
import time
import urllib.parse
import urllib.request
from datetime import date, datetime, timedelta
from statistics import NormalDist
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from common.enums import RainType, Sky # noqa: E402
from common.logger import LOG # noqa: E402
from services.calc.day_slot import SLOTS, slot_hours # noqa: E402
from services.calc.index_calc import Context, Hour, evaluate # noqa: E402
from services.calc.sun import sun_times # noqa: E402
from services.index_service import WEATHER_SCORE_DEF # noqa: E402
BACKEND = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
REGIONS = os.path.join(BACKEND, "seed", "region.csv")
OUT = os.path.join(BACKEND, "services", "calc", "weather_score_table.json")
MEAN, SIGMA = 60, 15
DAYS = 364
EVERY = 8
_WEATHER = "https://historical-forecast-api.open-meteo.com/v1/forecast"
_AIR = "https://air-quality-api.open-meteo.com/v1/air-quality"
_HOURLY = "apparent_temperature,precipitation,snowfall,precipitation_probability,wind_speed_10m,relative_humidity_2m,sunshine_duration,cloud_cover"
def fetch(url: str, params: dict) -> dict:
"""잠깐 막히면 쉬었다가 다시 부른다. 네 번 모두 안 되면 멈춘다."""
query = urllib.parse.urlencode(params)
for attempt in range(4):
try:
with urllib.request.urlopen(f"{url}?{query}", timeout=60) as r:
return json.load(r)
except OSError as e:
LOG.error(f"[weather-table] {url} 실패 {attempt + 1}회: {e}")
time.sleep(10 * (attempt + 1))
raise RuntimeError(f"{url} 를 받지 못함")
def region_scores(lat: float, lon: float, start: date, end: date) -> dict[str, list[int]]:
"""한 지점의 날마다 구간별 원래 점수. 앱과 같은 입력으로 맞춘다 (일조는 그 시각을 덮는 3시간 합 ÷ 3시간, 미세먼지는 구간 평균)."""
base = dict(latitude=lat, longitude=lon, start_date=start.isoformat(), end_date=(end + timedelta(days=1)).isoformat(), timezone="Asia/Seoul")
w = fetch(_WEATHER, base | dict(hourly=_HOURLY, wind_speed_unit="ms"))["hourly"]
air = fetch(_AIR, base | dict(hourly="pm2_5"))["hourly"]
pm = dict(zip(air["time"], air["pm2_5"]))
at_index = {t: i for i, t in enumerate(w["time"])}
def key(at: datetime) -> str:
return at.strftime("%Y-%m-%dT%H:%M")
def hour_at(at: datetime, h: int) -> tuple[Hour | None, float | None]:
i = at_index.get(key(at))
if i is None or w["apparent_temperature"][i] is None:
return None, None
end_at = datetime.combine(at.date(), datetime.min.time()) + timedelta(hours=(at.hour + 3) // 3 * 3)
sun = [w["sunshine_duration"][j] for j in (at_index.get(key(end_at - timedelta(hours=k))) for k in (3, 2, 1)) if j is not None and w["sunshine_duration"][j] is not None]
wet = (w["precipitation"][i] or 0) >= 0.1
cloud = w["cloud_cover"][i] or 0
return Hour(
hour=h, feels_c=w["apparent_temperature"][i],
rain_type=(RainType.SNOW if (w["snowfall"][i] or 0) > 0 else RainType.RAIN) if wet else RainType.NONE,
rain_prob=int(w["precipitation_probability"][i] or 0), wind_ms=w["wind_speed_10m"][i], humidity=int(w["relative_humidity_2m"][i]),
sky=Sky.CLOUDY if cloud >= 80 else Sky.PARTLY if cloud >= 40 else Sky.CLEAR,
sunshine_ratio=min(sum(sun) / 10800, 1.0) if len(sun) == 3 else None,
), pm.get(key(at))
out: dict[str, list[int]] = {s: [] for s in SLOTS}
day = start
while day <= end:
midnight = datetime.combine(day, datetime.min.time())
for slot, hours in slot_hours(day, sun_times(day, lat, lon).sunset_at).items():
got = [hour_at(midnight + timedelta(hours=h), h) for h in sorted(hours)]
if any(x is None for x, _ in got):
continue
pms = [p for _, p in got if p is not None]
ctx = Context(day=day, is_holiday=False, pm25=round(sum(pms) / len(pms)) if pms else None, air_label=None, moon=0, sunset_score=None,
wind_warning=False, lookahead_rain_prob=0)
r = evaluate(WEATHER_SCORE_DEF, [[x for x, _ in got]], ctx)
if r is not None:
out[slot].append(r.score)
day += timedelta(days=1)
return out
def table(scores: list[int]) -> list[int]:
"""원래 점수 0~100 각각을 '분포에서의 가운데 순위'로 정규분포 점수에 맞춘다. 순서는 그대로 (줄어들지 않게)."""
n = len(scores)
out = []
for v in range(101):
below = sum(1 for s in scores if s < v)
same = sum(1 for s in scores if s == v)
out.append(max(0, min(100, round(MEAN + SIGMA * NormalDist().inv_cdf((below + same / 2 + 0.5) / (n + 1))))))
for i in range(1, 101):
out[i] = max(out[i], out[i - 1])
return out
ANCHOR_SCORE = 83 # 위쪽 끝을 직선으로 잇기 시작하는 표시 점수
def straighten_top(t: list[int], top: int = 100) -> list[int]:
"""표 맨 위가 100으로 잘려 비슷한 원래 점수(96·97·99)가 모두 100점이 되던 것을 막는다.
표시 점수가 ANCHOR_SCORE 이하인 마지막 원래 점수에서 top(그 구간에서 나올 수 있는 가장 높은 원래 점수)의 100점까지 직선으로 잇는다.
100점은 원래 점수가 top 이상일 때만 나온다. 그 아래 점수는 바뀌지 않는다."""
anchor = max(i for i, v in enumerate(t[: top + 1]) if v <= ANCHOR_SCORE)
out = list(t)
for raw in range(anchor + 1, 101):
out[raw] = 100 if raw >= top else min(99, round(t[anchor] + (100 - t[anchor]) * (raw - anchor) / (top - anchor)))
return out
def main() -> None:
end = date.today() - timedelta(days=2)
start = end - timedelta(days=DAYS)
regions = list(csv.DictReader(open(REGIONS, encoding="utf-8")))[::EVERY]
scores: dict[str, list[int]] = {s: [] for s in SLOTS}
for r in regions:
for slot, got in region_scores(float(r["lat"]), float(r["lon"]), start, end).items():
scores[slot] += got
LOG.info(f"[weather-table] {r['name']} 완료")
time.sleep(1)
doc = {
"about": f"지금 날씨 점수 바꾸기 표: 원래 점수 0~100 → 표시 점수. 평균 {MEAN}·표준편차 {SIGMA}. scripts/gen_weather_score_table.py 가 만든다",
"period": [start.isoformat(), end.isoformat()], "regions": len(regions), "samples": {s: len(v) for s, v in scores.items()},
# 밤은 해 난 비율이 늘 0점이라 원래 점수가 100 - 그 비중까지만 나온다
"slots": {s: straighten_top(table(v), 100 - WEATHER_SCORE_DEF.weight_sun if s == "night" else 100) for s, v in scores.items()},
}
with open(OUT, "w", encoding="utf-8") as f:
json.dump(doc, f, ensure_ascii=False, indent=1)
print(len(regions), "regions", doc["samples"])
if __name__ == "__main__":
main()
+22 -11
View File
@@ -18,13 +18,17 @@ _FALL_FLOOR = exp(-0.5)
# 편한 범위 안에서 최적값 ±이만큼은 100점 (기온 °, 습도 %p)
_TEMP_PLATEAU = 2
_HUMIDITY_PLATEAU = 5
# 각 중요도(index_definition.priority)별 순위 가중치: 1=상 2=중 3=하. 순위만 바꾸고 보이는 점수는 그대로 둔다.
PRIORITY_WEIGHT = {1: 1.0, 2: 0.85, 3: 0.7}
def rank_score(score: int, priority: int) -> float:
"""각 순위를 정하는 값 = 점수 × 중요도 가중치."""
return score * PRIORITY_WEIGHT[priority]
def priority_score(score: int, priority: int) -> int:
"""중요도 배율을 한 번 적용하고 정수로 반올림한 표시·순위 공통 점수."""
return round(score * PRIORITY_WEIGHT[priority])
def rank_score(score: int, priority: int) -> tuple[int, int]:
"""중요도 반영이 끝난 표시 점수 내림차순. 동점이면 중요도 순."""
return score, -priority
@dataclass(frozen=True)
@@ -57,6 +61,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 +214,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,9 +301,14 @@ 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]) -> int:
worst = min((factors[a] for a in AXES if weights[a]), default=100)
return round(sum(factors[a] * weights[a] for a in AXES) / 100 * (1 - _WORST_PULL + _WORST_PULL * worst / 100))
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] and not (time_is_binary and a == "time")), default=100)
return round(mixed * (1 - _WORST_PULL + _WORST_PULL * worst / 100))
def _until(definition) -> str:
@@ -338,7 +348,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)
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)),
@@ -395,7 +405,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)
score = _weighted(factors, weights, getattr(definition, "worst_pull", True), rules["time"]["type"] == "fixed")
# 중기예보엔 눈 여부가 없어서, 눈이 와야 하는 각은 0점으로 둔다
# 하루 예보로는 비가 언제 그치는지 몰라 '앞서 비 옴'은 없는 것으로 본다
known = {"rain_prob": max_prob, "snow": "no", "rain_before": "no"}
@@ -413,7 +423,8 @@ def estimate(definition, fc: DayForecast, windows: list[list[int]], ctx: Context
# 나들이 날씨 점수: 낮 10~17시에 바깥에서 놀기 좋은 정도. 주말 전국 순위·당일치기 추천에 쓴다.
OUTING_HOURS = (10, 18)
_OUTING_WEIGHTS = {"temp": 35, "rain": 40, "sky": 15, "wind": 10}
_OUTING_RULES = {"temp": {"type": "range", "lo": 17, "hi": 24, "best": 21}, "rain": {"dir": "dry"}, "wind": {"type": "calm", "ok": 4, "limit": 12}}
# 만점 조건을 엄격하게: 기온은 최적 21° ±0.5°, 바람은 초속 1m 이하(ok/2)여야 100점 — 같은 예보를 받는 여러 지역이 한꺼번에 100점이 되던 것을 줄인다
_OUTING_RULES = {"temp": {"type": "range", "lo": 17, "hi": 24, "best": 21, "plateau": 0.5}, "rain": {"dir": "dry"}, "wind": {"type": "calm", "ok": 2, "limit": 12}}
_OUTING_SKY = {Sky.CLEAR: 100, Sky.PARTLY: 80, Sky.CLOUDY: 50}
_OUTING_RAIN_PROB, _OUTING_RAIN_CAP = 60, 30
@@ -0,0 +1,112 @@
{
"about": "나들이 점수 바꾸기 표: 원래 점수 0~100 → 표시 점수. 평균 60·표준편차 15. scripts/gen_outing_score_table.py 가 만든다",
"period": [
"2025-10-22",
"2026-10-21"
],
"regions": 32,
"samples": 11680,
"table": [
1,
1,
1,
1,
1,
1,
1,
1,
1,
8,
13,
17,
22,
25,
28,
30,
32,
34,
36,
37,
37,
38,
38,
39,
39,
40,
41,
41,
42,
42,
47,
50,
50,
50,
50,
50,
50,
50,
50,
50,
50,
51,
51,
51,
51,
52,
54,
57,
61,
62,
62,
62,
63,
63,
63,
63,
63,
64,
64,
64,
64,
64,
64,
65,
65,
65,
65,
66,
66,
66,
66,
67,
67,
67,
68,
68,
68,
69,
69,
70,
70,
71,
72,
73,
74,
75,
76,
78,
79,
81,
83,
85,
86,
88,
90,
92,
93,
95,
97,
98,
100
]
}
@@ -0,0 +1,428 @@
{
"about": "지금 날씨 점수 바꾸기 표: 원래 점수 0~100 → 표시 점수. 평균 60·표준편차 15. scripts/gen_weather_score_table.py 가 만든다",
"period": [
"2025-10-22",
"2026-10-21"
],
"regions": 32,
"samples": {
"morning": 11680,
"day": 11680,
"evening": 11680,
"night": 11680
},
"slots": {
"morning": [
1,
1,
1,
1,
1,
1,
1,
4,
5,
5,
9,
11,
14,
16,
17,
18,
20,
21,
23,
25,
26,
28,
29,
31,
31,
32,
33,
33,
34,
34,
35,
35,
35,
36,
37,
37,
38,
38,
39,
40,
41,
42,
43,
44,
45,
46,
47,
47,
48,
49,
50,
52,
53,
54,
55,
57,
59,
61,
62,
63,
64,
64,
65,
65,
66,
66,
67,
67,
68,
68,
69,
69,
70,
71,
71,
72,
73,
73,
74,
74,
75,
76,
77,
78,
79,
80,
82,
83,
84,
86,
87,
88,
90,
91,
92,
93,
95,
96,
97,
99,
100
],
"day": [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
4,
6,
9,
12,
15,
19,
22,
24,
26,
27,
28,
29,
30,
31,
31,
32,
32,
33,
33,
34,
35,
36,
37,
37,
38,
39,
40,
41,
41,
42,
42,
43,
43,
44,
44,
45,
45,
46,
46,
47,
47,
47,
48,
48,
48,
49,
49,
50,
50,
51,
52,
54,
56,
59,
61,
62,
63,
63,
64,
64,
64,
65,
65,
66,
66,
66,
67,
67,
68,
68,
69,
70,
71,
72,
73,
74,
76,
77,
79,
81,
83,
86,
89,
92,
94,
97,
100
],
"evening": [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
7,
11,
14,
17,
20,
23,
25,
27,
28,
29,
30,
31,
32,
32,
33,
34,
34,
35,
36,
37,
38,
38,
39,
39,
40,
40,
41,
41,
42,
42,
43,
43,
44,
45,
45,
46,
46,
47,
47,
48,
48,
48,
49,
50,
50,
51,
52,
53,
55,
56,
59,
60,
62,
63,
63,
64,
64,
65,
65,
66,
66,
67,
67,
68,
69,
69,
70,
71,
71,
72,
74,
75,
76,
78,
79,
81,
83,
85,
87,
89,
92,
94,
96,
98,
100
],
"night": [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
4,
7,
10,
11,
13,
15,
17,
20,
22,
26,
28,
30,
32,
33,
34,
34,
35,
35,
35,
36,
36,
37,
38,
38,
39,
40,
41,
41,
42,
43,
44,
45,
46,
48,
49,
50,
52,
53,
55,
57,
60,
62,
63,
65,
65,
66,
66,
66,
67,
68,
68,
69,
69,
70,
70,
71,
71,
72,
73,
74,
74,
75,
77,
78,
80,
82,
84,
86,
88,
90,
92,
94,
96,
98,
100,
100,
100,
100,
100,
100,
100,
100,
100,
100,
100,
100,
100,
100,
100,
100
]
}
}
+14 -7
View File
@@ -65,12 +65,18 @@ LINEUP = [
(20, PostType.UV, RefType.NONE, None),
(21, PostType.HERO, RefType.NONE, None),
(22, PostType.TODAY_GAK, RefType.NONE, None),
(23, PostType.FOLIAGE, RefType.NONE, None),
(24, PostType.EVENTS_BAND, RefType.NONE, None),
(25, PostType.SEASON_BAND, RefType.NONE, None),
]
# 피드 목록 대신 히어로·오늘의 각 카드에 좋아요·댓글만 붙는 자리
_PINNED = {PostType.HERO: "hero_post", PostType.TODAY_GAK: "gak_post"}
# 피드 목록 대신 히어로·오늘의 각·단풍 지도·띠에 좋아요·댓글만 붙는 자리
_PINNED = {
PostType.HERO: "hero_post", PostType.TODAY_GAK: "gak_post", PostType.FOLIAGE: "foliage_post",
PostType.EVENTS_BAND: "events_post", PostType.SEASON_BAND: "season_post",
}
# 좋아요·댓글 단위. 이 종류들은 전국이 같은 카드 하나, 나머지는 그 구 데이터로 채우는 카드라 시도마다 따로 만든다.
NATIONAL_SCOPE = "00"
NATIONAL_TYPES = frozenset({PostType.SEASON, PostType.TIP, PostType.QUOTE, PostType.MOON})
NATIONAL_TYPES = frozenset({PostType.SEASON, PostType.TIP, PostType.QUOTE, PostType.MOON, PostType.FOLIAGE, PostType.SEASON_BAND})
def sido_of(region_code: str) -> str:
@@ -148,6 +154,7 @@ def _hero_input(
now=now, night=slot in ("evening", "night"), after_dark=slot == "night", rain_at=rainy[0].at if rainy else None,
rain_later_at=later, today_known=bool(ahead),
air=AirGrade(now_w.air.grade) if now_w and now_w.air and now_w.air.grade is not None else None, uv=uv,
pm25=now_w.air.pm25 if now_w and now_w.air else None, pm10=now_w.air.pm10 if now_w and now_w.air else None,
temp_min=min(temps, default=None), temp_max=max(temps, default=None),
temp=float(cur.temp_c) if cur else None, feels=float(cur.feels_c) if cur else None,
moon=moon, humidity=cur.humidity if cur else None, discomfort=cur.discomfort_index if cur else None,
@@ -242,7 +249,7 @@ def _by_position(posts: list[Post]) -> list[Post]:
def _tomorrow_best(board: IndexBoard, day: date) -> Optional[tuple[IndexItem, IndexScore]]:
"""내일 하루 점수로 1위인 각과 그 점수 (점수 × 중요도)."""
"""내일 하루 점수로 1위인 각과 그 점수 (동점이면 중요도 순)."""
best = None
for i in board.items:
s = next((x for x in i.trend if x.score_date == day), None)
@@ -340,7 +347,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}:priority-score-v4:{slot}"
try:
cached = await REDIS.conn.get(key)
if cached:
@@ -475,7 +482,7 @@ class FeedService:
top1=_top(top) if top else None, bubble=bubble,
moon_name=moon[0].name if moon else None, moon_pct=round(moon[0].lit * 100) if moon else None,
stats=[HeroStat(icon=x.icon, label=x.label, value=x.value, tone=x.tone) for x in hero_stats(x_in)],
status=[HeroStat(icon=x.icon, label=x.label, value=x.value, tone=x.tone) for x in hero_status(x_in)],
status=[HeroStat(icon=x.icon, label=x.label, value=x.value, tone=x.tone, detail=x.detail) for x in hero_status(x_in)],
tomorrow=_hero_tomorrow(now.date() + timedelta(days=1), board) if board else None,
)
@@ -813,7 +820,7 @@ _CLOUDY = {Sky.CLEAR: 0.0, Sky.PARTLY: 0.5, Sky.CLOUDY: 1.0}
def _day_gaks(board: Optional[IndexBoard], day: date, n: int = 3) -> list[WeekGak]:
"""그날 대표 각: 각 상세의 날짜별 점수(하루 중 가장 좋은 시간대)를 점수 × 중요도 순으로."""
"""그날 대표 각: 날짜별 표시 점수 내림차순, 동점이면 중요도 순으로."""
scored = [(i.definition, s) for i in (board.items if board else []) for s in i.trend if s.score_date == day]
scored.sort(key=lambda x: rank_score(x[1].score, x[0].priority), reverse=True)
return [WeekGak(index_id=d.index_id, name=d.name, icon=d.icon, score=s.score) for d, s in scored[:n]]
+8 -4
View File
@@ -24,6 +24,7 @@ class HeroStatItem:
label: str
value: str
tone: Tone = "normal"
detail: Optional[str] = None # 단계 이름 밑의 실제 값 (예: 68%, 72, 2, 초미세먼지 15㎍/㎥)
@dataclass(frozen=True)
@@ -34,6 +35,8 @@ class HeroInput:
rain_later_at: Optional[datetime] = None # 그 뒤 오늘 안에 비 오는 첫 시각 (단기예보)
today_known: bool = False # 오늘 남은 시간 예보가 있어 '오늘 비 안 와요'라고 말할 수 있는지
air: Optional[AirGrade] = None
pm25: Optional[int] = None
pm10: Optional[int] = None
uv: Optional[float] = None
temp_min: Optional[float] = None
temp_max: Optional[float] = None
@@ -69,13 +72,14 @@ def hero_status(x: HeroInput) -> list[HeroStatItem]:
"""히어로 상태 한 줄: 습도·불쾌지수(늘)·자외선(해 있을 때, 저녁 포함)·미세먼지를 단계 이름으로. 값이 없는 칸은 뺀다. 조심할 것만 warn."""
out: list[HeroStatItem] = []
if x.humidity is not None:
out.append(HeroStatItem("humidity", "muggy", "습도", humidity_label(x.humidity)))
out.append(HeroStatItem("humidity", "muggy", "습도", humidity_label(x.humidity), detail=f"{x.humidity}%"))
if x.discomfort is not None:
out.append(HeroStatItem("discomfort", "muggy", "불쾌지수", discomfort_label(x.discomfort), "warn" if x.discomfort >= MUGGY_DI else "normal"))
out.append(HeroStatItem("discomfort", "muggy", "불쾌지수", discomfort_label(x.discomfort), "warn" if x.discomfort >= MUGGY_DI else "normal", detail=str(x.discomfort)))
if not x.after_dark and x.uv is not None:
out.append(HeroStatItem("uv", "glasses", "자외선", uv_label(x.uv), "warn" if x.uv >= UV_HIGH else "normal"))
out.append(HeroStatItem("uv", "glasses", "자외선", uv_label(x.uv), "warn" if x.uv >= UV_HIGH else "normal", detail=f"{x.uv:g}"))
if x.air is not None:
out.append(HeroStatItem("air", "mask", "미세먼지", GRADE_LABEL[x.air], "warn" if x.air in (AirGrade.BAD, AirGrade.VERY_BAD) else "normal"))
pm = " · ".join(s for s in (f"초미세먼지 {x.pm25}㎍/㎥" if x.pm25 is not None else "", f"미세먼지 {x.pm10}㎍/㎥" if x.pm10 is not None else "") if s) or None
out.append(HeroStatItem("air", "mask", "미세먼지", GRADE_LABEL[x.air], "warn" if x.air in (AirGrade.BAD, AirGrade.VERY_BAD) else "normal", detail=pm))
return out
+50 -41
View File
@@ -1,6 +1,8 @@
import asyncio
import json
from dataclasses import dataclass, field, replace
from datetime import date, datetime, time, timedelta
from pathlib import Path
from types import SimpleNamespace
from typing import Optional
@@ -17,7 +19,7 @@ from crud.weather_crud import WeatherCRUD
from crud.week_crud import WeekCRUD
from services.air_service import GRADE_LABEL, AirService
from services.calc.day_slot import NIGHT_END_HOUR, SLOTS, slot_hours, slot_of
from services.calc.index_calc import AXES, Context, DayForecast, Hour, Result, estimate, evaluate, rank_score
from services.calc.index_calc import AXES, Context, DayForecast, Hour, Result, estimate, evaluate, priority_score, rank_score
from services.calc.moon import night, up_ratio, view_line
from services.calc.sun import sun_times
from services.external.open_meteo import is_dark_slot
@@ -39,15 +41,12 @@ WEATHER_SCORE_DEF = SimpleNamespace(
"air": {"zero": 75, "full": 10}, "sun": {"zero": 0.2, "full": 0.9}, "time": {"type": "fixed", "value": 100},
},
zero_rules=[], windows=[{"from": NIGHT_END_HOUR, "to": 24 + NIGHT_END_HOUR}],
# 가장 낮은 요소로 깎지 않는다: 밤엔 해 난 비율이 늘 0점이라 깎기가 밤 점수를 눌렀다
worst_pull=False,
)
WEATHER_AXIS_NAME = {"temp": "기온", "rain": "비", "wind": "바람", "humidity": "습도", "air": "미세먼지", "sun": "햇볕"}
def strict_weather(raw: int) -> int:
"""날씨 점수는 높을수록 깐깐하게: 90점까지는 8/9, 그 위는 두 배로 깎아 100점은 모든 조건이 완벽할 때만 (96 → 92)."""
return round(raw * 8 / 9) if raw <= 90 else round(80 + (raw - 90) * 2)
@dataclass
class WeatherWhy:
label: str
@@ -61,6 +60,9 @@ def weather_why(r: Result) -> list[WeatherWhy]:
axes = sorted((a for a in WEATHER_AXIS_NAME if getattr(WEATHER_SCORE_DEF, f"weight_{a}")), key=lambda a: -getattr(WEATHER_SCORE_DEF, f"weight_{a}"))
return [WeatherWhy(label=WEATHER_AXIS_NAME[a], weight=getattr(WEATHER_SCORE_DEF, f"weight_{a}"), score=r.factors[a], note=r.notes.get(a, "")) for a in axes]
# 지금 날씨 점수 바꾸기 표: 구간마다 원래 점수 0~100 → 표시 점수(평균 60, 90점 이상은 드물게). scripts/gen_weather_score_table.py 가 만든다
WEATHER_SCORE_TABLE: dict[str, list[int]] = json.loads((Path(__file__).parent / "calc" / "weather_score_table.json").read_text(encoding="utf-8"))["slots"]
SEASONS = ("겨울", "봄", "여름", "가을")
@@ -90,8 +92,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 # 제철이 아니면 순위·피드에서 빼고 목록 맨 끝에 둔다
@@ -109,7 +111,7 @@ class IndexBoard:
@property
def ranked(self) -> list[IndexItem]:
"""지금 구간에 해당하는 각만 (순위·피드용)."""
"""활성화된 각 (순위·피드용)."""
return [i for i in self.items if i.active]
@@ -199,7 +201,6 @@ def windows_for(
EARLY = "early" # 0~5시: 전날 밤 구간
MIN_SLOT_HOURS = 2 # 각 시간대가 구간과 이만큼은 겹쳐야 그 구간 점수를 낸다 (한 시간짜리 각은 한 시간)
def current_slot(now: datetime, sunset_at: datetime) -> str:
@@ -216,6 +217,16 @@ def _shown_parts(parts: dict, cur: str) -> dict:
return {k: shown[k] for k in SLOTS if k in shown}
def calibrated_weather(slot: str, score: int) -> int:
"""지금 날씨 점수의 원래 점수를 그 구간 표로 바꾼다. 0~5시(전날 밤 구간)는 밤 표."""
return WEATHER_SCORE_TABLE[shown_slot(slot)][score]
def weather_slot_scores(results: dict[str, Result]) -> dict[str, Result]:
"""구간별 날씨 점수 결과의 점수를 표시 점수로 바꾼다 (점수 근거 factors 는 그대로)."""
return {k: replace(r, score=calibrated_weather(k, r.score)) for k, r in results.items()}
def rain_hours(by_at: dict[datetime, WeatherHourly], day: date) -> frozenset[int]:
"""그날 비·눈 오는 시각(0~23)."""
start = kst_midnight(day)
@@ -226,16 +237,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
@@ -263,6 +279,13 @@ def _with_slot(row: IndexScore, data: dict) -> IndexScore:
return out
def _with_priority(row: IndexScore, priority: int) -> IndexScore:
"""DB의 원점수·요소 점수는 보존하고 응답용 사본의 최종 점수에만 중요도를 적용한다."""
out = IndexScore(**{c.key: getattr(row, c.key, None) for c in IndexScore.__table__.columns})
out.score = priority_score(row.score, priority)
return out
def day_forecast(d: WeatherDaily) -> DayForecast:
return DayForecast(
temp_min_c=float(d.temp_min_c) if d.temp_min_c is not None else None,
@@ -344,37 +367,23 @@ 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_priority(_with_slot(row, row.slots[cur]), d.priority)
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):
row = by_key[(d.index_id, today)]
parts = _shown_parts({k: v["score"] for k, v in row.slots.items()}, cur)
parts = _shown_parts({k: priority_score(v["score"], d.priority) for k, v in row.slots.items()}, cur)
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],
trend=[now_score[d.index_id] if day == today else _with_priority(by_key[(d.index_id, day)], d.priority) 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):
@@ -383,8 +392,8 @@ class IndexService:
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,
definition=d, score=_with_priority(row, d.priority), rank=len(items) + 1,
trend=[_with_priority(by_key[(d.index_id, day)], d.priority) 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[cur].score if cur in weather_parts else None, items=items,
@@ -459,8 +468,8 @@ class IndexService:
tomorrow_ctx = Context(day=tomorrow, is_holiday=False, moon=0, sunset_score=None, lookahead_rain_prob=0, rain_hours=rain_hours(by_at, tomorrow), **base_ctx)
tomorrow_sunset = sun_times(tomorrow, float(region.lat), float(region.lon)).sunset_at
weather_parts = {
today: {k: replace(r, score=strict_weather(r.score)) for k, r in slot_results(WEATHER_SCORE_DEF, today, region, by_at, by_om, today_ctx, sunset_at, now).items()},
tomorrow: {k: replace(r, score=strict_weather(r.score)) for k, r in slot_results(WEATHER_SCORE_DEF, tomorrow, region, by_at, by_om, tomorrow_ctx, tomorrow_sunset).items()},
today: weather_slot_scores(slot_results(WEATHER_SCORE_DEF, today, region, by_at, by_om, today_ctx, sunset_at, now)),
tomorrow: weather_slot_scores(slot_results(WEATHER_SCORE_DEF, tomorrow, region, by_at, by_om, tomorrow_ctx, tomorrow_sunset)),
}
issued = max([r.issued_at for r in rows] + [d.issued_at for d in daily_rows or []])
+45 -3
View File
@@ -4,10 +4,13 @@ import re
import uuid
from typing import Optional
from azure.core.exceptions import AzureError
from azure.storage.blob import BlobServiceClient, ContainerClient, ContentSettings
from PIL import Image, ImageOps, UnidentifiedImageError
from config.settings import settings
from common.enums import ErrorType
from common.logger import LOG
MAX_BYTES = 10 * 1024 * 1024 # 올릴 수 있는 원본 크기
MAX_SIDE = 1080 # 긴 변을 이만큼으로 줄인다
@@ -21,6 +24,35 @@ def folder() -> str:
return path
def _container() -> Optional[ContainerClient]:
"""Azure Blob 컨테이너: 접속 문자열 또는 컨테이너 주소 + SAS 토큰. 둘 다 없으면 None (서버 폴더에 저장)"""
if settings.azure_storage_connection_string and settings.azure_storage_container:
return BlobServiceClient.from_connection_string(settings.azure_storage_connection_string).get_container_client(settings.azure_storage_container)
if settings.azure_blob_base_url and settings.azure_blob_sas_token:
return ContainerClient.from_container_url(f"{settings.azure_blob_base_url.rstrip('/')}?{settings.azure_blob_sas_token.lstrip('?')}")
return None
def _public(url: str) -> str:
"""글에 붙일 주소: SAS 토큰(쓰기 권한)을 떼어 낸 공개 주소"""
return url.split("?", 1)[0]
def _blob_name(name: str) -> str:
return f"{settings.azure_storage_prefix.strip('/')}/talk/{name}"
def is_ours(url: str) -> bool:
"""우리가 올린 사진 주소인지: 서버 폴더에 있거나, 우리 Blob 폴더의 우리가 만든 이름"""
if file_of(url) is not None:
return True
c = _container()
if c is None:
return False
base = f"{_public(c.url)}/{_blob_name('')}"
return url.startswith(base) and bool(_NAME.match(url.removeprefix(base)))
def file_of(url: str) -> Optional[str]:
"""올린 사진 주소 → 저장된 파일 경로. 우리가 만든 이름이 아니거나 파일이 없으면 None."""
name = url.removeprefix(URL_PREFIX)
@@ -31,7 +63,7 @@ def file_of(url: str) -> Optional[str]:
def save(data: bytes) -> tuple[ErrorType, Optional[str]]:
"""사진을 다시 그려 저장한다. 다시 그리면 찍은 위치(GPS)·기기 같은 메타데이터가 모두 빠진다. 돌려준 값은 글에 붙일 주소."""
"""사진을 다시 그려 저장한다(Azure Blob, 설정이 없으면 서버 폴더). 다시 그리면 찍은 위치(GPS)·기기 같은 메타데이터가 모두 빠진다. 돌려준 값은 글에 붙일 주소."""
if len(data) > MAX_BYTES:
return ErrorType.INVALID_INPUT, None
try:
@@ -41,5 +73,15 @@ def save(data: bytes) -> tuple[ErrorType, Optional[str]]:
return ErrorType.INVALID_INPUT, None
img.thumbnail((MAX_SIDE, MAX_SIDE))
name = f"{uuid.uuid4().hex}.webp"
img.save(os.path.join(folder(), name), "WEBP", quality=82)
return ErrorType.SUCCESS, URL_PREFIX + name
c = _container()
if c is None:
img.save(os.path.join(folder(), name), "WEBP", quality=82)
return ErrorType.SUCCESS, URL_PREFIX + name
buf = io.BytesIO()
img.save(buf, "WEBP", quality=82)
try:
blob = c.upload_blob(_blob_name(name), buf.getvalue(), content_settings=ContentSettings(content_type="image/webp", cache_control="public, max-age=31536000, immutable"))
except AzureError as e:
LOG.error(f"[talk_image] blob upload: {e}")
return ErrorType.EXTERNAL_API_ERROR, None
return ErrorType.SUCCESS, _public(blob.url)
+64 -8
View File
@@ -1,19 +1,20 @@
import math
import re
from dataclasses import dataclass
from datetime import timedelta
from datetime import datetime, timedelta
from typing import Optional
from fastapi import Depends
from common.database.db_session_manager import DB_SESSION_MNG
from common.database.model.models import Talk, User, WeatherHourly
from common.enums import ErrorType, RainType, Sky, TalkReport
from common.enums import ErrorType, RainType, Sky, TalkReport, TalkTopic
from common.liker import Liker
from common.utils.kma_time import kst_midnight, now_kst
from crud.region_crud import RegionCRUD
from crud.talk_crud import TalkCRUD
from crud.weather_crud import WeatherCRUD
from services.talk_image import file_of
from services.talk_image import is_ours
BODY_MAX = 100
DAILY_MAX = 5
@@ -22,6 +23,13 @@ HIDE_AT = 3
PAGE = 20
# 보는 사람과 같은 시도에서 쓴 글은 이만큼 늦게 쓴 글처럼 앞에 둔다
LOCAL_BOOST = timedelta(hours=12)
# 피드 묶음: 최근 이 기간 글 중에서 고른다. 한 묶음 최대 장수, 이보다 적으면 주제 묶음은 숨긴다
GROUP_WINDOW = timedelta(days=7)
GROUP_POOL = 300
GROUP_MAX = 10
GROUP_MIN = 3
# 묶음 순서는 '덜 지난 것처럼 쳐 주는 시간'으로 매긴다: 같은 구 6시간, 같은 시도 3시간, 좋아요는 2시간 × log2(1+좋아요)
NEAR_GU_H, NEAR_SIDO_H, LIKE_H = 6, 3, 2
# 링크(http, www, 도메인 꼴)와 전화번호(010-1234-5678, 01012345678, 02-123-4567)
_LINK = re.compile(r"https?://|www\.|[a-z0-9-]+\.(?:com|net|kr|co|org|io|me|ly|gl)\b", re.I)
@@ -51,6 +59,30 @@ def spread_authors(views: list["TalkView"]) -> list["TalkView"]:
return out
def group_age(t: Talk, region_code: Optional[str], now: datetime) -> float:
"""묶음 안 정렬 값(작을수록 앞): 지난 시간에서 가까운 동네·좋아요만큼 뺀다. 오래된 글은 좋아요가 많아도 결국 뒤로 간다"""
age = (now - t.created_at).total_seconds() / 3600
near = NEAR_GU_H if region_code and t.region_code == region_code else NEAR_SIDO_H if region_code and t.region_code[:2] == region_code[:2] else 0
return age - near - LIKE_H * math.log2(1 + t.like_count)
def pick_group(views: list["TalkView"], region_code: Optional[str], now: datetime) -> list["TalkView"]:
"""한 사람 한 장, 최대 GROUP_MAX 장. 첫 장은 신고 받은 적 없는 글"""
out: list[TalkView] = []
seen: set = set()
for v in sorted(views, key=lambda v: group_age(v.talk, region_code, now)):
if v.author.user_id in seen:
continue
seen.add(v.author.user_id)
out.append(v)
if len(out) == GROUP_MAX:
break
clean = next((i for i, v in enumerate(out) if v.talk.report_count == 0), None)
if clean:
out.insert(0, out.pop(clean))
return out
def parse_cursor(cursor: str) -> Optional[tuple[int, int]]:
key, _, talk_id = cursor.partition("_")
return (int(key), int(talk_id)) if key.lstrip("-").isdigit() and talk_id.isdigit() else None
@@ -69,14 +101,36 @@ class TalkService:
def __init__(self, crud: TalkCRUD = Depends(TalkCRUD), regions: RegionCRUD = Depends(RegionCRUD), weather: WeatherCRUD = Depends(WeatherCRUD)) -> None:
self.crud, self.regions, self.weather = crud, regions, weather
async def page(self, user: Optional[User], ip_hash: str, region_code: Optional[str], cursor: Optional[str]) -> tuple[ErrorType, list[TalkView], Optional[str]]:
async def groups(self, user: Optional[User], ip_hash: str, region_code: Optional[str]) -> tuple[ErrorType, dict[int, list[TalkView]]]:
"""피드 묶음. 0은 '동네 사람들'(모든 주제), 나머지는 주제별(GROUP_MIN 장 이상일 때만)"""
now = now_kst()
viewer = user.user_id if user else None
err, rows = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.recent(s, viewer, now - GROUP_WINDOW, GROUP_POOL))
if err is not ErrorType.SUCCESS:
return err, {}
err, liked = await self._liked(user, ip_hash, [t.talk_id for t, *_ in rows])
if err is not ErrorType.SUCCESS:
return err, {}
views = [TalkView(talk=t, author=u, region_name=name, liked=t.talk_id in liked, mine=viewer == t.user_id) for t, u, name in rows]
out = {0: pick_group(views, region_code, now)}
for topic in TalkTopic:
if topic is TalkTopic.LOCAL:
continue
group = pick_group([v for v in views if v.talk.topic == topic.value], region_code, now)
if len(group) >= GROUP_MIN:
out[topic.value] = group
return ErrorType.SUCCESS, out
async def page(
self, user: Optional[User], ip_hash: str, region_code: Optional[str], cursor: Optional[str], topic: Optional[int] = None
) -> tuple[ErrorType, list[TalkView], Optional[str]]:
"""한 페이지와 다음 페이지 cursor. 같은 사람 글은 페이지 안에서 떨어뜨린다."""
after = parse_cursor(cursor) if cursor else None
if cursor and after is None:
return ErrorType.INVALID_INPUT, [], None
viewer = user.user_id if user else None
sido = region_code[:2] if region_code else None
err, rows = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.page(s, viewer, sido, int(LOCAL_BOOST.total_seconds()), after, PAGE))
err, rows = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.page(s, viewer, sido, int(LOCAL_BOOST.total_seconds()), after, PAGE, topic))
if err is not ErrorType.SUCCESS:
return err, [], None
err, liked = await self._liked(user, ip_hash, [t.talk_id for t, *_ in rows])
@@ -111,11 +165,13 @@ class TalkService:
return None
return weather_line(min(rows, key=lambda r: abs(r.forecast_at - now)))
async def add(self, user: User, region_code: str, body: str, image: Optional[str] = None) -> tuple[ErrorType, Optional[TalkView]]:
async def add(
self, user: User, region_code: str, body: str, image: Optional[str] = None, topic: TalkTopic = TalkTopic.LOCAL
) -> tuple[ErrorType, Optional[TalkView]]:
body = " ".join(body.split())
if not body or len(body) > BODY_MAX:
return ErrorType.INVALID_INPUT, None
if image is not None and file_of(image) is None:
if image is not None and not is_ours(image):
return ErrorType.INVALID_INPUT, None
if _LINK.search(body) or _PHONE.search(body):
return ErrorType.LINK_NOT_ALLOWED, None
@@ -131,7 +187,7 @@ class TalkService:
if n >= DAILY_MAX:
return ErrorType.DAILY_LIMIT, None
weather = await self._weather_now(region_code)
err, t = await DB_SESSION_MNG.execute_lambda_write(lambda s: self.crud.add(s, user.user_id, region_code, body, weather, image))
err, t = await DB_SESSION_MNG.execute_lambda_write(lambda s: self.crud.add(s, user.user_id, region_code, body, weather, image, topic.value))
if err is not ErrorType.SUCCESS or t is None:
return err, None
return ErrorType.SUCCESS, TalkView(talk=t, author=user, region_name=region.short_name, liked=False, mine=True)
+3 -3
View File
@@ -22,7 +22,7 @@ from crud.index_crud import IndexCRUD
from crud.region_crud import RegionCRUD
from crud.weather_crud import WeatherCRUD
from crud.week_crud import WeekCRUD
from services.calc.index_calc import rank_score
from services.calc.index_calc import priority_score, rank_score
from services.external.culture_api import IMAGE_CREDIT as CULTURE_CREDIT
from services.external.culture_api import SOURCE_PREFIX as CULTURE_PREFIX
from services.external.culture_api import CONCERT, EXHIBITION, fetch_exhibitions, parse_exhibitions
@@ -291,14 +291,14 @@ class WeekService:
for d in daily:
rows = [r for r in hourly or [] if r.forecast_at.astimezone(KST).date() == d.forecast_date]
rain_hours = _rain_hours(rows)
top = sorted((x for x in scores or [] if x.score_date == d.forecast_date and not x.estimated), key=lambda x: rank_score(x.score, priority.get(x.index_id, 2)), reverse=True)[:2]
top = sorted((x for x in scores or [] if x.score_date == d.forecast_date and not x.estimated), key=lambda x: rank_score(priority_score(x.score, priority.get(x.index_id, 2)), priority.get(x.index_id, 2)), reverse=True)[:2]
holiday = (holidays or {}).get(d.forecast_date)
weekday = _WEEKDAY_KO[d.forecast_date.weekday()]
word = _weather_word(d, rain_hours)
temps = f" {round(float(d.temp_min_c))}~{round(float(d.temp_max_c))}°" if d.temp_min_c is not None and d.temp_max_c is not None else ""
is_rainy = d.rain_type != RainType.NONE.value
if top:
summary = ", ".join(f"{names.get(x.index_id, '')} {x.score}점" for x in top)
summary = ", ".join(f"{names.get(x.index_id, '')} {priority_score(x.score, priority.get(x.index_id, 2))}점" for x in top)
pick = "비 오는 날, 실내 일정이 좋아요" if is_rainy else f"{names.get(top[0].index_id, '')} 추천"
else:
summary, pick = f"비 확률 {d.rain_prob}%", ("실내 일정이 좋아요" if is_rainy else "바깥 일정 잡기 좋아요")
+19 -4
View File
@@ -22,7 +22,7 @@ from crud.region_crud import RegionCRUD
from crud.sky_crud import SkyCRUD
from crud.weather_crud import WeatherCRUD
from crud.week_crud import WeekCRUD
from services.calc.index_calc import OUTING_HOURS, outing, outing_estimate
from services.calc.index_calc import OUTING_HOURS, Outing, outing, outing_estimate
from services.index_service import day_forecast, windows_for
from services.weather_service import WeatherService
from services.week_service import _icon
@@ -30,14 +30,29 @@ from services.week_service import _icon
# 주말 전국 날씨 순위·당일치기 추천. 대표 지역(노을 순위 30곳)과 당일치기 후보 도시의 토·일 나들이 점수를
# 워커가 하루 두 번(06:40·18:40) 미리 계산해 Redis 에 둔다. 없으면 순위 API 가 그 자리에서 계산한다.
_SEED = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "seed", "trip_city.csv")
_KEY = "weekend_rank:{:%Y%m%d}"
_KEY = "weekend_rank:v2:{:%Y%m%d}" # v2: 점수를 바꾸기 표로 보정한 값 (옛 점수 캐시를 쓰지 않게 키를 바꿨다)
_TTL = 13 * 3600
_PARALLEL = 4 # 기상청 동시 호출 수
_WAIT_STEPS, _WAIT_SEC = 60, 0.5
_WINDOW = SimpleNamespace(windows=[{"from": OUTING_HOURS[0], "to": OUTING_HOURS[1]}])
# 나들이 점수 바꾸기 표: 원래 점수 0~100 → 표시 점수(평균 60, 90점 이상은 드물게). scripts/gen_outing_score_table.py 가 만든다
OUTING_SCORE_TABLE: list[int] = json.loads(
open(os.path.join(os.path.dirname(os.path.abspath(__file__)), "calc", "outing_score_table.json"), encoding="utf-8").read()
)["table"]
def calibrated_outing(score: int) -> int:
return OUTING_SCORE_TABLE[score]
def outing_day_score(result: Outing) -> int:
"""순위·당일치기에 쓰는 하루 나들이 점수. 시간별 예보로 낸 점수와 중기예보 예상 점수 모두 같은 표를 거친다."""
return calibrated_outing(result.score)
# 당일치기: 내 지역에서 직선 이 거리 안의 후보 도시만 (1~2시간 거리), 너무 가까운 곳(같은 동네)은 뺀다.
TRIP_MIN_KM, TRIP_MAX_KM = 20, 200
TRIP_MIN_SCORE = 50
TRIP_MIN_SCORE = calibrated_outing(50) # 원래 점수 50점과 같은 날씨 수준
@dataclass
@@ -205,7 +220,7 @@ class WeekendRank:
if result is None or row is None:
continue
out.append(DayScore(
region_code=region.code, day=d, score=result.score, reason=result.reason, icon=_icon(Sky(row.sky), RainType(row.rain_type)),
region_code=region.code, day=d, score=outing_day_score(result), reason=result.reason, icon=_icon(Sky(row.sky), RainType(row.rain_type)),
temp_min_c=float(row.temp_min_c) if row.temp_min_c is not None else None,
temp_max_c=float(row.temp_max_c) if row.temp_max_c is not None else None,
rain_prob=row.rain_prob, estimated=result.estimated,
+21 -9
View File
@@ -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():
+6 -1
View File
@@ -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)
+54 -13
View File
@@ -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
@@ -27,6 +27,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 = []
@@ -64,14 +72,17 @@ 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"]]
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 and i["in_season"]]
assert weighted == sorted(weighted, reverse=True)
scores = [i["score"] for i in body["items"] if i["active"] is group and i["in_season"]]
assert scores == sorted(scores, reverse=True)
order = [rank_score(i["score"], priority[i["code"]]) for i in body["items"] if i["active"] is group and i["in_season"]]
assert order == sorted(order, reverse=True)
today = now_kst().date()
for i in body["items"]:
assert [t["label"] for t in i["trend"]] == [slot_label(d, today) for d in slot_days(today)]
@@ -142,7 +153,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, {now_kst().date(): _WEATHER_50})))
@@ -155,30 +166,38 @@ async def test_board_puts_out_of_season_gak_last_without_rank_or_badge(monkeypat
@pytest.mark.anyio
async def test_board_ranks_by_score_times_priority_weight(monkeypatch):
async def test_board_displays_and_ranks_by_priority_adjusted_score(monkeypatch):
today = now_kst().date()
defs = [
SimpleNamespace(index_id=1, code="low", priority=3),
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))]
scores += [_board_score(x, today + timedelta(days=1), 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, {now_kst().date(): _WEATHER_50})))
err, board = await service.board(REGION)
assert err is ErrorType.SUCCESS
# 하 90점(63) < 중 80점(68) < 상 70점(70). 보이는 점수는 그대로
assert [(i.definition.code, i.score.score, i.rank) for i in board.items] == [("high", 70, 1), ("mid", 80, 2), ("low", 90, 3)]
assert [(i.definition.code, i.score.score, i.rank) for i in board.items] == [("high", 70, 1), ("mid", 68, 2), ("low", 63, 3)]
for item in board.items:
assert item.trend[0].score == item.score.score
assert item.trend[1].score == item.score.score
assert all(value == item.score.score for value in item.slots.values())
# 응답용 보정은 DB에서 읽은 원점수를 바꾸지 않으며, 같은 요청을 다시 해도 중복 적용하지 않는다.
assert [row.score for row in scores] == [90, 80, 70, 90, 80, 70]
_, again = await service.board(REGION)
assert [i.score.score for i in again.items] == [70, 68, 63]
@pytest.mark.anyio
async def test_board_ranks_each_slot_with_priority_weight(monkeypatch):
async def test_board_ranks_each_slot_by_displayed_score(monkeypatch):
today = now_kst().date()
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)
@@ -186,10 +205,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점, 상 70점은 표시 70점으로 순위와 화면 숫자가 일치한다.
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, {today: {cur: _RESULT_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):
+31 -13
View File
@@ -9,7 +9,7 @@ import pytest
from common.enums import RainType, Sky
from services.calc.index_calc import (
OUTING_HOURS, Context, DayForecast, Hour, air_score, axis_label, estimate, evaluate, hour_temp, outing, outing_estimate, rain_score, sun_score, temp_score,
uv_score, view_score, zero_rules_text,
priority_score, rank_score, uv_score, view_score, zero_rules_text,
)
from services.calc.moon import illumination
@@ -38,6 +38,36 @@ def test_perfect_evening_scores_100():
assert r.notes["temp"] == "체감 21°, 편한 범위 18~24° 안"
def test_rank_and_display_share_priority_adjusted_screenshot_scores():
items = [(83, 1), (82, 1), (80, 1), (91, 2), (77, 1), (77, 1), (76, 1), (89, 2), (87, 2)]
shown = [(priority_score(score, priority), priority) for score, priority in items]
ranked = sorted(shown, key=lambda item: rank_score(*item), reverse=True)
assert [score for score, _ in ranked] == [83, 82, 80, 77, 77, 77, 76, 76, 74]
assert priority_score(91, 2) == 77
assert priority_score(89, 2) == 76
def test_rank_uses_priority_only_to_break_ties():
items = [(80, 3), (80, 1), (81, 3), (80, 2)]
assert sorted(items, key=lambda item: rank_score(*item), reverse=True) == [(81, 3), (80, 1), (80, 2), (80, 3)]
@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
@@ -342,18 +372,6 @@ def test_umbrella_lost_needs_rain_that_stopped():
assert evaluate(defn, [[_h(10, rain=RainType.RAIN)]], replace(CTX, rain_hours=frozenset({9, 10}))).score == 0
def test_weather_score_is_strict_near_top():
"""좋은 날(96)도 92 수준, 100점은 모든 조건이 완벽할 때만. 낮은 점수도 조금씩 내려간다."""
from services.index_service import strict_weather
assert strict_weather(100) == 100
assert strict_weather(96) == 92
assert strict_weather(99) < 100
assert strict_weather(75) < 75
scores = [strict_weather(s) for s in range(101)]
assert scores == sorted(scores)
def test_weather_why_lists_every_condition_heaviest_first():
from services.index_service import WEATHER_SCORE_DEF, weather_why
+58
View File
@@ -0,0 +1,58 @@
from common.enums import RainType, Sky
from services.calc.index_calc import Hour, Outing, outing
from services.weekend_rank import OUTING_SCORE_TABLE, TRIP_MIN_SCORE, calibrated_outing, outing_day_score
def test_table_is_a_monotonic_0_to_100_lookup():
assert len(OUTING_SCORE_TABLE) == 101
assert all(0 <= v <= 100 for v in OUTING_SCORE_TABLE)
assert all(a <= b for a, b in zip(OUTING_SCORE_TABLE, OUTING_SCORE_TABLE[1:]))
assert OUTING_SCORE_TABLE[0] < OUTING_SCORE_TABLE[100] == 100
def test_table_makes_top_scores_rare_and_centers_60():
"""원래 점수가 높을수록 표시 점수가 오르되, 90점 이상으로 가는 원래 점수는 위쪽 일부뿐."""
assert any(55 <= v <= 65 for v in OUTING_SCORE_TABLE)
assert sum(v >= 90 for v in OUTING_SCORE_TABLE) <= 15
# 맑고 알맞은 날(원래 100)과 조금 못 미치는 날(원래 97)이 모두 100점으로 몰리지 않는다
assert calibrated_outing(95) < 100
def test_calibrated_outing_reads_the_table():
assert calibrated_outing(70) == OUTING_SCORE_TABLE[70]
assert calibrated_outing(0) == OUTING_SCORE_TABLE[0]
def test_day_score_uses_calibrated_value_for_hourly_and_estimated_results():
for estimated in (False, True):
r = Outing(score=80, factors={}, notes={}, reason="비 0% · 체감 21° · 맑음", capped=False, estimated=estimated)
assert outing_day_score(r) == OUTING_SCORE_TABLE[80]
def test_trip_min_score_keeps_the_same_weather_quality():
"""당일치기 최소 기준은 원래 점수 50과 같은 날씨 수준을 표시 점수로 옮긴 값."""
assert TRIP_MIN_SCORE == calibrated_outing(50)
# 표는 가까운 원래 점수끼리 같은 값이 될 수 있어, 눈에 띄게 낮은 날은 빠지고 높은 날은 들어가는지만 본다
assert calibrated_outing(45) < TRIP_MIN_SCORE <= calibrated_outing(55)
def _day(feels: float = 21.0, wind: float = 0.5, prob: int = 0, sky: Sky = Sky.CLEAR) -> list[Hour]:
return [Hour(hour=h, feels_c=feels, rain_type=RainType.NONE, rain_prob=prob, wind_ms=wind, humidity=50, sky=sky) for h in range(10, 18)]
def test_outing_100_needs_exact_temperature_and_very_calm_wind():
"""맑고 비 없는 날도 체감 21° 근처(±0.5°)·바람 초속 1m 이하여야 100점. 그래야 같은 예보의 여러 지역이 한꺼번에 100점이 되지 않는다."""
assert outing(_day()).score == 100
assert outing(_day(feels=21.4)).factors["temp"] == 100
assert outing(_day(feels=22.3)).factors["temp"] < 100
assert outing(_day(wind=1.0)).factors["wind"] == 100
assert outing(_day(wind=1.8)).factors["wind"] < 95
assert outing(_day(wind=1.2)).score > outing(_day(wind=1.8)).score > outing(_day(wind=2.0)).score
def test_100_only_for_a_perfect_original_score_and_top_scores_stay_distinct():
"""맨 위가 100으로 잘려 원래 96·97·99가 모두 100점이 되던 것을 막는다: 100점은 원래 100뿐, 그 아래는 서로 다른 점수."""
assert OUTING_SCORE_TABLE[100] == 100
assert OUTING_SCORE_TABLE[99] < 100
top = OUTING_SCORE_TABLE[90:]
assert all(a < b for a, b in zip(top, top[1:]))
+49 -1
View File
@@ -4,7 +4,9 @@ import pytest
from httpx import ASGITransport, AsyncClient
from router.router import app
from services.talk_service import DAILY_MAX, HIDE_AT, parse_cursor, spread_authors, weather_line
from datetime import datetime, timedelta, timezone
from services.talk_service import DAILY_MAX, GROUP_MAX, HIDE_AT, parse_cursor, pick_group, spread_authors, weather_line
REGION = "1144000000"
BUSAN = "2611000000"
@@ -143,3 +145,49 @@ def test_spread_authors_and_cursor():
assert [x.author.user_id for x in spread_authors([v("a"), v("a"), v("a"), v("b"), v("c")])] == ["a", "b", "a", "c", "a"]
assert parse_cursor("1760000000_42") == (1760000000, 42)
assert parse_cursor("12") is None and parse_cursor("x_1") is None
@pytest.mark.anyio
async def test_topic_is_saved_and_filters_list():
async with client() as c:
h = await _login(c, "talk_tp1")
sky = (await c.post("/v1/talk", json={"region_code": REGION, "body": "노을 분홍빛", "topic": 2}, headers=h)).json()["talk"]
plain = (await _write(c, h, "그냥 동네 이야기"))["talk"]
assert sky["topic"] == 2 and plain["topic"] == 1
only_sky = _ids((await c.get("/v1/talk/list", params={"topic": 2})).json())
only_foliage = _ids((await c.get("/v1/talk/list", params={"topic": 4})).json())
assert sky["talk_id"] in only_sky and plain["talk_id"] not in only_sky
assert sky["talk_id"] not in only_foliage
@pytest.mark.anyio
async def test_groups_have_near_group_and_topic_group_from_three_people():
async with client() as c:
for i in range(3):
h = await _login(c, f"talk_gr{i}")
for j in range(2):
await c.post("/v1/talk", json={"region_code": REGION, "body": f"단풍 물들었어요 {i}-{j}", "topic": 4}, headers=h)
groups = {g["topic"]: g["talks"] for g in (await c.get("/v1/talk/groups", params={"region": REGION})).json()["groups"]}
assert 0 in groups and 4 in groups
assert all(t["topic"] == 4 for t in groups[4])
for talks in groups.values():
names = [t["nickname"] for t in talks]
assert len(names) == len(set(names)) and len(talks) <= GROUP_MAX
def _view(talk_id, user, region, hours_ago, likes=0, reports=0):
now = datetime(2026, 10, 23, 12, tzinfo=timezone.utc)
talk = SimpleNamespace(talk_id=talk_id, region_code=region, created_at=now - timedelta(hours=hours_ago), like_count=likes, report_count=reports)
return SimpleNamespace(talk=talk, author=SimpleNamespace(user_id=user))
def test_pick_group_orders_near_fresh_first_one_per_person_clean_first():
now = datetime(2026, 10, 23, 12, tzinfo=timezone.utc)
far = _view(1, "a", BUSAN, 1)
same_sido = _view(2, "b", "1111000000", 1)
same_gu = _view(3, "c", REGION, 1)
old_popular = _view(4, "d", REGION, 30, likes=50)
again = _view(5, "c", REGION, 0)
assert [v.talk.talk_id for v in pick_group([far, same_sido, same_gu, old_popular, again], REGION, now)] == [5, 2, 1, 4]
reported = _view(6, "e", REGION, 0, reports=1)
assert pick_group([reported, far], REGION, now)[0].talk.talk_id == 1
+74
View File
@@ -0,0 +1,74 @@
from dataclasses import replace
from datetime import date
from services.calc.index_calc import Context, evaluate
from scripts.gen_weather_score_table import straighten_top
from services.index_service import EARLY, WEATHER_SCORE_DEF, WEATHER_SCORE_TABLE, calibrated_weather, weather_slot_scores
from tests.test_index_calc import _defn, _h
PERFECT = Context(day=date(2026, 10, 2), is_holiday=False, pm25=8, air_label="좋음", moon=0, sunset_score=None, wind_warning=False, lookahead_rain_prob=0)
SLOTS = ("morning", "day", "evening", "night")
def test_weather_score_has_no_worst_factor_pull():
"""해 난 비율만 0점(밤)이어도 나머지가 만점이면 비중대로 85점. 가장 낮은 요소로 25% 더 깎지 않는다."""
hours = [_h(h, feels=21.0, prob=0, wind=0.8, hum=50, sunshine_ratio=0.0) for h in range(19, 23)]
r = evaluate(WEATHER_SCORE_DEF, [hours], PERFECT)
assert r.factors["sun"] == 0
assert r.score == 85
def test_gak_scores_keep_worst_factor_pull():
"""각 점수는 그대로: 한 요소가 0점이면 섞은 점수에서 25% 깎인다."""
defn = _defn(zero_rules=[])
r = evaluate(defn, [[_h(19, wind=12.0)]], PERFECT)
assert r.factors["wind"] == 0
plain = round(sum(r.factors[a] * getattr(defn, f"weight_{a}", 0) for a in r.factors) / 100)
assert r.score == round(plain * 0.75)
def test_table_covers_every_slot_and_never_goes_down():
for slot in SLOTS:
table = WEATHER_SCORE_TABLE[slot]
assert len(table) == 101
assert all(0 <= v <= 100 for v in table)
assert all(a <= b for a, b in zip(table, table[1:]))
assert table[100] == 100
def test_table_makes_90_rare_and_centers_60():
"""구간마다 원래 점수 중앙값 근처가 60점 근처로, 90점 이상은 원래 점수 상위 몇 칸뿐."""
for slot in SLOTS:
table = WEATHER_SCORE_TABLE[slot]
assert any(55 <= v <= 65 for v in table)
assert sum(v >= 90 for v in table) < sum(v < 90 for v in table)
def test_calibrated_uses_slot_table_and_last_night_for_early():
assert calibrated_weather("day", 70) == WEATHER_SCORE_TABLE["day"][70]
assert calibrated_weather(EARLY, 70) == WEATHER_SCORE_TABLE["night"][70]
def test_weather_slot_scores_keeps_results_with_calibrated_scores():
"""점수 근거(factors)는 그대로 두고 점수만 표시 점수로 바꾼 결과를 돌려준다."""
results = {k: replace(evaluate(WEATHER_SCORE_DEF, [[_h(12)]], PERFECT), score=s) for k, s in {"morning": 40, "night": 60, EARLY: 60}.items()}
shown = weather_slot_scores(results)
assert {k: r.score for k, r in shown.items()} == {"morning": WEATHER_SCORE_TABLE["morning"][40], "night": WEATHER_SCORE_TABLE["night"][60], EARLY: WEATHER_SCORE_TABLE["night"][60]}
assert all(shown[k].factors == results[k].factors for k in results)
assert results["morning"].score == 40 # 원래 결과는 바뀌지 않는다
def test_straighten_top_makes_100_only_at_the_top_and_keeps_the_rest():
clamped = list(range(0, 80)) + [85, 90, 95] + [100] * 18 # 맨 위가 100으로 잘린 표 (원래 80~82 → 85·90·95, 83 이상은 모두 100)
fixed = straighten_top(clamped, top=100)
assert fixed[:80] == clamped[:80] # 아래쪽은 그대로
assert fixed[100] == 100 and max(fixed[:100]) < 100
above = fixed[80:]
assert all(a < b for a, b in zip(above, above[1:])) or above[-1] == 100 # 위쪽은 구별되는 점수로 오른다
assert straighten_top(clamped, top=90)[90] == 100 # 완벽한 점수가 100보다 낮은 구간(밤)은 거기서 100
def test_weather_table_gives_100_only_at_the_best_reachable_original_score():
assert WEATHER_SCORE_TABLE["day"][99] < 100 == WEATHER_SCORE_TABLE["day"][100]
night_top = 100 - WEATHER_SCORE_DEF.weight_sun # 밤은 해 난 비율이 늘 0점이라 원래 점수가 85까지만 나온다
assert WEATHER_SCORE_TABLE["night"][night_top - 1] < 100 == WEATHER_SCORE_TABLE["night"][night_top]
+1 -1
View File
@@ -10,7 +10,7 @@
- 시간대가 여러 개면 그중 가장 좋은 시간대 점수를 씁니다.
- 미세먼지는 초미세먼지 15㎍/㎥ 이하 100점 → 75㎍/㎥ 이상 0점입니다. 집콕각처럼 규칙을 따로 적은 각만 거꾸로(탁할수록 좋음) 셉니다.
- 바람·미세먼지·노을 정보가 없으면 70점으로 둡니다.
- 순위는 점수 × 중요도 가중치(상 1.0 · 중 0.85 · 하 0.7)로 정합니다. 화면에 보이는 점수는 그대로입니다.
- 최종 점수는 원점수 × 중요도 배율(상 1.0 · 중 0.85 · 하 0.7)을 정수로 반올림한 값입니다. 순위와 화면 표시 모두 이 최종 점수를 사용합니다.
## 한눈에 보기
+87
View File
@@ -0,0 +1,87 @@
# 검색 노출 기록
순위 = 결과에서 weather.o2o.kr이 몇 번째 사이트인지(같은 사이트는 한 번만 셈). `-` 첫 페이지에 없음. 적힌 검색어만 나온 것, 나머지는 `-`.
구글은 첫 페이지(사이트 6~9개)만 본다. 로그인한 브라우저·위치(성남) 기준.
## 검색어 묶음
- 기본: 날씨각 · 오늘 날씨 · 분당구 오늘 날씨 · 분당 날씨 · 성남 오늘 날씨 · 마포구 오늘 날씨 · 마포구 날씨 · 강남구 오늘 날씨 · 세차하기 좋은 날 · 빨래하기 좋은 날 · 오늘 노을 시간 · 이번 주말 날씨 · 세차각
- 지역(10/20~): 아래 29곳 × `{지역} 날씨` · `{지역} 오늘 날씨` · `오늘 {지역} 날씨`
분당구 성남 수원 부평구 연수구 강남구 구로구 마포구 성동구 송파구 / 서울 중구 광주 남구 이천 완도 동해 시흥 김해 춘천 수성구 화성 군산 제주 / 청주 상당구 용인 처인구 전주 완산구 포항 남구 해운대구 노원구 관악구
- 일반(10/20~): 날씨 각 · 날씨각 성남 · 오늘 일몰 시간 · 노을 시간 · 세차 날씨 · 빨래 날씨 · 등산 날씨 · 캠핑 날씨 · 산책하기 좋은 날씨 · 오늘 우산 필요 · 미세먼지 오늘
## 기록
| 날짜 | 엔진 | 범위 | 나온 검색어 (순위 · 주소) | 색인 수 | 비고 |
|---|---|---|---|---|---|
| 10/19 | 구글 | 기본 | 날씨각 3 | 약 10 | 사이트 이름 '에이아이오투오' |
| 10/19 | 네이버 | 기본 | 날씨각 1, 마포구 오늘 날씨 9 | 10 | |
| 10/20 | 구글 | 기본 | 날씨각 3 | | 사이트 이름 '에이아이오투오' |
| 10/20 | 네이버 | 기본 | 날씨각 1, 마포구 오늘 날씨 약 11, 강남구 오늘 날씨 약 6 | 10 | 분당·성남 3개 차단 |
| 10/20 밤 | 구글 | 기본+분당구·성남 날씨 | 날씨각 2 | 51 (`/today` 47, 구 주소 5) | 구 주소 색인: 분당·청주 상당·용인 처인·전주 완산·포항 남 |
| 10/20 밤 | 네이버 | 지역+일반 98개 | 날씨각 성남 1 `/today/gyeonggi/seongnam`, 부평구 오늘 6, 연수구 오늘 6, 강남구 오늘 6, 구로구 오늘 7, 성동구 오늘 7, 송파구 오늘 8, 마포구 오늘 12 | 10 | 색인: 홈·성남·수원·부평·연수·강남·구로·마포·성동·송파 |
| 10/21 | 구글 | 기본 2개 + 지역 11곳(분당구~서울 중구) | 날씨각 4 | | 37번째부터 막힘, 나머지 66개 못 봄 |
| 10/21 | 구글 | 구 39개 `오늘 {구} 날씨` (1~2페이지) | 구 주소로 25개: 장안·권선·팔달·영통·수정·만안·동안·원미·소사·덕양·일산동·일산서·수지·효행(1페이지)·병점·동탄·상당·서원·흥덕·청원·천안서북·의창·성산·완산·덕진. 시 주소로 2개: 중원→`/seongnam`, 만세→`/hwaseong` | 구 39개 모두 색인 | 없음 12개: 분당(2p에 보였다 안 보였다)·오정·상록·단원·처인·기흥·천안동남·포항남·포항북·마산합포·마산회원·진해 |
| 10/21 | 네이버 | 구 39개 `오늘 {구} 날씨` | 0개 | 구 주소 색인 0 | |
| 10/21 | 네이버 | 지역+일반 98개 | 날씨각 성남 1, 강남구 오늘 4, 연수구 오늘 5, 구로구 오늘 6, 날씨 각 6 `/`, 송파구 오늘 8, 마포구 오늘 10, 부평구 오늘 14 | | 성동구 오늘 빠짐 |
| 10/23 | 구글 | 10/21 없던 구 12개 `오늘 {구} 날씨`(1~2p) + 분당 + 내일 5개 + 날씨각 | 2p로 들어옴 7개: 오정 4·상록 6·단원 4·기흥 8(`/tomorrow/` 주소)·천안동남 7·마산합포 5·분당 6. `내일 날씨 뭐 할까` **1p 4위** `/tomorrow/gyeonggi/seongnam`. 날씨각 2 | 약 347 (10/20 51) | 여전히 없음 5개: 처인·포항남·포항북·마산회원·진해. `분당구·성남·수원·강남구 내일 날씨` 1p 없음. 1p는 전부 0 |
| 10/23 | 네이버 | 지역 29곳×4꼴(`내일` 추가) + 일반 13 + 구 39개 `오늘 {구} 날씨` (168개) | 날씨각 **1** (새로 나옴), 날씨각 성남 1, `{구} 오늘 날씨`: 부평 5·강남 5·성동 5·연수 6·구로 6·마포 6·송파 7, `오늘 {구} 날씨`(10/21엔 0): 성동 6·부평 7·강남 7·구로 10·마포 10·송파 10·연수 11 | 16 이상 (10/21 10) | 새 색인: 서울 종로·중구·용산, /sky·/week·/season. 경기 등 구 39개 여전히 0, `내일 날씨` 꼴 0 |
## 구글 구 39개 표
`2p6` = 2페이지 6번째 사이트. `내일` = 내일 페이지(`/tomorrow/`)가 나옴, `시` = 구 대신 시 페이지. `-` = 2페이지 안에 없음, 빈칸 = 안 봄.
| 구 | 10/21 `오늘 {구} 날씨` | 10/23 `오늘 {구} 날씨` | 10/23 `{구} 오늘 날씨` |
|---|---|---|---|
| 수원 장안 | 2p | | 2p6 |
| 수원 권선 | 2p | | 2p7 |
| 수원 팔달 | 2p | | 2p6 내일 |
| 수원 영통 | 2p | | 2p5 내일 |
| 성남 수정 | 2p | | 2p7 시 |
| 성남 중원 | 2p 시 | | 2p6 시 |
| 성남 분당 | - | 2p6 | 2p4 |
| 안양 만안 | 2p | | 2p5 |
| 안양 동안 | 2p | | 2p6 내일 |
| 부천 원미 | 2p | | 2p6 |
| 부천 소사 | 2p | | 2p5 |
| 부천 오정 | - | 2p4 | 2p2 내일 |
| 안산 상록 | - | 2p6 | 2p6 |
| 안산 단원 | - | 2p4 | - |
| 고양 덕양 | 2p | | 2p6 |
| 고양 일산동 | 2p | | 2p5 |
| 고양 일산서 | 2p | | - |
| 용인 처인 | - | - | 2p8 |
| 용인 기흥 | - | 2p8 내일 | - |
| 용인 수지 | 2p | | 2p7 |
| 화성 만세 | 2p 시 | | 2p3 |
| 화성 효행 | **1p** | | 2p1 내일 |
| 화성 병점 | 2p | | 2p4 |
| 화성 동탄 | 2p | | 2p7 내일 |
| 청주 상당 | 2p | | |
| 청주 서원 | 2p | | |
| 청주 흥덕 | 2p | | |
| 청주 청원 | 2p | | |
| 천안 동남 | - | 2p7 | |
| 천안 서북 | 2p | | |
| 포항 남 | - | - | |
| 포항 북 | - | - | |
| 창원 의창 | 2p | | |
| 창원 성산 | 2p | | |
| 창원 마산합포 | - | 2p5 | |
| 창원 마산회원 | - | - | |
| 창원 진해 | - | - | |
| 전주 완산 | 2p | | |
| 전주 덕진 | 2p | | |
## 메모
- 네이버는 `{구} 오늘 날씨` 꼴에서만 나온다. 같은 구라도 `{구} 날씨`·`오늘 {구} 날씨`는 안 나온다.
- 네이버는 색인된 9곳 밖 지역이 나올 수 없다. 성남·수원은 색인돼 있어도 안 나온다.
- 구글은 브라우저 fetch로 30여 개 치면 막힌다(결과 대신 확인 화면 → 보안문자). 하루 30개 안쪽으로 나눠 치거나 서치 콘솔 실적 보고서로 본다.
- 10/21 구글 '오늘 분당구 날씨' **2페이지**에 `/today/gyeonggi/seongnam/bundang`(제목 '분당구 오늘 날씨, 뭐 할까? · 성남시') 나옴. 사용자 화면 2번째, 내 화면 9번째. 10/20 배포한 구 주소가 하루 만에 잡힘. 첫 페이지만 보는 테스트로는 놓친다 → 2페이지까지 본다.
- 10/21 떨어진 것 확인: 우리 페이지(제목·설명·canonical)는 그대로, 네이버 색인 10개도 그대로(성동·부평 포함). 부평구 오늘 6→14는 위에 뉴스 4곳(newsinside·wikitree·YTN·KBS)이 새로 들어옴(비 오는 날). 성동구 오늘은 결과 사이트가 9곳뿐인 판에서 빠짐, 1~9위는 기상청·웨더아이·weather.com·accuweather 등. 구글 날씨각 2→4는 위 사이트를 저장 안 해서 원인 못 봄 → 다음부터 상위 사이트도 저장.
- 10/21 같은 날 1시간 안에 다시 쳤더니 성동구 오늘 -→6, 부평구 오늘 14→9, 강남구 4→5, 송파 8→7. 네이버는 요청마다 뉴스 칸 등 구성이 바뀌어 ±5 안팎 변동은 잡음. 하루 비교로 오르내림 판단 금지, 3일 이상 같은 방향일 때만 원인 분석.
- 10/21 서치 콘솔 URL 검사: 구 주소 39개 모두 "URL이 Google에 등록되어 있음" → 구글은 색인 문제가 아니라 순위 문제. 색인 생성 요청 안 함.
- 상위 사이트 목록: `docs/search_log/날짜_naver_top.tsv` (10/21, 10/23) (검색어 → 1~15위 호스트). 다음 날 이 파일과 비교해 누가 새로 위에 들어왔는지 본다.
- 10/20 구글 '분당구 오늘 날씨' 1~8위는 모두 제목에 '분당구'가 있는 구 단위 페이지.
- 10/23 서치 콘솔 URL 검사: 내일 페이지 13곳(송파·남양주·평택·강서·강남·달서·김해·시흥·파주·광진·부산진·완도·진해) 모두 "URL이 Google에 등록되어 있음" → 구글은 사이트맵으로 내일 페이지를 이미 가져감, 색인 요청 안 함. 네이버 서치어드바이저는 Claude in Chrome에서 막혀 사람이 넣어야 함(순서: `docs/search_log/색인요청_인구순.txt`).
+5 -5
View File
@@ -175,21 +175,21 @@
### 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) | 사진산책각 |
- **며칠 뒤 비까지 보는 각:** 세차각은 비 올 확률을 2일 뒤까지 보고, 그중 가장 높은 값을 씁니다.
- **순위** = 점수 × 중요도(상 1.0 · 중 0.85 · 하 0.7). 화면에 보이는 숫자는 곱하기 전 점수입니다.
- **최종 점수**는 원점수 × 중요도 배율(상 1.0 · 중 0.85 · 하 0.7)을 정수로 반올림한 값입니다. 순위와 화면 표시에 같은 점수를 사용합니다.
- **먼 날의 예상 점수:** 단기예보가 닿지 않는 날(주말 등)은 중기예보의 최저·최고 기온으로 시간별 기온을 어림합니다(새벽 6시 최저, 오후 3시 최고, 그 사이는 코사인 곡선). 비 확률은 오전·오후 값을 쓰고, 바람·습도·미세먼지·햇빛은 정보 없음(70점)입니다. 조건은 비 확률만 봅니다.
### 2-8. 나들이 점수 (주말 전국 순위, 당일치기)
+27 -10
View File
@@ -56,7 +56,7 @@
## 3. 지금 날씨 점수
**지금 구간**의 모든 시각이 밖에 나가기 좋은 정도. 1의 방식으로 계산합니다. 밤에는 밤 날씨 기준이라 낮보다 낮게 나오기 쉽습니다.
**지금 구간**의 모든 시각이 밖에 나가기 좋은 정도. 1의 방식으로 섞되 **'가장 낮은 요소로 깎기'(1의 3번)는 하지 않고**, 섞은 점수를 아래 '표시 점수로 바꾸기'로 바꿔 보여 줍니다. 밤엔 해 난 비율이 늘 0점이라 깎기를 하면 밤 점수가 62점을 못 넘었습니다 (`WEATHER_SCORE_DEF.worst_pull = False`).
| 요소 | 비중 | 100점 조건 |
|---|---:|---|
@@ -67,18 +67,32 @@
| 초미세먼지 | 10% | 10㎍/㎥ 이하 (75에서 0점) |
| 해 난 비율 (Open-Meteo) | 15% | 90% 이상 (20%에서 0점), 정보 없으면 70점 |
여섯 가지가 동시에 맞아야 100점입니다. 기준값은 눈대중으로 잡은 것이며 (낮 기준 최적값을 밤에도 똑같이 씀), 실제로 1년에 며칠 나오는지는 확인하지 않았습니다.
위 표의 점수가 **원래 점수**입니다. 밤엔 해 난 비율이 0점이라 나머지가 모두 만점이어도 85점이 최대입니다.
### 표시 점수로 바꾸기
원래 점수는 40~60점대에 몰리고 좋은 계절 낮에 90점 이상이 자주 나와 점수 분포가 고르지 않았습니다. 그래서 원래 점수를 **구간(아침·낮·저녁·밤)마다 1년 치 분포에서의 순위**로 보고, 평균 60·표준편차 15인 정규분포의 같은 위치 점수로 바꿔 보여 줍니다. 순서는 그대로라 더 좋은 날씨가 더 낮은 점수를 받는 일은 없습니다.
- 표시 점수 평균은 구간마다 60. 90점 이상은 약 1.5% (낮 약 2.7%, 그 밖 구간 약 1%), 80점 이상은 약 9%, 40점 미만도 약 9%입니다. 100점은 구간에서 나올 수 있는 가장 높은 원래 점수일 때만 나와 1년에 거의 안 나옵니다. 계절 차이는 남습니다 (가을 평균 약 68, 겨울 약 54).
- **위쪽 끝은 직선으로 이어 100점이 잘리지 않게 합니다.** 순위로만 바꾸면 위쪽 0.4%가 한꺼번에 100점으로 잘려 비슷한 원래 점수(96·97·99)가 모두 100점이 됩니다. 그래서 표시 점수 83 이하인 마지막 원래 점수에서 100점까지 직선으로 이어(`straighten_top`), 100점은 원래 점수 100(밤은 해 난 비율이 0점이라 85)에서만, 그 아래는 서로 다른 점수가 되게 했습니다.
- 구간마다 따로 바꾸는 이유: 한 표로 하면 밤 점수가 최대 70점대 초반에 머뭅니다. 구간별 표는 "그 시간대치고 얼마나 좋은 날씨인가"를 뜻합니다.
- 0~5시(전날 밤 구간)는 밤 표를 씁니다.
- 바꾸기 표: `backend/services/calc/weather_score_table.json` (`calibrated_weather`). 만드는 법: `cd backend && python scripts/gen_weather_score_table.py`. 지금 날씨 점수의 요소·비중·기준값(`WEATHER_SCORE_DEF`)이 바뀌면 다시 만들어야 합니다.
- 표 재료: Open-Meteo 과거 예보로 32개 지역(region.csv 8곳마다 1곳)의 최근 364일을 계산. 실제 앱은 기상청 단기예보를 쓰므로 분포가 조금 다를 수 있어, 기상청 자료가 쌓이면 다시 만드는 게 좋습니다.
- **각 점수에는 적용하지 않습니다.**
예: 체감 22.5°, 비 10%, 바람 2.5m, 습도 62%, 초미세먼지 15, 해 70% → 원래 점수는 95점 미만(깎기를 뺀 값).
예: 체감 22.5°, 비 10%, 바람 2.5m, 습도 62%, 초미세먼지 15, 해 70% → 95점 미만.
## 4. 각 점수
- 1의 방식. 요소·비중·시간대·0점 조건은 각마다 다르며 [각_계산기준.md](각_계산기준.md)에 있습니다.
- **오늘 점수 = 지금 구간 점수.** 각의 시간대 중 지금 구간에 드는 시각만으로 계산합니다(시간대가 여러 개면 그중 가장 좋은 쪽). 비가 오면 그 뒤 구간 점수가 내려갑니다.
- 각의 시간대가 지금 구간과 겹치지 않으면(예: 아침의 야장각) **순위·피드 카드·히어로 1위에서 빠집니다.** 스토리·각 탭 '전체'에는 맨 뒤에 '지금 아님'으로 남고, 점수는 하루 점수(가장 좋은 시간대)입니다.
- 각 상세 창에 오늘 아침·낮·저녁·밤 점수를 보여 줍니다. 안 겹치는 구간은 '–'.
- **오늘 점수 = 지금 구간 점수.** 지금 구간의 날씨로 계산하며, 현재 구간은 이미 지난 시각을 제외합니다. 비가 오면 그 뒤 구간 점수가 내려갑니다.
- 각의 시간대가 지금 구간과 겹치지 않아도 **현재 구간의 날씨 점수로 활성화하고 순위·피드 카드·히어로 1위 후보에 포함합니다.** 제철이 아닌 각의 비활성화는 유지합니다.
- **시간대 알맞음:** 활동 시간대와 겹치면 요소 점수 100점, 아니면 0점입니다. 가중치가 10%라면 10점 또는 0점을 반영하고, 불일치에 따른 추가 최저 요소 감점은 없습니다. 요일·달·노을·일출 요소는 기존 계산을 유지합니다.
- 각 상세 창과 시간대 미리보기의 아침·낮·저녁·밤 점수도 각 구간의 날씨로 계산하며 하루 점수로 대체하지 않습니다.
- 내일·토·일 칸은 하루 점수(가장 좋은 시간대)입니다.
- 순위는 점수 × 중요도(상 1.0 · 중 0.85 · 하 0.7). 화면 숫자는 점수 그대로입니다.
- 최종 점수는 원점수 × 중요도 배율(상 1.0 · 중 0.85 · 하 0.7)을 정수로 반올림한 값입니다. 순위와 화면 표시 모두 이 최종 점수를 사용합니다.
- 단기예보가 닿지 않는 날(토·일 등)은 중기예보의 최저·최고 기온으로 시각별 기온을 어림하고(새벽 6시 최저, 오후 3시 최고, 코사인 곡선), 바람·습도·미세먼지는 정보 없음으로 둔 '예상 점수'입니다.
## 5. 나들이 점수 (주말 순위·당일치기)
@@ -88,15 +102,18 @@
| 요소 | 비중 | 계산 |
|---|---:|---|
| 비 | 40% | 마른 날 규칙 (1 참고) |
| 체감온도 | 35% | 편한 범위 17~24°, 최적 21° |
| 체감온도 | 35% | 편한 범위 17~24°, 최적 21° (21°±0.5°만 100점, 만점 폭을 좁혀 같은 예보의 여러 지역이 다 100점이 되지 않게 함) |
| 하늘 | 15% | 시간마다 맑음 100 · 구름많음 80 · 흐림 50의 평균 |
| 바람 | 10% | 4m/s 이하 100 → 12m/s 0 |
| 바람 | 10% | 초속 1m 이하 100 → 2m에서 85 → 12m에서 0 |
- 1처럼 가장 낮은 요소로 깎습니다.
- 비 소식이 있거나 비 확률 60% 이상이면 **최대 30점**.
- 중기예보뿐인 날은 기온을 어림하고 바람은 70점입니다.
- 위 계산으로 나온 점수가 **원래 점수**이고, 화면에는 지금 날씨 점수(3절)와 같은 방식으로 **표시 점수로 바꿔** 보여 줍니다. 1년 치 원래 점수 분포의 순위를 평균 60·표준편차 15 정규분포의 같은 위치 점수로 바꾸는 것으로, 순서는 그대로입니다. 구간은 낮 하나라 표도 하나입니다. 원래 점수 50은 62점이고, 90점 이상은 원래 점수 94 이상에서만 나옵니다. 위쪽 끝은 3절처럼 직선으로 이어(`straighten_top`) **100점은 원래 점수 100(완벽한 날)일 때만** 나오고, 그 아래는 99→98, 97→95, 96→93, 95→92, 94→90처럼 서로 다른 점수가 됩니다. 맑고 알맞은 날이 100점으로 몰려 동점이 되던 것을 막습니다.
- 바꾸기 표: `backend/services/calc/outing_score_table.json` (`calibrated_outing`, `weekend_rank.py`). 만드는 법: `cd backend && python scripts/gen_outing_score_table.py`. 나들이 점수 규칙이 바뀌면 다시 만들어야 합니다. 표는 Open-Meteo 과거 예보(32개 지역, 364일)로 만들어 기상청 예보와 분포가 조금 다를 수 있습니다. 중기예보로 어림한 예상 점수에도 같은 표를 씁니다.
- 순위 캐시(`weekend_rank:v2:<토요일 날짜>`)는 표시 점수를 담습니다. 바꾸기 표를 적용하면서 키를 올려 옛 점수 캐시를 쓰지 않게 했습니다.
- 전국 순위: 노을 순위 대표 30곳을 점수순으로 정렬합니다.
- 당일치기: 내 지역에서 직선 20~200km 안 후보 도시 중 토·일 중 더 좋은 날 점수가 가장 높은 곳입니다. 동점이면 비 확률이 낮은 곳 → 이른 날 → 가까운 곳 순입니다. 1위가 50점 미만이면 카드를 보이지 않습니다.
- 당일치기: 내 지역에서 직선 20~200km 안 후보 도시 중 토·일 중 더 좋은 날 점수가 가장 높은 곳입니다. 동점이면 비 확률이 낮은 곳 → 이른 날 → 가까운 곳 순입니다. 1위가 50점 미만이면 카드를 보이지 않습니다. 표시 점수 기준 최소 62점(원래 점수 50과 같은 날씨 수준, `TRIP_MIN_SCORE`) 이상이어야 추천합니다.
## 6. 노을 점수
+1 -1
View File
@@ -8,7 +8,7 @@
- 제외: 소상공인·업종별 기능, 사용자 지수 만들기, 제철 식재료·축제(나중), 알림·제보
- 웹 먼저, 로그인 없음, 광고 없음, 국내 전국
- 웹 먼저, 로그인 없음, 피드 사이 인피드 광고(AdSense), 국내 전국
- 화면: PC와 모바일을 각각 설계. PC는 여러 지수를 한눈에, 카드 넘기기는 PC에서도 일부 유지
- 하루 날씨는 3시간 단위로 보여줌
- 공유: 이미지 카드 + 링크
+3 -3
View File
@@ -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. 저장과 갱신
+1
View File
@@ -10,6 +10,7 @@
gtag('config', 'G-D378J4X373');
</script>
<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-4414665130371841" crossorigin="anonymous"></script>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
<link rel="apple-touch-icon" href="/apple-touch-icon.png" />
+1
View File
@@ -0,0 +1 @@
google.com, pub-4414665130371841, DIRECT, f08c47fec0942fa0
+1 -1
View File
@@ -36,7 +36,7 @@
<p>회원 정보는 회원 탈퇴 시까지 보관하며, 탈퇴 요청을 받으면 지체 없이 파기합니다. 접속 기록은 「통신비밀보호법」에 따라 3개월간 보관합니다.</p>
<h2>3. 제3자 제공 및 처리 위탁</h2>
<p>회사는 이용자의 개인정보를 제3자에게 제공하지 않습니다. 이용 통계 분석을 위해 Google Analytics(Google LLC)를 사용하며, 이 과정에서 쿠키와 기기 정보가 Google에 전송될 수 있습니다. 브라우저 설정에서 쿠키를 거부할 수 있습니다.</p>
<p>회사는 이용자의 개인정보를 제3자에게 제공하지 않습니다. 이용 통계 분석을 위해 Google Analytics(Google LLC)를 사용하며, 이 과정에서 쿠키와 기기 정보가 Google에 전송될 수 있습니다. 광고 게재를 위해 Google AdSense(Google LLC)를 사용하며, Google은 쿠키로 이 사이트와 다른 사이트 방문 기록을 바탕으로 광고를 보여 줄 수 있습니다. 맞춤 광고는 Google 광고 설정(https://adssettings.google.com)에서 끌 수 있습니다. 브라우저 설정에서 쿠키를 거부할 수 있습니다.</p>
<h2>4. 파기 절차 및 방법</h2>
<p>보유 기간이 끝나거나 목적이 달성된 개인정보는 지체 없이 복구할 수 없는 방법으로 삭제합니다.</p>
+4
View File
@@ -1,8 +1,10 @@
import { BrowserRouter, Route, Routes } from 'react-router'
import { BLayout } from './b/BLayout'
import { FoliagePage } from './b/FoliagePage'
import { GakPage } from './b/GakPage'
import { SeasonPage } from './b/SeasonPage'
import { SkyPage } from './b/SkyPage'
import { TalkPage } from './b/TalkPage'
import { TodayPage } from './b/TodayPage'
import { WeekPage } from './b/WeekPage'
@@ -18,6 +20,8 @@ export default function App() {
<Route path="sky" element={<SkyPage />} />
<Route path="week" element={<WeekPage />} />
<Route path="season" element={<SeasonPage />} />
<Route path="foliage" element={<FoliagePage />} />
<Route path="talk" element={<TalkPage />} />
<Route path="*" element={<TodayPage />} />
</Route>
</Routes>
@@ -3,8 +3,8 @@
import { type DefaultError, type InfiniteData, infiniteQueryOptions, queryOptions, type UseMutationOptions } from '@tanstack/react-query';
import { client } from '../client.gen';
import { addComment, addMyGak, addTalk, authConfig, blockTalkAuthor, deleteComment, deleteMyGak, deleteTalk, getArticle, getFeed, getImage, getIndex, getPost, getSeasonWeek, getSky, getSkyRanking, getTalkImage, getTodayGuPage, getTodayPage, getWatchSummary, getWeatherNow, getWeatherToday, getWeek, getWeekRanking, googleLogin, healthzHealthzGet, likeComment, likePost, likeTalk, listArticles, listComments, listEvents, listIndices, listMyGak, listMyTalks, listPlaces, listPresets, listRegions, listSaved, listTalks, login, logout, me, nearestRegion, type Options, refresh, reportTalk, savePost, scoreMyGak, signup, unlikeComment, unlikePost, unlikeTalk, unsavePost, updateMe, uploadTalkImage } from '../sdk.gen';
import type { AddCommentData, AddCommentError, AddCommentResponse, AddMyGakData, AddMyGakError, AddMyGakResponse, AddTalkData, AddTalkError, AddTalkResponse, AuthConfigData, AuthConfigResponse, BlockTalkAuthorData, BlockTalkAuthorError, BlockTalkAuthorResponse, DeleteCommentData, DeleteCommentError, DeleteCommentResponse, DeleteMyGakData, DeleteMyGakError, DeleteMyGakResponse, DeleteTalkData, DeleteTalkError, DeleteTalkResponse, GetArticleData, GetArticleError, GetArticleResponse, GetFeedData, GetFeedError, GetFeedResponse, GetImageData, GetImageError, GetIndexData, GetIndexError, GetIndexResponse, GetPostData, GetPostError, GetPostResponse, GetSeasonWeekData, GetSeasonWeekResponse, GetSkyData, GetSkyError, GetSkyRankingData, GetSkyRankingResponse, GetSkyResponse, GetTalkImageData, GetTalkImageError, GetTodayGuPageData, GetTodayGuPageError, GetTodayGuPageResponse, GetTodayPageData, GetTodayPageError, GetTodayPageResponse, GetWatchSummaryData, GetWatchSummaryError, GetWatchSummaryResponse, GetWeatherNowData, GetWeatherNowError, GetWeatherNowResponse, GetWeatherTodayData, GetWeatherTodayError, GetWeatherTodayResponse, GetWeekData, GetWeekError, GetWeekRankingData, GetWeekRankingResponse, GetWeekResponse, GoogleLoginData, GoogleLoginError, GoogleLoginResponse, HealthzHealthzGetData, HealthzHealthzGetResponse, LikeCommentData, LikeCommentError, LikeCommentResponse, LikePostData, LikePostError, LikePostResponse, LikeTalkData, LikeTalkError, LikeTalkResponse, ListArticlesData, ListArticlesError, ListArticlesResponse, ListCommentsData, ListCommentsError, ListCommentsResponse, ListEventsData, ListEventsError, ListEventsResponse, ListIndicesData, ListIndicesError, ListIndicesResponse, ListMyGakData, ListMyGakError, ListMyGakResponse, ListMyTalksData, ListMyTalksError, ListMyTalksResponse, ListPlacesData, ListPlacesError, ListPlacesResponse, ListPresetsData, ListPresetsResponse, ListRegionsData, ListRegionsError, ListRegionsResponse, ListSavedData, ListSavedError, ListSavedResponse, ListTalksData, ListTalksError, ListTalksResponse, LoginData, LoginError, LoginResponse, LogoutData, LogoutError, LogoutResponse, MeData, MeError, MeResponse, NearestRegionData, NearestRegionError, NearestRegionResponse, RefreshData, RefreshError, RefreshResponse, ReportTalkData, ReportTalkError, ReportTalkResponse, SavePostData, SavePostError, SavePostResponse, ScoreMyGakData, ScoreMyGakError, ScoreMyGakResponse, SignupData, SignupError, SignupResponse, UnlikeCommentData, UnlikeCommentError, UnlikeCommentResponse, UnlikePostData, UnlikePostError, UnlikePostResponse, UnlikeTalkData, UnlikeTalkError, UnlikeTalkResponse, UnsavePostData, UnsavePostError, UnsavePostResponse, UpdateMeData, UpdateMeError, UpdateMeResponse, UploadTalkImageData, UploadTalkImageError, UploadTalkImageResponse } from '../types.gen';
import { addComment, addMyGak, addTalk, authConfig, blockTalkAuthor, deleteComment, deleteMyGak, deleteTalk, getArticle, getFeed, getImage, getIndex, getPost, getSeasonWeek, getSky, getSkyRanking, getTalkImage, getTodayGuPage, getTodayPage, getTomorrowGuPage, getTomorrowPage, getWatchSummary, getWeatherNow, getWeatherToday, getWeek, getWeekRanking, googleLogin, healthzHealthzGet, likeComment, likePost, likeTalk, listArticles, listComments, listEvents, listIndices, listMyGak, listMyTalks, listPlaces, listPresets, listRegions, listSaved, listTalks, login, logout, me, nearestRegion, type Options, refresh, reportTalk, savePost, scoreMyGak, signup, talkGroups, unlikeComment, unlikePost, unlikeTalk, unsavePost, updateMe, uploadTalkImage } from '../sdk.gen';
import type { AddCommentData, AddCommentError, AddCommentResponse, AddMyGakData, AddMyGakError, AddMyGakResponse, AddTalkData, AddTalkError, AddTalkResponse, AuthConfigData, AuthConfigResponse, BlockTalkAuthorData, BlockTalkAuthorError, BlockTalkAuthorResponse, DeleteCommentData, DeleteCommentError, DeleteCommentResponse, DeleteMyGakData, DeleteMyGakError, DeleteMyGakResponse, DeleteTalkData, DeleteTalkError, DeleteTalkResponse, GetArticleData, GetArticleError, GetArticleResponse, GetFeedData, GetFeedError, GetFeedResponse, GetImageData, GetImageError, GetIndexData, GetIndexError, GetIndexResponse, GetPostData, GetPostError, GetPostResponse, GetSeasonWeekData, GetSeasonWeekResponse, GetSkyData, GetSkyError, GetSkyRankingData, GetSkyRankingResponse, GetSkyResponse, GetTalkImageData, GetTalkImageError, GetTodayGuPageData, GetTodayGuPageError, GetTodayGuPageResponse, GetTodayPageData, GetTodayPageError, GetTodayPageResponse, GetTomorrowGuPageData, GetTomorrowGuPageError, GetTomorrowGuPageResponse, GetTomorrowPageData, GetTomorrowPageError, GetTomorrowPageResponse, GetWatchSummaryData, GetWatchSummaryError, GetWatchSummaryResponse, GetWeatherNowData, GetWeatherNowError, GetWeatherNowResponse, GetWeatherTodayData, GetWeatherTodayError, GetWeatherTodayResponse, GetWeekData, GetWeekError, GetWeekRankingData, GetWeekRankingResponse, GetWeekResponse, GoogleLoginData, GoogleLoginError, GoogleLoginResponse, HealthzHealthzGetData, HealthzHealthzGetResponse, LikeCommentData, LikeCommentError, LikeCommentResponse, LikePostData, LikePostError, LikePostResponse, LikeTalkData, LikeTalkError, LikeTalkResponse, ListArticlesData, ListArticlesError, ListArticlesResponse, ListCommentsData, ListCommentsError, ListCommentsResponse, ListEventsData, ListEventsError, ListEventsResponse, ListIndicesData, ListIndicesError, ListIndicesResponse, ListMyGakData, ListMyGakError, ListMyGakResponse, ListMyTalksData, ListMyTalksError, ListMyTalksResponse, ListPlacesData, ListPlacesError, ListPlacesResponse, ListPresetsData, ListPresetsResponse, ListRegionsData, ListRegionsError, ListRegionsResponse, ListSavedData, ListSavedError, ListSavedResponse, ListTalksData, ListTalksError, ListTalksResponse, LoginData, LoginError, LoginResponse, LogoutData, LogoutError, LogoutResponse, MeData, MeError, MeResponse, NearestRegionData, NearestRegionError, NearestRegionResponse, RefreshData, RefreshError, RefreshResponse, ReportTalkData, ReportTalkError, ReportTalkResponse, SavePostData, SavePostError, SavePostResponse, ScoreMyGakData, ScoreMyGakError, ScoreMyGakResponse, SignupData, SignupError, SignupResponse, TalkGroupsData, TalkGroupsError, TalkGroupsResponse, UnlikeCommentData, UnlikeCommentError, UnlikeCommentResponse, UnlikePostData, UnlikePostError, UnlikePostResponse, UnlikeTalkData, UnlikeTalkError, UnlikeTalkResponse, UnsavePostData, UnsavePostError, UnsavePostResponse, UpdateMeData, UpdateMeError, UpdateMeResponse, UploadTalkImageData, UploadTalkImageError, UploadTalkImageResponse } from '../types.gen';
export type QueryKey<TOptions extends Options> = [
Pick<TOptions, 'baseUrl' | 'body' | 'headers' | 'path' | 'query'> & {
@@ -831,6 +831,24 @@ export const deleteMyGakMutation = (options?: Partial<Options<DeleteMyGakData>>)
return mutationOptions;
};
export const talkGroupsQueryKey = (options?: Options<TalkGroupsData>) => createQueryKey('talkGroups', options);
/**
* 오늘 피드 묶음 (동네 사람들 + 주제별, 가까운 동네·덜 지난 글 먼저, 한 사람 한 장)
*/
export const talkGroupsOptions = (options?: Options<TalkGroupsData>) => queryOptions<TalkGroupsResponse, TalkGroupsError, TalkGroupsResponse, ReturnType<typeof talkGroupsQueryKey>>({
queryFn: async ({ queryKey, signal }) => {
const { data } = await talkGroups({
...options,
...queryKey[0],
signal,
throwOnError: true
});
return data;
},
queryKey: talkGroupsQueryKey(options)
});
export const listTalksQueryKey = (options?: Options<ListTalksData>) => createQueryKey('listTalks', options);
/**
@@ -1136,6 +1154,42 @@ export const getTodayGuPageOptions = (options: Options<GetTodayGuPageData>) => q
queryKey: getTodayGuPageQueryKey(options)
});
export const getTomorrowPageQueryKey = (options: Options<GetTomorrowPageData>) => createQueryKey('getTomorrowPage', options);
/**
* 지역 내일 날씨 페이지: 정적 HTML 에 내일 예보를 채운다 (nginx 가 /tomorrow/... 를 넘김)
*/
export const getTomorrowPageOptions = (options: Options<GetTomorrowPageData>) => queryOptions<GetTomorrowPageResponse, GetTomorrowPageError, GetTomorrowPageResponse, ReturnType<typeof getTomorrowPageQueryKey>>({
queryFn: async ({ queryKey, signal }) => {
const { data } = await getTomorrowPage({
...options,
...queryKey[0],
signal,
throwOnError: true
});
return data;
},
queryKey: getTomorrowPageQueryKey(options)
});
export const getTomorrowGuPageQueryKey = (options: Options<GetTomorrowGuPageData>) => createQueryKey('getTomorrowGuPage', options);
/**
* 구로 나뉜 시의 구 내일 날씨 페이지
*/
export const getTomorrowGuPageOptions = (options: Options<GetTomorrowGuPageData>) => queryOptions<GetTomorrowGuPageResponse, GetTomorrowGuPageError, GetTomorrowGuPageResponse, ReturnType<typeof getTomorrowGuPageQueryKey>>({
queryFn: async ({ queryKey, signal }) => {
const { data } = await getTomorrowGuPage({
...options,
...queryKey[0],
signal,
throwOnError: true
});
return data;
},
queryKey: getTomorrowGuPageQueryKey(options)
});
export const healthzHealthzGetQueryKey = (options?: Options<HealthzHealthzGetData>) => createQueryKey('healthzHealthzGet', options);
/**
+2 -2
View File
@@ -1,4 +1,4 @@
// This file is auto-generated by @hey-api/openapi-ts
export { addComment, addMyGak, addTalk, authConfig, blockTalkAuthor, deleteComment, deleteMyGak, deleteTalk, getArticle, getFeed, getImage, getIndex, getPost, getSeasonWeek, getSky, getSkyRanking, getTalkImage, getTodayGuPage, getTodayPage, getWatchSummary, getWeatherNow, getWeatherToday, getWeek, getWeekRanking, googleLogin, healthzHealthzGet, likeComment, likePost, likeTalk, listArticles, listComments, listEvents, listIndices, listMyGak, listMyTalks, listPlaces, listPresets, listRegions, listSaved, listTalks, login, logout, me, nearestRegion, type Options, refresh, reportTalk, savePost, scoreMyGak, signup, unlikeComment, unlikePost, unlikeTalk, unsavePost, updateMe, uploadTalkImage } from './sdk.gen';
export { type AddCommentData, type AddCommentError, type AddCommentErrors, type AddCommentResponse, type AddCommentResponses, type AddMyGakData, type AddMyGakError, type AddMyGakErrors, type AddMyGakResponse, type AddMyGakResponses, type AddTalkData, type AddTalkError, type AddTalkErrors, type AddTalkResponse, type AddTalkResponses, type AirData, AirGrade, ArticleCategory, type ArticleSummary, type AuthConfigData, type AuthConfigResponse, type AuthConfigResponses, AuthProvider, type BandArticle, type BandEvent, type Bands, type BestTime, type BlockTalkAuthorData, type BlockTalkAuthorError, type BlockTalkAuthorErrors, type BlockTalkAuthorResponse, type BlockTalkAuthorResponses, type BodyUploadTalkImageV1TalkImagePost, type ClientOptions, type CommentData, type CommuteData, Confidence, type Cut, type DayData, type DeleteCommentData, type DeleteCommentError, type DeleteCommentErrors, type DeleteCommentResponse, type DeleteCommentResponses, type DeleteMyGakData, type DeleteMyGakError, type DeleteMyGakErrors, type DeleteMyGakResponse, type DeleteMyGakResponses, type DeleteTalkData, type DeleteTalkError, type DeleteTalkErrors, type DeleteTalkResponse, type DeleteTalkResponses, type ErrorInfo, type EventData, type Factor, type GakSlide, type GetArticleData, type GetArticleError, type GetArticleErrors, type GetArticleResponse, type GetArticleResponses, type GetFeedData, type GetFeedError, type GetFeedErrors, type GetFeedResponse, type GetFeedResponses, type GetImageData, type GetImageError, type GetImageErrors, type GetImageResponses, type GetIndexData, type GetIndexError, type GetIndexErrors, type GetIndexResponse, type GetIndexResponses, type GetPostData, type GetPostError, type GetPostErrors, type GetPostResponse, type GetPostResponses, type GetSeasonWeekData, type GetSeasonWeekResponse, type GetSeasonWeekResponses, type GetSkyData, type GetSkyError, type GetSkyErrors, type GetSkyRankingData, type GetSkyRankingResponse, type GetSkyRankingResponses, type GetSkyResponse, type GetSkyResponses, type GetTalkImageData, type GetTalkImageError, type GetTalkImageErrors, type GetTalkImageResponses, type GetTodayGuPageData, type GetTodayGuPageError, type GetTodayGuPageErrors, type GetTodayGuPageResponse, type GetTodayGuPageResponses, type GetTodayPageData, type GetTodayPageError, type GetTodayPageErrors, type GetTodayPageResponse, type GetTodayPageResponses, type GetWatchSummaryData, type GetWatchSummaryError, type GetWatchSummaryErrors, type GetWatchSummaryResponse, type GetWatchSummaryResponses, type GetWeatherNowData, type GetWeatherNowError, type GetWeatherNowErrors, type GetWeatherNowResponse, type GetWeatherNowResponses, type GetWeatherTodayData, type GetWeatherTodayError, type GetWeatherTodayErrors, type GetWeatherTodayResponse, type GetWeatherTodayResponses, type GetWeekData, type GetWeekError, type GetWeekErrors, type GetWeekRankingData, type GetWeekRankingResponse, type GetWeekRankingResponses, type GetWeekResponse, type GetWeekResponses, type GoogleLoginData, type GoogleLoginError, type GoogleLoginErrors, type GoogleLoginResponse, type GoogleLoginResponses, type HealthzHealthzGetData, type HealthzHealthzGetResponse, type HealthzHealthzGetResponses, type Hero, type HeroStat, type HeroTomorrow, type HourCell, type HoursSlide, type HttpValidationError, IndexCategory, type IndexSummary, type LikeCommentData, type LikeCommentError, type LikeCommentErrors, type LikeCommentResponse, type LikeCommentResponses, type LikePostData, type LikePostError, type LikePostErrors, type LikePostResponse, type LikePostResponses, type LikeTalkData, type LikeTalkError, type LikeTalkErrors, type LikeTalkResponse, type LikeTalkResponses, type ListArticlesData, type ListArticlesError, type ListArticlesErrors, type ListArticlesResponse, type ListArticlesResponses, type ListCommentsData, type ListCommentsError, type ListCommentsErrors, type ListCommentsResponse, type ListCommentsResponses, type ListEventsData, type ListEventsError, type ListEventsErrors, type ListEventsResponse, type ListEventsResponses, type ListIndicesData, type ListIndicesError, type ListIndicesErrors, type ListIndicesResponse, type ListIndicesResponses, type ListMyGakData, type ListMyGakError, type ListMyGakErrors, type ListMyGakResponse, type ListMyGakResponses, type ListMyTalksData, type ListMyTalksError, type ListMyTalksErrors, type ListMyTalksResponse, type ListMyTalksResponses, type ListPlacesData, type ListPlacesError, type ListPlacesErrors, type ListPlacesResponse, type ListPlacesResponses, type ListPresetsData, type ListPresetsResponse, type ListPresetsResponses, type ListRegionsData, type ListRegionsError, type ListRegionsErrors, type ListRegionsResponse, type ListRegionsResponses, type ListSavedData, type ListSavedError, type ListSavedErrors, type ListSavedResponse, type ListSavedResponses, type ListTalksData, type ListTalksError, type ListTalksErrors, type ListTalksResponse, type ListTalksResponses, type LoginData, type LoginError, type LoginErrors, type LogLine truncated
export { addComment, addMyGak, addTalk, authConfig, blockTalkAuthor, deleteComment, deleteMyGak, deleteTalk, getArticle, getFeed, getImage, getIndex, getPost, getSeasonWeek, getSky, getSkyRanking, getTalkImage, getTodayGuPage, getTodayPage, getTomorrowGuPage, getTomorrowPage, getWatchSummary, getWeatherNow, getWeatherToday, getWeek, getWeekRanking, googleLogin, healthzHealthzGet, likeComment, likePost, likeTalk, listArticles, listComments, listEvents, listIndices, listMyGak, listMyTalks, listPlaces, listPresets, listRegions, listSaved, listTalks, login, logout, me, nearestRegion, type Options, refresh, reportTalk, savePost, scoreMyGak, signup, talkGroups, unlikeComment, unlikePost, unlikeTalk, unsavePost, updateMe, uploadTalkImage } from './sdk.gen';
export { type AddCommentData, type AddCommentError, type AddCommentErrors, type AddCommentResponse, type AddCommentResponses, type AddMyGakData, type AddMyGakError, type AddMyGakErrors, type AddMyGakResponse, type AddMyGakResponses, type AddTalkData, type AddTalkError, type AddTalkErrors, type AddTalkResponse, type AddTalkResponses, type AirData, AirGrade, ArticleCategory, type ArticleSummary, type AuthConfigData, type AuthConfigResponse, type AuthConfigResponses, AuthProvider, type BandArticle, type BandEvent, type Bands, type BestTime, type BlockTalkAuthorData, type BlockTalkAuthorError, type BlockTalkAuthorErrors, type BlockTalkAuthorResponse, type BlockTalkAuthorResponses, type BodyUploadTalkImageV1TalkImagePost, type ClientOptions, type CommentData, type CommuteData, Confidence, type Cut, type DayData, type DeleteCommentData, type DeleteCommentError, type DeleteCommentErrors, type DeleteCommentResponse, type DeleteCommentResponses, type DeleteMyGakData, type DeleteMyGakError, type DeleteMyGakErrors, type DeleteMyGakResponse, type DeleteMyGakResponses, type DeleteTalkData, type DeleteTalkError, type DeleteTalkErrors, type DeleteTalkResponse, type DeleteTalkResponses, type ErrorInfo, type EventData, type Factor, type GakSlide, type GetArticleData, type GetArticleError, type GetArticleErrors, type GetArticleResponse, type GetArticleResponses, type GetFeedData, type GetFeedError, type GetFeedErrors, type GetFeedResponse, type GetFeedResponses, type GetImageData, type GetImageError, type GetImageErrors, type GetImageResponses, type GetIndexData, type GetIndexError, type GetIndexErrors, type GetIndexResponse, type GetIndexResponses, type GetPostData, type GetPostError, type GetPostErrors, type GetPostResponse, type GetPostResponses, type GetSeasonWeekData, type GetSeasonWeekResponse, type GetSeasonWeekResponses, type GetSkyData, type GetSkyError, type GetSkyErrors, type GetSkyRankingData, type GetSkyRankingResponse, type GetSkyRankingResponses, type GetSkyResponse, type GetSkyResponses, type GetTalkImageData, type GetTalkImageError, type GetTalkImageErrors, type GetTalkImageResponses, type GetTodayGuPageData, type GetTodayGuPageError, type GetTodayGuPageErrors, type GetTodayGuPageResponse, type GetTodayGuPageResponses, type GetTodayPageData, type GetTodayPageError, type GetTodayPageErrors, type GetTodayPageResponse, type GetTodayPageResponses, type GetTomorrowGuPageData, type GetTomorrowGuPageError, type GetTomorrowGuPageErrors, type GetTomorrowGuPageResponse, type GetTomorrowGuPageResponses, type GetTomorrowPageData, type GetTomorrowPageError, type GetTomorrowPageErrors, type GetTomorrowPageResponse, type GetTomorrowPageResponses, type GetWatchSummaryData, type GetWatchSummaryError, type GetWatchSummaryErrors, type GetWatchSummaryResponse, type GetWatchSummaryResponses, type GetWeatherNowData, type GetWeatherNowError, type GetWeatherNowErrors, type GetWeatherNowResponse, type GetWeatherNowResponses, type GetWeatherTodayData, type GetWeatherTodayError, type GetWeatherTodayErrors, type GetWeatherTodayResponse, type GetWeatherTodayResponses, type GetWeekData, type GetWeekError, type GetWeekErrors, type GetWeekRankingData, type GetWeekRankingResponse, type GetWeekRankingResponses, type GetWeekResponse, type GetWeekResponses, type GoogleLoginData, type GoogleLoginError, type GoogleLoginErrors, type GoogleLoginResponse, type GoogleLoginResponses, type HealthzHealthzGetData, type HealthzHealthzGetResponse, type HealthzHealthzGetResponses, type Hero, type HeroStat, type HeroTomorrow, type HourCell, type HoursSlide, type HttpValidationError, IndexCategory, type IndexSummary, type LikeCommentData, type LikeCommentError, type LikeCommentErrors, type LikeCommentResponse, type LikeCommentResponses, type LikePostData, type LikePostError, type LikePostErrors, type LikePostResponse, type LikePostResponses, type LikeTalkData, type LikeTalkError, type LikeTalkErrors, type LikeTalkResponse, type LikeTalkResponses, type ListArticlesData, type ListArticlesError, type ListArticlesErrors, type ListArticlesResponse, type ListArticlesResponses, type ListCommentsData, type ListCommentsError, type ListCommentsErrors, type ListCommentsResponse, type ListCommentsResponses, type ListEventsData, type ListEventsError, type ListEventsErrors, type ListEventsResponse, type ListEventsResponses, type ListIndicesData, type ListIndicesError, type ListIndicesErrors, type ListIndicesResponse, type ListIndicesResponses, type ListMyGakData, type ListMyGakError, type ListMyGakErrors, type ListMyGakResponse, type ListMyGakResponses, type ListMyTalksData, type ListMyTalksError, type ListMyTalksErrors, type ListMyTalksResponse, type ListMyTalksResponses, type ListPlacesData, type ListPlacesError, type ListPlacesErrors, type ListPlacesResponse, type ListPlacesResponses, type ListPresetsData, type ListPresetsResponse, type ListPresetsResponses, type ListRegionsData, type ListRegionsError, type ListRegionsErrors, type ListRegionsResponse, type ListRegionsLine truncated
+16 -1
View File
@@ -2,7 +2,7 @@
import { type Client, type ClientMeta, formDataBodySerializer, type Options as Options2, type RequestResult, type TDataShape } from './client';
import { client } from './client.gen';
import type { AddCommentData, AddCommentErrors, AddCommentResponses, AddMyGakData, AddMyGakErrors, AddMyGakResponses, AddTalkData, AddTalkErrors, AddTalkResponses, AuthConfigData, AuthConfigResponses, BlockTalkAuthorData, BlockTalkAuthorErrors, BlockTalkAuthorResponses, DeleteCommentData, DeleteCommentErrors, DeleteCommentResponses, DeleteMyGakData, DeleteMyGakErrors, DeleteMyGakResponses, DeleteTalkData, DeleteTalkErrors, DeleteTalkResponses, GetArticleData, GetArticleErrors, GetArticleResponses, GetFeedData, GetFeedErrors, GetFeedResponses, GetImageData, GetImageErrors, GetImageResponses, GetIndexData, GetIndexErrors, GetIndexResponses, GetPostData, GetPostErrors, GetPostResponses, GetSeasonWeekData, GetSeasonWeekResponses, GetSkyData, GetSkyErrors, GetSkyRankingData, GetSkyRankingResponses, GetSkyResponses, GetTalkImageData, GetTalkImageErrors, GetTalkImageResponses, GetTodayGuPageData, GetTodayGuPageErrors, GetTodayGuPageResponses, GetTodayPageData, GetTodayPageErrors, GetTodayPageResponses, GetWatchSummaryData, GetWatchSummaryErrors, GetWatchSummaryResponses, GetWeatherNowData, GetWeatherNowErrors, GetWeatherNowResponses, GetWeatherTodayData, GetWeatherTodayErrors, GetWeatherTodayResponses, GetWeekData, GetWeekErrors, GetWeekRankingData, GetWeekRankingResponses, GetWeekResponses, GoogleLoginData, GoogleLoginErrors, GoogleLoginResponses, HealthzHealthzGetData, HealthzHealthzGetResponses, LikeCommentData, LikeCommentErrors, LikeCommentResponses, LikePostData, LikePostErrors, LikePostResponses, LikeTalkData, LikeTalkErrors, LikeTalkResponses, ListArticlesData, ListArticlesErrors, ListArticlesResponses, ListCommentsData, ListCommentsErrors, ListCommentsResponses, ListEventsData, ListEventsErrors, ListEventsResponses, ListIndicesData, ListIndicesErrors, ListIndicesResponses, ListMyGakData, ListMyGakErrors, ListMyGakResponses, ListMyTalksData, ListMyTalksErrors, ListMyTalksResponses, ListPlacesData, ListPlacesErrors, ListPlacesResponses, ListPresetsData, ListPresetsResponses, ListRegionsData, ListRegionsErrors, ListRegionsResponses, ListSavedData, ListSavedErrors, ListSavedResponses, ListTalksData, ListTalksErrors, ListTalksResponses, LoginData, LoginErrors, LoginResponses, LogoutData, LogoutErrors, LogoutResponses, MeData, MeErrors, MeResponses, NearestRegionData, NearestRegionErrors, NearestRegionResponses, RefreshData, RefreshErrors, RefreshResponses, ReportTalkData, ReportTalkErrors, ReportTalkResponses, SavePostData, SavePostErrors, SavePostResponses, ScoreMyGakData, ScoreMyGakErrors, ScoreMyGakResponses, SignupData, SignupErrors, SignupResponses, UnlikeCommentData, UnlikeCommentErrors, UnlikeCommentResponses, UnlikePostData, UnlikePostErrors, UnlikePostResponses, UnlikeTalkData, UnlikeTalkErrors, UnlikeTalkResponses, UnsavePostData, UnsavePostErrors, UnsavePostResponses, UpdateMeData, UpdateMeErrors, UpdateMeResponses, UploadTalkImageData, UploadTalkImageErrors, UploadTalkImageResponses } from './types.gen';
import type { AddCommentData, AddCommentErrors, AddCommentResponses, AddMyGakData, AddMyGakErrors, AddMyGakResponses, AddTalkData, AddTalkErrors, AddTalkResponses, AuthConfigData, AuthConfigResponses, BlockTalkAuthorData, BlockTalkAuthorErrors, BlockTalkAuthorResponses, DeleteCommentData, DeleteCommentErrors, DeleteCommentResponses, DeleteMyGakData, DeleteMyGakErrors, DeleteMyGakResponses, DeleteTalkData, DeleteTalkErrors, DeleteTalkResponses, GetArticleData, GetArticleErrors, GetArticleResponses, GetFeedData, GetFeedErrors, GetFeedResponses, GetImageData, GetImageErrors, GetImageResponses, GetIndexData, GetIndexErrors, GetIndexResponses, GetPostData, GetPostErrors, GetPostResponses, GetSeasonWeekData, GetSeasonWeekResponses, GetSkyData, GetSkyErrors, GetSkyRankingData, GetSkyRankingResponses, GetSkyResponses, GetTalkImageData, GetTalkImageErrors, GetTalkImageResponses, GetTodayGuPageData, GetTodayGuPageErrors, GetTodayGuPageResponses, GetTodayPageData, GetTodayPageErrors, GetTodayPageResponses, GetTomorrowGuPageData, GetTomorrowGuPageErrors, GetTomorrowGuPageResponses, GetTomorrowPageData, GetTomorrowPageErrors, GetTomorrowPageResponses, GetWatchSummaryData, GetWatchSummaryErrors, GetWatchSummaryResponses, GetWeatherNowData, GetWeatherNowErrors, GetWeatherNowResponses, GetWeatherTodayData, GetWeatherTodayErrors, GetWeatherTodayResponses, GetWeekData, GetWeekErrors, GetWeekRankingData, GetWeekRankingResponses, GetWeekResponses, GoogleLoginData, GoogleLoginErrors, GoogleLoginResponses, HealthzHealthzGetData, HealthzHealthzGetResponses, LikeCommentData, LikeCommentErrors, LikeCommentResponses, LikePostData, LikePostErrors, LikePostResponses, LikeTalkData, LikeTalkErrors, LikeTalkResponses, ListArticlesData, ListArticlesErrors, ListArticlesResponses, ListCommentsData, ListCommentsErrors, ListCommentsResponses, ListEventsData, ListEventsErrors, ListEventsResponses, ListIndicesData, ListIndicesErrors, ListIndicesResponses, ListMyGakData, ListMyGakErrors, ListMyGakResponses, ListMyTalksData, ListMyTalksErrors, ListMyTalksResponses, ListPlacesData, ListPlacesErrors, ListPlacesResponses, ListPresetsData, ListPresetsResponses, ListRegionsData, ListRegionsErrors, ListRegionsResponses, ListSavedData, ListSavedErrors, ListSavedResponses, ListTalksData, ListTalksErrors, ListTalksResponses, LoginData, LoginErrors, LoginResponses, LogoutData, LogoutErrors, LogoutResponses, MeData, MeErrors, MeResponses, NearestRegionData, NearestRegionErrors, NearestRegionResponses, RefreshData, RefreshErrors, RefreshResponses, ReportTalkData, ReportTalkErrors, ReportTalkResponses, SavePostData, SavePostErrors, SavePostResponses, ScoreMyGakData, ScoreMyGakErrors, ScoreMyGakResponses, SignupData, SignupErrors, SignupResponses, TalkGroupsData, TalkGroupsErrors, TalkGroupsResponses, UnlikeCommentData, UnlikeCommentErrors, UnlikeCommentResponses, UnlikePostData, UnlikePostErrors, UnlikePostResponses, UnlikeTalkData, UnlikeTalkErrors, UnlikeTalkResponses, UnsavePostData, UnsavePostErrors, UnsavePostResponses, UpdateMeData, UpdateMeErrors, UpdateMeResponses, UploadTalkImageData, UploadTalkImageErrors, UploadTalkImageResponses } from './types.gen';
export type Options<TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown> = Options2<TData, ThrowOnError, TResponse> & {
/**
@@ -274,6 +274,11 @@ export const scoreMyGak = <ThrowOnError extends boolean = true>(options: Options
*/
export const deleteMyGak = <ThrowOnError extends boolean = true>(options: Options<DeleteMyGakData, ThrowOnError>): RequestResult<DeleteMyGakResponses, DeleteMyGakErrors, ThrowOnError> => (options.client ?? client).delete<DeleteMyGakResponses, DeleteMyGakErrors, ThrowOnError>({ url: '/v1/my-gak/{my_gak_id}', ...options });
/**
* 오늘 피드 묶음 (동네 사람들 + 주제별, 가까운 동네·덜 지난 글 먼저, 한 사람 한 장)
*/
export const talkGroups = <ThrowOnError extends boolean = true>(options?: Options<TalkGroupsData, ThrowOnError>): RequestResult<TalkGroupsResponses, TalkGroupsErrors, ThrowOnError> => (options?.client ?? client).get<TalkGroupsResponses, TalkGroupsErrors, ThrowOnError>({ url: '/v1/talk/groups', ...options });
/**
* 동네 이야기 (전국 최신순, 보는 동네와 같은 시도 글은 앞으로, 같은 사람 글은 띄움, 로그인 없이 보기)
*/
@@ -366,6 +371,16 @@ export const getTodayPage = <ThrowOnError extends boolean = true>(options: Optio
*/
export const getTodayGuPage = <ThrowOnError extends boolean = true>(options: Options<GetTodayGuPageData, ThrowOnError>): RequestResult<GetTodayGuPageResponses, GetTodayGuPageErrors, ThrowOnError> => (options.client ?? client).get<GetTodayGuPageResponses, GetTodayGuPageErrors, ThrowOnError>({ url: '/v1/seo/today/{sido}/{place}/{gu}', ...options });
/**
* 지역 내일 날씨 페이지: 정적 HTML 에 내일 예보를 채운다 (nginx 가 /tomorrow/... 를 넘김)
*/
export const getTomorrowPage = <ThrowOnError extends boolean = true>(options: Options<GetTomorrowPageData, ThrowOnError>): RequestResult<GetTomorrowPageResponses, GetTomorrowPageErrors, ThrowOnError> => (options.client ?? client).get<GetTomorrowPageResponses, GetTomorrowPageErrors, ThrowOnError>({ url: '/v1/seo/tomorrow/{sido}/{place}', ...options });
/**
* 구로 나뉜 시의 구 내일 날씨 페이지
*/
export const getTomorrowGuPage = <ThrowOnError extends boolean = true>(options: Options<GetTomorrowGuPageData, ThrowOnError>): RequestResult<GetTomorrowGuPageResponses, GetTomorrowGuPageErrors, ThrowOnError> => (options.client ?? client).get<GetTomorrowGuPageResponses, GetTomorrowGuPageErrors, ThrowOnError>({ url: '/v1/seo/tomorrow/{sido}/{place}/{gu}', ...options });
/**
* 헬스체크
*/
+214 -4
View File
@@ -687,6 +687,12 @@ export type HeroStat = {
* normal=기본, warn=조심(노랑), rain=비(파랑)
*/
tone: 'normal' | 'warn' | 'rain';
/**
* Detail
*
* 단계 이름 밑의 실제 값 (예: 68%, 72, 2, 초미세먼지 15㎍/㎥). 상태 줄에만
*/
detail?: string | null;
};
/**
@@ -1186,7 +1192,7 @@ export type PostData = {
/**
* PostReaction
*
* 포스트 틀이 아닌 카드(히어로·오늘의 각)에 붙는 좋아요·댓글.
* 포스트 틀이 아닌 카드(히어로·오늘의 각·단풍 지도·띠)에 붙는 좋아요·댓글.
*/
export type PostReaction = {
/**
@@ -1278,7 +1284,19 @@ export const PostType = {
/**
* TODAY_GAK
*/
TODAY_GAK: 17
TODAY_GAK: 17,
/**
* FOLIAGE
*/
FOLIAGE: 18,
/**
* EVENTS_BAND
*/
EVENTS_BAND: 19,
/**
* SEASON_BAND
*/
SEASON_BAND: 20
} as const;
/**
@@ -1524,6 +1542,10 @@ export type ReqTalk = {
* 먼저 올린 사진 주소 (POST /v1/talk/image 결과)
*/
image?: string | null;
/**
* 글 주제. 안 고르면 동네 이야기
*/
topic?: TalkTopic;
};
/**
@@ -1720,6 +1742,9 @@ export type ResFeed = {
posts?: Array<PostData>;
hero_post?: PostReaction | null;
gak_post?: PostReaction | null;
foliage_post?: PostReaction | null;
events_post?: PostReaction | null;
season_post?: PostReaction | null;
bands?: Bands | null;
};
@@ -2140,6 +2165,23 @@ export type ResTalk = {
talk?: TalkData | null;
};
/**
* Res_TalkGroups
*/
export type ResTalkGroups = {
result?: ErrorInfo;
/**
* Msg
*/
msg?: string | null;
/**
* Groups
*
* 동네 사람들 묶음은 늘 있고(비어 있을 수 있음), 주제 묶음은 3장 이상일 때만
*/
groups?: Array<TalkGroup>;
};
/**
* Res_TalkImage
*/
@@ -2848,6 +2890,7 @@ export type TalkData = {
* 올린 사진 주소
*/
image?: string | null;
topic?: TalkTopic;
/**
* Like Count
*/
@@ -2866,6 +2909,22 @@ export type TalkData = {
created_at: string;
};
/**
* TalkGroup
*/
export type TalkGroup = {
/**
* Topic
*
* 0 이면 '동네 사람들'(모든 주제), 아니면 TalkTopic
*/
topic: number;
/**
* Talks
*/
talks?: Array<TalkData>;
};
/**
* TalkReport
*/
@@ -2893,6 +2952,41 @@ export const TalkReport = {
*/
export type TalkReport = typeof TalkReport[keyof typeof TalkReport];
/**
* TalkTopic
*
* 사람 글 주제. 안 고르면 동네 이야기. 피드에서 같은 주제 포스트 옆에 묶어 보여 준다
*/
export const TalkTopic = {
/**
* LOCAL
*/
LOCAL: 1,
/**
* SKY
*/
SKY: 2,
/**
* RAIN
*/
RAIN: 3,
/**
* FOLIAGE
*/
FOLIAGE: 4,
/**
* OUTFIT
*/
OUTFIT: 5
} as const;
/**
* TalkTopic
*
* 사람 글 주제. 안 고르면 동네 이야기. 피드에서 같은 주제 포스트 옆에 묶어 보여 준다
*/
export type TalkTopic = typeof TalkTopic[keyof typeof TalkTopic];
/**
* TermData
*/
@@ -2974,7 +3068,7 @@ export type TopIndex = {
/**
* Slot Ranks
*
* 오늘 구간별 순위 (점수 × 중요도 가중치). 각 시간대와 안 겹치는 구간은 없음
* 오늘 구간별 순위 (중요도 배율을 반영한 최종 표시 점수 내림차순, 동점이면 중요도 순)
*/
slot_ranks?: {
[key: string]: number;
@@ -3339,7 +3433,7 @@ export type WeekDay = {
/**
* Gaks
*
* 그날 대표 각 (점수 × 중요도 순 3개). 각 점수가 아직 없는 날은 비어 있음
* 그날 대표 각 (중요도 배율을 반영한 최종 표시 점수 내림차순 3개, 동점이면 중요도 순). 각 점수가 아직 없는 날은 비어 있음
*/
gaks?: Array<WeekGak>;
};
@@ -4705,6 +4799,44 @@ export type DeleteMyGakResponses = {
export type DeleteMyGakResponse = DeleteMyGakResponses[keyof DeleteMyGakResponses];
export type TalkGroupsData = {
body?: never;
headers?: {
/**
* Authorization
*/
authorization?: string | null;
};
path?: never;
query?: {
/**
* Region
*
* 보는 사람의 구 행정코드
*/
region?: string | null;
};
url: '/v1/talk/groups';
};
export type TalkGroupsErrors = {
/**
* Validation Error
*/
422: HttpValidationError;
};
export type TalkGroupsError = TalkGroupsErrors[keyof TalkGroupsErrors];
export type TalkGroupsResponses = {
/**
* Successful Response
*/
200: ResTalkGroups;
};
export type TalkGroupsResponse = TalkGroupsResponses[keyof TalkGroupsResponses];
export type ListTalksData = {
body?: never;
headers?: {
@@ -4721,6 +4853,12 @@ export type ListTalksData = {
* 보는 사람의 구 행정코드
*/
region?: string | null;
/**
* Topic
*
* 이 주제 글만. 없으면 전체
*/
topic?: TalkTopic | null;
/**
* Cursor
*/
@@ -5201,6 +5339,78 @@ export type GetTodayGuPageResponses = {
export type GetTodayGuPageResponse = GetTodayGuPageResponses[keyof GetTodayGuPageResponses];
export type GetTomorrowPageData = {
body?: never;
path: {
/**
* Sido
*/
sido: string;
/**
* Place
*/
place: string;
};
query?: never;
url: '/v1/seo/tomorrow/{sido}/{place}';
};
export type GetTomorrowPageErrors = {
/**
* Validation Error
*/
422: HttpValidationError;
};
export type GetTomorrowPageError = GetTomorrowPageErrors[keyof GetTomorrowPageErrors];
export type GetTomorrowPageResponses = {
/**
* Successful Response
*/
200: string;
};
export type GetTomorrowPageResponse = GetTomorrowPageResponses[keyof GetTomorrowPageResponses];
export type GetTomorrowGuPageData = {
body?: never;
path: {
/**
* Sido
*/
sido: string;
/**
* Place
*/
place: string;
/**
* Gu
*/
gu: string;
};
query?: never;
url: '/v1/seo/tomorrow/{sido}/{place}/{gu}';
};
export type GetTomorrowGuPageErrors = {
/**
* Validation Error
*/
422: HttpValidationError;
};
export type GetTomorrowGuPageError = GetTomorrowGuPageErrors[keyof GetTomorrowGuPageErrors];
export type GetTomorrowGuPageResponses = {
/**
* Successful Response
*/
200: string;
};
export type GetTomorrowGuPageResponse = GetTomorrowGuPageResponses[keyof GetTomorrowGuPageResponses];
export type HealthzHealthzGetData = {
body?: never;
path?: never;
+33 -4
View File
@@ -1,5 +1,5 @@
import { useCallback, useEffect, useMemo, useState, type ReactNode } from 'react'
import { NavLink, Outlet, useLocation } from 'react-router'
import { NavLink, Outlet, useLocation, useNavigationType } from 'react-router'
import { useIsFetching, useQuery } from '@tanstack/react-query'
import { getSeasonWeekOptions } from '../api/client/@tanstack/react-query.gen'
import { cx } from '../lib/utils'
@@ -202,12 +202,41 @@ function FirstLoad() {
)
}
// 페이지마다 마지막 스크롤 위치: 뒤로 가기로 돌아오면 그 자리로
const scrolled = new Map<string, number>()
function Shell() {
const { pathname } = useLocation()
const { pathname, key } = useLocation()
const navType = useNavigationType()
const { kind } = useSky()
useEffect(() => {
window.scrollTo({ top: 0 })
}, [pathname])
const save = () => scrolled.set(key, window.scrollY)
window.addEventListener('scroll', save, { passive: true })
return () => window.removeEventListener('scroll', save)
}, [key])
useEffect(() => {
const top = navType === 'POP' ? scrolled.get(key) : undefined
if (top == null) {
window.scrollTo({ top: 0 })
return
}
// 피드가 다시 그려져 그 높이가 될 때까지 최대 3초 맞추고, 그 사이 사람이 화면을 만지면 멈춘다
let tries = 0
let raf = 0
const stop = () => cancelAnimationFrame(raf)
const go = () => {
window.scrollTo({ top })
if (Math.abs(window.scrollY - top) > 2 && ++tries < 180) raf = requestAnimationFrame(go)
}
go()
window.addEventListener('touchstart', stop, { once: true, passive: true })
window.addEventListener('wheel', stop, { once: true, passive: true })
return () => {
stop()
window.removeEventListener('touchstart', stop)
window.removeEventListener('wheel', stop)
}
}, [pathname, key, navType])
// 지금 보고 있는 탭을 다시 누르면 맨 위로
const toTopIfHere = (to: string) => () => {
if (pathname === to) window.scrollTo({ top: 0, behavior: 'smooth' })
+480
View File
@@ -0,0 +1,480 @@
import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react'
import { useNavigate, useSearchParams } from 'react-router'
import { cx } from '../lib/utils'
import { ICON_R, LABEL, LABEL_INK, LEAF_SHADOW, MAP_IMG, MAP_SRC, PROVINCE, PROVINCES, labelBoxes, placeProvinces, rankNow, STAGE, headline, md, placeLabels, spread, useFoliage, useLabelSize, type Box, type Kind, type Pt, type Spot, type Stage } from './foliage'
import { useSheet } from './sheetContext'
import { FoliageMapShare, FoliageSpotShare } from './shareCards'
import { SendIcon } from './svg'
import { Chips, Ic, TAP44 } from './ui'
type View = { s: number; tx: number; ty: number }
type Filter = 'all' | Kind
const DOT_R: Record<Stage, number> = { peak: ICON_R, first: 4, before: 3, gone: 3 }
const MAX_ZOOM = 5
const FIT_TOP = 30
const FIT_BOTTOM = 14
// 이름 우선순위(절정 단풍 > 절정 은행 > 첫 단풍 > 나머지)와 그 이름이 나오기 시작하는 배율(처음 화면 대비)
const pri = (m: Spot) => (m.stage === 'peak' ? (m.kind === 'maple' ? 0 : 1) : m.stage === 'first' ? 2 : 3)
const LABEL_FROM = [1, 1.6, 2.5, 3.5]
// 점이 나오기 시작하는 배율: 처음엔 절정 잎만 보여 차분하게
const DOT_FROM: Record<Stage, number> = { peak: 1, first: 1.6, before: 2.5, gone: 2.5 }
const TAP_R = 24
const SHARE_ICON = 'relative grid size-9 shrink-0 cursor-pointer place-items-center rounded-full [&_svg]:size-[19px] [&_svg]:fill-none [&_svg]:stroke-(--ink2) [&_svg]:stroke-[1.9]'
const SHARE_BTN = `${SHARE_ICON} bg-white/80`
const GROUPS: [Stage, string][] = [
['peak', '지금 절정'],
['first', '곧 절정'],
['before', '아직'],
['gone', '절정 지남'],
]
const FILTERS: [Filter, string][] = [
['all', '전체'],
['maple', '단풍'],
['ginkgo', '은행'],
]
// 단계 표시: 절정은 잎, 첫 단풍은 주황 점, 단풍 전·지남은 회색 점(고르면 점을 크게)
const DOT_CLASS: Record<Stage, string> = { peak: '', first: 'bg-[#d9772e]/85', before: 'bg-[#8f8a80]/60', gone: 'bg-[#8f8a80]/60' }
function StageMark({ m, big }: { m: Spot; big?: boolean }) {
if (m.stage === 'peak') return <Ic name={m.kind} className={cx('relative', big ? 'size-8' : 'size-5', LEAF_SHADOW)} />
return <i className={cx('b-keep-bg relative rounded-full', DOT_CLASS[m.stage], big ? 'size-3.5' : m.stage === 'first' ? 'size-[7px]' : 'size-[5px]')} />
}
function Marker({ p, sel }: { p: Pt; sel: boolean }) {
return (
<span className={cx('pointer-events-none absolute grid -translate-x-1/2 -translate-y-1/2 place-items-center', sel && 'z-[3]')} style={{ left: p.x, top: p.y }}>
{/* 고른 명소는 속이 빈 고리만: 옆 명소를 가리지 않게 */}
{sel && <i className="b-keep-bg absolute size-8 rounded-full border-[2.5px] border-[#28304a] bg-[#ffffff4d]" />}
<StageMark m={p.m} big={sel && p.m.stage !== 'peak'} />
</span>
)
}
/** 단풍 지도 페이지: 명소 65곳을 지도에서 확대해 보고 목록으로 고른다. 한 손가락은 확대 전엔 페이지 스크롤, 확대 뒤엔 지도 이동 */
export function FoliagePage() {
const navigate = useNavigate()
const [params] = useSearchParams()
const { today, spots } = useFoliage()
const [filter, setFilter] = useState<Filter>('all')
const [sel, setSel] = useState<string | null>(params.get('spot'))
const linked = useRef(params.get('spot'))
const { open } = useSheet()
const [shareSpot, setShareSpot] = useState<Spot | null>(null)
const [shareReq, setShareReq] = useState(0)
const spotShotRef = useRef<HTMLDivElement>(null)
const mapShotRef = useRef<HTMLDivElement>(null)
const shown = useMemo(() => spots.filter((m) => filter === 'all' || m.kind === filter), [spots, filter])
const vpRef = useRef<HTMLDivElement>(null)
const [box, setBox] = useState({ W: 0, H: 0 })
const [view, setView] = useState<View>({ s: 1, tx: 0, ty: 0 })
const viewRef = useRef(view)
useLayoutEffect(() => {
viewRef.current = view
}, [view])
const size = useLabelSize(vpRef, spots)
// 처음 화면: 명소가 다 들어오는 만큼 확대해 가운데
const fit = useMemo<View>(() => {
const { W, H } = box
if (!W) return { s: 1, tx: 0, ty: 0 }
const xs = spots.map((m) => m.x)
const ys = spots.map((m) => m.y)
const [x0, x1, y0, y1] = [Math.min(...xs), Math.max(...xs), Math.min(...ys), Math.max(...ys)]
// 위쪽은 맨 북쪽 이름표가 잘리지 않게 FIT_TOP 만큼 띄우고, 아래는 제주까지만
const h = H - FIT_TOP - FIT_BOTTOM
const s = Math.min(W / ((x1 - x0 + 0.14) * W), h / ((y1 - y0) * W))
return { s, tx: W / 2 - ((x0 + x1) / 2) * W * s, ty: FIT_TOP + h / 2 - ((y0 + y1) / 2) * W * s }
}, [box, spots])
const clamp = useCallback(
(v: View): View => {
const { W, H } = box
const s = Math.min(fit.s * MAX_ZOOM, Math.max(fit.s, v.s))
const w = W * s
// 지도 그림 가장자리가 화면 안쪽으로 너무 들어오지 않게
const tx = Math.min(W * 0.25, Math.max(W * 0.75 - w, v.tx))
const ty = Math.min(H * 0.25, Math.max(H * 0.75 - w, v.ty))
return { s, tx, ty }
},
[box, fit],
)
const anim = useRef(0)
const set = useCallback((v: View) => {
cancelAnimationFrame(anim.current)
setView(v)
}, [])
const animateTo = useCallback(
(to: View) => {
cancelAnimationFrame(anim.current)
const from = viewRef.current
const target = clamp(to)
const start = performance.now()
const step = (now: number) => {
const k = Math.min(1, (now - start) / 280)
const e = 1 - (1 - k) ** 3
setView({ s: from.s + (target.s - from.s) * e, tx: from.tx + (target.tx - from.tx) * e, ty: from.ty + (target.ty - from.ty) * e })
if (k < 1) anim.current = requestAnimationFrame(step)
}
anim.current = requestAnimationFrame(step)
},
[clamp],
)
const zoomAt = useCallback(
(f: number, cx: number, cy: number, smooth = false) => {
const v = viewRef.current
const s = Math.min(fit.s * MAX_ZOOM, Math.max(fit.s, v.s * f))
const k = s / v.s
const next = clamp({ s, tx: cx - (cx - v.tx) * k, ty: cy - (cy - v.ty) * k })
if (smooth) animateTo(next)
else set(next)
},
[fit, clamp, animateTo, set],
)
const focus = useCallback(
(m: Spot) => {
const { W, H } = box
const s = Math.max(viewRef.current.s, fit.s * 2.5)
animateTo({ s, tx: W / 2 - m.x * W * s, ty: H * 0.42 - m.y * W * s })
},
[box, fit, animateTo],
)
useLayoutEffect(() => {
const el = vpRef.current
if (!el) return
const ro = new ResizeObserver(() => setBox({ W: el.clientWidth, H: el.clientHeight }))
ro.observe(el)
return () => ro.disconnect()
}, [])
// 크기가 정해지면 처음 화면으로, 링크로 고른 명소가 있으면 그곳으로
const started = useRef(false)
useEffect(() => {
if (!box.W) return
if (started.current) {
set(clamp(viewRef.current))
return
}
started.current = true
set(fit)
const m = spots.find((s) => s.name === linked.current)
if (m) focus(m)
}, [box, fit, spots, set, clamp, focus])
const pts = useMemo(() => {
const ratio = view.s / fit.s
const visible = shown.filter((m) => m.name === sel || ratio >= DOT_FROM[m.stage] - 0.01)
return spread(visible.map((m) => ({ m, x: view.tx + m.x * box.W * view.s, y: view.ty + m.y * box.W * view.s, r: DOT_R[m.stage] })))
}, [shown, view, box.W, fit.s, sel])
const ptsRef = useRef(pts)
useLayoutEffect(() => {
ptsRef.current = pts
}, [pts])
const labelAt = useMemo(() => {
const ratio = view.s / fit.s
const order = pts.filter((p) => p.m.name === sel || ratio >= LABEL_FROM[pri(p.m)]).sort((a, b) => Number(b.m.name === sel) - Number(a.m.name === sel) || pri(a.m) - pri(b.m))
const blocked: Box[] = [{ l: box.W - 52, t: 0, r: box.W, b: 100 }]
return placeLabels(order, pts, size, { l: 4, t: 4, r: box.W - 4, b: box.H - 4 }, blocked, (p) => p.m.stage === 'peak' || p.m.name === sel)
}, [pts, size, sel, view.s, fit.s, box])
const provs = useMemo(
() => placeProvinces(PROVINCES.map((v) => ({ name: v.name, x: view.tx + v.x * box.W * view.s, y: view.ty + v.y * box.W * view.s })), pts, labelBoxes(labelAt, size)),
[view, box.W, pts, labelAt, size],
)
const pickAt = useCallback((x: number, y: number) => {
let best: string | null = null
let bestD = TAP_R
for (const p of ptsRef.current) {
const d = Math.hypot(p.x - x, p.y - y)
if (d < bestD) [best, bestD] = [p.m.name, d]
}
setSel((cur) => (best && best !== cur ? best : null))
}, [])
// 손가락: 두 손가락은 확대·이동, 한 손가락은 확대했을 때만 지도 이동(아니면 페이지 스크롤), 두 번 누르면 확대
useEffect(() => {
const el = vpRef.current
if (!el) return
let pinch: { d: number; x: number; y: number } | null = null
let one: { x: number; y: number; moved: boolean; scroll: boolean } | null = null
let lastTap = 0
const local = (t: { clientX: number; clientY: number }) => {
const r = el.getBoundingClientRect()
return { x: t.clientX - r.left, y: t.clientY - r.top }
}
const zoomed = () => viewRef.current.s > fit.s * 1.01
const onStart = (e: TouchEvent) => {
if ((e.target as HTMLElement).closest('button')) {
one = null
return
}
cancelAnimationFrame(anim.current)
if (e.touches.length === 2) {
const [a, b] = [local(e.touches[0]), local(e.touches[1])]
pinch = { d: Math.hypot(a.x - b.x, a.y - b.y), x: (a.x + b.x) / 2, y: (a.y + b.y) / 2 }
one = null
} else if (e.touches.length === 1) {
one = { ...local(e.touches[0]), moved: false, scroll: false }
}
}
const onMove = (e: TouchEvent) => {
if (e.touches.length === 2 && pinch) {
e.preventDefault()
const [a, b] = [local(e.touches[0]), local(e.touches[1])]
const d = Math.hypot(a.x - b.x, a.y - b.y)
const x = (a.x + b.x) / 2
const y = (a.y + b.y) / 2
const v = viewRef.current
const s = Math.min(fit.s * MAX_ZOOM, Math.max(fit.s, (v.s * d) / pinch.d))
const k = s / v.s
set(clamp({ s, tx: x - (pinch.x - v.tx) * k, ty: y - (pinch.y - v.ty) * k }))
pinch = { d, x, y }
return
}
if (e.touches.length !== 1 || !one) return
const p = local(e.touches[0])
const first = !one.moved
if (Math.hypot(p.x - one.x, p.y - one.y) > 6) one.moved = true
if (!zoomed() || one.scroll) return
const v = viewRef.current
const next = clamp({ s: v.s, tx: v.tx + p.x - one.x, ty: v.ty + p.y - one.y })
// 첫 움직임이 세로인데 지도가 그쪽 끝에 닿아 더 못 가면 이번 손짓은 페이지 스크롤로 넘긴다
if (first && Math.abs(p.y - one.y) > Math.abs(p.x - one.x) && next.ty === v.ty) {
one.scroll = true
return
}
e.preventDefault()
set(next)
one = { ...p, moved: one.moved, scroll: false }
}
const onEnd = (e: TouchEvent) => {
if (e.touches.length < 2) pinch = null
if (e.touches.length || !one || one.moved) {
if (!e.touches.length) one = null
return
}
e.preventDefault()
const now = Date.now()
if (now - lastTap < 300) {
lastTap = 0
zoomAt(2, one.x, one.y, true)
} else {
lastTap = now
pickAt(one.x, one.y)
}
one = null
}
// 마우스: 끌어서 이동, 누르면 고르기, 두 번 누르면 확대, 트랙패드 오므리기(ctrl+휠)로 확대
let drag: { x: number; y: number; moved: boolean } | null = null
const onDown = (e: PointerEvent) => {
if (e.pointerType !== 'mouse' || (e.target as HTMLElement).closest('button')) return
cancelAnimationFrame(anim.current)
drag = { ...local(e), moved: false }
}
const onPMove = (e: PointerEvent) => {
if (!drag) return
const p = local(e)
if (Math.hypot(p.x - drag.x, p.y - drag.y) > 3) drag.moved = true
const v = viewRef.current
set(clamp({ s: v.s, tx: v.tx + p.x - drag.x, ty: v.ty + p.y - drag.y }))
drag = { ...p, moved: drag.moved }
}
const onUp = () => {
if (drag && !drag.moved) pickAt(drag.x, drag.y)
drag = null
}
const onDbl = (e: MouseEvent) => {
const p = local(e)
zoomAt(2, p.x, p.y, true)
}
const onWheel = (e: WheelEvent) => {
if (!e.ctrlKey) return
e.preventDefault()
const p = local(e)
zoomAt(Math.exp(-e.deltaY * 0.01), p.x, p.y)
}
el.addEventListener('touchstart', onStart, { passive: true })
el.addEventListener('touchmove', onMove, { passive: false })
el.addEventListener('touchend', onEnd, { passive: false })
el.addEventListener('pointerdown', onDown)
window.addEventListener('pointermove', onPMove)
window.addEventListener('pointerup', onUp)
el.addEventListener('dblclick', onDbl)
el.addEventListener('wheel', onWheel, { passive: false })
return () => {
el.removeEventListener('touchstart', onStart)
el.removeEventListener('touchmove', onMove)
el.removeEventListener('touchend', onEnd)
el.removeEventListener('pointerdown', onDown)
window.removeEventListener('pointermove', onPMove)
window.removeEventListener('pointerup', onUp)
el.removeEventListener('dblclick', onDbl)
el.removeEventListener('wheel', onWheel)
}
}, [fit, clamp, set, zoomAt, pickAt])
const chosen = spots.find((m) => m.name === sel)
const pickFromList = (m: Spot) => {
setSel(m.name)
const el = vpRef.current
if (el) window.scrollTo({ top: window.scrollY + el.getBoundingClientRect().top - 120, behavior: 'smooth' })
focus(m)
}
// 보내기: 공유 창이 이미지(명소 하나면 그 명소 지도 조각, 아니면 전체 지도)와 링크를 같이 보낸다
const share = (m?: Spot) => {
setShareSpot(m ?? null)
setShareReq((n) => n + 1)
}
useEffect(() => {
if (!shareReq) return
const el = shareSpot ? spotShotRef.current : mapShotRef.current
if (el) open({ type: 'share', share: { title: shareSpot ? `${shareSpot.name} 단풍` : '단풍 지도', slides: [el] } })
}, [shareReq, shareSpot, open])
const back = () => (window.history.state?.idx > 0 ? navigate(-1) : navigate('/'))
const peakSpots = spots.filter((m) => m.stage === 'peak')
const peakCount = peakSpots.length
const ranked = rankNow(spots)
return (
<div className="pb-6">
<div className="flex items-start gap-1 px-3 pt-1">
<button type="button" onClick={back} aria-label="뒤로" className={cx('relative mt-0.5 grid size-9 shrink-0 cursor-pointer place-items-center rounded-full bg-white/80 text-[22px] font-bold shadow-[0_4px_10px_rgb(40_48_74/0.08)]', TAP44)}>
‹
</button>
<div className="min-w-0 flex-1 px-1">
<p className="m-0 flex items-center gap-1 text-[13px] font-extrabold opacity-75">
<Ic name="maple" className="size-4" />
단풍 지도 · {md(today)}
</p>
<h2 className="m-0 mt-0.5 font-jua text-[26px] leading-tight font-normal text-balance">{headline(spots)}</h2>
</div>
<button type="button" onClick={() => share()} aria-label="단풍 지도 보내기" className={cx(SHARE_BTN, 'mt-0.5 shadow-[0_4px_10px_rgb(40_48_74/0.08)]', TAP44)}>
<SendIcon />
</button>
</div>
<div ref={vpRef} className="b-keep-bg relative mt-2 h-[min(122vw,calc(100dvh-330px),560px)] min-h-[300px] touch-pan-y overflow-hidden bg-[#fff6ea] select-none">
<img src={MAP_SRC} alt="단풍 지도" draggable={false} className={cx(MAP_IMG, 'max-w-none')} style={{ inset: 'auto', left: view.tx, top: view.ty, width: box.W * view.s, height: box.W * view.s }} />
{provs.map((v) => (
<span key={v.name} aria-hidden="true" className={PROVINCE} style={{ left: v.x, top: v.y }}>
{v.name}
</span>
))}
{[...pts].sort((a, b) => Number(a.m.stage === 'peak') - Number(b.m.stage === 'peak')).map((p) => (
<Marker key={p.m.name} p={p} sel={p.m.name === sel} />
))}
{spots.map((m) => (
<button
key={m.name}
type="button"
data-label={m.name}
aria-label={`${m.name} 고르기`}
onClick={() => setSel(m.name === sel ? null : m.name)}
className={cx(LABEL, 'cursor-pointer border-0', m.name === sel ? 'z-[3] bg-[#28304a] text-[#ffffff]' : m.stage === 'peak' ? LABEL_INK[m.kind] : 'bg-[#ffffffeb] text-[#5b6075]', !labelAt[m.name] && 'invisible')}
style={labelAt[m.name] ?? { left: 0, top: 0 }}
>
{m.name}
</button>
))}
<div className="absolute top-2.5 right-2.5 z-[4] flex flex-col gap-2">
{(
[
['+', '확대', 1.6],
['−', '축소', 1 / 1.6],
] as const
).map(([t, label, f]) => (
<button key={t} type="button" aria-label={label} onClick={() => zoomAt(f, box.W / 2, box.H / 2, true)} className="b-keep-bg grid size-9 cursor-pointer place-items-center rounded-full bg-[#ffffff] text-[20px] font-bold text-[#28304a] shadow-[0_2px_6px_rgb(40_48_74/0.2)]">
{t}
</button>
))}
</div>
</div>
{/* 고른 명소는 범례 자리에: 지도 위를 가리지 않고, 다시 누르거나 빈 곳을 누르면 풀린다 */}
{chosen ? (
<div className="mx-3 mt-2 flex h-[60px] items-center gap-3 rounded-[18px] bg-white px-3.5 shadow-[inset_0_-4px_0_var(--shade)]">
<span className="grid size-8 shrink-0 place-items-center">
<StageMark m={chosen} big />
</span>
<div className="min-w-0 flex-1">
<p className="m-0 flex items-center gap-1.5">
<b className="truncate font-jua text-[18px] leading-tight font-normal">{chosen.name}</b>
<span className={cx('shrink-0 rounded-full px-1.5 py-px text-[11px] font-extrabold', chosen.stage === 'peak' ? 'bg-[#ffe3db] text-[#b5321f]' : chosen.stage === 'first' ? 'bg-[#ffe8d2] text-[#a34f12]' : 'bg-(--chip) text-(--ink2)')}>{STAGE[chosen.stage]}</span>
</p>
<p className="m-0 flex gap-1 text-[12px] font-bold text-(--ink3)">
<span className="truncate">{chosen.region}</span>
<span className="shrink-0">· 절정 예상 {md(chosen.peak)}</span>
</p>
</div>
<button type="button" onClick={() => share(chosen)} aria-label={`${chosen.name} 보내기`} className={cx(SHARE_BTN, TAP44)}>
<SendIcon />
</button>
</div>
) : (
<div className="mx-3 mt-2 flex h-[60px] flex-wrap items-center justify-center gap-x-3 gap-y-1 text-[12.5px] font-bold">
<span className="flex items-center gap-1">
<Ic name="maple" className={cx('size-4', LEAF_SHADOW)} />
단풍 절정
</span>
<span className="flex items-center gap-1">
<Ic name="ginkgo" className={cx('size-4', LEAF_SHADOW)} />
은행 절정
</span>
<span className="flex items-center gap-1">
<i className="b-keep-bg size-[7px] rounded-full bg-[#d9772e]/85" />첫 단풍
</span>
<span className="flex items-center gap-1">
<i className="b-keep-bg size-[5px] rounded-full bg-[#8f8a80]/60" />단풍 전
</span>
</div>
)}
<Chips label="종류" items={FILTERS} value={filter} onChange={setFilter} />
<div className="px-4">
{GROUPS.map(([g, title]) => {
const rows = shown.filter((m) => m.stage === g).sort((a, b) => a.peak.localeCompare(b.peak))
if (!rows.length) return null
return (
<section key={g} aria-label={title} className="pt-5">
<h3 className="m-0 flex items-baseline gap-1.5 px-1 pb-1.5 font-jua text-[19px] font-normal">
{title}
<span className="font-sans text-[13px] font-extrabold text-(--ink3)">{rows.length}곳</span>
</h3>
<ul className="m-0 list-none border-t border-(--line) p-0">
{rows.map((m) => (
<li key={m.name} className={cx('flex items-center border-b border-(--line)', m.name === sel && 'bg-[rgb(255_122_69/0.08)]')}>
<button type="button" onClick={() => pickFromList(m)} aria-current={m.name === sel || undefined} className="flex min-w-0 flex-1 cursor-pointer items-center gap-3 py-2.5 pl-1 text-left">
<span className="grid size-7 shrink-0 place-items-center">
<StageMark m={m} big />
</span>
<span className="min-w-0 flex-1">
<b className="block truncate text-[15px] font-extrabold">{m.name}</b>
<small className="block truncate text-[12px] font-semibold text-(--ink3)">
{m.region} · {m.own ? '절정 예상' : '가까운 지점 날짜'}
</small>
</span>
<b className={cx('shrink-0 font-jua text-[18px] font-normal tabular-nums', g === 'peak' ? 'text-(--orange)' : 'text-(--ink2)')}>{md(m.peak)}</b>
</button>
<button type="button" onClick={() => share(m)} aria-label={`${m.name} 보내기`} className={cx(SHARE_ICON, 'ml-1', TAP44)}>
<SendIcon />
</button>
</li>
))}
</ul>
</section>
)
})}
<FoliageSpotShare spot={shareSpot} peak={peakSpots} ref={spotShotRef} />
<FoliageMapShare title={headline(spots)} peak={peakSpots} ranked={ranked} ref={mapShotRef} />
<p className="m-0 px-1.5 pt-4 text-[11.5px] leading-relaxed font-semibold text-(--ink3)">
출처: 산림청 2026 단풍절정 예측 · 잎 절반이 물든 때를 절정으로, 그 2주 전부터 첫 단풍으로 봐요{peakCount ? ` · 지금 절정 ${peakCount}곳` : ''}
</p>
</div>
</div>
)
}
+3
View File
@@ -31,6 +31,9 @@ const ACCOUNTS: Record<PostType, readonly [string, string]> = {
[PostType.UV]: ['자외선', 'glasses'],
[PostType.HERO]: ['오늘 날씨', 'sun'],
[PostType.TODAY_GAK]: ['오늘의 각', 'rabbit'],
[PostType.FOLIAGE]: ['단풍 지도', 'maple'],
[PostType.EVENTS_BAND]: ['이번 주 가까운 행사', 'fireworks'],
[PostType.SEASON_BAND]: ['이번 주 계절 이야기', 'fallen_leaf'],
}
type Slide = HoursSlide | RowsSlide | GakSlide | SunsetSlide | WeekSlide | PlanSlide
+1 -1
View File
@@ -363,7 +363,7 @@ function GakSheet({ indexId, onTitle }: { indexId: number; onTitle: (t: string)
</div>
<b className={cx('ml-auto font-bagel text-[42px] font-normal', g.active ? 'text-(--orange)' : 'text-(--ink3)')}>{g.score}</b>
</div>
{!g.active && <p className="mt-2 text-[13px] font-bold text-(--ink2)">지금 시간대엔 해당 없어요. 점수는 오늘 가장 좋은 시간대 기준이에요.</p>}
{!g.active && <p className="mt-2 text-[13px] font-bold text-(--ink2)">지금은 제철이 아니에요. 점수는 오늘 가장 좋은 시간대 기준이에요.</p>}
{now && (
<p className="mt-3 rounded-2xl bg-[#fff4ec] px-3.5 py-2.5 text-[14.5px] font-bold">
<b className="mr-1.5 font-jua font-normal text-(--orange)">{now.low}~{now.high}점</b>
+44
View File
@@ -0,0 +1,44 @@
import { useSearchParams } from 'react-router'
import type { TalkTopic } from '../api/client/types.gen'
import { cx } from '../lib/utils'
import { TalkCard } from './talk'
import { TOPICS, useTopicTalks } from './talkState'
import { Sec } from './ui'
/** 주제별 사람 글: 위 주제 탭, 아래 글 목록. 피드 묶음의 '전체 보기'가 ?topic= 으로 연다 */
export function TalkPage() {
const [params, setParams] = useSearchParams()
const raw = Number(params.get('topic'))
const topic = TOPICS.some(([k]) => k === raw) ? (raw as TalkTopic) : undefined
const { talks, loaded, more, loadMore } = useTopicTalks(topic)
const tabs: (readonly [TalkTopic | undefined, string])[] = [[undefined, '전체'], ...TOPICS]
return (
<section aria-label="동네 사람들 글">
<Sec title="동네 사람들 글" sub="가까운 동네 글부터 보여요" />
<div className="flex flex-wrap gap-1.5 px-4 pb-1" role="tablist" aria-label="글 주제">
{tabs.map(([k, label]) => (
<button
key={label}
type="button"
role="tab"
aria-selected={topic === k}
onClick={() => setParams(k ? { topic: String(k) } : {}, { replace: true })}
className={cx('cursor-pointer rounded-full px-3 py-1.5 text-[13px] font-extrabold', topic === k ? 'bg-(--ink) text-white' : 'bg-white text-(--ink2)')}
>
{label}
</button>
))}
</div>
{loaded && !talks.length && <p className="mx-4 mt-6 text-center text-[14px] font-semibold text-(--ink3)">아직 이 주제 글이 없어요. 오늘 탭에서 첫 글을 써 주세요.</p>}
{talks.map((t) => (
<TalkCard key={`${t.talk_id}:${t.liked}:${t.like_count}`} t={t} />
))}
{more && (
<button type="button" onClick={() => loadMore()} className="mx-3 mt-3 w-[calc(100%-1.5rem)] cursor-pointer rounded-[14px] bg-white py-2.5 text-[13.5px] font-extrabold text-(--ink2)">
더 보기
</button>
)}
</section>
)
}
+82 -60
View File
@@ -3,8 +3,10 @@ import { Link, useLocation } from 'react-router'
import { useQuery } from '@tanstack/react-query'
import { getFeedOptions, getWeatherTodayOptions } from '../api/client/@tanstack/react-query.gen'
import {
PostType,
RainType,
Sky,
TalkTopic,
type BandArticle,
type BandEvent,
type Hero as HeroData,
@@ -21,9 +23,9 @@ import { InstallBanner } from './installBanner'
import { MyGakRow } from './myGak'
import { fromShare } from './myGakState'
import { PostCard, PostCardSkel, PostFrame } from './Post'
import { usePinnedLike } from './pinnedLike'
import { FeedComposer, TalkCard } from './talk'
import { useFeedTalks } from './talkState'
import { usePinnedLike, type PinnedKey } from './pinnedLike'
import { FeedComposer, NearTalks, TalkCard, TalkGroup } from './talk'
import { topicName, useTalkGroups } from './talkState'
import { useRegion } from './regionContext'
import { useSheet } from './sheetContext'
import { useSky } from './skyContext'
@@ -106,7 +108,7 @@ const SLOT_KEY: Record<TimeKind, string> = {
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
@@ -365,7 +367,7 @@ function Hero({ hero, post, today, ranked, all, feedLoad, todayLoad }: HeroProps
<span className="b-cloud b-bob inset-0" />
</span>
))}
<div className="b-fall absolute top-2 left-1/2 -ml-16 aspect-square w-32" style={fall('0s', '5.6s')}>
<div className={'b-fall absolute top-2 left-1/2 -ml-16 aspect-square w-32'} style={fall('0s', '5.6s')}>
<div className="b-sun b-bob relative grid size-full place-items-center rounded-full text-center">
{/* 안 보이는 쪽을 덮어 오늘 밤 달 모양으로 */}
{moon && (
@@ -373,34 +375,34 @@ function Hero({ hero, post, today, ranked, all, feedLoad, todayLoad }: HeroProps
<path d={moonPath(moon.pct, 1, false)} fill={kind === 'sunset' ? 'rgb(96 40 86 / .55)' : 'rgb(34 30 86 / .62)'} transform={moon.waning ? 'scale(-1,1)' : undefined} />
</svg>
)}
<span className={cx('relative', moon && '[text-shadow:0_0_6px_#fff,0_0_12px_#fff]')}>
<small className="block font-jua text-[12px]">
{failed(feedLoad) ? '점수를 못 불러왔어요' : `${tmr && mode !== 'now' ? `내일 ${PREVIEW[mode].label}` : slotScore != null && mode !== 'now' ? PREVIEW[mode].label : '지금'} 날씨 점수`}
</small>
<b className="block font-bagel text-[52px] leading-[0.95] font-normal">{heroVal(feedLoad, score, 'w-[84px]')}</b>
</span>
{why && score != null && (
<button
type="button"
onClick={() =>
open({
type: 'weatherWhy',
why: { label: whyLabel, score, why },
})
}
aria-label={`${whyLabel} 날씨 점수 ${score}점, 어떻게 나왔는지 보기`}
className={cx(
'absolute right-0 bottom-1 z-[2] grid size-7 cursor-pointer place-items-center rounded-full bg-white font-jua text-[16px] text-(--orange-deep) shadow-[0_2px_6px_rgb(40_48_74/0.25)]',
TAP44,
)}
>
?
</button>
)}
{/* 점수 근거가 있으면 해를 눌러도 근거 창: 구석 버튼은 구름에 가려져서 상태 줄 끝으로 옮김 */}
{(() => {
const body = (
<>
<small className="block font-jua text-[12px]">
{failed(feedLoad) ? '점수를 못 불러왔어요' : `${tmr && mode !== 'now' ? `내일 ${PREVIEW[mode].label}` : slotScore != null && mode !== 'now' ? PREVIEW[mode].label : '지금'} 날씨 점수`}
</small>
<b className="block font-bagel text-[52px] leading-[0.95] font-normal">{heroVal(feedLoad, score, 'w-[84px]')}</b>
</>
)
const cls = cx('relative', moon && '[text-shadow:0_0_6px_#fff,0_0_12px_#fff]')
if (!why || score == null) return <span className={cls}>{body}</span>
return (
<button
type="button"
onClick={() => open({ type: 'weatherWhy', why: { label: whyLabel, score, why, status } })}
aria-label={`${whyLabel} 날씨 점수 ${score}점, 어떻게 나왔는지 보기`}
className={cx(cls, 'flex cursor-pointer flex-col items-center')}
>
{body}
</button>
)
})()}
</div>
</div>
</div>
<div className="relative z-[3] text-center">
{/* 다 불러온 높이(한 줄 말·날씨 한 줄·상태 두 줄)를 미리 잡아 둔다: 늦게 채워지며 아래 피드가 밀려 내려가지 않게 */}
<div className="relative z-[3] min-h-[103px] text-center">
{top1 ? (
<button
type="button"
@@ -429,6 +431,11 @@ function Hero({ hero, post, today, ranked, all, feedLoad, todayLoad }: HeroProps
</span>
</Fragment>
))}
{why && score != null && (
<button type="button" onClick={() => open({ type: 'weatherWhy', why: { label: whyLabel, score, why, status } })} aria-label={`${whyLabel} 날씨 점수 ${score}점, 어떻게 나왔는지 보기`} className={cx('relative cursor-pointer whitespace-nowrap text-(--orange-deep)', TAP44)}>
· 점수 근거 ›
</button>
)}
</p>
)}
</div>
@@ -517,18 +524,21 @@ function PostsSkel() {
)
}
function Band({ tone, title, sub, to, children }: { tone: 1 | 2 | 3; title: string; sub: string; to: string; children: ReactNode }) {
/** 띠도 포스트 틀에 담아 좋아요·댓글·보내기를 단다 (post 는 서버의 띠 자리) */
function Band({ tone, title, sub, to, avatar, post, pinKey, children }: { tone: 1 | 2 | 3; title: string; sub: string; to: string; avatar: string; post?: PostReaction | null; pinKey: PinnedKey; children: ReactNode }) {
return (
<section className={cx('mt-3.5 pt-4 pb-3.5', `b-band-${tone}`)} aria-label={title}>
<Sec title={title} sub={sub} more={{ to }} className="pt-0" />
{children}
</section>
<PostFrame title={title} account={title} avatar={avatar} pinned={{ key: pinKey, post }}>
<section className={cx('pt-4 pb-3.5', `b-band-${tone}`)} aria-label={title}>
<Sec title={title} sub={sub} more={{ to }} className="pt-0" />
{children}
</section>
</PostFrame>
)
}
function EventsBand({ events }: { events: BandEvent[] }) {
function EventsBand({ events, post }: { events: BandEvent[]; post?: PostReaction | null }) {
return (
<Band tone={1} title="이번 주 가까운 행사" sub="30km 안 · 날씨까지 같이 보고 골라요" to="/week">
<Band tone={1} title="이번 주 가까운 행사" sub="30km 안 · 날씨까지 같이 보고 골라요" to="/week" avatar="fireworks" post={post} pinKey="events_post">
<Rail>
{events.map((e, i) => (
<Link key={e.event_id} to="/week" className="w-[200px] overflow-hidden rounded-[22px] bg-white shadow-[inset_0_-5px_0_var(--shade),0_8px_16px_rgb(40_48_74/0.06)]">
@@ -545,10 +555,10 @@ function EventsBand({ events }: { events: BandEvent[] }) {
)
}
function SeasonBand({ news }: { news: BandArticle[] }) {
function SeasonBand({ news, post }: { news: BandArticle[]; post?: PostReaction | null }) {
const { open } = useSheet()
return (
<Band tone={3} title="이번 주 계절 이야기" sub="예년 이맘때의 소식" to="/season">
<Band tone={3} title="이번 주 계절 이야기" sub="예년 이맘때의 소식" to="/season" avatar="fallen_leaf" post={post} pinKey="season_post">
<Rail>
{news.map((a) => (
<button key={a.article_id} type="button" onClick={() => open({ type: 'article', articleId: a.article_id })} className="w-[200px] cursor-pointer overflow-hidden rounded-[22px] bg-white text-left shadow-[inset_0_-5px_0_var(--shade),0_8px_16px_rgb(40_48_74/0.06)]">
@@ -564,8 +574,6 @@ function SeasonBand({ news }: { news: BandArticle[] }) {
)
}
const TALK_EVERY = 3
export function TodayPage() {
const { region } = useRegion()
const feed = useQuery(getFeedOptions({ query: { region: region.code } }))
@@ -580,19 +588,18 @@ export function TodayPage() {
const nowAt = f?.hero?.now_at
const load = loadOf(feed)
const [mine, setMine] = useState<TalkData[]>([])
// 사람들이 쓴 글은 4·7·10번째 포스트 뒤에 하나씩(3번째 뒤 행사 띠와 안 붙게), 남은 글은 피드 끝에. 방금 올린 내 글은 글쓰기 칸 아래에 따로 있으니 빼고
const feedTalks = useFeedTalks()
const talks = feedTalks.talks.filter((t) => !mine.some((m) => m.talk_id === t.talk_id))
const between = Math.max(0, Math.floor((posts.length - 1) / TALK_EVERY))
const moreRef = useRef<HTMLDivElement>(null)
const { more, loadMore } = feedTalks
useEffect(() => {
const el = moreRef.current
if (!el || !more) return
const io = new IntersectionObserver((es) => es.some((e) => e.isIntersecting) && loadMore(), { rootMargin: '600px' })
io.observe(el)
return () => io.disconnect()
}, [more, loadMore])
// 사람 글은 묶음으로: '동네 사람들'은 오늘의 각 아래, 주제 묶음은 같은 주제 포스트 아래. 방금 올린 내 글은 글쓰기 칸 아래에 따로 있으니 빼고
const talkGroups = useTalkGroups()
const groupOf = (topic: number) => (talkGroups.groups.get(topic) ?? []).filter((t) => !mine.some((m) => m.talk_id === t.talk_id))
const group = (topic: number) => {
const talks = groupOf(topic)
return talks.length ? <TalkGroup key={`talk-${topic}`} title={topicName(topic)} topic={topic} talks={talks} /> : null
}
// 비·눈이 오거나 2시간 안에 올 때만 비·눈 묶음을 히어로 바로 아래로
const at = nowAt ? Date.parse(nowAt) : 0
const nowSlot = (today.data?.slots ?? []).filter((x) => x.temp_c != null).reduce<WeatherSlot | undefined>((a, b) => (!a || Math.abs(Date.parse(b.at) - at) < Math.abs(Date.parse(a.at) - at) ? b : a), undefined)
const raining = ['rain', 'snow', 'sleet'].includes(weatherOf(nowSlot)) || !!f?.hero?.will_rain_2h
const sunsetAt = posts.findIndex((p) => p.post_type === PostType.SUNSET)
useEffect(() => {
window.scrollTo({ top: 0 })
@@ -611,10 +618,21 @@ export function TodayPage() {
// 디자인대로 3·6·9번째 글 뒤에 띠를 넣고, 글이 모자라면 남은 띠는 맨 뒤에 붙인다
const bandAt: [number, ReactNode][] = [
[3, bands?.events?.length ? <EventsBand key="events" events={bands.events} /> : null],
[9, bands?.season?.length ? <SeasonBand key="season" news={bands.season} /> : null],
[3, bands?.events?.length ? <EventsBand key="events" events={bands.events} post={f?.events_post} /> : null],
[9, bands?.season?.length ? <SeasonBand key="season" news={bands.season} post={f?.season_post} /> : null],
]
// 사람 글 묶음은 포스트 사이사이에 하나씩: 묶음·띠·단풍 카드가 이미 붙는 자리와 바로 앞 자리는 건너뛰어 가로 목록이 연달아 나오지 않게
const spreadTopics = [TalkTopic.OUTFIT, ...(raining ? [] : [TalkTopic.RAIN]), ...(sunsetAt < 0 ? [TalkTopic.SKY] : []), ...(posts.length < 2 ? [TalkTopic.FOLIAGE] : [])].filter((tp) => groupOf(tp).length)
const taken = new Set([1, sunsetAt, ...bandAt.map(([at]) => at - 1)])
const spreadAt = new Map<number, ReactNode>()
let spreadN = 0
for (let i = 0; i < posts.length && spreadN < spreadTopics.length; i++) {
if (taken.has(i) || spreadAt.has(i - 1)) continue
spreadAt.set(i, group(spreadTopics[spreadN++]))
}
const spreadLeft = spreadTopics.slice(spreadN).map((tp) => group(tp))
return (
// 피드 칸은 전국 공통이라 지역이 바뀌어도 글 번호가 같다. 지역마다 새로 그려 넘긴 슬라이드·펼친 상태가 남지 않게 한다
<section key={region.code} aria-label="오늘" aria-busy={load === 'loading'} className={cx('transition-opacity', feed.isPlaceholderData && 'opacity-60')}>
@@ -623,6 +641,7 @@ export function TodayPage() {
{mine.map((t) => (
<TalkCard key={t.talk_id} t={t} onGone={() => setMine((m) => m.filter((x) => x.talk_id !== t.talk_id))} />
))}
{raining && group(TalkTopic.RAIN)}
<MyGakRow />
{/* 실패 안내는 여기 한 번만, 각 카드 스켈레톤과 같은 크기로 */}
{stories.some((g) => g.active) ? (
@@ -632,6 +651,7 @@ export function TodayPage() {
) : (
<StateBox load={load} onRetry={() => feed.refetch()} empty="오늘 계산된 각이 없어요." hold={<PostCardSkel />} className="inset-x-3 top-3 bottom-1" />
)}
<NearTalks talks={groupOf(0)} loaded={talkGroups.loaded} />
<InstallBanner />
<div>
{load === 'loading' && <PostsSkel />}
@@ -642,14 +662,16 @@ export function TodayPage() {
{posts.map((p, i) => (
<Fragment key={p.post_id}>
<PostCard post={p} />
{i === 1 && <FoliageCard />}
{i > 0 && i % TALK_EVERY === 0 && talks[i / TALK_EVERY - 1] && <TalkCard t={talks[i / TALK_EVERY - 1]} />}
{i === sunsetAt && group(TalkTopic.SKY)}
{i === 1 && <FoliageCard post={f?.foliage_post} />}
{i === 1 && group(TalkTopic.FOLIAGE)}
{bandAt.find(([at]) => at === i + 1)?.[1]}
{spreadAt.get(i)}
</Fragment>
))}
{/* 글이 모자라 끼울 자리가 없던 묶음은 맨 뒤에 */}
{feed.isSuccess && spreadLeft}
{feed.isSuccess && bandAt.filter(([at]) => at > posts.length).map(([at, node]) => <Fragment key={at}>{node}</Fragment>)}
{load !== 'loading' && talks.slice(between).map((t) => <TalkCard key={t.talk_id} t={t} />)}
<div ref={moreRef} aria-hidden />
</div>
</section>
)
+2 -1
View File
@@ -611,7 +611,8 @@ html.b-sheet-open .b-app :is(.b-fall, .b-bob, .b-blob, .b-skystars i, .b-shoot,
.b-app[data-t='night'] .bg-\(--ink\) .text-\[\#ffb3c4\] {
color: #ffd0dc;
}
.b-app[data-t='night'] .text-\[\#28304a\] {
/* b-keep-bg(밤에도 밝은 바탕 그대로) 안은 글자도 그대로 */
.b-app[data-t='night'] .text-\[\#28304a\]:not(.b-keep-bg, .b-keep-bg *) {
color: var(--ink);
}
.b-app[data-t='night'] :is(.text-\[\#1f9d62\], .text-\[\#1f7a4f\]) {
+213
View File
@@ -0,0 +1,213 @@
import { useLayoutEffect, useMemo, useState, type RefObject } from 'react'
import data from '../../seo/foliage_2026.json'
import { kst } from './lib'
export type Kind = 'maple' | 'ginkgo'
export type Stage = 'before' | 'first' | 'peak' | 'gone'
type Raw = { name: string; kind: Kind; region: string; lat: number; lon: number; peak: string; basis: string }
/** x·y 는 지도 그림 안 위치(0~1), own 은 산림청 예측 지점 자기 날짜인지(아니면 가까운 지점에서 빌린 날짜) */
export type Spot = Omit<Raw, 'basis' | 'lat' | 'lon'> & { stage: Stage; d: number; x: number; y: number; own: boolean }
// 지도 그림(public/foliage/korea-map.webp, 정사각형)의 위경도 → 그림 위 위치. generated-images/foliage-map/south_outline.json 과 같은 값
const MAP = { lon0: 124.5, lat1: 38.75, k: 0.809017, s: 153.5327, ox: 40, oy: 62.92, size: 1024 }
export const MAP_SRC = '/foliage/korea-map.webp'
// 발표에 시작일이 없어 절정 FIRST_DAYS 일 전부터 첫 단풍, PEAK_DAYS 일 전부터 PEAK_AFTER 일 뒤까지 절정으로 본다
const FIRST_DAYS = 14
const PEAK_DAYS = 3
const PEAK_AFTER = 7
export const STAGE: Record<Stage, string> = { before: '단풍 전', first: '첫 단풍', peak: '절정', gone: '절정 지남' }
export const KIND: Record<Kind, string> = { maple: '단풍', ginkgo: '은행' }
const DAY = 86_400_000
const days = (from: string, to: string) => Math.round((Date.parse(to) - Date.parse(from)) / DAY)
function stage(peak: string, today: string): Stage {
const d = days(today, peak)
if (d < -PEAK_AFTER) return 'gone'
if (d <= PEAK_DAYS) return 'peak'
return d <= FIRST_DAYS ? 'first' : 'before'
}
const toXY = (lat: number, lon: number) => ({ x: (MAP.ox + (lon - MAP.lon0) * MAP.k * MAP.s) / MAP.size, y: (MAP.oy + (MAP.lat1 - lat) * MAP.s) / MAP.size })
// 지도 위 시·도 이름 자리(위경도). 서울·경기는 겹치지 않게 경기를 북쪽으로 조금 올림
export const PROVINCES = (
[
['서울', 37.56, 126.98],
['경기', 37.95, 127.05],
['강원', 37.65, 128.35],
['충북', 36.8, 127.75],
['충남', 36.45, 126.85],
['전북', 35.72, 127.1],
['전남', 34.85, 126.9],
['경북', 36.3, 128.75],
['경남', 35.3, 128.2],
['제주', 33.38, 126.55],
] as const
).map(([name, lat, lon]) => ({ name, ...toXY(lat, lon) }))
export const md = (iso: string) => `${Number(iso.slice(5, 7))}/${Number(iso.slice(8, 10))}`
const province = (m: Spot) => m.region.split(' ')[0].split('·')
/** 오늘(한국 시각) 기준 명소 65곳과 단계. 단풍철이 아니면 inSeason 이 false */
export function useFoliage() {
const [today] = useState(() => {
const t = kst(new Date())
return `${t.y}-${String(t.mo).padStart(2, '0')}-${String(t.d).padStart(2, '0')}`
})
return useMemo(() => {
const spots: Spot[] = (data.spots as Raw[]).map(({ basis, lat, lon, ...m }) => ({
...m,
stage: stage(m.peak, today),
d: days(today, m.peak),
...toXY(lat, lon),
own: basis.startsWith('산림청'),
}))
// 가장 이른 명소가 첫 단풍에 들 때부터 가장 늦은 명소의 절정이 끝날 때까지
const peaks = spots.map((m) => m.peak).sort()
const inSeason = days(peaks[0], today) >= -FIRST_DAYS && days(peaks[peaks.length - 1], today) <= PEAK_AFTER
return { today, spots, inSeason }
}, [today])
}
/** 절정 명소가 많은 시·도 3곳, 절정이 없으면 가장 먼저 올 절정, 다 지났으면 지는 중 */
export function headline(spots: Spot[]) {
const peak = spots.filter((m) => m.stage === 'peak')
if (peak.length) {
const count = new Map<string, number>()
for (const p of peak.flatMap(province)) count.set(p, (count.get(p) ?? 0) + 1)
return `지금 절정: ${[...count].sort((a, b) => b[1] - a[1]).slice(0, 3).map(([p]) => p).join('·')}`
}
if (spots.some((m) => m.stage === 'gone')) return '올해 단풍이 지고 있어요'
const first = spots.reduce((a, b) => (b.peak < a.peak ? b : a))
return `첫 절정은 ${province(first)[0]}, ${md(first.peak)}쯤`
}
/** 지금 가기 좋은 순: 절정인 곳 중 절정 예상일이 오늘과 가까운 순, 같으면 자기 예측 날짜 먼저, 그다음 이름 순 */
export const rankNow = (spots: Spot[]) =>
spots.filter((m) => m.stage === 'peak').sort((a, b) => Math.abs(a.d) - Math.abs(b.d) || Number(b.own) - Number(a.own) || a.name.localeCompare(b.name))
/** 시·도 이름 자리(명소 이름표를 먼저 놓은 뒤): 원래 자리가 잎·점·이름표에 덮이면 둘레를 돌며 가장 가까운 빈자리로 옮긴다(최대 반경 R, 바다 쪽도 됨) */
export function placeProvinces(provs: { name: string; x: number; y: number }[], pts: Pt[], labels: Box[] = [], R = 90) {
// 앞에서 놓은 시·도 이름도 피한다(서울·경기처럼 붙은 곳)
const placed: Box[] = []
const free = (x: number, y: number) =>
pts.every((p) => Math.abs(p.x - x) > p.r + 17 || Math.abs(p.y - y) > p.r + 10) && [...labels, ...placed].every((b) => !overlaps(provinceBox(x, y), b))
return provs.map((v) => {
const at = pick(v)
placed.push(provinceBox(at.x, at.y))
return at
})
function pick(v: { name: string; x: number; y: number }) {
if (free(v.x, v.y)) return v
for (let d = 5; d <= R; d += 5)
for (let a = 0; a < 24; a++) {
const x = v.x + Math.cos((a / 24) * 2 * Math.PI) * d
const y = v.y + Math.sin((a / 24) * 2 * Math.PI) * d
if (free(x, y)) return { ...v, x, y }
}
return v
}
}
export function provinceBox(x: number, y: number): Box {
return { l: x - 16, t: y - 9, r: x + 16, b: y + 9 }
}
/** placeLabels 결과를 상자로: 시·도 이름이 피해 갈 자리 */
export const labelBoxes = (at: Record<string, { left: number; top: number }>, size: Record<string, { w: number; h: number }>) =>
Object.entries(at).map(([n, a]) => ({ l: a.left, t: a.top, r: a.left + (size[n]?.w ?? 0), b: a.top + (size[n]?.h ?? 0) }))
export type Pt = { m: Spot; x: number; y: number; r: number }
const LABEL_GAP = 4
export type Box = { l: number; t: number; r: number; b: number }
const overlaps = (a: Box, b: Box) => a.l < b.r && b.l < a.r && a.t < b.b && b.t < a.b
/** 화면 위 점끼리 겹치면 서로 밀어 떼어 놓는다 (pts 를 고쳐서 돌려줌) */
export function spread(pts: Pt[], gap = 1.5) {
for (let it = 0; it < 60; it++) {
let moved = false
for (let i = 0; i < pts.length; i++)
for (let j = i + 1; j < pts.length; j++) {
const a = pts[i]
const b = pts[j]
let dx = b.x - a.x
let dy = b.y - a.y
let d = Math.hypot(dx, dy)
const need = a.r + b.r + gap
if (d >= need) continue
if (d < 0.01) [dx, dy, d] = [Math.cos(i + j), Math.sin(i + j), 1]
const push = (need - d) / 2
a.x -= (dx / d) * push
a.y -= (dy / d) * push
b.x += (dx / d) * push
b.y += (dy / d) * push
moved = true
}
if (!moved) break
}
return pts
}
/** 이름표를 점 오른쪽·왼쪽 순으로 놓아 보고(잎과 짝이 헷갈리지 않게 옆 먼저), 점·다른 이름표·막힌 칸과 겹치거나 영역 밖이면 그 이름은 뺀다. 앞 순서가 먼저 자리를 잡는다 */
export function placeLabels(order: Pt[], all: Pt[], size: Record<string, { w: number; h: number }>, area: Box, blocked: Box[] = [], vertical: (p: Pt) => boolean = () => false) {
const dots = all.map((p) => ({ name: p.m.name, box: { l: p.x - p.r, t: p.y - p.r, r: p.x + p.r, b: p.y + p.r } }))
const taken = [...blocked.map((box) => ({ name: '', box })), ...dots]
const out: Record<string, { left: number; top: number }> = {}
for (const p of order) {
const s = size[p.m.name]
if (!s || p.x < area.l || p.x > area.r || p.y < area.t || p.y > area.b) continue
// 옆 자리가 없을 때 vertical 인 명소(절정)만 위·아래도 써 본다
const tries = [
[p.r + 2, -s.h / 2],
[-s.w - p.r - 2, -s.h / 2],
...(vertical(p) ? [[-s.w / 2, -s.h - p.r - 1], [-s.w / 2, p.r + 1]] : []),
]
for (const [dx, dy] of tries) {
const r = { l: p.x + dx, t: p.y + dy, r: p.x + dx + s.w, b: p.y + dy + s.h }
if (r.l < area.l || r.t < area.t || r.r > area.r || r.b > area.b) continue
// 이름표끼리는 LABEL_GAP 만큼 띄워 손가락으로 옆 이름을 잘못 누르지 않게
const pad = { l: r.l - LABEL_GAP, t: r.t - LABEL_GAP, r: r.r + LABEL_GAP, b: r.b + LABEL_GAP }
if (taken.some((o) => o.name !== p.m.name && overlaps(o.name ? r : pad, o.box))) continue
// 위·아래 자리는 이름표에서 가장 가까운 표시가 자기 것일 때만: 아니면 다른 점의 이름처럼 읽힌다
const cx = (r.l + r.r) / 2
const cy = (r.t + r.b) / 2
const mine = Math.hypot(cx - p.x, cy - p.y)
if (dy !== -s.h / 2 && all.some((q) => q.m.name !== p.m.name && Math.hypot(cx - q.x, cy - q.y) < mine)) continue
taken.push({ name: '', box: r })
out[p.m.name] = { left: r.l, top: r.t }
break
}
}
return out
}
/** 이름표 크기를 재 둔다: host 안 data-label 이 붙은 요소의 폭·높이 (host 크기가 바뀌면 다시) */
export function useLabelSize(host: RefObject<HTMLElement | null>, key: unknown) {
const [size, setSize] = useState<Record<string, { w: number; h: number }>>({})
useLayoutEffect(() => {
const el = host.current
if (!el) return
const ro = new ResizeObserver(() => {
const out: Record<string, { w: number; h: number }> = {}
el.querySelectorAll<HTMLElement>('[data-label]').forEach((l) => {
out[l.dataset.label ?? ''] = { w: l.offsetWidth, h: l.offsetHeight }
})
setSize(out)
})
ro.observe(el)
return () => ro.disconnect()
}, [host, key])
return size
}
export const LEAF_SHADOW = 'drop-shadow-[0_0_1.5px_#fff] drop-shadow-[0_1px_1px_rgb(40_48_74/0.45)]'
// 밤 화면에서도 지도는 밝은 종이 그대로라 이름표도 흰 바탕 그대로(b-keep-bg)
export const LABEL = "b-keep-bg absolute rounded-[7px] before:absolute before:-inset-x-1 before:-inset-y-2 before:content-[''] px-[5px] py-px text-[11.5px] leading-[1.35] font-extrabold whitespace-nowrap shadow-[0_1px_3px_rgb(40_48_74/0.18)]"
export const LABEL_INK: Record<Kind, string> = { maple: 'bg-[#ffffffeb] text-[#b5321f]', ginkgo: 'bg-[#ffffffeb] text-[#8a6508]' }
// 지도 그림 색을 빼서 단풍 아이콘이 묻히지 않게
export const MAP_IMG = 'pointer-events-none absolute inset-0 size-full select-none mix-blend-multiply brightness-[1.08] saturate-[.3]'
export const ICON_R = 10
// 시·도 이름: 지도에 옅게 깔리는 글자
// 어두운 산 무늬 위에서도 읽히게 종이색 테두리를 두른다
export const PROVINCE = 'pointer-events-none absolute -translate-x-1/2 -translate-y-1/2 font-jua text-[13px] leading-none whitespace-nowrap text-[#5c4a36]/85 [text-shadow:0_0_2px_#fff6ea,0_0_4px_#fff6ea,0_0_6px_#fff6ea]'
+147 -96
View File
@@ -1,108 +1,159 @@
import { useState } from 'react'
import data from '../../seo/foliage_2026.json'
import { useLayoutEffect, useMemo, useRef, useState, type MouseEvent } from 'react'
import { useNavigate } from 'react-router'
import { cx } from '../lib/utils'
import { kst } from './lib'
import type { PostReaction } from '../api/client/types.gen'
import { useCarousel } from './carousel'
import { headline, ICON_R, LABEL, LABEL_INK, LEAF_SHADOW, MAP_IMG, MAP_SRC, md, placeLabels, PROVINCE, PROVINCES, labelBoxes, placeProvinces, rankNow, spread, useFoliage, useLabelSize } from './foliage'
import { PostFrame } from './Post'
import { useSheet } from './sheetContext'
import { FoliageSpotShare } from './shareCards'
import { SendIcon } from './svg'
import { Ic } from './ui'
type Kind = 'maple' | 'ginkgo'
type Spot = { name: string; kind: Kind; region: string; lat: number; lon: number; peak: string; basis: string }
type Stage = 'before' | 'first' | 'peak'
const TAP_R = 24
const RANK_N = 7
// 지도 그림(public/foliage/korea-map.webp, 정사각형)의 위경도 → 그림 위 위치. generated-images/foliage-map/south_outline.json 과 같은 값
const MAP = { lon0: 124.5, lat1: 38.75, k: 0.809017, s: 153.5327, ox: 40, oy: 62.92, size: 1024 }
// 발표에 시작일이 없어 절정 FIRST_DAYS 일 전부터 첫 단풍, PEAK_DAYS 일 전부터 절정으로 본다
const FIRST_DAYS = 14
const PEAK_DAYS = 3
const SEASON = { from: '09-20', to: '11-25' }
const SEOUL = { lat: 37.566, lon: 126.978 }
const STAGE: Record<Stage, { label: string; icon: string }> = {
before: { label: '단풍 전', icon: 'size-3 opacity-60 grayscale' },
first: { label: '첫 단풍', icon: 'size-3.5' },
peak: { label: '절정', icon: 'size-[18px]' },
}
const KIND: Record<Kind, { label: string; icon: string }> = {
maple: { label: '단풍', icon: 'maple' },
ginkgo: { label: '은행', icon: 'ginkgo' },
}
const pos = (m: Spot) => ({
left: `${((MAP.ox + (m.lon - MAP.lon0) * MAP.k * MAP.s) / MAP.size) * 100}%`,
top: `${((MAP.oy + (MAP.lat1 - m.lat) * MAP.s) / MAP.size) * 100}%`,
})
const DAY = 86_400_000
const days = (from: string, to: string) => Math.round((Date.parse(to) - Date.parse(from)) / DAY)
function stage(m: Spot, today: string): Stage {
const d = days(today, m.peak)
if (d <= PEAK_DAYS) return 'peak'
return d <= FIRST_DAYS ? 'first' : 'before'
}
const md = (iso: string) => `${Number(iso.slice(5, 7))}/${Number(iso.slice(8, 10))}`
/** 단풍철에만 나오는 단풍 지도 카드. 산마다 절정 예측일로 지금 절정·곧·아직·지남을 점으로 */
export function FoliageCard() {
const [now] = useState(() => new Date())
const t = kst(now)
const today = `${t.y}-${String(t.mo).padStart(2, '0')}-${String(t.d).padStart(2, '0')}`
/** 피드의 단풍 지도 카드: 1장은 지금 절정인 곳만 잎 아이콘으로(누르면 카드 안에 정보), 2장은 지금 가기 좋은 순위. '지도 크게 보기'로 단풍 지도 페이지 */
export function FoliageCard({ post }: { post?: PostReaction | null }) {
const navigate = useNavigate()
const { today, spots, inSeason } = useFoliage()
const peak = useMemo(() => spots.filter((m) => m.stage === 'peak').sort((a, b) => Number(a.kind === 'ginkgo') - Number(b.kind === 'ginkgo') || a.y - b.y), [spots])
const mapRef = useRef<HTMLDivElement>(null)
const size = useLabelSize(mapRef, peak)
const [W, setW] = useState(0)
const [picked, setPicked] = useState<string | null>(null)
const mmdd = today.slice(5)
if (mmdd < SEASON.from || mmdd > SEASON.to) return null
const spots = (data.spots as Spot[]).map((m) => ({ ...m, stage: stage(m, today) }))
const peakNow = spots.filter((m) => m.stage === 'peak').map((m) => m.name)
// 발표 지도에 서울 안 산은 없어 서울 시청에서 가장 가까운 단풍 예측 산으로
const forecast = spots.filter((m) => m.kind === 'maple' && m.basis.startsWith('산림청'))
const seoul = forecast.reduce((a, b) => (Math.hypot(b.lat - SEOUL.lat, b.lon - SEOUL.lon) < Math.hypot(a.lat - SEOUL.lat, a.lon - SEOUL.lon) ? b : a))
const sel = spots.find((m) => m.name === picked)
const { open } = useSheet()
const spotShotRef = useRef<HTMLDivElement>(null)
const { ref: sliderRef, index } = useCarousel({ align: 'start' })
useLayoutEffect(() => {
const el = mapRef.current
if (!el) return
const ro = new ResizeObserver(() => setW(el.clientWidth))
ro.observe(el)
return () => ro.disconnect()
}, [inSeason])
const pts = useMemo(() => spread(peak.map((m) => ({ m, x: m.x * W, y: m.y * W, r: ICON_R }))), [peak, W])
const labelAt = useMemo(() => placeLabels(pts, pts, size, { l: 0, t: 0, r: W, b: W }, [], () => true), [pts, size, W])
const provs = useMemo(() => placeProvinces(PROVINCES.map((v) => ({ name: v.name, x: v.x * W, y: v.y * W })), pts, labelBoxes(labelAt, size)), [pts, W, labelAt, size])
if (!inSeason) return null
const go = (name?: string) => navigate(name ? `/foliage?spot=${encodeURIComponent(name)}` : '/foliage')
const toggle = (name: string) => setPicked(name === picked ? null : name)
// 잎이 작아 손가락으로 겨냥하기 어려우니 누른 자리에서 가까운 명소를 고른다
const tapMap = (e: MouseEvent<HTMLDivElement>) => {
const r = e.currentTarget.getBoundingClientRect()
let best: string | null = null
let bestD = TAP_R
for (const p of pts) {
const d = Math.hypot(p.x - (e.clientX - r.left), p.y - (e.clientY - r.top))
if (d < bestD) [best, bestD] = [p.m.name, d]
}
setPicked(best && best !== picked ? best : null)
}
const sel = peak.find((m) => m.name === picked)
// 2번째 장: 지금 절정인 곳을 절정 예상일이 오늘과 가까운 순서로
const ranked = rankNow(spots).slice(0, RANK_N)
return (
<PostFrame title="단풍 지도" account="단풍 지도" avatar="maple" caption={peakNow.length ? `지금 절정 ${peakNow.length}곳: ${peakNow.slice(0, 5).join(' · ')}${peakNow.length > 5 ? ' 외' : ''}` : undefined}>
<div className="relative bg-[#fff6ea] px-4 pt-4 pb-3">
<PostFrame title="단풍 지도" account="단풍 지도" avatar="maple" pinned={{ key: 'foliage_post', post }} caption={peak.length ? `지금 절정 ${peak.length}곳: ${peak.slice(0, 5).map((m) => m.name).join(' · ')}${peak.length > 5 ? ' 외' : ''}` : undefined}>
<div className="b-keep-bg relative bg-[#fff6ea] px-4 pt-4 pb-3 text-[#28304a]">
<p className="m-0 text-[13px] font-extrabold opacity-75">단풍 지도 · {md(today)}</p>
<p className="m-0 mt-1 font-jua text-[24px] leading-tight">서울 근교 {seoul.name} 절정 예상 {md(seoul.peak)}</p>
<div className="relative mx-auto mt-1 aspect-square w-full">
<img src="/foliage/korea-map.webp" alt="단풍 지도" className="absolute inset-0 size-full" />
{spots.map((m) => (
<button
key={m.name}
type="button"
onClick={() => setPicked(m.name === picked ? null : m.name)}
aria-label={`${m.name} ${KIND[m.kind].label} ${STAGE[m.stage].label}, 절정 예상 ${md(m.peak)}`}
className={cx('absolute grid -translate-x-1/2 -translate-y-1/2 cursor-pointer place-items-center p-0.5', m.name === picked && 'z-[2] scale-150')}
style={pos(m)}
>
<Ic name={KIND[m.kind].icon} className={cx('drop-shadow-[0_0_1.5px_#fff] drop-shadow-[0_1px_1px_rgb(40_48_74/0.4)]', STAGE[m.stage].icon)} />
</button>
))}
{sel && (
<p className="absolute right-0 bottom-0 z-[3] m-0 max-w-[75%] rounded-[14px] bg-white/95 px-3 py-2 text-[13px] font-bold shadow-[0_4px_12px_rgb(40_48_74/0.15)]">
<b className="font-jua text-[16px] font-normal">{sel.name}</b> {sel.region}
<br />
{KIND[sel.kind].label} {STAGE[sel.stage].label} · 절정 예상 {md(sel.peak)}
{!sel.basis.startsWith('산림청') && <small className="block text-[11px] font-semibold text-(--ink3)">가까운 예측 지점 날짜예요</small>}
</p>
)}
<p className="m-0 mt-1 font-jua text-[24px] leading-tight">{headline(spots)}</p>
<div className="relative mt-1">
<span data-noshot aria-hidden="true" className="absolute top-0 right-0 z-[4] rounded-full bg-[rgb(30_36_56/0.55)] px-[9px] py-[3px] text-xs font-extrabold text-white">
{index + 1}/2
</span>
<div ref={sliderRef} className="overflow-hidden" role="region" aria-label="슬라이드 2장, 옆으로 넘겨 보세요">
<div className="flex">
<div className="min-w-0 shrink-0 grow-0 basis-full">
<div ref={mapRef} onClick={tapMap} className="b-keep-bg relative mx-auto aspect-square w-full bg-[#fff6ea]">
<img src={MAP_SRC} alt="" className={MAP_IMG} />
{provs.map((v) => (
<span key={v.name} aria-hidden="true" className={PROVINCE} style={{ left: v.x, top: v.y }}>
{v.name}
</span>
))}
{pts.map((p) => (
<span key={p.m.name} className="pointer-events-none absolute grid -translate-x-1/2 -translate-y-1/2 place-items-center" style={{ left: p.x, top: p.y }}>
{p.m.name === picked && <i className="b-keep-bg absolute size-8 rounded-full border-[2.5px] border-[#28304a] bg-[#ffffff4d]" />}
<Ic name={p.m.kind} className={cx('relative size-5', LEAF_SHADOW)} />
</span>
))}
{peak.map((m) => (
<button
key={m.name}
type="button"
data-label={m.name}
aria-label={`${m.name} 정보 보기`}
onClick={(e) => {
e.stopPropagation()
toggle(m.name)
}}
className={cx(LABEL, LABEL_INK[m.kind], 'cursor-pointer border-0', !labelAt[m.name] && 'invisible')}
style={labelAt[m.name] ?? { left: 0, top: 0 }}
>
{m.name}
</button>
))}
</div>
{/* 고른 명소 정보는 지도 밖, 범례 자리에: 지도 위 잎을 가리지 않게 */}
{sel ? (
<div className="b-keep-bg mt-2 flex items-center gap-3 rounded-[16px] bg-[#ffffff] px-3 py-2.5 shadow-[inset_0_-3px_0_rgb(40_48_74/0.08)]">
<Ic name={sel.kind} className="size-8 shrink-0" />
<div className="min-w-0 flex-1">
<b className="block truncate font-jua text-[18px] leading-tight font-normal">{sel.name}</b>
<span className="flex gap-1 text-[12px] font-bold text-[#6b7189]">
<span className="shrink-0">{sel.region.split(' ')[0]}</span>
<span className="shrink-0">· 절정 예상 {md(sel.peak)}</span>
</span>
</div>
<button type="button" onClick={() => sel && open({ type: 'share', share: { title: `${sel.name} 단풍`, slides: spotShotRef.current ? [spotShotRef.current] : [] } })} aria-label={`${sel.name} 보내기`} className="relative grid size-9 shrink-0 cursor-pointer place-items-center rounded-full [&_svg]:size-[19px] [&_svg]:fill-none [&_svg]:stroke-[#28304a] [&_svg]:stroke-[1.9]">
<SendIcon />
</button>
<button type="button" onClick={() => go(sel.name)} className="b-keep-bg shrink-0 cursor-pointer rounded-full bg-[#28304a] px-3 py-1.5 text-[12.5px] font-extrabold text-[#ffffff]">
지도에서 보기 ›
</button>
</div>
) : (
<span className="mt-2 flex h-[52px] items-center gap-3 text-[12.5px] font-bold">
<span className="flex items-center gap-1">
<Ic name="maple" className="size-4" />
단풍 절정
</span>
<span className="flex items-center gap-1">
<Ic name="ginkgo" className="size-4" />
은행 절정
</span>
</span>
)}
</div>
<div className="flex min-w-0 shrink-0 grow-0 basis-full flex-col pl-1">
<p className="m-0 font-jua text-[20px] leading-tight">지금 가기 좋은 곳</p>
<p className="m-0 mt-0.5 text-[12px] font-bold text-[#6b7189]">절정 예상일이 오늘과 가까운 순서예요</p>
<ol className="m-0 mt-2 flex flex-1 list-none flex-col justify-between p-0">
{ranked.map((m, i) => (
<li key={m.name}>
<button type="button" onClick={() => go(m.name)} className="flex w-full cursor-pointer items-center gap-2.5 border-0 bg-transparent py-1.5 text-left">
<b className={cx('w-6 shrink-0 text-center font-jua text-[22px] font-normal', i < 3 ? 'text-[#b5321f]' : 'text-[#9a8f80]')}>{i + 1}</b>
<Ic name={m.kind} className={cx('size-7 shrink-0', LEAF_SHADOW)} />
<span className="min-w-0 flex-1">
<b className="block truncate text-[15px] font-extrabold">{m.name}</b>
<small className="block truncate text-[12px] font-semibold text-[#6b7189]">{m.region}</small>
</span>
<span className="shrink-0 text-[14px] font-extrabold tabular-nums">{md(m.peak)}</span>
</button>
</li>
))}
</ol>
</div>
</div>
</div>
</div>
<div className="mt-2 flex flex-wrap items-center justify-center gap-x-3 gap-y-1 text-[12.5px] font-bold">
{(Object.keys(KIND) as Kind[]).map((k) => (
<span key={k} className="flex items-center gap-1">
<Ic name={KIND[k].icon} className="size-4" />
{KIND[k].label}
</span>
))}
<span className="opacity-30" aria-hidden="true">|</span>
{(Object.keys(STAGE) as Stage[]).map((st) => (
<span key={st} className="flex items-center gap-1">
<Ic name="maple" className={cx('size-4', STAGE[st].icon)} />
{STAGE[st].label}
</span>
))}
</div>
<p className="m-0 mt-1.5 text-center text-[11px] font-semibold text-(--ink3)">
출처: 산림청 2026 단풍절정 예측 · 잎 절반이 물든 때를 절정으로, 그 2주 전부터 첫 단풍으로 봐요
</p>
<FoliageSpotShare spot={sel ?? null} peak={peak} ref={spotShotRef} />
<button type="button" onClick={() => go()} className="b-keep-bg mt-2 w-full cursor-pointer rounded-full bg-[#ffffff] py-2 text-[14px] font-extrabold text-[#28304a] shadow-[inset_0_-3px_0_rgb(40_48_74/0.08)]">
지도 크게 보기 ›
</button>
</div>
</PostFrame>
)
+2 -2
View File
@@ -3,9 +3,9 @@ import { useMutation, useQueryClient } from '@tanstack/react-query'
import { likePostMutation, unlikePostMutation } from '../api/client/@tanstack/react-query.gen'
import type { PostReaction, ResFeed } from '../api/client/types.gen'
export type PinnedKey = 'hero_post' | 'gak_post'
export type PinnedKey = 'hero_post' | 'gak_post' | 'foliage_post' | 'events_post' | 'season_post'
/** 히어로·오늘의 각처럼 포스트 틀이 아닌 카드의 좋아요. 화면을 먼저 바꾸고 실패하면 되돌린다 */
/** 히어로·오늘의 각·단풍 지도·띠처럼 포스트 틀이 아닌 카드의 좋아요. 화면을 먼저 바꾸고 실패하면 되돌린다 */
export function usePinnedLike(key: PinnedKey, r?: PostReaction | null) {
const queryClient = useQueryClient()
const like = useMutation(likePostMutation())
+71
View File
@@ -2,6 +2,7 @@ import type { Ref } from 'react'
import { createPortal } from 'react-dom'
import { cx } from '../lib/utils'
import type { TopIndex } from '../api/client/types.gen'
import { LEAF_SHADOW, MAP_IMG, MAP_SRC, md, PROVINCE, PROVINCES, STAGE, type Spot } from './foliage'
import { MEDALS, type TimeKind } from './lib'
import { Ic } from './ui'
@@ -114,3 +115,73 @@ export function GakShareCard({ items, title, ref }: { items: TopIndex[]; title:
</Offscreen>
)
}
/** 단풍 명소 하나 공유: 그 명소를 가운데 둔 지도 조각(둘레 시·도 이름과 다른 절정 잎) 위에 큰 잎, 아래에 이름·지역·절정 예상일 */
export function FoliageSpotShare({ spot, peak, ref }: { spot: Spot | null; peak: Spot[]; ref: Ref<HTMLDivElement> }) {
if (!spot) return null
const near = peak.filter((m) => m.name !== spot.name)
return (
<Offscreen>
<div ref={ref} className="flex aspect-[4/5] flex-col bg-[#fff6ea] text-[#28304a]">
<div className="relative flex-1 overflow-hidden">
{/* 명소가 가운데 오게 지도 그림을 3배로 키워 옮긴다 */}
<div className="absolute top-1/2 left-1/2 aspect-square w-[220%] bg-[#fff6ea]" style={{ transform: `translate(-${spot.x * 100}%, -${spot.y * 100}%)` }}>
<img src={MAP_SRC} alt="" className={MAP_IMG} />
{PROVINCES.map((v) => (
<span key={v.name} className={cx(PROVINCE, 'text-[15px]')} style={{ left: `${v.x * 100}%`, top: `${v.y * 100}%` }}>
{v.name}
</span>
))}
{near.map((m) => (
<Ic key={m.name} name={m.kind} className={cx('absolute size-5 -translate-x-1/2 -translate-y-1/2', LEAF_SHADOW)} style={{ left: `${m.x * 100}%`, top: `${m.y * 100}%` }} />
))}
</div>
<span className="absolute top-1/2 left-1/2 grid size-[92px] -translate-x-1/2 -translate-y-1/2 place-items-center rounded-full border-[3px] border-[#28304a] bg-[#ffffff99]">
<Ic name={spot.kind} className={cx('w-[60px]', LEAF_SHADOW)} />
</span>
</div>
<div className="px-5 pt-3 pb-4">
<p className="m-0 flex items-center gap-2">
<b className="font-jua text-[34px] leading-tight font-normal">{spot.name}</b>
<span className={cx('rounded-full px-2 py-0.5 text-[14px] font-extrabold', spot.stage === 'peak' ? 'bg-[#ffe3db] text-[#b5321f]' : 'bg-[#efe6d8] text-[#5b6075]')}>{STAGE[spot.stage]}</span>
</p>
<p className="m-0 mt-0.5 text-[15px] font-bold text-[#6b7189]">{spot.region}</p>
<p className="m-0 mt-2 font-jua text-[22px]">절정 예상 {md(spot.peak)}</p>
</div>
</div>
</Offscreen>
)
}
/** 단풍 지도 전체 공유: 지금 절정 제목, 절정 잎만 찍힌 지도, 가기 좋은 곳 1~3위 */
export function FoliageMapShare({ title, peak, ranked, ref }: { title: string; peak: Spot[]; ranked: Spot[]; ref: Ref<HTMLDivElement> }) {
return (
<Offscreen>
<div ref={ref} className="flex aspect-[4/5] flex-col bg-[#fff6ea] px-4 pt-4 pb-3 text-[#28304a]">
<p className="m-0 font-jua text-[24px] leading-tight">{title}</p>
<div className="relative mx-auto mt-1 aspect-square w-[78%] bg-[#fff6ea]">
<img src={MAP_SRC} alt="" className={MAP_IMG} />
{PROVINCES.map((v) => (
<span key={v.name} className={PROVINCE} style={{ left: `${v.x * 100}%`, top: `${v.y * 100}%` }}>
{v.name}
</span>
))}
{peak.map((m) => (
<Ic key={m.name} name={m.kind} className={cx('absolute size-4 -translate-x-1/2 -translate-y-1/2', LEAF_SHADOW)} style={{ left: `${m.x * 100}%`, top: `${m.y * 100}%` }} />
))}
</div>
<ol className="m-0 mt-auto grid list-none gap-1.5 p-0">
{ranked.slice(0, 3).map((m, i) => (
<li key={m.name} className="flex items-center gap-2.5 rounded-[14px] bg-[#ffffff] px-3 py-1.5">
<Ic name={MEDALS[i]} className="w-[22px] shrink-0" />
<Ic name={m.kind} className="w-[22px] shrink-0" />
<b className="min-w-0 flex-1 truncate font-jua text-[17px] font-normal">{m.name}</b>
<span className="shrink-0 text-[13px] font-bold text-[#6b7189]">{m.region.split(' ')[0]}</span>
<span className="shrink-0 font-jua text-[16px] text-[#b5321f]">{md(m.peak)}</span>
</li>
))}
</ol>
</div>
</Offscreen>
)
}
+80 -9
View File
@@ -1,5 +1,6 @@
import { useMutation, useQueryClient } from '@tanstack/react-query'
import { useEffect, useRef, useState, type ChangeEvent, type FormEvent } from 'react'
import { Link } from 'react-router'
import {
addTalkMutation,
blockTalkAuthorMutation,
@@ -9,16 +10,16 @@ import {
unlikeTalkMutation,
} from '../api/client/@tanstack/react-query.gen'
import { uploadTalkImage } from '../api/client/sdk.gen'
import { TalkReport, type TalkData } from '../api/client/types.gen'
import { TalkReport, TalkTopic, type TalkData } from '../api/client/types.gen'
import { API_BASE_URL } from '../api/setup'
import { cx } from '../lib/utils'
import { useAuth } from './authContext'
import { ago, kst } from './lib'
import { useRegion } from './regionContext'
import { useMyTalks } from './talkState'
import { topicName, TOPICS, useMyTalks } from './talkState'
import { useSheet } from './sheetContext'
import { HeartIcon } from './svg'
import { Avatar, TAP44 } from './ui'
import { Avatar, Rail, TAP44 } from './ui'
const BODY_MAX = 100
const PHOTO_MAX = 10 * 1024 * 1024
@@ -30,6 +31,10 @@ const WRITE_ERRORS: Record<string, string> = {
INVALID_INPUT: '100자 안으로 써 주세요.',
}
// 글이 이보다 적으면 '동네 사람들' 묶음 대신 첫 글 쓰기 카드
const GROUP_MIN = 3
const COMPOSE_ID = 'talk-compose'
const REASONS = [
[TalkReport.ABUSE, '욕설·비하'],
[TalkReport.SPAM, '광고·도배'],
@@ -45,7 +50,7 @@ function slotWord(iso: string) {
function useRefreshTalks() {
const queryClient = useQueryClient()
return () => queryClient.invalidateQueries({ predicate: (q) => ['listTalks', 'listMyTalks'].includes((q.queryKey[0] as { _id?: string } | undefined)?._id ?? '') })
return () => queryClient.invalidateQueries({ predicate: (q) => ['listTalks', 'listMyTalks', 'talkGroups'].includes((q.queryKey[0] as { _id?: string } | undefined)?._id ?? '') })
}
function Composer({ onDone }: { onDone?: (t: TalkData) => void }) {
@@ -55,6 +60,7 @@ function Composer({ onDone }: { onDone?: (t: TalkData) => void }) {
const refresh = useRefreshTalks()
const add = useMutation(addTalkMutation())
const [text, setText] = useState('')
const [topic, setTopic] = useState<TalkTopic>(TalkTopic.LOCAL)
const [error, setError] = useState<string | null>(null)
const [photo, setPhoto] = useState<{ file: File; src: string } | null>(null)
const [uploading, setUploading] = useState(false)
@@ -97,12 +103,13 @@ function Composer({ onDone }: { onDone?: (t: TalkData) => void }) {
upload().then(
(image) =>
add.mutate(
{ body: { region_code: region.code, body, image } },
{ body: { region_code: region.code, body, image, topic } },
{
onSuccess: (res) => {
if (!res.result?.success) return setError(WRITE_ERRORS[res.result?.desc ?? ''] ?? '글을 올리지 못했어요. 다시 해 주세요.')
setText('')
setPhoto(null)
setTopic(TalkTopic.LOCAL)
refresh()
if (res.talk) onDone?.(res.talk)
},
@@ -119,6 +126,7 @@ function Composer({ onDone }: { onDone?: (t: TalkData) => void }) {
return (
<form onSubmit={submit} className="mx-3 rounded-[22px] bg-white p-3 shadow-[inset_0_-5px_0_var(--shade)]">
<textarea
id={COMPOSE_ID}
value={text}
onChange={(e) => setText(e.target.value)}
onFocus={() => !loggedIn && open({ type: 'login' })}
@@ -137,6 +145,20 @@ function Composer({ onDone }: { onDone?: (t: TalkData) => void }) {
</button>
</div>
)}
<div className="mt-2 flex flex-wrap gap-1.5" role="radiogroup" aria-label="글 주제">
{TOPICS.map(([k, label]) => (
<button
key={k}
type="button"
role="radio"
aria-checked={topic === k}
onClick={() => setTopic(k)}
className={cx('cursor-pointer rounded-full px-2.5 py-1 text-[12.5px] font-extrabold', topic === k ? 'bg-(--ink) text-white' : 'bg-[#f3f6fb] text-(--ink2)')}
>
{label}
</button>
))}
</div>
<input ref={fileRef} type="file" accept="image/*" onChange={pick} hidden />
<div className="mt-1.5 flex items-center gap-2 text-xs font-bold text-(--ink3)">
<button type="button" onClick={() => (loggedIn ? fileRef.current?.click() : open({ type: 'login' }))} disabled={busy} className="shrink-0 cursor-pointer rounded-full bg-[#eef4fc] px-3 py-1.5 text-[13px] font-extrabold text-(--ink2) disabled:opacity-40">
@@ -160,7 +182,7 @@ function Composer({ onDone }: { onDone?: (t: TalkData) => void }) {
}
/** onGone: 내 글을 지웠을 때. 목록을 다시 받아도 빠지지 않는 곳(방금 쓴 글)에서 직접 뺀다 */
function TalkRow({ t, onGone }: { t: TalkData; onGone?: () => void }) {
function TalkRow({ t, onGone, compact }: { t: TalkData; onGone?: () => void; compact?: boolean }) {
const { loggedIn } = useAuth()
const { open } = useSheet()
const refresh = useRefreshTalks()
@@ -205,6 +227,7 @@ function TalkRow({ t, onGone }: { t: TalkData; onGone?: () => void }) {
onError: () => setFailed(true),
}
const guard = (run: () => void) => (loggedIn ? run() : open({ type: 'login' }))
const src = t.image?.startsWith('/v1/') ? API_BASE_URL + t.image : (t.image ?? undefined)
return (
<div className="grid grid-cols-[34px_1fr_24px] items-start gap-2.5 border-b border-(--line) py-2.5 last:border-b-0">
@@ -212,10 +235,11 @@ function TalkRow({ t, onGone }: { t: TalkData; onGone?: () => void }) {
<div className="min-w-0">
<small className="block text-xs font-bold text-(--ink3)">
<b className="mr-1 font-extrabold text-(--ink)">{t.nickname}</b>
{[t.region_name, slotWord(t.created_at), t.weather].filter(Boolean).join(' · ')}
{[t.region_name, slotWord(t.created_at), t.weather, t.topic && t.topic !== TalkTopic.LOCAL ? topicName(t.topic) : null].filter(Boolean).join(' · ')}
</small>
<p className="m-0 mt-0.5 text-[14.5px] break-words whitespace-pre-wrap">{t.body}</p>
{t.image && <img src={t.image.startsWith('/v1/') ? API_BASE_URL + t.image : t.image} alt="" loading="lazy" className="mt-2 aspect-[4/5] w-full rounded-2xl bg-[#eef4fc] object-cover" />}
{t.image && compact && <img src={src} alt="" loading="lazy" className="float-right mt-1 ml-2 size-12 rounded-xl bg-[#eef4fc] object-cover" />}
<p className={cx('m-0 mt-0.5 text-[14.5px] break-words whitespace-pre-wrap', compact && 'line-clamp-2')}>{t.body}</p>
{t.image && !compact && <img src={src} alt="" loading="lazy" className="mt-2 aspect-[4/5] w-full rounded-2xl bg-[#eef4fc] object-cover" />}
<small className="mt-0.5 block text-xs font-bold text-(--ink3)">
{ago(t.created_at)} · 좋아요 {count}개 ·{' '}
<button type="button" onClick={() => setMenu(menu === 'closed' ? 'open' : 'closed')} aria-expanded={menu !== 'closed'} className="cursor-pointer font-bold text-(--ink3)">
@@ -280,6 +304,53 @@ export function TalkCard({ t, onGone }: { t: TalkData; onGone?: () => void }) {
)
}
/** 오늘 피드의 사람 글 묶음: 옆으로 넘기는 카드, 끝에 그 주제 전체 보기 */
export function TalkGroup({ title, topic, talks }: { title: string; topic?: number; talks: TalkData[] }) {
return (
<section aria-label={title} className="mt-3.5">
<div className="flex items-end justify-between px-4">
<h2 className="m-0 font-jua text-[19px] font-normal">{title}</h2>
<Link to={topic ? `/talk?topic=${topic}` : '/talk'} className="text-[13px] font-bold text-(--ink2)">
전체 보기
</Link>
</div>
<Rail label={title}>
{talks.map((t) => (
<article key={`${t.talk_id}:${t.liked}:${t.like_count}`} className="w-[78%] max-w-[320px] rounded-[20px] bg-white px-3 shadow-[inset_0_-4px_0_var(--shade)]" aria-label={`${t.nickname}의 글`}>
<TalkRow t={t} compact />
</article>
))}
</Rail>
</section>
)
}
/** '동네 사람들' 글이 적을 때 묶음 대신: 위 쓰기 칸으로 데려간다 */
export function FirstTalkCard() {
const { region } = useRegion()
const place = region.name.split(' ').at(-1)
const go = () => {
const el = document.getElementById(COMPOSE_ID)
el?.scrollIntoView({ behavior: 'smooth', block: 'center' })
el?.focus({ preventScroll: true })
}
return (
<button type="button" onClick={go} className="mx-3 mt-3.5 flex w-[calc(100%-1.5rem)] cursor-pointer items-center gap-3 rounded-[22px] bg-white p-3.5 text-left shadow-[inset_0_-5px_0_var(--shade)]">
<span className="font-jua text-[16.5px] leading-snug">
지금 {place} 하늘 어때요?
<small className="block font-sans text-[12.5px] font-semibold text-(--ink2)">첫 이야기를 남겨 주세요</small>
</span>
<span className="ml-auto shrink-0 rounded-full bg-(--orange) px-3.5 py-1.5 text-[13px] font-extrabold text-white">쓰기</span>
</button>
)
}
/** '동네 사람들' 자리: 글이 GROUP_MIN 개 이상이면 묶음, 아니면 첫 글 쓰기 */
export function NearTalks({ talks, loaded }: { talks: TalkData[]; loaded: boolean }) {
if (!loaded) return null
return talks.length >= GROUP_MIN ? <TalkGroup title="동네 사람들" talks={talks} /> : <FirstTalkCard />
}
/** 내 정보 창의 내가 쓴 글 */
export function MyTalks() {
const { talks, loaded, more, loadMore } = useMyTalks()
+25 -5
View File
@@ -1,17 +1,37 @@
import { useInfiniteQuery } from '@tanstack/react-query'
import { listMyTalksInfiniteOptions, listTalksInfiniteOptions } from '../api/client/@tanstack/react-query.gen'
import { useInfiniteQuery, useQuery } from '@tanstack/react-query'
import { listMyTalksInfiniteOptions, listTalksInfiniteOptions, talkGroupsOptions } from '../api/client/@tanstack/react-query.gen'
import { TalkTopic, type TalkData } from '../api/client/types.gen'
import { useRegion } from './regionContext'
/** 사람들이 쓴 글. 오늘 피드에 운영 포스트 사이사이 섞고, 남은 글은 피드 끝에 이어 붙인다 */
export function useFeedTalks() {
// 글 주제와 피드 묶음 이름
export const TOPICS = [
[TalkTopic.LOCAL, '동네 이야기'],
[TalkTopic.SKY, '하늘·노을'],
[TalkTopic.RAIN, '비·눈'],
[TalkTopic.FOLIAGE, '단풍·꽃'],
[TalkTopic.OUTFIT, '오늘 옷차림'],
] as const
export const topicName = (t?: number) => TOPICS.find(([k]) => k === t)?.[1] ?? '동네 이야기'
/** 오늘 피드 묶음: 0 은 '동네 사람들', 나머지는 주제별(3장 이상일 때만 옴) */
export function useTalkGroups() {
const { region } = useRegion()
const q = useQuery(talkGroupsOptions({ query: { region: region.code } }))
const groups = new Map<number, TalkData[]>((q.data?.groups ?? []).map((g) => [g.topic, g.talks ?? []]))
return { groups, loaded: q.isSuccess }
}
/** 주제별 글 페이지 목록 (topic 없으면 전체) */
export function useTopicTalks(topic?: TalkTopic) {
const { region } = useRegion()
const list = useInfiniteQuery({
...listTalksInfiniteOptions({ query: { region: region.code } }),
...listTalksInfiniteOptions({ query: { region: region.code, ...(topic ? { topic } : {}) } }),
initialPageParam: {},
getNextPageParam: (last) => last.next_cursor ?? undefined,
})
return {
talks: list.data?.pages.flatMap((p) => p.talks ?? []) ?? [],
loaded: list.isSuccess,
more: list.hasNextPage && !list.isFetchingNextPage,
loadMore: list.fetchNextPage,
}
+35 -1
View File
@@ -1,6 +1,8 @@
import type { WeatherWhy } from '../api/client/types.gen'
import { cx } from '../lib/utils'
export type WeatherWhyPayload = { label: string; score: number; why: WeatherWhy[] }
/** status: 히어로 상태 줄 그대로 (단계 이름, 실제 값) */
export type WeatherWhyPayload = { label: string; score: number; why: WeatherWhy[]; status?: { label: string; value: string; tone?: string; detail?: string | null }[] }
// 조건마다 같은 색을 막대 칸과 아래 줄 점에 같이 써서 이어 보이게
const COLOR: Record<string, string> = {
@@ -13,6 +15,14 @@ const COLOR: Record<string, string> = {
}
const colorOf = (label: string) => COLOR[label] ?? '#9aa3b8'
// 상태 줄 항목마다 단계를 나누는 기준 (backend/services/hero_stats.py 와 같은 값)
const RULE: Record<string, string> = {
습도: '30% 아래는 건조, 60% 넘으면 습함이에요',
불쾌지수: '68 아래는 쾌적, 75부터 불쾌예요',
자외선: '3 아래는 낮음, 6부터 높음이에요',
미세먼지: '에어코리아 기준 등급이에요',
}
/** 날씨 점수 근거: 비중만큼 나눈 막대(채운 만큼 얻은 점수)와 조건별 지금 값 */
export function WeatherWhySheet({ d }: { d: WeatherWhyPayload }) {
return (
@@ -46,6 +56,30 @@ export function WeatherWhySheet({ d }: { d: WeatherWhyPayload }) {
))}
</ul>
{d.status && d.status.length > 0 && (
<>
<h4 className="m-0 mt-5 font-jua text-[17px] font-normal">지금 상태</h4>
<ul className="m-0 mt-2 flex list-none flex-col gap-1.5 p-0">
{d.status.map((s) => (
<li key={s.label} className="flex items-center gap-3 rounded-2xl bg-[#f5f8fc] px-3.5 py-2.5">
<span className="min-w-0 flex-1">
<b className="block font-jua text-[16px] leading-tight font-normal">{s.label}</b>
{RULE[s.label] && <small className="block text-[12.5px] font-semibold text-(--ink3)">{RULE[s.label]}</small>}
</span>
<span className="shrink-0 text-right">
<b className={cx('block font-jua text-[18px] leading-tight font-normal', s.tone === 'warn' && 'b-warn')}>{s.value}</b>
{s.detail?.split(' · ').map((x) => (
<small key={x} className="block text-[12px] font-bold whitespace-nowrap text-(--ink2) tabular-nums">
{x}
</small>
))}
</span>
</li>
))}
</ul>
</>
)}
<p className="m-0 mt-3 text-[13px] leading-relaxed font-semibold text-(--ink2)">
조건마다 점수를 매겨 비중대로 합쳐요. 유난히 아쉬운 조건이 있으면 조금 더 깎고, 모든 조건이 완벽할 때만 만점이 나와요.
</p>