diff --git a/TODO.md b/TODO.md index 8ab932e..dbde673 100644 --- a/TODO.md +++ b/TODO.md @@ -34,14 +34,41 @@ | [ ] | 단풍 지도·단풍 포스트, 새 각 — 야구각 문장(숫자 뺌)만 반영. 농구·배구·제철 수산물각 초안은 보류(scratchpad `new_gak_draft.json`) | 10/20 회의 | `backend/seed/index_definition.json`, `backend/seed/article.json` | | [x] | 불쾌지수 항상 표시 | 10/20 회의 결정 (10/8도 결정) | `backend/services/hero_stats.py:70` | | [x] | 나만의 각을 '이름+조건(기온·비·바람·미세먼지·습도·시간대 수치) 저장'으로 바꿈 — 섞기 방식 대체, 점수는 서버가 그 동네 예보로 계산(조건에서 멀수록 깎기), 받은 링크에 조건을 담아 친구 동네 점수로. 피드에 올려 좋아요는 아직 | 10/20 회의 결정 (조합 방식 대체) | `frontend/src/b/myGak.tsx` | -| [ ] | 비로그인 좋아요·댓글·공유 허용, 포스팅만 로그인. 중복 막기는 IP 기준(사용자 결정 10/20). 댓글 로그인 여부 확인 필요 | 10/20 회의 결정 | `backend/router/v1/reaction/reaction.py` | -| [ ] | 구글·토스 로그인, 앱인토스 정산 계좌 오류 토스 문의 | 10/20 회의 결정 | `backend/router/v1/auth/account.py` | +| [x] | 비로그인 좋아요·댓글·공유 허용, 포스팅만 로그인. 중복 막기는 IP 기준(사용자 결정 10/20). 댓글도 로그인 없이(10/21 회의 결정) — 아래 10/21 행으로 이어짐 | 10/20 회의 결정 | `backend/router/v1/reaction/reaction.py` | +| [ ] | 구글·토스 로그인, 앱인토스 정산 계좌 오류 토스 문의 — 구글 로그인 됨(`4e9b0ba`), 토스 문의 보냄(답변 대기). 남은 것은 아래 10/21 행 | 10/20 회의 결정 | `backend/router/v1/auth/account.py` | | [ ] | 사람 글 사진 올리기 — 보여 주기(talk.image)는 됨, 올리기는 패키지 설치 확인 후(python-multipart·Pillow, 위치 정보 지우기) | 10/20 회의 결정 | `backend/router/v1/talk/talk.py`, `frontend/src/b/talk.tsx` | | [ ] | 날씨 타로·오늘 날씨 코디 기획 (옷차림 [보류] 행과 합침). 타로는 운세 주제별 귀여운 각 이름으로 — 예: 애정 날씨 타로 → '다툼구름각' (사용자 10/21) | 10/20 회의 | | | [ ] | **[결정 필요]** 피드 각 카드에서 빨래각 같은 평이한 각 빼기 — 피드 각 3개는 전체 순위로 골라 빨래각(priority 1)이 들어감. priority를 낮추면 히어로·각 탭 순위도 바뀜. priority 조정 vs 피드에선 is_fun 각 먼저 | 피드 순서 작업 중 발견 | `backend/seed/index_definition.json`, `backend/services/feed_service.py` | | [ ] | 오늘의 각 카드 순위와 점수 순서가 다름(1위 83점, 2위 97점) — 순위에 중요도를 섞어서. 카드로 보이니 어색함 | 카드화 중 발견 | `backend/services/index_service.py` | +| [ ] | AdSense 게재 — 피드 포스트 사이 인피드 광고(포스트 틀, '광고' 표시, 몇 개마다 넣을지 결정). 게시자 ID(ca-pub-…) 받은 뒤 진행, `public/ads.txt`·`privacy.html` 광고 쿠키 고지·`docs/콘텐츠_설계서.md:11` '광고 없음' 수정 같이 | 사용자 결정 10/21, ID 없음 (https://adsense.google.com/start/) | `frontend/index.html`, `frontend/src/b/TodayPage.tsx` | | [ ] | 테스트 실패 2건: `test_feed.py::test_feed_assembles_hero_stories_posts_and_bands`(각 57개, 기대 40 — 커밋 전 각 추가 영향), `test_weather_today.py:60`(날짜 따라 18시 아이콘 moon) | 피드 순서 작업 중 발견 | `backend/tests/` | +## 10/21 회의 (`docs/meetings/2026-10-21.md`) + +| 상태 | 할 일 | 이유 | 관련 파일 | +|---|---|---|---| +| [x] | 공유에 링크 반드시 포함 — 공유창에 고정 URL을 url 칸으로 넘기고 링크도 클립보드에 복사(이미지만 받는 앱 대비) (금일 핵심) | 10/21 회의 결정 | `frontend/src/b/Sheets.tsx:564` | +| [x] | 히어로는 지금 형태 유지 + 좋아요·댓글 추가 (공유는 원래 있음). 서버에 히어로용 포스트(PostType.HERO)를 날마다 시도별로 만듦 | 10/21 회의 결정 | `frontend/src/b/TodayPage.tsx`, `backend/services/feed_service.py` | +| [x] | 오늘의 각부터 모든 카드에 좋아요·댓글·공유 — 오늘의 각 카드에 붙임(PostType.TODAY_GAK). 단풍 지도 카드는 아직 보내기만 (금일 핵심) | 10/21 회의 결정 | `frontend/src/b/TodayPage.tsx`, `backend/services/reaction_service.py` | +| [x] | 로그인은 포스팅할 때만, 댓글은 로그인 없이 — 이름 '마포구 익명'(사용자 결정 10/21), 링크·전화번호 막기, IP당 하루 20개, 지우기는 같은 IP (금일 핵심) | 10/21 회의 결정 | `backend/router/v1/reaction/reaction.py` | +| [x] | 웹 로그인 구글로 통일 — 로그인 창에서 아이디·비밀번호 칸 뺌. 서버 `/v1/auth/signup`·`/login`은 테스트 6개 파일이 계정 만들 때 써서 남김 (금일 핵심) | 10/21 회의 결정 | `frontend/src/b/Sheets.tsx`, `backend/router/v1/auth/account.py:25` | +| [ ] | 모바일에서 창이 닫히지 않는 오류 — 어느 창인지 확인 필요 (금일 핵심) | 10/21 회의 | `frontend/src/b/Sheets.tsx` | +| [x] | '내일 날씨' — 별도 카드 대신 히어로에 오늘/내일 스위치(사용자 결정 10/21). 내일은 시간대별 날씨 점수·기온, 최저·최고, 습도, 내일 1위 각 | 10/21 회의 결정 | `frontend/src/b/TodayPage.tsx` | +| [ ] | 넣을 수 있는 지역은 모두 날씨 페이지 추가 (지금 274개) | 10/21 회의 결정 | `backend/seed/region.csv` | +| [x] | 단풍 지도 UI 수정 — 단풍 그림 지도(Codex), 카카오처럼 단계 3개(단풍 전·첫 단풍·절정)와 단풍잎·은행잎 아이콘, 명소 65곳(단풍 39·은행 26) | 10/21 회의 후속, 사용자 10/21 | `frontend/src/b/foliageMap.tsx`, `frontend/seo/foliage_2026.json` | +| [ ] | 단풍 지도 '첫 단풍'은 절정 14일 전부터로 추정(발표에 시작일 없음). 예측 지점이 아닌 명소 32곳은 가장 가까운 예측 지점 날짜를 빌림(예: 남산공원·창덕궁 ← 수리산). 실제 관측과 다를 수 있음 | 사용자 결정 10/21 | `frontend/seo/foliage_2026.json` | +| [ ] | 토스 미니앱 최신 버전 재등록 — 웹이 바뀌면 자동 반영 안 됨 | 10/21 회의 | | +| [ ] | 유튜브 숏폼 자동화 진행 방안 협의 (김성경, 10/22) | 10/21 회의 | | +| [ ] | 인스타 운영 관리자 페이지(자동 게시 전 승인 메일) + 초기 이야기형 피드(각 100개·빨래각·소맥각·점수 산정법) | 10/21 회의 | | +| [ ] | 레이어 공유 아이디어 — 사용자 사진 위에 날씨각 정보를 얹어 공유(캐시워크식), 앱 기능으로 | 10/21 회의 (황 본부장 의견, 대표 방향) | | +| [ ] | iOS 개발자 계정 — 소장에게 기존 계정 확인, 어려우면 회사 계정 새로 만들기. 안드로이드 앱 계속 준비 | 10/21 회의 결정 | | +| [ ] | 앱인토스 정산 계좌 법인 계좌로 등록(대표) 후 토스 로그인 연동 가입 | 10/21 회의 결정 | | +| [ ] | '○○구 내일 날씨' 검색 태깅 — 스위치 뒤 내용은 눌러야 보여 구글이 읽는지 공식 문서로 확인 필요. 구 페이지(SEO)에 내일 기온·습도 넣는 안과 비교 | 10/21 회의 결정 | `backend/router/v1/seo/` | +| [ ] | **운영 DB 반영 필요** — 댓글 표 `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` | +| [ ] | 익명 댓글이 링크·하루 제한에 걸려도 '댓글을 올리지 못했어요'만 나옴 — 이유별 안내 | 익명 댓글 작업 중 발견 | `frontend/src/b/Sheets.tsx` | +| [ ] | 매일 대표에게 진행 보고 (미완료 포함) | 10/21 회의 결정 | | + ## 진행 순서 결정이 필요 없는 것부터, 사용자 눈에 틀린 정보가 보이는 것 → 기능 → 다듬기 순. @@ -193,3 +220,11 @@ | [ ] | **[결정 필요]** 기존 각과 겹침 — 센치↔감성노래, 게임↔넷플릭스·집콕, 곱슬머리↔화장붕괴, 효도↔트로트, 셀카↔사진산책. 둘 다 둘지 합칠지 | 새 각 추가 중 발견 (10/20) | `backend/seed/index_definition.json` | | [ ] | 감사각은 '어제보다 날씨가 크게 바뀐 날'을 못 봄 — 지금은 덥거나 춥거나 비 오면 높음. 전날 대비 기온 변화 요소를 계산에 넣을지 | 새 각 추가 중 발견 (10/20) | `backend/services/calc/index_calc.py` | | [ ] | 테스트 2개가 날짜·시각에 따라 깨짐 — `test_feed` 스토리 수 40 고정(10월엔 계절 각이 늘어 다름, 각 추가 전 42·후 57), `test_weather_today` 7번째 칸이 시각에 따라 노을/달 | 새 각 추가 중 테스트에서 발견 (10/20) | `backend/tests/test_feed.py:64`, `backend/tests/test_weather_today.py` | +| [x] | 내 각 만들기 '있는 각에서 불러오기' 문구 검토 — 그대로 쓰기로 확정 (10/21) | 각 불러오기 카로셀 추가 (10/21) | `frontend/src/b/myGak.tsx` | +| [ ] | 내 각 만들기 숫자 칸이 좁아 세 자리(습도 100)가 잘림 — 불러온 각에 100이 자주 나옴 | 각 불러오기 카로셀 확인 중 발견 (10/21) | `frontend/src/b/myGak.tsx` `Num` | +| [ ] | 불러온 각 점수가 공식 각과 다름 — 더울수록·멀수록·바람 셀수록·요일 같은 규칙은 내 각 조건으로 비슷하게만 옮기거나 뺌(파티·게임·감사각은 비 조건만 남음) | 각 불러오기 카로셀 추가 (10/21) | `backend/services/calc/my_gak_calc.py` `preset` | +| [x] | 피드에 사람 글이 6개까지만 보임 — 20개를 받고 운영 포스트 3개마다 1개씩만 끼움(포스트 18개 → 6개). 나머지 14개와 다음 페이지는 안 보임 | 피드 정렬 점검 (10/21) | `frontend/src/b/TodayPage.tsx:419`, `frontend/src/b/talkState.ts` | +| [x] | 방금 쓴 글을 지워도 글쓰기 칸 아래에 남음 — 화면에만 들고 있는 내 글 목록(`mine`)에서 빼지 않음 | 피드 정렬 점검 (10/21) | `frontend/src/b/TodayPage.tsx:366`, `frontend/src/b/talk.tsx:201` | +| [x] | 내가 쓴 글 모아 보기 없음 → 내 정보 창에 '내 글' 목록(10/21) — 새로고침하면 위 고정이 풀리고 전국 최신순에 섞여 6개 안에 못 들면 못 찾음. 내 정보 창에 '내 글' 목록을 둘지 | 피드 정렬 점검 (10/21) | `backend/crud/talk_crud.py`, `frontend/src/b/Sheets.tsx:870` | +| [x] | 사람 글 정렬이 전국 최신순뿐 → 같은 시도 글 12시간 앞당김, 같은 사람 연속 금지(10/21) — 우리 동네 글 우선 없음, 한 사람이 하루 5개 쓰면 피드 사람 글 칸을 거의 다 차지함 | 피드 정렬 점검 (10/21) | `backend/crud/talk_crud.py:27` | +| [ ] | **[결정 필요]** 내 글 문구 검토 — '내 글', '아직 쓴 글이 없어요', '더 보기'를 확인받지 않고 넣음 | 피드 정렬 개선 (10/21) | `frontend/src/b/talk.tsx` `MyTalks` | diff --git a/backend/common/database/model/models.py b/backend/common/database/model/models.py index 02b6627..a048600 100644 --- a/backend/common/database/model/models.py +++ b/backend/common/database/model/models.py @@ -357,7 +357,9 @@ class Comment(Base): comment_id: Mapped[int] = mapped_column(BigInteger, primary_key=True) post_id: Mapped[int] = mapped_column(BigInteger) - user_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True)) + user_id: Mapped[Optional[uuid.UUID]] = mapped_column(UUID(as_uuid=True), nullable=True) + ip_hash: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + region_name: Mapped[Optional[str]] = mapped_column(String(20), nullable=True) body: Mapped[str] = mapped_column(String(60)) like_count: Mapped[int] = mapped_column(Integer, default=0) created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now()) diff --git a/backend/common/enums.py b/backend/common/enums.py index 09d5a97..7759acf 100644 --- a/backend/common/enums.py +++ b/backend/common/enums.py @@ -145,6 +145,8 @@ class PostType(CodeEnum): DAY_TRIP = 13 # 당일치기: 1~2시간 거리 후보 도시 중 주말 날씨 1위 + 그곳 행사 MOON = 14 # 오늘 밤 달 (보름·삭이면 그 이야기) UV = 15 # 오늘 낮 자외선 (아침·낮, '보통' 이상인 날만) + HERO = 16 # 히어로(오늘 날씨)의 좋아요·댓글 자리. 피드 목록엔 안 나온다 + TODAY_GAK = 17 # 오늘의 각 카드의 좋아요·댓글 자리. 피드 목록엔 안 나온다 class EventKind(CodeEnum): diff --git a/backend/crud/reaction_crud.py b/backend/crud/reaction_crud.py index 274f9f8..5defe41 100644 --- a/backend/crud/reaction_crud.py +++ b/backend/crud/reaction_crud.py @@ -1,7 +1,8 @@ import uuid +from datetime import datetime from typing import Optional -from sqlalchemy import delete, select, update +from sqlalchemy import delete, func, select, update from sqlalchemy.dialects.postgresql import insert from sqlalchemy.ext.asyncio import AsyncSession @@ -51,8 +52,9 @@ class ReactionCRUD: stmt = stmt.where(Post.post_id < cursor) return list((await s.execute(stmt.order_by(Post.post_id.desc()).limit(limit))).all()) - async def comments(self, s: AsyncSession, post_id: int, cursor: Optional[int], limit: int) -> list[tuple[Comment, str, str, str, Optional[str]]]: - stmt = select(Comment, User.nickname, User.character, User.color, User.mood).join(User, User.user_id == Comment.user_id).where(Comment.post_id == post_id, Comment.deleted.is_(False)) + async def comments(self, s: AsyncSession, post_id: int, cursor: Optional[int], limit: int) -> list[tuple[Comment, Optional[str], Optional[str], Optional[str], Optional[str]]]: + """로그인 없이 쓴 댓글은 User 칸이 모두 None 이다.""" + stmt = select(Comment, User.nickname, User.character, User.color, User.mood).outerjoin(User, User.user_id == Comment.user_id).where(Comment.post_id == post_id, Comment.deleted.is_(False)) if cursor is not None: stmt = stmt.where(Comment.comment_id > cursor) return list((await s.execute(stmt.order_by(Comment.comment_id).limit(limit))).all()) @@ -65,16 +67,20 @@ class ReactionCRUD: stmt = select(CommentLikeAnon.comment_id).where(CommentLikeAnon.ip_hash == ip_hash, CommentLikeAnon.comment_id.in_(comment_ids)) return set((await s.scalars(stmt)).all()) - async def add_comment(self, s: AsyncSession, post_id: int, user_id: uuid.UUID, body: str) -> Comment: - c = Comment(post_id=post_id, user_id=user_id, body=body) + async def add_comment(self, s: AsyncSession, post_id: int, who: Liker, body: str, region_name: Optional[str]) -> Comment: + c = Comment(post_id=post_id, user_id=who.user_id, body=body) if who.user_id is not None else Comment(post_id=post_id, ip_hash=who.ip_hash, region_name=region_name, body=body) s.add(c) await s.execute(update(Post).where(Post.post_id == post_id).values(comment_count=Post.comment_count + 1)) await s.flush() return c - async def delete_comment(self, s: AsyncSession, comment_id: int, user_id: uuid.UUID) -> bool: + async def anon_comments_since(self, s: AsyncSession, ip_hash: str, since: datetime) -> int: + return await s.scalar(select(func.count()).select_from(Comment).where(Comment.user_id.is_(None), Comment.ip_hash == ip_hash, Comment.created_at >= since)) + + async def delete_comment(self, s: AsyncSession, comment_id: int, who: Liker) -> bool: + owner = Comment.user_id == who.user_id if who.user_id is not None else (Comment.user_id.is_(None) & (Comment.ip_hash == who.ip_hash)) res = await s.execute( - update(Comment).where(Comment.comment_id == comment_id, Comment.user_id == user_id, Comment.deleted.is_(False)) + update(Comment).where(Comment.comment_id == comment_id, owner, Comment.deleted.is_(False)) .values(deleted=True).returning(Comment.post_id) ) post_id = res.scalar() diff --git a/backend/crud/talk_crud.py b/backend/crud/talk_crud.py index 2c59ad5..11c8e78 100644 --- a/backend/crud/talk_crud.py +++ b/backend/crud/talk_crud.py @@ -2,7 +2,7 @@ import uuid from datetime import datetime from typing import Optional -from sqlalchemy import delete, func, select, update +from sqlalchemy import BigInteger, case, cast, delete, func, select, tuple_, update from sqlalchemy.dialects.postgresql import insert from sqlalchemy.ext.asyncio import AsyncSession @@ -12,16 +12,29 @@ from crud.reaction_crud import toggle_like_row class TalkCRUD: - async def page(self, s: AsyncSession, viewer: Optional[uuid.UUID], cursor: Optional[int], limit: int) -> list[tuple[Talk, User, Optional[str]]]: - """최신 글부터. 숨김·지운 글과 내가 안 보기로 한 사람의 글은 뺀다.""" + async def page( + self, s: AsyncSession, viewer: Optional[uuid.UUID], sido: Optional[str], boost_sec: int, cursor: Optional[tuple[int, int]], limit: int + ) -> list[tuple[Talk, User, Optional[str], int]]: + """최신 글부터. 보는 사람과 같은 시도 글은 boost_sec 만큼 늦게 쓴 것처럼 앞에 둔다. 숨김·지운 글과 내가 안 보기로 한 사람의 글은 뺀다. + cursor 는 앞 페이지 마지막 글의 (정렬 키, talk_id).""" + key = cast(func.floor(func.extract("epoch", Talk.created_at)), BigInteger) + if sido: + key = key + case((func.left(Talk.region_code, 2) == sido, boost_sec), else_=0) stmt = ( - select(Talk, User, Region.short_name) + select(Talk, User, Region.short_name, key) .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)) ) if viewer is not None: stmt = stmt.where(Talk.user_id.not_in(select(UserBlock.blocked_id).where(UserBlock.user_id == viewer))) + 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 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)) if cursor is not None: stmt = stmt.where(Talk.talk_id < cursor) return list((await s.execute(stmt.order_by(Talk.talk_id.desc()).limit(limit))).all()) diff --git a/backend/postgres-init/init.sql b/backend/postgres-init/init.sql index 0550fab..e2abd89 100644 --- a/backend/postgres-init/init.sql +++ b/backend/postgres-init/init.sql @@ -237,6 +237,11 @@ CREATE TABLE IF NOT EXISTS public.comment ( deleted BOOLEAN NOT NULL DEFAULT FALSE ); CREATE INDEX IF NOT EXISTS idx_comment_post ON public.comment (post_id, created_at) WHERE deleted = FALSE; +-- 로그인 없이 쓴 댓글은 user_id 가 비고 IP 해시와 쓸 때의 동네 이름('마포구 익명'으로 보임)을 남긴다 +ALTER TABLE public.comment ALTER COLUMN user_id DROP NOT NULL; +ALTER TABLE public.comment ADD COLUMN IF NOT EXISTS ip_hash VARCHAR(64) NULL; +ALTER TABLE public.comment ADD COLUMN IF NOT EXISTS region_name VARCHAR(20) NULL; +CREATE INDEX IF NOT EXISTS idx_comment_ip ON public.comment (ip_hash, created_at) WHERE user_id IS NULL; -- 댓글 신고 (보류) -- ALTER TABLE public.comment ADD COLUMN report_count INTEGER NOT NULL DEFAULT 0; diff --git a/backend/router/v1/feed/feed.py b/backend/router/v1/feed/feed.py index 90dc77a..5296168 100644 --- a/backend/router/v1/feed/feed.py +++ b/backend/router/v1/feed/feed.py @@ -22,11 +22,15 @@ async def get_feed( err, feed = await service.feed(region) if err is not ErrorType.SUCCESS: return Res_Feed(result=error_info(err)) - ids = [p.post_id for p in feed.posts] + pinned = [x for x in (feed.hero_post, feed.gak_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) # 캐시된 피드는 모두에게 같으니, 로그인 안 한 사람의 좋아요 표시는 캐시 밖에서 IP 해시로 덧붙인다 anon_liked = await reactions.anon_liked(who.ip_hash, ids) if user is None else set() + for x in pinned: + x.like_count, x.comment_count = counts.get(x.post_id, (x.like_count, x.comment_count)) + x.liked = x.post_id in (liked if user is not None else anon_liked) for p in feed.posts: p.like_count, p.comment_count = counts.get(p.post_id, (p.like_count, p.comment_count)) if user is not None: diff --git a/backend/router/v1/feed/protocol.py b/backend/router/v1/feed/protocol.py index d69251e..add81af 100644 --- a/backend/router/v1/feed/protocol.py +++ b/backend/router/v1/feed/protocol.py @@ -136,6 +136,14 @@ class PostData(WebPacketProtocol): saved: Optional[bool] = None +class PostReaction(WebPacketProtocol): + """포스트 틀이 아닌 카드(히어로·오늘의 각)에 붙는 좋아요·댓글.""" + post_id: int + like_count: int + comment_count: int + liked: Optional[bool] = None + + class TopIndex(WebPacketProtocol): index_id: int code: str @@ -163,6 +171,14 @@ class WeatherWhy(WebPacketProtocol): note: str = Field(description="지금 값 (예: 체감 19°, 편한 범위 18~24° 안)") +class HeroTomorrow(WebPacketProtocol): + """히어로 '내일' 스위치. 3시간 칸 날씨는 /v1/weather/today?day=tomorrow 로 따로 받는다.""" + day: date + weather_slots: dict[str, int] = Field(default_factory=dict, description="내일 구간별 날씨 점수 {morning·day·evening·night: 점수}") + weather_why: dict[str, list[WeatherWhy]] = Field(default_factory=dict, description="내일 구간별 날씨 점수 근거") + top1: Optional[TopIndex] = Field(default=None, description="내일 하루 점수로 1위인 각. score·summary 는 내일 값") + + class Hero(WebPacketProtocol): now_at: datetime sky_mode: Literal["morning", "day", "sunset", "night"] @@ -182,6 +198,7 @@ class Hero(WebPacketProtocol): moon_pct: Optional[int] = Field(default=None, description="달에서 빛나는 면의 비율 0~100 (모양 그림용, 밝기 아님)") stats: list[HeroStat] = Field(default_factory=list, description="히어로 상황 칸 1개. 지금 챙길 것(비·미세먼지·자외선·일교차·체감) 먼저") status: list[HeroStat] = Field(default_factory=list, description="히어로 상태 한 줄: 습도·불쾌지수·자외선(밤 구간 빼고)·미세먼지 단계 이름. tone=warn 이면 조심(앱이 주황 글자로)") + tomorrow: Optional[HeroTomorrow] = None class BandEvent(WebPacketProtocol): @@ -215,6 +232,8 @@ class Res_Feed(Res_WebPacketProtocol): hero: Optional[Hero] = None stories: list[TopIndex] = [] posts: list[PostData] = [] + hero_post: Optional[PostReaction] = None + gak_post: Optional[PostReaction] = None bands: Optional[Bands] = None diff --git a/backend/router/v1/my_gak/my_gak.py b/backend/router/v1/my_gak/my_gak.py index c70c546..525d18b 100644 --- a/backend/router/v1/my_gak/my_gak.py +++ b/backend/router/v1/my_gak/my_gak.py @@ -7,7 +7,7 @@ from common.database.model.models import MyGak, User from common.enums import ErrorType from common.models.errors import error_info from common.models.gmodel import Res_WebPacketProtocol -from router.v1.my_gak.protocol import MyGakData, MyGakRule, MyGakScore, Req_MyGak, Req_MyGakScore, Res_MyGak, Res_MyGakList, Res_MyGakScore +from router.v1.my_gak.protocol import MyGakData, MyGakPreset, MyGakRule, MyGakScore, Req_MyGak, Req_MyGakScore, Res_MyGak, Res_MyGakList, Res_MyGakPresets, Res_MyGakScore from services.my_gak_service import MyGakService router = APIRouter(prefix="/v1/my-gak", tags=["my-gak"]) @@ -33,6 +33,14 @@ async def add_my_gak(req: Req_MyGak, user: User = Depends(current_user), service return Res_MyGak(result=error_info(err)) if err is not ErrorType.SUCCESS or g is None else Res_MyGak(item=_data(g)) +@router.get("/presets", response_model=Res_MyGakPresets, response_model_exclude_none=True, summary="공식 각을 내 각 조건으로 옮긴 목록 (내 각 만들기에서 골라 채우기)") +async def list_presets(service: MyGakService = Depends()) -> Res_MyGakPresets: + err, items = await service.presets() + if err is not ErrorType.SUCCESS: + return Res_MyGakPresets(result=error_info(err)) + return Res_MyGakPresets(items=[MyGakPreset(**x) for x in items]) + + @router.post("/score", response_model=Res_MyGakScore, response_model_exclude_none=True, summary="조건들의 그 동네 오늘 점수 (로그인 없이, 받은 링크의 각도)") async def score_my_gak(req: Req_MyGakScore, service: MyGakService = Depends()) -> Res_MyGakScore: err, got = await service.score(req.region_code, [r.model_dump(exclude_none=True) for r in req.rules]) diff --git a/backend/router/v1/my_gak/protocol.py b/backend/router/v1/my_gak/protocol.py index 5f29dea..69762d1 100644 --- a/backend/router/v1/my_gak/protocol.py +++ b/backend/router/v1/my_gak/protocol.py @@ -37,6 +37,17 @@ class Req_MyGak(Req_WebPacketProtocol): rule: MyGakRule +class MyGakPreset(WebPacketProtocol): + code: str + name: str + icon: str + rule: MyGakRule = Field(description="공식 각을 내 각 조건으로 비슷하게 옮긴 값. 점수는 공식 각과 다를 수 있음") + + +class Res_MyGakPresets(Res_WebPacketProtocol): + items: list[MyGakPreset] = [] + + class Res_MyGakList(Res_WebPacketProtocol): items: list[MyGakData] = Field(default=[], description="내 각. 로그인하지 않았으면 비어 있음") diff --git a/backend/router/v1/reaction/protocol.py b/backend/router/v1/reaction/protocol.py index cfbf179..411fb5c 100644 --- a/backend/router/v1/reaction/protocol.py +++ b/backend/router/v1/reaction/protocol.py @@ -1,6 +1,8 @@ from datetime import date, datetime from typing import Optional +from pydantic import Field + from common.enums import PostType from common.models.gmodel import Req_WebPacketProtocol, Res_WebPacketProtocol, WebPacketProtocol @@ -46,6 +48,7 @@ class Res_CommentList(Res_WebPacketProtocol): class Req_Comment(Req_WebPacketProtocol): body: str + region: Optional[str] = Field(None, description="로그인 없이 쓸 때 보고 있는 동네 코드. 이름이 '마포구 익명'으로 보인다") class Res_Comment(Res_WebPacketProtocol): diff --git a/backend/router/v1/reaction/reaction.py b/backend/router/v1/reaction/reaction.py index 6e8ec63..302cc61 100644 --- a/backend/router/v1/reaction/reaction.py +++ b/backend/router/v1/reaction/reaction.py @@ -69,15 +69,17 @@ async def list_comments( return Res_CommentList(comments=[_comment(v) for v in items], next_cursor=items[-1].comment.comment_id if len(items) == PAGE else None) -@router.post("/post/{post_id}/comment", response_model=Res_Comment, response_model_exclude_none=True, summary="댓글 쓰기 (60자)") -async def add_comment(post_id: int = Path(...), req: Req_Comment = ..., user: User = Depends(current_user), service: ReactionService = Depends()) -> Res_Comment: - err, v = await service.add_comment(post_id, user, req.body) +@router.post("/post/{post_id}/comment", response_model=Res_Comment, response_model_exclude_none=True, summary="댓글 쓰기 (60자, 로그인 없으면 '동네 익명'으로 IP 당 하루 20개)") +async def add_comment( + post_id: int = Path(...), req: Req_Comment = ..., user: Optional[User] = Depends(optional_user), who: Liker = Depends(liker), service: ReactionService = Depends(), +) -> Res_Comment: + err, v = await service.add_comment(post_id, user, who, req.body, req.region) return Res_Comment(result=error_info(err)) if err is not ErrorType.SUCCESS else Res_Comment(comment=_comment(v)) -@router.delete("/comment/{comment_id}", response_model=Res_WebPacketProtocol, response_model_exclude_none=True, summary="내 댓글 지우기") -async def delete_comment(comment_id: int = Path(...), user: User = Depends(current_user), service: ReactionService = Depends()) -> Res_WebPacketProtocol: - return Res_WebPacketProtocol(result=error_info(await service.delete_comment(comment_id, user))) +@router.delete("/comment/{comment_id}", response_model=Res_WebPacketProtocol, response_model_exclude_none=True, summary="내 댓글 지우기 (로그인 없이 쓴 댓글은 같은 IP 에서)") +async def delete_comment(comment_id: int = Path(...), who: Liker = Depends(liker), service: ReactionService = Depends()) -> Res_WebPacketProtocol: + return Res_WebPacketProtocol(result=error_info(await service.delete_comment(comment_id, who))) async def _clike(comment_id: int, who: Liker, on: bool, service: ReactionService) -> Res_CommentLike: diff --git a/backend/router/v1/talk/protocol.py b/backend/router/v1/talk/protocol.py index 31a1bfb..7ba2435 100644 --- a/backend/router/v1/talk/protocol.py +++ b/backend/router/v1/talk/protocol.py @@ -35,7 +35,7 @@ class Req_TalkReport(Req_WebPacketProtocol): class Res_TalkList(Res_WebPacketProtocol): talks: list[TalkData] = [] - next_cursor: Optional[int] = None + next_cursor: Optional[str] = Field(None, description="다음 페이지를 받을 때 그대로 cursor 로 보낸다") class Res_Talk(Res_WebPacketProtocol): diff --git a/backend/router/v1/talk/talk.py b/backend/router/v1/talk/talk.py index c4f7e89..b134371 100644 --- a/backend/router/v1/talk/talk.py +++ b/backend/router/v1/talk/talk.py @@ -14,7 +14,7 @@ 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 services.talk_image import MAX_BYTES, URL_PREFIX, file_of, save -from services.talk_service import PAGE, TalkService, TalkView +from services.talk_service import TalkService, TalkView router = APIRouter(prefix="/v1/talk", tags=["talk"]) @@ -27,15 +27,28 @@ def _data(v: TalkView) -> TalkData: ) -@router.get("/list", response_model=Res_TalkList, response_model_exclude_none=True, summary="동네 이야기 (전국, 최신순, 로그인 없이 보기)") +@router.get("/list", response_model=Res_TalkList, response_model_exclude_none=True, summary="동네 이야기 (전국 최신순, 보는 동네와 같은 시도 글은 앞으로, 같은 사람 글은 띄움, 로그인 없이 보기)") async def list_talks( - cursor: Optional[int] = Query(None), user: Optional[User] = Depends(optional_user), who: Liker = Depends(liker), service: TalkService = Depends() + region: Optional[str] = Query(None, min_length=10, max_length=10, 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 = await service.page(user, who.ip_hash, cursor) + err, views, nxt = await service.page(user, who.ip_hash, region, cursor) if err is not ErrorType.SUCCESS: return Res_TalkList(result=error_info(err)) - talks = [_data(v) for v in views] - return Res_TalkList(talks=talks, next_cursor=talks[-1].talk_id if len(talks) == PAGE else None) + return Res_TalkList(talks=[_data(v) for v in views], next_cursor=nxt) + + +@router.get("/mine", response_model=Res_TalkList, response_model_exclude_none=True, summary="내가 쓴 글 (최신순)") +async def list_my_talks(cursor: Optional[str] = Query(None, max_length=20), user: User = Depends(current_user), service: TalkService = Depends()) -> Res_TalkList: + if cursor is not None and not cursor.isdigit(): + return Res_TalkList(result=error_info(ErrorType.INVALID_INPUT)) + err, views, nxt = await service.mine(user, int(cursor) if cursor 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=str(nxt) if nxt else None) @router.post("", response_model=Res_Talk, response_model_exclude_none=True, summary="동네 이야기 쓰기 (링크·전화번호 불가, 하루 5개)") diff --git a/backend/router/v1/weather/protocol.py b/backend/router/v1/weather/protocol.py index d12e3fc..9c230f8 100644 --- a/backend/router/v1/weather/protocol.py +++ b/backend/router/v1/weather/protocol.py @@ -13,6 +13,7 @@ class WeatherSlot(WebPacketProtocol): sky: Optional[Sky] = None rain_type: Optional[RainType] = None rain_prob: Optional[int] = None + humidity: Optional[int] = None icon: str tone: SlotTone note: str diff --git a/backend/router/v1/weather/weather.py b/backend/router/v1/weather/weather.py index 397392c..5572a62 100644 --- a/backend/router/v1/weather/weather.py +++ b/backend/router/v1/weather/weather.py @@ -1,8 +1,11 @@ +from datetime import timedelta +from typing import Literal + from fastapi import APIRouter, Depends, Query from common.enums import AirGrade, ErrorType, RainType, Sky from common.models.errors import error_info -from common.utils.kma_time import KST +from common.utils.kma_time import KST, now_kst from router.v1.weather.protocol import ( AirData, CommuteData, @@ -24,13 +27,16 @@ def _to_slot(s: Slot) -> WeatherSlot: data = WeatherSlot(at=s.at, label=f"{s.at.astimezone(KST).hour}시", icon=s.icon, tone=s.tone, note=s.note) if s.row is not None: data.temp_c, data.feels_c = float(s.row.temp_c), float(s.row.feels_c) - data.sky, data.rain_type, data.rain_prob = Sky(s.row.sky), RainType(s.row.rain_type), s.row.rain_prob + data.sky, data.rain_type, data.rain_prob, data.humidity = Sky(s.row.sky), RainType(s.row.rain_type), s.row.rain_prob, s.row.humidity return data -@router.get("/today", response_model=Res_WeatherToday, response_model_exclude_none=True, summary="오늘 3시간 칸 날씨") -async def get_weather_today(region: str = Query(..., description="구 행정코드"), service: WeatherService = Depends()) -> Res_WeatherToday: - err, today = await service.today(region) +@router.get("/today", response_model=Res_WeatherToday, response_model_exclude_none=True, summary="오늘(또는 내일) 3시간 칸 날씨") +async def get_weather_today( + region: str = Query(..., description="구 행정코드"), day: Literal["today", "tomorrow"] = Query("today", description="tomorrow 면 내일 칸"), + service: WeatherService = Depends(), +) -> Res_WeatherToday: + err, today = await service.today(region, now_kst().date() + timedelta(days=1) if day == "tomorrow" else None) if err is not ErrorType.SUCCESS: return Res_WeatherToday(result=error_info(err)) return Res_WeatherToday( diff --git a/backend/services/calc/my_gak_calc.py b/backend/services/calc/my_gak_calc.py index 4231f8b..d7b4a89 100644 --- a/backend/services/calc/my_gak_calc.py +++ b/backend/services/calc/my_gak_calc.py @@ -50,3 +50,69 @@ def definition(rule: MyRule) -> SimpleNamespace: zero_rules=[{"field": "rain", "op": "==", "value": "yes", "cap": 20}] if rule.rain == "dry" else [], windows=[{"from": NIGHT_END_HOUR, "to": 24 + NIGHT_END_HOUR}], ) + + +# 공식 각을 내 각 조건으로 옮길 때 쓰는 대표 시각(해 뜨고 지는 시각은 계절마다 달라 가운데 값으로) +_SUNRISE_HOUR, _SUNSET_HOUR = 6, 18 +_TEMP_MIN, _TEMP_MAX = -20, 40 + + +def _slot_of_hour(h: int) -> str: + h %= 24 + if NIGHT_END_HOUR <= h < 11: + return "morning" + if 11 <= h < _SUNSET_HOUR - 2: + return "day" + if _SUNSET_HOUR - 2 <= h < _SUNSET_HOUR + 1: + return "evening" + return "night" + + +def _window_slots(windows: list[dict]) -> list[str]: + hours: set[int] = set() + for w in windows: + if "around" in w: + mid = _SUNRISE_HOUR if w["around"] == "sunrise" else _SUNSET_HOUR + hours.update(range(mid - w["hours"], mid + w["hours"])) + else: + hours.update(range(w["from"], w["to"])) + got = {_slot_of_hour(h) for h in hours} + return [s for s in SLOTS if s in got] + + +def _preset_temp(r: dict) -> Optional[list[float]]: + off = r.get("offset", 0) + t = r["type"] + if t == "range": + lo, hi = r["lo"] - off, r["hi"] - off + elif t == "higher": + lo, hi = r["full"] - off, _TEMP_MAX + elif t == "lower": + lo, hi = _TEMP_MIN, r["full"] - off + else: + return None # 범위에서 멀수록 좋은 규칙은 범위 하나로 옮길 수 없다 + lo, hi = max(_TEMP_MIN, lo), min(_TEMP_MAX, hi) + return [_n(lo), _n(hi)] if lo < hi else None + + +_PRESET_HUMIDITY = {"higher": [60, 100], "lower": [0, 60]} + + +def preset(defn) -> dict: + """공식 각을 내 각 조건(MyGakRule 모양)으로 비슷하게 옮긴다. 비중 0인 요소와 옮길 수 없는 규칙은 뺀다.""" + r = defn.factor_rules + out: dict = {"slots": _window_slots(defn.windows) or list(SLOTS)} + if defn.weight_temp and (temp := _preset_temp(r["temp"])): + out["temp"] = temp + if defn.weight_rain: + out["rain"] = r["rain"]["dir"] + wind = r.get("wind", {}) + if defn.weight_wind and wind.get("type") in ("calm", "moderate"): + out["wind_max"] = _n(max(1, wind["ok"])) if wind["type"] == "calm" else 5 + air = r.get("air") + if defn.weight_air and not (air and air["full"] > air["zero"]): + out["air"] = "normal" + hum = r.get("humidity", {}) + if defn.weight_humidity and hum.get("type") in ("range", "higher", "lower"): + out["humidity"] = [hum["lo"], hum["hi"]] if hum["type"] == "range" else _PRESET_HUMIDITY[hum["type"]] + return out diff --git a/backend/services/feed_service.py b/backend/services/feed_service.py index 5b1a6c6..ae3f7b2 100644 --- a/backend/services/feed_service.py +++ b/backend/services/feed_service.py @@ -11,7 +11,7 @@ from redis.exceptions import RedisError from common.cache.lock import redis_lock from common.cache.redis_client import REDIS from common.database.db_session_manager import DB_SESSION_MNG -from common.database.model.models import Article, OpenMeteoHourly, Post, Region, WeatherHourly +from common.database.model.models import Article, IndexScore, OpenMeteoHourly, Post, Region, WeatherHourly from common.enums import AirGrade, ArticleCategory, ErrorType, PostType, RainType, RefType, Sky, SkyGrade, SkySituation, SkyType, WarningType from common.logger import LOG from common.utils.kma_time import KST, ULTRA_DELAY, kst_midnight, latest_ultra_base, next_vilage_available, now_kst @@ -21,7 +21,7 @@ from crud.region_crud import RegionCRUD from crud.season_crud import SeasonCRUD from crud.weather_crud import WeatherCRUD from router.v1.feed.protocol import ( - BandArticle, BandEvent, Bands, Cut, GakSlide, Hero, HeroStat, HourCell, HoursSlide, PostData, Res_Feed, Row, RowsSlide, SunsetSlide, + BandArticle, BandEvent, Bands, Cut, GakSlide, Hero, HeroStat, HeroTomorrow, HourCell, HoursSlide, PostData, PostReaction, Res_Feed, Row, RowsSlide, SunsetSlide, PlanSlide, PlanStep, TopIndex, WeatherWhy, WeekDay, WeekGak, WeekSlide, ) from services.air_service import GRADE_LABEL as AIR_GRADE_LABEL @@ -63,7 +63,11 @@ LINEUP = [ (18, PostType.DAY_TRIP, RefType.NONE, None), (19, PostType.MOON, RefType.NONE, None), (20, PostType.UV, RefType.NONE, None), + (21, PostType.HERO, RefType.NONE, None), + (22, PostType.TODAY_GAK, RefType.NONE, None), ] +# 피드 목록 대신 히어로·오늘의 각 카드에 좋아요·댓글만 붙는 자리 +_PINNED = {PostType.HERO: "hero_post", PostType.TODAY_GAK: "gak_post"} # 좋아요·댓글 단위. 이 종류들은 전국이 같은 카드 하나, 나머지는 그 구 데이터로 채우는 카드라 시도마다 따로 만든다. NATIONAL_SCOPE = "00" NATIONAL_TYPES = frozenset({PostType.SEASON, PostType.TIP, PostType.QUOTE, PostType.MOON}) @@ -237,6 +241,28 @@ def _by_position(posts: list[Post]) -> list[Post]: return list(out.values()) +def _tomorrow_best(board: IndexBoard, day: date) -> Optional[tuple[IndexItem, IndexScore]]: + """내일 하루 점수로 1위인 각과 그 점수 (점수 × 중요도).""" + best = None + for i in board.items: + s = next((x for x in i.trend if x.score_date == day), None) + if s is not None and (best is None or rank_score(s.score, i.definition.priority) > rank_score(best[1].score, best[0].definition.priority)): + best = (i, s) + return best + + +def _hero_tomorrow(day: date, board: IndexBoard) -> HeroTomorrow: + best = _tomorrow_best(board, day) + top1 = None + if best is not None: + d, s = best[0].definition, best[1] + top1 = TopIndex(index_id=d.index_id, code=d.code, name=d.name, icon=d.icon, score=s.score, rank=1, summary=s.summary) + return HeroTomorrow( + day=day, weather_slots=board.tomorrow_slots, top1=top1, + weather_why={k: [WeatherWhy(label=w.label, weight=w.weight, score=w.score, note=w.note) for w in ws] for k, ws in board.tomorrow_why.items()}, + ) + + def _top(i: IndexItem) -> TopIndex: d = i.definition return TopIndex(index_id=d.index_id, code=d.code, name=d.name, icon=d.icon, score=i.score.score, rank=i.rank, summary=i.score.summary, active=i.active, @@ -369,8 +395,10 @@ class FeedService: gak = sorted(board.ranked[:3], key=lambda i: _gak_key(i, now.hour)) if board else [] cards = [] + pinned = {_PINNED[PostType(p.post_type)]: PostReaction(post_id=p.post_id, like_count=p.like_count, comment_count=p.comment_count) + for p in posts or [] if PostType(p.post_type) in _PINNED} for p in posts or []: - if PostType(p.post_type) is PostType.GAK: + if PostType(p.post_type) is PostType.GAK or PostType(p.post_type) in _PINNED: continue data = self._render(p, ctx) if data is not None: @@ -384,7 +412,7 @@ class FeedService: feed = Res_Feed( region_code=region.code, region_name=region.name, slot=slot, hero=self._hero(now, slot, hourly[0] if hourly else None, now_w, board, today, await self._uv(region.code, hour), _moon_view(region, now, hourly or [])), - stories=[_top(i) for i in items], posts=arrange(cards, slot, now, sunset_at, has_warning, f"{day}:{region.code}"), + stories=[_top(i) for i in items], posts=arrange(cards, slot, now, sunset_at, has_warning, f"{day}:{region.code}"), **pinned, bands=Bands( events=[BandEvent(event_id=e.event.event_id, name=e.event.name, status_label=e.status_label, icon=e.event.icon, image=e.event.image_url, image_credit=image_credit(e.event)) for e in mix_kinds(events)[:4]], @@ -448,6 +476,7 @@ class FeedService: 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)], + tomorrow=_hero_tomorrow(now.date() + timedelta(days=1), board) if board else None, ) @staticmethod @@ -689,13 +718,8 @@ class FeedService: return PostData(**base, title=plan.title, icon=icon, caption=caption, slides=slides, share_messages=[share]) def _tomorrow(self, base: dict, c: "_Ctx") -> PostData: - tomorrow = c.now.date() + timedelta(days=1) rows = [Row(label=x.label, value=x.text) for x in c.now_w.commute] - best = None - for i in c.board.items if c.board else []: - s = next((x for x in i.trend if x.score_date == tomorrow), None) - if s is not None and (best is None or rank_score(s.score, i.definition.priority) > rank_score(best[1].score, best[0].definition.priority)): - best = (i, s) + best = _tomorrow_best(c.board, c.now.date() + timedelta(days=1)) if c.board else None if best is not None: rows.append(Row(label="내일 1위 각", value=f"{best[0].definition.name} {best[1].score}점")) caption = _temp_change(c.today, c.tomorrow) or "출근 전에 한 번 더 확인해 주세요." diff --git a/backend/services/index_service.py b/backend/services/index_service.py index 2a482a5..790c234 100644 --- a/backend/services/index_service.py +++ b/backend/services/index_service.py @@ -104,6 +104,8 @@ class IndexBoard: items: list[IndexItem] weather_slots: dict[str, int] = field(default_factory=dict) weather_why: dict[str, list[WeatherWhy]] = field(default_factory=dict) + tomorrow_slots: dict[str, int] = field(default_factory=dict) # 내일 아침·낮·저녁·밤 날씨 점수 + tomorrow_why: dict[str, list[WeatherWhy]] = field(default_factory=dict) @property def ranked(self) -> list[IndexItem]: @@ -326,10 +328,12 @@ class IndexService: if region is None: return ErrorType.NOT_FOUND, None now = now_kst() - err, weather_parts = await self.ensure(region, now) + err, weather_days = await self.ensure(region, now) if err is not ErrorType.SUCCESS: return err, None today = now.date() + weather_parts = weather_days[today] + tomorrow_parts = weather_days.get(today + timedelta(days=1), {}) cur = current_slot(now, sun_times(today, float(region.lat), float(region.lon)).sunset_at) slots = slot_days(today) err, defs = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.definitions(s)) @@ -386,6 +390,8 @@ class IndexService: region=region, day=today, weather_score=weather_parts[cur].score if cur in weather_parts else None, items=items, weather_slots=_shown_parts({k: r.score for k, r in weather_parts.items()}, cur), weather_why=_shown_parts({k: weather_why(r) for k, r in weather_parts.items()}, cur), + tomorrow_slots=_shown_parts({k: r.score for k, r in tomorrow_parts.items()}, ""), + tomorrow_why=_shown_parts({k: weather_why(r) for k, r in tomorrow_parts.items()}, ""), ) async def custom(self, region_code: str, defns: list) -> tuple[ErrorType, Optional[tuple[str, list[dict[str, Result]]]]]: @@ -418,8 +424,8 @@ class IndexService: out.append({shown_slot(k): r for k, r in parts.items() if k != ("night" if cur == EARLY else EARLY)}) return ErrorType.SUCCESS, (shown_slot(cur), out) - async def ensure(self, region: Region, now: datetime) -> tuple[ErrorType, Optional[dict[str, Result]]]: - """재료(예보·미세먼지)가 지수 계산 뒤에 바뀌었으면 오늘~모레와 이번 주말을 다시 계산한다. 오늘 구간별 날씨 점수도 같이 낸다.""" + async def ensure(self, region: Region, now: datetime) -> tuple[ErrorType, Optional[dict[date, dict[str, Result]]]]: + """재료(예보·미세먼지)가 지수 계산 뒤에 바뀌었으면 오늘~모레와 이번 주말을 다시 계산한다. 오늘·내일 구간별 날씨 점수도 같이 낸다.""" _, _, _, warnings, ultra = await asyncio.gather( self.weather_service.ensure_vilage(region, now), self.weather_service.ensure_mid(region, now), self.air_service.ensure(now), self.warning_service.for_region(region, now), ultra_hours(region, now, wait=True), @@ -449,7 +455,13 @@ class IndexService: ) today_ctx = Context(day=today, is_holiday=False, moon=0, sunset_score=None, lookahead_rain_prob=0, rain_hours=rain_hours(by_at, today), **base_ctx) sunset_at = sun_times(today, float(region.lat), float(region.lon)).sunset_at - weather_parts = {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 = today + timedelta(days=1) + 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()}, + } issued = max([r.issued_at for r in rows] + [d.issued_at for d in daily_rows or []]) inputs_at = max(issued, air.measured_at) if air else issued diff --git a/backend/services/my_gak_service.py b/backend/services/my_gak_service.py index 7f7e6d1..c8b5e63 100644 --- a/backend/services/my_gak_service.py +++ b/backend/services/my_gak_service.py @@ -8,7 +8,7 @@ from common.database.model.models import MyGak, User from common.enums import ErrorType from crud.my_gak_crud import MyGakCRUD from services.calc.day_slot import SLOTS -from services.calc.my_gak_calc import MyRule, axes, definition +from services.calc.my_gak_calc import MyRule, axes, definition, preset from services.index_service import IndexService # 한 사람이 만들 수 있는 내 각 수 @@ -57,6 +57,12 @@ class MyGakService: return err return ErrorType.SUCCESS if found else ErrorType.NOT_FOUND + async def presets(self) -> tuple[ErrorType, list[dict]]: + err, defs = await DB_SESSION_MNG.execute_lambda(lambda s: self.index.crud.definitions(s)) + if err is not ErrorType.SUCCESS: + return err, [] + return err, [{"code": d.code, "name": d.name, "icon": d.icon, "rule": preset(d)} for d in defs] + async def score(self, region_code: str, rules: list[dict]) -> tuple[ErrorType, Optional[tuple[str, list[dict]]]]: """조건마다 그 동네 오늘 시간대별 점수. 지금 시간대를 골랐으면 그 점수, 아니면 고른 시간대 중 가장 좋은 점수.""" mine = [my_rule(r) for r in rules] diff --git a/backend/services/reaction_service.py b/backend/services/reaction_service.py index bbdc157..a0e7454 100644 --- a/backend/services/reaction_service.py +++ b/backend/services/reaction_service.py @@ -8,10 +8,16 @@ from common.database.db_session_manager import DB_SESSION_MNG from common.database.model.models import Comment, Post, User from common.enums import ErrorType from common.liker import Liker +from common.utils.kma_time import kst_midnight, now_kst from crud.feed_crud import FeedCRUD from crud.reaction_crud import ReactionCRUD +from crud.region_crud import RegionCRUD +from services.talk_service import _LINK, _PHONE COMMENT_MAX = 60 +# 로그인 없이 IP 하나가 하루에 쓸 수 있는 댓글 수 +ANON_DAILY_MAX = 20 +ANON_CHARACTER, ANON_COLOR = "rabbit", "orange" PAGE = 20 @@ -33,8 +39,8 @@ class SavedView: class ReactionService: - def __init__(self, crud: ReactionCRUD = Depends(ReactionCRUD), feed: FeedCRUD = Depends(FeedCRUD)) -> None: - self.crud, self.feed = crud, feed + def __init__(self, crud: ReactionCRUD = Depends(ReactionCRUD), feed: FeedCRUD = Depends(FeedCRUD), regions: RegionCRUD = Depends(RegionCRUD)) -> None: + self.crud, self.feed, self.regions = crud, feed, regions async def _post_exists(self, post_id: int) -> ErrorType: err, post = await DB_SESSION_MNG.execute_lambda(lambda s: self.feed.get(s, post_id)) @@ -78,6 +84,13 @@ class ReactionService: err, rows = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.saved_posts(s, user.user_id, cursor, PAGE)) return err, [SavedView(post=p, saved_at=ps.created_at) for p, ps in rows or []] + @staticmethod + def _view(c: Comment, nickname: Optional[str], character: Optional[str], color: Optional[str], mood: Optional[str], liked: bool, who: Liker) -> CommentView: + if c.user_id is None: + mine = who.user_id is None and c.ip_hash == who.ip_hash + return CommentView(comment=c, nickname=f"{c.region_name} 익명" if c.region_name else "익명", character=ANON_CHARACTER, color=ANON_COLOR, mood=None, liked=liked, mine=mine) + return CommentView(comment=c, nickname=nickname or "", character=character or ANON_CHARACTER, color=color or ANON_COLOR, mood=mood, liked=liked, mine=c.user_id == who.user_id) + async def comments(self, post_id: int, user: Optional[User], ip_hash: str, cursor: Optional[int]) -> tuple[ErrorType, list[CommentView]]: err, rows = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.comments(s, post_id, cursor, PAGE)) if err is not ErrorType.SUCCESS: @@ -88,23 +101,41 @@ class ReactionService: _, liked = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.liked_comments(s, user.user_id, ids)) elif rows: _, liked = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.anon_liked_comments(s, ip_hash, ids)) - return ErrorType.SUCCESS, [ - CommentView(comment=c, nickname=n, character=ch, color=co, mood=mo, liked=c.comment_id in (liked or set()), mine=user is not None and c.user_id == user.user_id) - for c, n, ch, co, mo in rows - ] + who = Liker(user_id=user.user_id if user else None, ip_hash=ip_hash) + return ErrorType.SUCCESS, [self._view(c, n, ch, co, mo, c.comment_id in (liked or set()), who) for c, n, ch, co, mo in rows] - async def add_comment(self, post_id: int, user: User, body: str) -> tuple[ErrorType, Optional[CommentView]]: + async def add_comment(self, post_id: int, user: Optional[User], who: Liker, body: str, region_code: Optional[str] = None) -> tuple[ErrorType, Optional[CommentView]]: + """로그인 없이도 쓴다. 그때는 링크·전화번호를 막고 IP 하나에 하루 ANON_DAILY_MAX 개까지, 이름은 쓸 때 동네로 '마포구 익명'.""" body = body.strip() if not body or len(body) > COMMENT_MAX: return ErrorType.INVALID_INPUT, None err = await self._post_exists(post_id) if err is not ErrorType.SUCCESS: return err, None - err, c = await DB_SESSION_MNG.execute_lambda_write(lambda s: self.crud.add_comment(s, post_id, user.user_id, body)) - return err, (CommentView(comment=c, nickname=user.nickname, character=user.character, color=user.color, mood=user.mood, liked=False, mine=True) if c else None) + region_name = None + if user is None: + if _LINK.search(body) or _PHONE.search(body): + return ErrorType.LINK_NOT_ALLOWED, None + today = kst_midnight(now_kst().date()) + err, n = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.anon_comments_since(s, who.ip_hash, today)) + if err is not ErrorType.SUCCESS: + return err, None + if n >= ANON_DAILY_MAX: + return ErrorType.DAILY_LIMIT, None + if region_code: + err, region = await DB_SESSION_MNG.execute_lambda(lambda s: self.regions.get(s, region_code)) + if err is not ErrorType.SUCCESS: + return err, None + region_name = region.short_name if region else None + err, c = await DB_SESSION_MNG.execute_lambda_write(lambda s: self.crud.add_comment(s, post_id, who, body, region_name)) + if c is None: + return err, None + if user is None: + return err, self._view(c, None, None, None, None, False, who) + return err, self._view(c, user.nickname, user.character, user.color, user.mood, False, who) - async def delete_comment(self, comment_id: int, user: User) -> ErrorType: - err, ok = await DB_SESSION_MNG.execute_lambda_write(lambda s: self.crud.delete_comment(s, comment_id, user.user_id)) + async def delete_comment(self, comment_id: int, who: Liker) -> ErrorType: + err, ok = await DB_SESSION_MNG.execute_lambda_write(lambda s: self.crud.delete_comment(s, comment_id, who)) if err is not ErrorType.SUCCESS: return err return ErrorType.SUCCESS if ok else ErrorType.NOT_FOUND diff --git a/backend/services/talk_service.py b/backend/services/talk_service.py index 215e862..fcf15a1 100644 --- a/backend/services/talk_service.py +++ b/backend/services/talk_service.py @@ -20,6 +20,8 @@ DAILY_MAX = 5 # 로그인한 서로 다른 사람의 신고가 이만큼 쌓이면 운영자 확인 전까지 숨긴다 HIDE_AT = 3 PAGE = 20 +# 보는 사람과 같은 시도에서 쓴 글은 이만큼 늦게 쓴 글처럼 앞에 둔다 +LOCAL_BOOST = timedelta(hours=12) # 링크(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) @@ -38,6 +40,22 @@ def weather_line(row: Optional[WeatherHourly]) -> Optional[str]: return f"{round(float(row.temp_c))}° {word}".strip() +def spread_authors(views: list["TalkView"]) -> list["TalkView"]: + """같은 사람 글이 붙으면 뒤에서 다른 사람 글을 당겨 끼운다.""" + out = list(views) + for i in range(1, len(out)): + if out[i].author.user_id == out[i - 1].author.user_id: + j = next((k for k in range(i + 1, len(out)) if out[k].author.user_id != out[i - 1].author.user_id), None) + if j is not None: + out.insert(i, out.pop(j)) + 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 + + @dataclass class TalkView: talk: Talk @@ -51,21 +69,39 @@ 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, cursor: Optional[int]) -> tuple[ErrorType, list[TalkView]]: + async def page(self, user: Optional[User], ip_hash: str, region_code: Optional[str], cursor: Optional[str]) -> 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 - err, rows = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.page(s, viewer, cursor, PAGE)) + 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)) if err is not ErrorType.SUCCESS: - return err, [] - liked: set[int] = set() - if rows: - ids = [t.talk_id for t, *_ in rows] - if user is not None: - err, liked = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.liked(s, user.user_id, ids)) - else: - err, liked = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.anon_liked(s, ip_hash, ids)) - if err is not ErrorType.SUCCESS: - return err, [] - return ErrorType.SUCCESS, [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] + return err, [], None + err, liked = await self._liked(user, ip_hash, [t.talk_id for t, *_ in rows]) + if err is not ErrorType.SUCCESS: + return err, [], None + 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] + last = rows[-1] if len(rows) == PAGE else None + return ErrorType.SUCCESS, spread_authors(views), f"{last[3]}_{last[0].talk_id}" if last else None + + async def mine(self, user: User, cursor: Optional[int]) -> tuple[ErrorType, list[TalkView], Optional[int]]: + err, rows = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.mine(s, user.user_id, cursor, PAGE)) + if err is not ErrorType.SUCCESS: + return err, [], None + err, liked = await self._liked(user, "", [t.talk_id for t, _ in rows]) + if err is not ErrorType.SUCCESS: + return err, [], None + views = [TalkView(talk=t, author=user, region_name=name, liked=t.talk_id in liked, mine=True) for t, name in rows] + return ErrorType.SUCCESS, views, rows[-1][0].talk_id if len(rows) == PAGE else None + + async def _liked(self, user: Optional[User], ip_hash: str, ids: list[int]) -> tuple[ErrorType, set[int]]: + if not ids: + return ErrorType.SUCCESS, set() + if user is not None: + return await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.liked(s, user.user_id, ids)) + return await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.anon_liked(s, ip_hash, ids)) async def _weather_now(self, region_code: str) -> Optional[str]: """지금 시각에 가장 가까운 예보 한 칸. 못 읽으면 날씨 없이 쓴다.""" diff --git a/backend/tests/test_anon_like.py b/backend/tests/test_anon_like.py index e956a54..98072bb 100644 --- a/backend/tests/test_anon_like.py +++ b/backend/tests/test_anon_like.py @@ -85,3 +85,65 @@ async def test_anon_talk_like(): assert next(x for x in talks if x["talk_id"] == talk_id)["liked"] is False assert (await c.delete(url, headers=IP_A)).json()["like_count"] == 2 + + +@pytest.mark.anyio +async def test_anon_comment_shows_region_and_only_same_ip_deletes(offline): + async with client() as c: + post_id = (await c.get("/v1/feed", params={"region": REGION})).json()["posts"][0]["post_id"] + url = f"/v1/reaction/post/{post_id}/comment" + made = (await c.post(url, headers=IP_A, json={"body": " 우산 챙겨요 ", "region": REGION})).json()["comment"] + assert made["body"] == "우산 챙겨요" and made["nickname"] == "마포구 익명" and made["mine"] is True + assert (await c.post(url, headers=IP_A, json={"body": "www.example.com 보세요"})).json()["result"]["desc"] == "LINK_NOT_ALLOWED" + no_region = (await c.post(url, headers=IP_A, json={"body": "안녕"})).json()["comment"] + assert no_region["nickname"] == "익명" + + listed = (await c.get(f"{url}/list", headers=IP_B)).json()["comments"] + assert [(x["nickname"], x["mine"]) for x in listed] == [("마포구 익명", False), ("익명", False)] + assert next(x for x in (await c.get(f"{url}/list", headers=IP_A)).json()["comments"] if x["comment_id"] == made["comment_id"])["mine"] is True + + h = await _login(c, "anon_cmt_01") + delete = f"/v1/reaction/comment/{made['comment_id']}" + assert (await c.delete(delete, headers=IP_B)).json()["result"]["desc"] == "NOT_FOUND" + assert (await c.delete(delete, headers={**h, **IP_A})).json()["result"]["desc"] == "NOT_FOUND" + assert (await c.delete(delete, headers=IP_A)).json()["result"]["success"] is True + feed = (await c.get("/v1/feed", params={"region": REGION})).json() + assert next(x for x in feed["posts"] if x["post_id"] == post_id)["comment_count"] == 1 + + +@pytest.mark.anyio +async def test_anon_comment_daily_limit_per_ip(offline): + async with client() as c: + post_id = (await c.get("/v1/feed", params={"region": REGION})).json()["posts"][0]["post_id"] + url = f"/v1/reaction/post/{post_id}/comment" + ip = {"X-Forwarded-For": "203.0.113.40"} + for i in range(20): + assert (await c.post(url, headers=ip, json={"body": f"댓글{i}"})).json()["result"]["success"] is True + assert (await c.post(url, headers=ip, json={"body": "하나 더"})).json()["result"]["desc"] == "DAILY_LIMIT" + assert (await c.post(url, headers=IP_B, json={"body": "다른 사람"})).json()["result"]["success"] is True + h = await _login(c, "anon_cmt_02") + assert (await c.post(url, headers={**h, **ip}, json={"body": "로그인하면 따로"})).json()["result"]["success"] is True + + +@pytest.mark.anyio +async def test_hero_and_today_gak_take_likes_and_comments(offline): + async with client() as c: + feed = (await c.get("/v1/feed", params={"region": REGION})).json() + hero, gak = feed["hero_post"]["post_id"], feed["gak_post"]["post_id"] + assert hero != gak and {hero, gak}.isdisjoint(p["post_id"] for p in feed["posts"]) + assert (await c.post(f"/v1/reaction/post/{hero}/like", headers=IP_A)).json()["like_count"] == 1 + assert (await c.post(f"/v1/reaction/post/{gak}/comment", headers=IP_A, json={"body": "좋다"})).json()["result"]["success"] is True + + mine = (await c.get("/v1/feed", params={"region": REGION}, headers=IP_A)).json() + assert mine["hero_post"] == {"post_id": hero, "like_count": 1, "comment_count": 0, "liked": True} + assert mine["gak_post"] == {"post_id": gak, "like_count": 0, "comment_count": 1, "liked": False} + assert (await c.get("/v1/feed", params={"region": REGION}, headers=IP_B)).json()["hero_post"]["liked"] is False + + +@pytest.mark.anyio +async def test_hero_tomorrow_and_tomorrow_slots(offline): + async with client() as c: + hero = (await c.get("/v1/feed", params={"region": REGION})).json()["hero"] + assert set(hero["tomorrow"]["weather_slots"]) <= {"morning", "day", "evening", "night"} + res = (await c.get("/v1/weather/today", params={"region": REGION, "day": "tomorrow"})).json() + assert res["day"] == hero["tomorrow"]["day"] diff --git a/backend/tests/test_auth_reaction.py b/backend/tests/test_auth_reaction.py index 4d4b749..50ba209 100644 --- a/backend/tests/test_auth_reaction.py +++ b/backend/tests/test_auth_reaction.py @@ -50,11 +50,12 @@ async def test_signup_rejects_bad_input(): @pytest.mark.anyio -async def test_comment_requires_login_and_reactions_update_feed(offline): +async def test_comment_without_login_is_anonymous_and_reactions_update_feed(offline): async with client() as c: feed = (await c.get("/v1/feed", params={"region": REGION})).json() post_id = feed["posts"][0]["post_id"] - assert (await c.post(f"/v1/reaction/post/{post_id}/comment", json={"body": "안녕"})).status_code == 401 + anon = (await c.post(f"/v1/reaction/post/{feed['posts'][1]['post_id']}/comment", json={"body": "안녕"})).json() + assert anon["result"]["success"] is True and anon["comment"]["nickname"] == "익명" token = (await _signup(c))["access_token"] h = {"Authorization": f"Bearer {token}"} diff --git a/backend/tests/test_index_api.py b/backend/tests/test_index_api.py index 686ef44..c7f9af0 100644 --- a/backend/tests/test_index_api.py +++ b/backend/tests/test_index_api.py @@ -145,7 +145,7 @@ async def test_board_puts_out_of_season_gak_last_without_rank_or_badge(monkeypat scores = [SimpleNamespace(index_id=x, score_date=today, score=v, slots={}) for x, v in ((1, 50), (2, 60), (3, 99))] crud = SimpleNamespace(definitions=lambda s: _async(defs), scores=lambda s, *a: _async(scores)) service = IndexService(RegionCRUD(), crud, None, None, None, None, None, None) - monkeypatch.setattr(service, "ensure", lambda *a: _async((ErrorType.SUCCESS, _WEATHER_50))) + monkeypatch.setattr(service, "ensure", lambda *a: _async((ErrorType.SUCCESS, {now_kst().date(): _WEATHER_50}))) _, board = await service.board(REGION) view = [(i.definition.code, i.active, i.in_season, i.season) for i in board.items] # 점수가 가장 높아도 제철이 아니면 순위 밖 맨 끝. 계절 표시는 제철 달이 정해진 각에만 @@ -165,7 +165,7 @@ async def test_board_ranks_by_score_times_priority_weight(monkeypatch): scores = [SimpleNamespace(index_id=x, score_date=today, score=v, slots={}) 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, _WEATHER_50))) + 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). 보이는 점수는 그대로 @@ -182,7 +182,7 @@ async def test_board_ranks_each_slot_with_priority_weight(monkeypatch): 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) - monkeypatch.setattr(service, "ensure", lambda *a: _async((ErrorType.SUCCESS, {k: _RESULT_50 for k in every}))) + monkeypatch.setattr(service, "ensure", lambda *a: _async((ErrorType.SUCCESS, {now_kst().date(): {k: _RESULT_50 for k in every}}))) 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} diff --git a/backend/tests/test_my_gak.py b/backend/tests/test_my_gak.py index b57368f..0d5558b 100644 --- a/backend/tests/test_my_gak.py +++ b/backend/tests/test_my_gak.py @@ -1,12 +1,16 @@ +import json +import os from datetime import date +from types import SimpleNamespace import pytest from httpx import ASGITransport, AsyncClient from common.enums import RainType, Sky from router.router import app +from router.v1.my_gak.protocol import MyGakRule from services.calc.index_calc import Context, Hour, evaluate -from services.calc.my_gak_calc import MyRule, axes, definition +from services.calc.my_gak_calc import MyRule, axes, definition, preset from services.my_gak_service import MAX_PER_USER, gak_name RULE = {"temp": [15, 25], "rain": "dry", "slots": ["evening", "night"]} @@ -84,3 +88,32 @@ async def test_rejects_bad_rules(): assert (await bad({"temp": [25, 15]})).status_code == 422 assert (await bad({"temp": [15, 25], "slots": []})).status_code == 422 assert (await bad({"humidity": [10, 120]})).status_code == 422 + + +def _defn(rules: dict, windows: list[dict], **weights) -> SimpleNamespace: + w = {"temp": 30, "rain": 30, "wind": 0, "humidity": 0, "air": 0} | weights + return SimpleNamespace(factor_rules=rules, windows=windows, **{f"weight_{k}": v for k, v in w.items()}) + + +def test_preset_copies_rules_that_fit_and_drops_the_rest(): + base = {"rain": {"dir": "dry"}, "wind": {"type": "calm", "ok": 3, "limit": 10}, "humidity": {"type": "range", "lo": 30, "hi": 60}} + p = preset(_defn(base | {"temp": {"type": "range", "lo": 18, "hi": 24}}, [{"from": 18, "to": 24}], wind=15, humidity=10, air=10)) + assert p == {"slots": ["evening", "night"], "temp": [18, 24], "rain": "dry", "wind_max": 3, "air": "normal", "humidity": [30, 60]} + # 더울수록·추울수록은 만점 기온부터 끝까지, 산 정상 보정은 되돌린다 + assert preset(_defn(base | {"temp": {"type": "higher", "zero": 16, "full": 27}}, [{"from": 9, "to": 11}]))["temp"] == [27, 40] + assert preset(_defn(base | {"temp": {"type": "lower", "zero": 10, "full": -5}}, [{"from": 9, "to": 11}]))["temp"] == [-20, -5] + assert preset(_defn(base | {"temp": {"type": "range", "lo": 10, "hi": 20, "offset": -4}}, [{"from": 9, "to": 11}]))["temp"] == [14, 24] + # 범위에서 멀수록 좋은 기온, 탁할수록 좋은 미세먼지, 비중 0인 바람은 옮기지 않는다 + p = preset(_defn(base | {"temp": {"type": "away", "lo": 15, "hi": 24}, "air": {"zero": 15, "full": 75}}, [{"around": "sunset", "hours": 1}], air=20)) + assert p == {"slots": ["evening"], "rain": "dry"} + + +@pytest.mark.anyio +async def test_presets_cover_every_gak_with_valid_rules(): + async with client() as c: + body = (await c.get("/v1/my-gak/presets")).json() + with open(os.path.join(os.path.dirname(os.path.dirname(__file__)), "seed", "index_definition.json"), encoding="utf-8") as f: + seed = json.load(f) + assert [x["code"] for x in body["items"]] == [x["code"] for x in sorted(seed, key=lambda x: x["sort_order"])] + for x in body["items"]: + MyGakRule(**x["rule"]) diff --git a/backend/tests/test_talk.py b/backend/tests/test_talk.py index 0f0e50e..fd52b8b 100644 --- a/backend/tests/test_talk.py +++ b/backend/tests/test_talk.py @@ -1,10 +1,13 @@ +from types import SimpleNamespace + import pytest from httpx import ASGITransport, AsyncClient from router.router import app -from services.talk_service import DAILY_MAX, HIDE_AT, weather_line +from services.talk_service import DAILY_MAX, HIDE_AT, parse_cursor, spread_authors, weather_line REGION = "1144000000" +BUSAN = "2611000000" def client(): @@ -16,8 +19,8 @@ async def _login(c, login_id: str) -> dict: return {"Authorization": f"Bearer {body['access_token']}"} -async def _write(c, h, body="망원동 하늘 진짜 맑아요"): - return (await c.post("/v1/talk", json={"region_code": REGION, "body": body}, headers=h)).json() +async def _write(c, h, body="망원동 하늘 진짜 맑아요", region=REGION): + return (await c.post("/v1/talk", json={"region_code": region, "body": body}, headers=h)).json() @pytest.mark.anyio @@ -87,3 +90,56 @@ def test_weather_line(): assert weather_line(Row()) == "18° 맑음" assert weather_line(Wet()) == "12° 비" assert weather_line(None) is None + + +def _ids(body: dict) -> list[int]: + return [x["talk_id"] for x in body["talks"]] + + +@pytest.mark.anyio +async def test_same_sido_talks_come_first_for_that_viewer(): + async with client() as c: + busan = (await _write(c, await _login(c, "talk_bs1"), "광안리 바람 시원해요", BUSAN))["talk"]["talk_id"] + seoul = (await _write(c, await _login(c, "talk_se1"), "망원동 비 그쳤어요"))["talk"]["talk_id"] + nation = _ids((await c.get("/v1/talk/list")).json()) + local = _ids((await c.get("/v1/talk/list", params={"region": BUSAN})).json()) + assert nation.index(seoul) < nation.index(busan) + assert local.index(busan) < local.index(seoul) + + +@pytest.mark.anyio +async def test_pages_follow_cursor_without_repeats(): + async with client() as c: + mine = [] + for i in range(5): + h = await _login(c, f"talk_pg{i}") + for j in range(DAILY_MAX): + mine.append((await _write(c, h, f"페이지 글 {i}-{j}", BUSAN if j % 2 else REGION))["talk"]["talk_id"]) + seen, cursor = [], None + while True: + body = (await c.get("/v1/talk/list", params={"region": BUSAN} | ({"cursor": cursor} if cursor else {}))).json() + seen += _ids(body) + cursor = body.get("next_cursor") + if not cursor: + break + assert (await c.get("/v1/talk/list", params={"cursor": "abc"})).json()["result"]["desc"] == "INVALID_INPUT" + assert len(seen) == len(set(seen)) and set(mine) <= set(seen) + + +@pytest.mark.anyio +async def test_mine_lists_only_my_talks_newest_first(): + async with client() as c: + assert (await c.get("/v1/talk/mine")).status_code == 401 + h = await _login(c, "talk_mine") + ids = [(await _write(c, h, f"내 글 {i}"))["talk"]["talk_id"] for i in range(3)] + await _write(c, await _login(c, "talk_notmine"), "남의 글") + await c.delete(f"/v1/talk/{ids[0]}", headers=h) + body = (await c.get("/v1/talk/mine", headers=h)).json() + assert _ids(body) == [ids[2], ids[1]] and all(x["mine"] for x in body["talks"]) + + +def test_spread_authors_and_cursor(): + v = lambda who: SimpleNamespace(author=SimpleNamespace(user_id=who)) # noqa: E731 + 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 diff --git a/docs/meetings/2026-10-21.md b/docs/meetings/2026-10-21.md new file mode 100644 index 0000000..c0133eb --- /dev/null +++ b/docs/meetings/2026-10-21.md @@ -0,0 +1,68 @@ +# 2026-10-21(수) 회의 — 날씨각 + +주제: '내일 날씨' 검색 공략, 공유·로그인 정리, 앱·위젯 확장 준비 +참석: 대표, 황 본부장, 최미나 + +## 금일 핵심 업무 (최미나) +1. 공유 링크·좋아요·댓글·로그인 수정분 배포 +2. '내일 날씨' 카드 추가 및 태깅 테스트 + +## 진행 관리 +- 미완료 항목을 포함해 진행 상황을 매일 대표에게 보고 (결정) +- 전일 회의 내용은 병렬로 반영 중이고, 일부는 로컬에만 반영된 상태 + +## 설치·토스 미니앱 +- 토스 미니앱은 라이브 상태이고 홈 화면 바로가기를 추가할 수 있음 +- 토스 밖 웹에서도 홈 화면 바로가기를 쉽게 추가하게 (방향) — 이미 반영됨(`e5716c0`, `dff03f6`) +- 미니앱은 웹 업데이트가 자동 반영되지 않음. 웹이 바뀔 때마다 다시 올려야 하고, 지금 토스 바로가기는 이전 버전 + +## 공유·좋아요·로그인 +- 공유하면 이미지는 가지만 링크가 빠짐 → 공유에 링크를 반드시 포함 (결정). 지금은 이미지와 함께 링크를 공유 text에 실어 보냄(`frontend/src/b/Sheets.tsx:564`) +- 히어로는 포스트 형태로 바꾸지 않고 지금 형태를 유지하며, 공유·좋아요를 추가 (결정) +- 오늘의 각부터 모든 카드에 좋아요·댓글·공유 (결정) +- 로그인은 포스팅할 때만 요청하고, 댓글을 쓸 때는 띄우지 않음 (결정) — 10/20 '확인 필요'였던 댓글 로그인 여부가 이로써 정해짐 +- 웹 로그인은 구글로 통일하고 일반 로그인은 제거 (결정) — 구글 로그인은 있음(`4e9b0ba`), 아이디·비밀번호 로그인·가입은 남아 있음(`backend/router/v1/auth/account.py:25`, `:31`) +- 의견(황 본부장): 공유 이미지는 각마다 달라도 링크는 날씨각 고정 URL 하나로 하면 개발이 쉬움 +- 의견(황 본부장): 통이미지 공유는 몇 번 하다 그만둠. 캐시워크처럼 사용자 사진 위에 날씨각 정보 레이어를 얹어 '내 콘텐츠'로 공유하게 해야 함 → 앱 기능으로 넣는 방향(대표), 구현 아이디어 검토 +- 모바일에서 창이 닫히지 않는 오류 → 수정 예정 + +## 검색 노출 +- 구별 페이지로 '분당구 오늘 날씨' 구글 2위 확인. 넣을 수 있는 지역은 모두 추가 (결정) +- 구글 트렌드상 '내일 날씨'가 '오늘 날씨'보다 검색량이 압도적으로 많음 +- 메인 타임라인(나의 각 아래)에 '내일 날씨' 카드를 넣고 '○○구 내일 날씨'로 검색 등록되게 태깅. 별도 페이지는 만들지 않음 (결정). 결정 사항 요약에는 '히어로에 추가'로 적혀 있어 위치는 확인 필요 +- 구글에 등록되려면 페이지에 실제 내일 기온·습도가 있어야 함 +- 스테이머뭄은 중복 사이트를 내리고 하나만 남겨 다시 상위 노출됨 +- 김성경 FAQ 반영 완료 + +## 홍보·제휴 +- 유튜브 숏폼 자동화: 수석이 방향을 제시함. 10/22 김성경과 협의 후 진행 +- 인스타 운영 자동화 관리자 페이지 제작 중. 자동 게시 전 담당자에게 승인 메일을 보내고, 승인·수정 후 게시 +- 날씨 타로는 날마다 주제를 바꿈(회사 생활 등). 코디는 20·30·40대 이상 연령대별로 색 등을 바꿔 자동 게시 +- 인스타 초기 피드는 이야기형('각이 100개 있어요', 빨래각·소맥각 소개, 날씨 점수 산정법)으로 하고 이후 자동화 피드로 전환 (방향) +- 캐시워크 미팅(10/21 17시, 황 본부장): 날씨각 URL 전달. 1단계 제휴 목적은 날씨각을 위젯으로 플랫폼에 넣고 '더 보기'로 유입시키는 것 + +## 위젯·앱 +- 의견(대표): 위젯은 그 자체로 정보를 줌. 통신사(KT 등)가 날씨각 위젯을 기본 탑재하면 포털처럼 쓸 수 있음 +- 위젯을 제공하려면 앱이 필요함. 기존 날씨 위젯과는 각 콘텐츠로 차별화 +- 안드로이드 앱은 계속 준비하고 iOS도 함께 출시 추진 (결정) +- iOS 개발자 계정은 이전 담당자 개인 계정으로 보이고 비밀번호를 모름 → 소장에게 확인 요청, 어려우면 회사 계정으로 새로 만듦 +- 의견(대표·황 본부장): 필사·하루 한 구절 같은 루틴형 위젯도 수요가 있음 + +## 앱인토스 정산 계좌 +- 토스에 계좌 오류 화면을 보내 문의했고 답변 대기 중. 개인이 아니라 법인(주식회사 AI O2O) 계좌로 등록해야 함 +- 조수현 부장이 법인 통장 사본을 대표에게 전달 → 대표가 등록 → 토스 로그인 연동 가입 (결정) + +## 담당·기한 +| 할 일 | 담당 | 기한 | 보고 | +|---|---|---|---| +| 공유 링크 포함, 전 카드 좋아요·댓글·공유, 로그인 수정, 모바일 창 닫힘 오류 수정 후 배포 | 최미나 | 미정 | 대표 데일리 보고 | +| '내일 날씨' 카드 추가, 지역별 태깅 테스트 | 최미나 | 미정 | 대표 데일리 보고 | +| 전 지역 날씨 페이지 추가 | 최미나 | 미정 | 대표 데일리 보고 | +| 단풍 지도 UI 수정 | 최미나 | 미정 | 대표 공유 | +| 토스 미니앱 최신 버전 재등록 | 최미나 | 미정 | 황 본부장 공유 | +| 유튜브 숏폼 자동화 진행 방안 협의 | 김성경·최미나 | 10/22 | 대표 보고 | +| 인스타 운영 관리자 페이지, 초기 피드 | 최미나 | 미정 | 대표 보고 | +| 레이어 공유 방식 아이디어 | 최미나 | 미정 | 황 본부장 공유 | +| iOS 개발자 계정 확인(소장) 또는 회사 계정 새로 만들기 | 최미나 | 미정 | 대표 보고 | +| 법인 통장 사본 전달, 앱인토스 계좌 등록, 토스 로그인 가입 | 조수현(사본)·대표(등록)·최미나(가입) | 10/21 | 대표 확인 | +| 캐시워크 미팅 | 황 본부장 | 10/21 17:00 | 대표 공유 | diff --git a/frontend/public/foliage/korea-map.webp b/frontend/public/foliage/korea-map.webp index f6a44f8..29b85db 100644 Binary files a/frontend/public/foliage/korea-map.webp and b/frontend/public/foliage/korea-map.webp differ diff --git a/frontend/public/icons/ginkgo.png b/frontend/public/icons/ginkgo.png new file mode 100644 index 0000000..2aed517 Binary files /dev/null and b/frontend/public/icons/ginkgo.png differ diff --git a/frontend/seo/foliage_2026.json b/frontend/seo/foliage_2026.json index 4560dcb..795fa35 100644 --- a/frontend/seo/foliage_2026.json +++ b/frontend/seo/foliage_2026.json @@ -1,218 +1,661 @@ { - "source": "산림청·국립수목원·국립산림과학원 「2026년 한반도 단풍절정 예측지도」(2026.9.22 보도자료, 단풍나무류 지도)", + "source": "산림청·국립수목원·국립산림과학원 「2026년 한반도 단풍절정 예측지도」(2026.9.22 보도자료, 단풍나무류·은행나무 지도)", "source_url": "https://www.korea.kr/briefing/pressReleaseView.do?newsId=156782827", "map_image_url": "https://www.korea.kr/common/download.do?fileId=198558074&tblKey=GMN", - "basis": "단풍나무류 잎의 50% 이상이 물든 때(지도 기준: 단풍나무류 단풍 50% 이상). 산별 시작일은 발표에 없어 start는 null", + "basis": "절정: 그 수종 잎의 50% 이상이 물든 때. 첫 단풍: 발표에 시작일이 없어 절정 14일 전부터로 추정. 예측 지점이 아닌 명소는 basis에 적은 가장 가까운 예측 지점 날짜를 씀", "license": "공공누리 제1유형(출처표시) — 정책브리핑 게재본은 '텍스트에 한하여' 1유형, 사진·이미지는 저작권자 허락 필요(지도 이미지 자체 재사용은 확인 필요)", - "coord_source": "한국관광공사 TourAPI(KorService2 searchKeyword2) 관광지 좌표 mapy/mapx; 산마다 쓴 지점명은 coord_point(정상이 아닌 국립공원·탐방 지점일 수 있음)", + "coord_source": "한국관광공사 TourAPI(KorService2 searchKeyword2) 좌표; 소리봉(포천)은 광릉숲길 좌표로 근사(가까운 지점 계산용, 지도엔 안 나옴)", "updated": "2026-10-21", - "mountains": [ + "spots": [ { "name": "설악산", + "kind": "maple", "region": "강원 속초·양양·인제", "lat": 38.119, "lon": 128.465, - "start": null, "peak": "2026-10-20", + "basis": "산림청 예측(단풍나무류)", "coord_point": "설악산 대청봉" }, { "name": "점봉산", + "kind": "maple", "region": "강원 인제·양양", "lat": 38.036, "lon": 128.471, - "start": null, "peak": "2026-10-21", + "basis": "산림청 예측(단풍나무류)", "coord_point": "점봉산 곰배령" }, { "name": "광덕산", + "kind": "maple", "region": "강원 화천·경기 포천", "lat": 38.115, "lon": 127.439, - "start": null, "peak": "2026-10-22", + "basis": "산림청 예측(단풍나무류)", "coord_point": "광덕산(화천)" }, { "name": "화악산", + "kind": "maple", "region": "강원 화천·경기 가평", "lat": 38.048, "lon": 127.522, - "start": null, "peak": "2026-10-20", + "basis": "산림청 예측(단풍나무류)", "coord_point": "화악산" }, { "name": "축령산", + "kind": "maple", "region": "경기 남양주·가평", "lat": 37.753, "lon": 127.309, - "start": null, "peak": "2026-10-26", + "basis": "산림청 예측(단풍나무류)", "coord_point": "축령산" }, { "name": "용문산", + "kind": "maple", "region": "경기 양평", "lat": 37.551, "lon": 127.569, - "start": null, "peak": "2026-10-23", + "basis": "산림청 예측(단풍나무류)", "coord_point": "용문산" }, { "name": "수리산", + "kind": "maple", "region": "경기 군포·안양·안산", "lat": 37.348, "lon": 126.901, - "start": null, "peak": "2026-11-02", + "basis": "산림청 예측(단풍나무류)", "coord_point": "수리산도립공원" }, { "name": "가야산(충남)", + "kind": "maple", "region": "충남 서산·예산", "lat": 36.704, "lon": 126.609, - "start": null, "peak": "2026-10-31", + "basis": "산림청 예측(단풍나무류)", "coord_point": "가야산(서산)" }, { "name": "소백산", + "kind": "maple", "region": "충북 단양·경북 영주", "lat": 36.935, "lon": 128.457, - "start": null, "peak": "2026-10-20", + "basis": "산림청 예측(단풍나무류)", "coord_point": "소백산 천문대" }, { "name": "속리산", + "kind": "maple", "region": "충북 보은·경북 상주", "lat": 36.517, "lon": 127.817, - "start": null, "peak": "2026-10-28", + "basis": "산림청 예측(단풍나무류)", "coord_point": "속리산국립공원(충북)" }, { "name": "계룡산", + "kind": "maple", "region": "충남 공주·계룡, 대전", "lat": 36.357, "lon": 127.232, - "start": null, "peak": "2026-11-01", + "basis": "산림청 예측(단풍나무류)", "coord_point": "계룡산국립공원" }, { "name": "주왕산", + "kind": "maple", "region": "경북 청송", "lat": 36.394, "lon": 129.142, - "start": null, "peak": "2026-10-26", + "basis": "산림청 예측(단풍나무류)", "coord_point": "주왕산국립공원" }, { "name": "팔공산", + "kind": "maple", "region": "대구·경북", "lat": 35.99, "lon": 128.696, - "start": null, "peak": "2026-10-30", + "basis": "산림청 예측(단풍나무류)", "coord_point": "팔공산국립공원(동화사지구)" }, { "name": "가야산(경북)", + "kind": "maple", "region": "경북 성주·경남 합천", "lat": 35.8, "lon": 128.142, - "start": null, "peak": "2026-10-28", + "basis": "산림청 예측(단풍나무류)", "coord_point": "가야산국립공원(백운동 지구)" }, { "name": "금원산", + "kind": "maple", "region": "경남 거창", "lat": 35.731, "lon": 127.761, - "start": null, "peak": "2026-10-25", + "basis": "산림청 예측(단풍나무류)", "coord_point": "금원산" }, { "name": "지리산", + "kind": "maple", "region": "경남·전남·전북", "lat": 35.304, "lon": 127.749, - "start": null, "peak": "2026-10-27", + "basis": "산림청 예측(단풍나무류)", "coord_point": "지리산 천왕봉" }, { "name": "변산반도", + "kind": "maple", "region": "전북 부안", "lat": 35.642, "lon": 126.58, - "start": null, "peak": "2026-11-04", + "basis": "산림청 예측(단풍나무류)", "coord_point": "변산반도국립공원" }, { "name": "내장산", + "kind": "maple", "region": "전북 정읍·전남 장성", "lat": 35.471, "lon": 126.867, - "start": null, "peak": "2026-11-04", + "basis": "산림청 예측(단풍나무류)", "coord_point": "내장산국립공원" }, { "name": "월출산", + "kind": "maple", "region": "전남 영암·강진", "lat": 34.775, "lon": 126.722, - "start": null, "peak": "2026-11-09", + "basis": "산림청 예측(단풍나무류)", "coord_point": "월출산국립공원" }, { "name": "두륜산", + "kind": "maple", "region": "전남 해남", "lat": 34.49, "lon": 126.616, - "start": null, "peak": "2026-11-11", + "basis": "산림청 예측(단풍나무류)", "coord_point": "두륜산도립공원" }, { "name": "상왕봉", + "kind": "maple", "region": "전남 완도", "lat": 34.348, "lon": 126.693, - "start": null, "peak": "2026-11-11", + "basis": "산림청 예측(단풍나무류)", "coord_point": "상왕산" }, { "name": "교래곶자왈", + "kind": "maple", "region": "제주 제주시 조천", "lat": 33.442, "lon": 126.667, - "start": null, "peak": "2026-11-02", + "basis": "산림청 예측(단풍나무류)", "coord_point": "제주 교래자연휴양림" }, { "name": "한라산(1100도로)", + "kind": "maple", "region": "제주", "lat": 33.358, "lon": 126.463, - "start": null, "peak": "2026-11-06", + "basis": "산림청 예측(단풍나무류)", "coord_point": "1100고지습지" + }, + { + "name": "국립수목원", + "kind": "ginkgo", + "region": "경기 포천", + "lat": 37.75954, + "lon": 127.16892, + "peak": "2026-10-31", + "basis": "산림청 예측(은행나무)", + "coord_point": "국립수목원" + }, + { + "name": "물향기수목원", + "kind": "ginkgo", + "region": "경기 오산", + "lat": 37.16737, + "lon": 127.0622, + "peak": "2026-11-06", + "basis": "산림청 예측(은행나무)", + "coord_point": "물향기수목원" + }, + { + "name": "강원도립화목원", + "kind": "ginkgo", + "region": "강원 춘천", + "lat": 37.92264, + "lon": 127.72516, + "peak": "2026-10-27", + "basis": "산림청 예측(은행나무)", + "coord_point": "강원도립화목원" + }, + { + "name": "미동산수목원", + "kind": "ginkgo", + "region": "충북 청주", + "lat": 36.62743, + "lon": 127.66884, + "peak": "2026-10-29", + "basis": "산림청 예측(은행나무)", + "coord_point": "미동산수목원" + }, + { + "name": "금강수목원", + "kind": "ginkgo", + "region": "세종", + "lat": 36.4377, + "lon": 127.23274, + "peak": "2026-11-04", + "basis": "산림청 예측(은행나무)", + "coord_point": "금강수목원" + }, + { + "name": "대구수목원", + "kind": "ginkgo", + "region": "대구 달서", + "lat": 35.80265, + "lon": 128.52063, + "peak": "2026-11-04", + "basis": "산림청 예측(은행나무)", + "coord_point": "대구수목원" + }, + { + "name": "대아수목원", + "kind": "ginkgo", + "region": "전북 완주", + "lat": 35.97624, + "lon": 127.30039, + "peak": "2026-11-02", + "basis": "산림청 예측(은행나무)", + "coord_point": "대아수목원" + }, + { + "name": "경남수목원", + "kind": "ginkgo", + "region": "경남 진주", + "lat": 35.1572, + "lon": 128.29574, + "peak": "2026-11-05", + "basis": "산림청 예측(은행나무)", + "coord_point": "경남수목원" + }, + { + "name": "완도수목원", + "kind": "ginkgo", + "region": "전남 완도", + "lat": 34.36065, + "lon": 126.66353, + "peak": "2026-11-12", + "basis": "산림청 예측(은행나무)", + "coord_point": "완도수목원" + }, + { + "name": "한라수목원", + "kind": "ginkgo", + "region": "제주 제주", + "lat": 33.46959, + "lon": 126.49324, + "peak": "2026-11-16", + "basis": "산림청 예측(은행나무)", + "coord_point": "한라수목원" + }, + { + "name": "북한산", + "kind": "maple", + "region": "서울 강북", + "lat": 37.65831, + "lon": 126.99095, + "peak": "2026-10-26", + "basis": "가장 가까운 산림청 예측 지점(축령산, 단풍나무류) 날짜", + "coord_point": "북한산 백운대(우이동)" + }, + { + "name": "도봉산", + "kind": "maple", + "region": "서울 도봉", + "lat": 37.69945, + "lon": 127.01578, + "peak": "2026-10-26", + "basis": "가장 가까운 산림청 예측 지점(축령산, 단풍나무류) 날짜", + "coord_point": "도봉산" + }, + { + "name": "남산공원", + "kind": "maple", + "region": "서울 중구", + "lat": 37.55563, + "lon": 126.99222, + "peak": "2026-11-02", + "basis": "가장 가까운 산림청 예측 지점(수리산, 단풍나무류) 날짜", + "coord_point": "남산공원(서울)" + }, + { + "name": "창덕궁", + "kind": "maple", + "region": "서울 종로", + "lat": 37.5777, + "lon": 126.99024, + "peak": "2026-11-02", + "basis": "가장 가까운 산림청 예측 지점(수리산, 단풍나무류) 날짜", + "coord_point": "창덕궁 낙선재" + }, + { + "name": "화담숲", + "kind": "maple", + "region": "경기 광주", + "lat": 37.34076, + "lon": 127.28942, + "peak": "2026-10-23", + "basis": "가장 가까운 산림청 예측 지점(용문산, 단풍나무류) 날짜", + "coord_point": "화담숲" + }, + { + "name": "오대산", + "kind": "maple", + "region": "강원 평창", + "lat": 37.78652, + "lon": 128.56441, + "peak": "2026-10-21", + "basis": "가장 가까운 산림청 예측 지점(점봉산, 단풍나무류) 날짜", + "coord_point": "상원사(오대산)" + }, + { + "name": "치악산", + "kind": "maple", + "region": "강원 원주", + "lat": 37.408, + "lon": 128.0455, + "peak": "2026-10-23", + "basis": "가장 가까운 산림청 예측 지점(용문산, 단풍나무류) 날짜", + "coord_point": "치악산 구룡자동차야영장" + }, + { + "name": "덕유산", + "kind": "maple", + "region": "전북 무주", + "lat": 35.89192, + "lon": 127.74295, + "peak": "2026-10-25", + "basis": "가장 가까운 산림청 예측 지점(금원산, 단풍나무류) 날짜", + "coord_point": "덕유산 향적봉" + }, + { + "name": "대둔산", + "kind": "maple", + "region": "충남 논산·전북 완주", + "lat": 36.14381, + "lon": 127.30481, + "peak": "2026-11-01", + "basis": "가장 가까운 산림청 예측 지점(계룡산, 단풍나무류) 날짜", + "coord_point": "대둔산 도립공원 수락캠핑장" + }, + { + "name": "마이산", + "kind": "maple", + "region": "전북 진안", + "lat": 35.75846, + "lon": 127.41119, + "peak": "2026-10-25", + "basis": "가장 가까운 산림청 예측 지점(금원산, 단풍나무류) 날짜", + "coord_point": "마이산 탑사" + }, + { + "name": "강천산", + "kind": "maple", + "region": "전북 순창", + "lat": 35.40879, + "lon": 127.0675, + "peak": "2026-11-04", + "basis": "가장 가까운 산림청 예측 지점(내장산, 단풍나무류) 날짜", + "coord_point": "강천산 군립공원" + }, + { + "name": "선운산", + "kind": "maple", + "region": "전북 고창", + "lat": 35.49769, + "lon": 126.57953, + "peak": "2026-11-04", + "basis": "가장 가까운 산림청 예측 지점(변산반도, 단풍나무류) 날짜", + "coord_point": "도솔계곡(선운산)" + }, + { + "name": "백양사", + "kind": "maple", + "region": "전남 장성", + "lat": 35.43966, + "lon": 126.88372, + "peak": "2026-11-04", + "basis": "가장 가까운 산림청 예측 지점(내장산, 단풍나무류) 날짜", + "coord_point": "백양사" + }, + { + "name": "무등산", + "kind": "maple", + "region": "광주 동구", + "lat": 35.13148, + "lon": 126.981, + "peak": "2026-11-04", + "basis": "가장 가까운 산림청 예측 지점(내장산, 단풍나무류) 날짜", + "coord_point": "덕산너덜(무등산)" + }, + { + "name": "청량산", + "kind": "maple", + "region": "경북 봉화", + "lat": 36.78866, + "lon": 128.89501, + "peak": "2026-10-20", + "basis": "가장 가까운 산림청 예측 지점(소백산, 단풍나무류) 날짜", + "coord_point": "청량산도립공원" + }, + { + "name": "가지산", + "kind": "maple", + "region": "경남 밀양·울산 울주", + "lat": 35.58033, + "lon": 128.98046, + "peak": "2026-10-30", + "basis": "가장 가까운 산림청 예측 지점(팔공산, 단풍나무류) 날짜", + "coord_point": "가지산도립공원(밀양)" + }, + { + "name": "반계리 은행나무", + "kind": "ginkgo", + "region": "강원 원주", + "lat": 37.29388, + "lon": 127.78795, + "peak": "2026-10-29", + "basis": "가장 가까운 산림청 예측 지점(용문산, 은행나무) 날짜", + "coord_point": "반계리 은행나무" + }, + { + "name": "남이섬", + "kind": "ginkgo", + "region": "강원 춘천", + "lat": 37.79627, + "lon": 127.52549, + "peak": "2026-10-25", + "basis": "가장 가까운 산림청 예측 지점(축령산, 은행나무) 날짜", + "coord_point": "남이섬" + }, + { + "name": "서울숲", + "kind": "ginkgo", + "region": "서울 성동", + "lat": 37.54307, + "lon": 127.0418, + "peak": "2026-11-04", + "basis": "가장 가까운 산림청 예측 지점(수리산, 은행나무) 날짜", + "coord_point": "서울숲" + }, + { + "name": "덕수궁 돌담길", + "kind": "ginkgo", + "region": "서울 중구", + "lat": 37.56608, + "lon": 126.97489, + "peak": "2026-11-04", + "basis": "가장 가까운 산림청 예측 지점(수리산, 은행나무) 날짜", + "coord_point": "덕수궁 돌담길" + }, + { + "name": "성균관 명륜당", + "kind": "ginkgo", + "region": "서울 종로", + "lat": 37.5861, + "lon": 126.9957, + "peak": "2026-10-31", + "basis": "가장 가까운 산림청 예측 지점(국립수목원, 은행나무) 날짜", + "coord_point": "성균관 명륜당" + }, + { + "name": "용문사 은행나무", + "kind": "ginkgo", + "region": "경기 양평", + "lat": 37.55022, + "lon": 127.57169, + "peak": "2026-10-29", + "basis": "가장 가까운 산림청 예측 지점(용문산, 은행나무) 날짜", + "coord_point": "용문사 은행나무" + }, + { + "name": "곡교천 은행나무길", + "kind": "ginkgo", + "region": "충남 아산", + "lat": 36.79955, + "lon": 127.01683, + "peak": "2026-10-26", + "basis": "가장 가까운 산림청 예측 지점(가야산(충남), 은행나무) 날짜", + "coord_point": "곡교천 은행나무길" + }, + { + "name": "현충사", + "kind": "ginkgo", + "region": "충남 아산", + "lat": 36.80655, + "lon": 127.0312, + "peak": "2026-10-26", + "basis": "가장 가까운 산림청 예측 지점(가야산(충남), 은행나무) 날짜", + "coord_point": "현충사" + }, + { + "name": "문광저수지", + "kind": "ginkgo", + "region": "충북 괴산", + "lat": 36.76832, + "lon": 127.75077, + "peak": "2026-10-29", + "basis": "가장 가까운 산림청 예측 지점(미동산수목원, 은행나무) 날짜", + "coord_point": "문광저수지" + }, + { + "name": "홍천 은행나무숲", + "kind": "ginkgo", + "region": "강원 홍천", + "lat": 37.83213, + "lon": 128.47071, + "peak": "2026-10-27", + "basis": "가장 가까운 산림청 예측 지점(강원도립화목원, 은행나무) 날짜", + "coord_point": "홍천 은행나무숲" + }, + { + "name": "운곡서원", + "kind": "ginkgo", + "region": "경북 경주", + "lat": 35.941, + "lon": 129.30208, + "peak": "2026-10-29", + "basis": "가장 가까운 산림청 예측 지점(주왕산, 은행나무) 날짜", + "coord_point": "운곡서원" + }, + { + "name": "도리마을 은행나무숲", + "kind": "ginkgo", + "region": "경북 경주", + "lat": 35.9185, + "lon": 129.0908, + "peak": "2026-11-04", + "basis": "가장 가까운 산림청 예측 지점(대구수목원, 은행나무) 날짜", + "coord_point": "도리마을 은행나무숲" + }, + { + "name": "청라 은행마을", + "kind": "ginkgo", + "region": "충남 보령", + "lat": 36.42721, + "lon": 126.6756, + "peak": "2026-10-26", + "basis": "가장 가까운 산림청 예측 지점(가야산(충남), 은행나무) 날짜", + "coord_point": "청라 은행마을" + }, + { + "name": "전주향교", + "kind": "ginkgo", + "region": "전북 전주", + "lat": 35.81295, + "lon": 127.15654, + "peak": "2026-11-02", + "basis": "가장 가까운 산림청 예측 지점(대아수목원, 은행나무) 날짜", + "coord_point": "전주향교" + }, + { + "name": "부석사", + "kind": "ginkgo", + "region": "경북 영주", + "lat": 36.9984, + "lon": 128.6871, + "peak": "2026-10-29", + "basis": "가장 가까운 산림청 예측 지점(주왕산, 은행나무) 날짜", + "coord_point": "부석사" + }, + { + "name": "보석사", + "kind": "ginkgo", + "region": "충남 금산", + "lat": 36.05436, + "lon": 127.47587, + "peak": "2026-11-02", + "basis": "가장 가까운 산림청 예측 지점(대아수목원, 은행나무) 날짜", + "coord_point": "보석사" } ] -} \ No newline at end of file +} diff --git a/frontend/src/api/client/@tanstack/react-query.gen.ts b/frontend/src/api/client/@tanstack/react-query.gen.ts index 3dd0b27..31d315a 100644 --- a/frontend/src/api/client/@tanstack/react-query.gen.ts +++ b/frontend/src/api/client/@tanstack/react-query.gen.ts @@ -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, 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, 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, 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'; export type QueryKey = [ Pick & { @@ -78,7 +78,7 @@ export const nearestRegionOptions = (options: Options) => que export const getWeatherTodayQueryKey = (options: Options) => createQueryKey('getWeatherToday', options); /** - * 오늘 3시간 칸 날씨 + * 오늘(또는 내일) 3시간 칸 날씨 */ export const getWeatherTodayOptions = (options: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { @@ -677,7 +677,7 @@ export const listCommentsInfiniteOptions = (options: Options) }; /** - * 댓글 쓰기 (60자) + * 댓글 쓰기 (60자, 로그인 없으면 '동네 익명'으로 IP 당 하루 20개) */ export const addCommentMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { @@ -694,7 +694,7 @@ export const addCommentMutation = (options?: Partial>): }; /** - * 내 댓글 지우기 + * 내 댓글 지우기 (로그인 없이 쓴 댓글은 같은 IP 에서) */ export const deleteCommentMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { @@ -834,7 +834,7 @@ export const deleteMyGakMutation = (options?: Partial>) export const listTalksQueryKey = (options?: Options) => createQueryKey('listTalks', options); /** - * 동네 이야기 (전국, 최신순, 로그인 없이 보기) + * 동네 이야기 (전국 최신순, 보는 동네와 같은 시도 글은 앞으로, 같은 사람 글은 띄움, 로그인 없이 보기) */ export const listTalksOptions = (options?: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { @@ -852,10 +852,10 @@ export const listTalksOptions = (options?: Options) => queryOptio export const listTalksInfiniteQueryKey = (options?: Options): QueryKey> => createQueryKey('listTalks', options, true); /** - * 동네 이야기 (전국, 최신순, 로그인 없이 보기) + * 동네 이야기 (전국 최신순, 보는 동네와 같은 시도 글은 앞으로, 같은 사람 글은 띄움, 로그인 없이 보기) */ export const listTalksInfiniteOptions = (options?: Options) => { - const opts = infiniteQueryOptions, QueryKey>, number | null | Pick>[0], 'body' | 'headers' | 'path' | 'query'>>( + const opts = infiniteQueryOptions, QueryKey>, string | null | Pick>[0], 'body' | 'headers' | 'path' | 'query'>>( // @ts-ignore { queryFn: async ({ pageParam, queryKey, signal }) => { @@ -879,6 +879,54 @@ export const listTalksInfiniteOptions = (options?: Options) => { return opts as Omit; }; +export const listMyTalksQueryKey = (options?: Options) => createQueryKey('listMyTalks', options); + +/** + * 내가 쓴 글 (최신순) + */ +export const listMyTalksOptions = (options?: Options) => queryOptions>({ + queryFn: async ({ queryKey, signal }) => { + const { data } = await listMyTalks({ + ...options, + ...queryKey[0], + signal, + throwOnError: true + }); + return data; + }, + queryKey: listMyTalksQueryKey(options) +}); + +export const listMyTalksInfiniteQueryKey = (options?: Options): QueryKey> => createQueryKey('listMyTalks', options, true); + +/** + * 내가 쓴 글 (최신순) + */ +export const listMyTalksInfiniteOptions = (options?: Options) => { + const opts = infiniteQueryOptions, QueryKey>, string | null | Pick>[0], 'body' | 'headers' | 'path' | 'query'>>( + // @ts-ignore + { + queryFn: async ({ pageParam, queryKey, signal }) => { + // @ts-ignore + const page: Pick>[0], 'body' | 'headers' | 'path' | 'query'> = typeof pageParam === 'object' ? pageParam : { + query: { + cursor: pageParam + } + }; + const params = createInfiniteParams(queryKey, page); + const { data } = await listMyTalks({ + ...options, + ...params, + signal, + throwOnError: true + }); + return data; + }, + queryKey: listMyTalksInfiniteQueryKey(options) + }); + return opts as Omit; +}; + /** * 동네 이야기 쓰기 (링크·전화번호 불가, 하루 5개) */ diff --git a/frontend/src/api/client/index.ts b/frontend/src/api/client/index.ts index 4b52f78..6de1a88 100644 --- a/frontend/src/api/client/index.ts +++ b/frontend/src/api/client/index.ts @@ -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, 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 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 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 LoginResponse, type LoginResponses, type LogoutData, type LogoutError, type LogoutErrors, type LogoutResponse, type LogoutResponses, type Me, type MeData, type MeError, type MeErrors, type MeResponse, type MeResponses, type MyGakData, type MyGakPreset, type MyGakRule, type MyGakScore, type NearestRegionData, type NearestRegionError, type NearestRegionErrors, type NearestRegionResponse, type NearestRegionResponses, type PlaceData, type PlanSlide, type PlanSpot, type PlanStep, type PostData, PostType, type Rain2h, type RainHourData, RainType, type RankData, type RefreshData, type RefreshError, type RefreshErrors, type RefreshResponse, type RefreshResponses, type RegionData, type ReportTalkData, type ReportTalkError, type ReportTalkErrors, type ReportTalkResponse, type ReportTalkResponses, type ReqComment, type ReqGoogle, type ReqLogin, type ReqMyGak, type ReqMyGakScore, type ReqRefresh, type ReqSignup, type ReqTalk, type ReqTalkReport, type ReqUpdateMe, type ResArticle, type ResArticleList, type ResAuth, type ResAuthConfig, type ResComment, type ResCommentLike, type ResCommentList, type ResEventList, type ResFeed, type ResHealth, type ResIndexDetail, type ResIndexList, type ResLogout, type ResMe, type ResMyGak, type ResMyGakList, type ResMyGakPresets, type ResMyGakScore, type ResPlaceList, type ResPost, type ResPostLike, type ResPostSave, type ResRegion, type ResRegionList, type ResSavedList, type ResSeasonWeek, type ResSky, type ResSkyRanking, type ResTalk, type ResTalkImage, type ResTalkLike, type ResTalkList, type ResWatchSummary, type ResWeatherNow, type ResWeatherToday, type ResWebPacketProtocol, type ResWeek, type ResWeekRanking, type Row, type RowsSlide, type SavedPost, type SavePostData, type SavePostError, type SavePostErrors, type SavePostResponse, type SavePostResponses, type ScoreBand, type ScoreMyGakData, type ScoreMyGakError, type ScoreMyGakErrors, type ScoreMyGakResponse, type ScoreMyGakResponses, type SignupData, type SignupError, type SignupErrors, type SignupResponse, type SignupResponses, Sky, SkyGrade, type SkyPlanData, type SkyScoreData, SkySituation, SkyType, type SlotPoint, SlotTone, type SpotData, type SunsetSlide, type TalkData, TalkReport, type TermData, type Tomorrow, type TopIndex, type TrendPoint, type UnlikeCommentData, type UnlikeCommentError, type UnlikeCommentErrors, type UnlikeCommentResponse, type UnlikeCommentResponses, type UnlikePostData, type UnlikePostError, type UnlikePostErrors, type UnlikePostResponse, type UnlikePostResponses, type UnlikeTalkData, type UnlikeTalkError, type UnlikeTalkErrors, type UnlikeTalkResponse, type UnlikeTalkResponses, type UnsavePostData, type UnsavePostError, type UnsavePostErrors, type UnsavePostResponse, type UnsavePostResponses, type UpdateMeData, type UpdateMeError, type UpdateMeErrors, type UpdateMeResponse, type UpdateMeResponses, type UploadTalkImageData, type UploadTalkImageError, type UploadTalkImageErrors, type UploadTalkImageResponse, type UploadTalkImageResponses, type ValidationError, type WarningData, WarningLevel, WarningType, type WatchEvent, type WatchNow, type WatchSlot, type WatchSunset, type WatchTimeline, type WeatherSlot, type WeatherWhy, type WeekDay, type WeekGak, type WeekRankDay, type WeekRankItem, type WeekSlide } from './types.gen'; +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 LoginResponse, type LoginResponses, type LogoutData, type LogoutError, type LogoutErrors, type LogoutResponse, type LogoutResponses, type Me, type MeData, type MeError, type MeErrors, type MeResponse, type MeResponses, type MyGakData, type MyGakPreset, type MyGakRule, type MyGakScore, type NearestRegionData, type NearestRegionError, type NearestRegionErrors, type NearestRegionResponse, type NearestRegionResponses, type PlaceData, type PlanSlide, type PlanSpot, type PlanStep, type PostData, type PostReaction, PostType, type Rain2h, type RainHourData, RainType, type RankData, type RefreshData, type RefreshError, type RefreshErrors, type RefreshResponse, type RefreshResponses, type RegionData, type ReportTalkData, type ReportTalkError, type ReportTalkErrors, type ReportTalkResponse, type ReportTalkResponses, type ReqComment, type ReqGoogle, type ReqLogin, type ReqMyGak, type ReqMyGakScore, type ReqRefresh, type ReqSignup, type ReqTalk, type ReqTalkReport, type ReqUpdateMe, type ResArticle, type ResArticleList, type ResAuth, type ResAuthConfig, type ResComment, type ResCommentLike, type ResCommentList, type ResEventList, type ResFeed, type ResHealth, type ResIndexDetail, type ResIndexList, type ResLogout, type ResMe, type ResMyGak, type ResMyGakList, type ResMyGakPresets, type ResMyGakScore, type ResPlaceList, type ResPost, type ResPostLike, type ResPostSave, type ResRegion, type ResRegionList, type ResSavedList, type ResSeasonWeek, type ResSky, type ResSkyRanking, type ResTalk, type ResTalkImage, type ResTalkLike, type ResTalkList, type ResWatchSummary, type ResWeatherNow, type ResWeatherToday, type ResWebPacketProtocol, type ResWeek, type ResWeekRanking, type Row, type RowsSlide, type SavedPost, type SavePostData, type SavePostError, type SavePostErrors, type SavePostResponse, type SavePostResponses, type ScoreBand, type ScoreMyGakData, type ScoreMyGakError, type ScoreMyGakErrors, type ScoreMyGakResponse, type ScoreMyGakResponses, type SignupData, type SignupError, type SignupErrors, type SignupResponse, type SignupResponses, Sky, SkyGrade, type SkyPlanData, type SkyScoreData, SkySituation, SkyType, type SlotPoint, SlotTone, type SpotData, type SunsetSlide, type TalkData, TalkReport, type TermData, type Tomorrow, type TopIndex, type TrendPoint, type UnlikeCommentData, type UnlikeCommentError, type UnlikeCommentErrors, type UnlikeCommentResponse, type UnlikeCommentResponses, type UnlikePostData, type UnlikePostError, type UnlikePostErrors, type UnlikePostResponse, type UnlikePostResponses, type UnlikeTalkData, type UnlikeTalkError, type UnlikeTalkErrors, type UnlikeTalkResponse, type UnlikeTalkResponses, type UnsavePostData, type UnsavePostError, type UnsavePostErrors, type UnsavePostResponse, type UnsavePostResponses, type UpdateMeData, type UpdateMeError, type UpdateMeErrors, type UpdateMeResponse, type UpdateMeResponses, type UploadTalkImageData, type UploadTalkImageError, type UploadTalkImageErrors, type UploadTalkImageResponse, type UploadTalkImageResponses, type ValidationError, type WarningData, WarningLevel, WarningType, type WatchEvent, type WatchNow, type WatchSlot, type WatchSunset, type WatchTimeline, type WeatherSlot, type WeatherWhy, type WeekDay, type WeekGak, type WeekRankDay, type WeekRankItem, type WeekSlide } from './types.gen'; diff --git a/frontend/src/api/client/sdk.gen.ts b/frontend/src/api/client/sdk.gen.ts index 445f1eb..80e37c2 100644 --- a/frontend/src/api/client/sdk.gen.ts +++ b/frontend/src/api/client/sdk.gen.ts @@ -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, 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, 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'; export type Options = Options2 & { /** @@ -29,7 +29,7 @@ export const listRegions = (options?: Optio export const nearestRegion = (options: Options): RequestResult => (options.client ?? client).get({ url: '/v1/region/nearest', ...options }); /** - * 오늘 3시간 칸 날씨 + * 오늘(또는 내일) 3시간 칸 날씨 */ export const getWeatherToday = (options: Options): RequestResult => (options.client ?? client).get({ url: '/v1/weather/today', ...options }); @@ -209,7 +209,7 @@ export const listSaved = (options?: Options export const listComments = (options: Options): RequestResult => (options.client ?? client).get({ url: '/v1/reaction/post/{post_id}/comment/list', ...options }); /** - * 댓글 쓰기 (60자) + * 댓글 쓰기 (60자, 로그인 없으면 '동네 익명'으로 IP 당 하루 20개) */ export const addComment = (options: Options): RequestResult => (options.client ?? client).post({ url: '/v1/reaction/post/{post_id}/comment', @@ -221,7 +221,7 @@ export const addComment = (options: Options }); /** - * 내 댓글 지우기 + * 내 댓글 지우기 (로그인 없이 쓴 댓글은 같은 IP 에서) */ export const deleteComment = (options: Options): RequestResult => (options.client ?? client).delete({ url: '/v1/reaction/comment/{comment_id}', ...options }); @@ -275,10 +275,15 @@ export const scoreMyGak = (options: Options export const deleteMyGak = (options: Options): RequestResult => (options.client ?? client).delete({ url: '/v1/my-gak/{my_gak_id}', ...options }); /** - * 동네 이야기 (전국, 최신순, 로그인 없이 보기) + * 동네 이야기 (전국 최신순, 보는 동네와 같은 시도 글은 앞으로, 같은 사람 글은 띄움, 로그인 없이 보기) */ export const listTalks = (options?: Options): RequestResult => (options?.client ?? client).get({ url: '/v1/talk/list', ...options }); +/** + * 내가 쓴 글 (최신순) + */ +export const listMyTalks = (options?: Options): RequestResult => (options?.client ?? client).get({ url: '/v1/talk/mine', ...options }); + /** * 동네 이야기 쓰기 (링크·전화번호 불가, 하루 5개) */ diff --git a/frontend/src/api/client/types.gen.ts b/frontend/src/api/client/types.gen.ts index 134387b..a42d0c5 100644 --- a/frontend/src/api/client/types.gen.ts +++ b/frontend/src/api/client/types.gen.ts @@ -662,6 +662,7 @@ export type Hero = { * 히어로 상태 한 줄: 습도·불쾌지수·자외선(밤 구간 빼고)·미세먼지 단계 이름. tone=warn 이면 조심(앱이 주황 글자로) */ status?: Array; + tomorrow?: HeroTomorrow | null; }; /** @@ -688,6 +689,38 @@ export type HeroStat = { tone: 'normal' | 'warn' | 'rain'; }; +/** + * HeroTomorrow + * + * 히어로 '내일' 스위치. 3시간 칸 날씨는 /v1/weather/today?day=tomorrow 로 따로 받는다. + */ +export type HeroTomorrow = { + /** + * Day + */ + day: string; + /** + * Weather Slots + * + * 내일 구간별 날씨 점수 {morning·day·evening·night: 점수} + */ + weather_slots?: { + [key: string]: number; + }; + /** + * Weather Why + * + * 내일 구간별 날씨 점수 근거 + */ + weather_why?: { + [key: string]: Array; + }; + /** + * 내일 하루 점수로 1위인 각. score·summary 는 내일 값 + */ + top1?: TopIndex | null; +}; + /** * HourCell */ @@ -1150,6 +1183,30 @@ export type PostData = { saved?: boolean | null; }; +/** + * PostReaction + * + * 포스트 틀이 아닌 카드(히어로·오늘의 각)에 붙는 좋아요·댓글. + */ +export type PostReaction = { + /** + * Post Id + */ + post_id: number; + /** + * Like Count + */ + like_count: number; + /** + * Comment Count + */ + comment_count: number; + /** + * Liked + */ + liked?: boolean | null; +}; + /** * PostType */ @@ -1213,7 +1270,15 @@ export const PostType = { /** * UV */ - UV: 15 + UV: 15, + /** + * HERO + */ + HERO: 16, + /** + * TODAY_GAK + */ + TODAY_GAK: 17 } as const; /** @@ -1350,6 +1415,12 @@ export type ReqComment = { * Body */ body: string; + /** + * Region + * + * 로그인 없이 쓸 때 보고 있는 동네 코드. 이름이 '마포구 익명'으로 보인다 + */ + region?: string | null; }; /** @@ -1647,6 +1718,8 @@ export type ResFeed = { * Posts */ posts?: Array; + hero_post?: PostReaction | null; + gak_post?: PostReaction | null; bands?: Bands | null; }; @@ -2118,8 +2191,10 @@ export type ResTalkList = { talks?: Array; /** * Next Cursor + * + * 다음 페이지를 받을 때 그대로 cursor 로 보낸다 */ - next_cursor?: number | null; + next_cursor?: string | null; }; /** @@ -3186,6 +3261,10 @@ export type WeatherSlot = { * Rain Prob */ rain_prob?: number | null; + /** + * Humidity + */ + humidity?: number | null; /** * Icon */ @@ -3455,6 +3534,12 @@ export type GetWeatherTodayData = { * 구 행정코드 */ region: string; + /** + * Day + * + * tomorrow 면 내일 칸 + */ + day?: 'today' | 'tomorrow'; }; url: '/v1/weather/today'; }; @@ -4630,10 +4715,16 @@ export type ListTalksData = { }; path?: never; query?: { + /** + * Region + * + * 보는 사람의 구 행정코드 + */ + region?: string | null; /** * Cursor */ - cursor?: number | null; + cursor?: string | null; }; url: '/v1/talk/list'; }; @@ -4656,6 +4747,42 @@ export type ListTalksResponses = { export type ListTalksResponse = ListTalksResponses[keyof ListTalksResponses]; +export type ListMyTalksData = { + body?: never; + headers?: { + /** + * Authorization + */ + authorization?: string | null; + }; + path?: never; + query?: { + /** + * Cursor + */ + cursor?: string | null; + }; + url: '/v1/talk/mine'; +}; + +export type ListMyTalksErrors = { + /** + * Validation Error + */ + 422: HttpValidationError; +}; + +export type ListMyTalksError = ListMyTalksErrors[keyof ListMyTalksErrors]; + +export type ListMyTalksResponses = { + /** + * Successful Response + */ + 200: ResTalkList; +}; + +export type ListMyTalksResponse = ListMyTalksResponses[keyof ListMyTalksResponses]; + export type AddTalkData = { body: ReqTalk; headers?: { diff --git a/frontend/src/b/Post.tsx b/frontend/src/b/Post.tsx index 771e8cc..873d8bc 100644 --- a/frontend/src/b/Post.tsx +++ b/frontend/src/b/Post.tsx @@ -1,12 +1,13 @@ import { useEffect, useRef, useState, type CSSProperties, type MouseEvent, type ReactNode, type RefObject } from 'react' import { createPortal } from 'react-dom' -import { PostType, SlotTone, type GakSlide, type HoursSlide, type PlanSlide, type PostData, type ResFeed, type RowsSlide, type SunsetSlide, type WeekSlide } from '../api/client/types.gen' +import { PostType, SlotTone, type GakSlide, type HoursSlide, type PlanSlide, type PostData, type PostReaction, type ResFeed, type RowsSlide, type SunsetSlide, type WeekSlide } from '../api/client/types.gen' import { cx } from '../lib/utils' import { cardBg, clockShort, fall } from './lib' import type { SlideBg } from './types' import { deg } from './weatherText' import { useMutation, useQueryClient, type QueryClient } from '@tanstack/react-query' import { likePostMutation, unlikePostMutation } from '../api/client/@tanstack/react-query.gen' +import { usePinnedLike, type PinnedKey } from './pinnedLike' import { useSheet } from './sheetContext' import { CommentIcon, HeartIcon, SendIcon } from './svg' import { useCarousel } from './carousel' @@ -28,6 +29,8 @@ const ACCOUNTS: Record = { [PostType.DAY_TRIP]: ['당일치기', 'picnic'], [PostType.MOON]: ['오늘 밤 달', 'moon'], [PostType.UV]: ['자외선', 'glasses'], + [PostType.HERO]: ['오늘 날씨', 'sun'], + [PostType.TODAY_GAK]: ['오늘의 각', 'rabbit'], } type Slide = HoursSlide | RowsSlide | GakSlide | SunsetSlide | WeekSlide | PlanSlide @@ -478,12 +481,23 @@ function FullCard({ post }: PostProps) { ) } -type FrameProps = { title: string; account: string; avatar: string; caption?: ReactNode; more?: ReactNode; shot?: RefObject; children: ReactNode } +type FrameProps = { + title: string + account: string + avatar: string + caption?: ReactNode + more?: ReactNode + shot?: RefObject + pinned?: { key: PinnedKey; post?: PostReaction | null } + children: ReactNode +} /** 피드 글과 같은 틀(계정 줄·본문·보내기 줄)에 날씨·각 같은 화면 조각을 담는다. 보내기는 shot(공유용 틀)이 있으면 그것을, 없으면 본문을 이미지로 */ -export function PostFrame({ title, account, avatar, caption, more, shot, children }: FrameProps) { +export function PostFrame({ title, account, avatar, caption, more, shot, pinned, children }: FrameProps) { const { open } = useSheet() const bodyRef = useRef(null) + const like = usePinnedLike(pinned?.key ?? 'gak_post', pinned?.post) + const postId = pinned?.post?.post_id const share = () => { const el = shot?.current ?? bodyRef.current if (el) open({ type: 'share', share: { title, slides: [el] } }) @@ -503,17 +517,37 @@ export function PostFrame({ title, account, avatar, caption, more, shot, childre
{children}
+ {postId != null && ( + <> + + + + )} {more && {more}}
+ {postId != null && ( +

+ {like.failed ? 좋아요를 반영하지 못했어요. 다시 해 주세요. : `좋아요 ${like.count.toLocaleString()}개`} +

+ )} {caption && (

날씨각 {caption}

)} + {postId != null && ( + + )} ) } diff --git a/frontend/src/b/Sheets.tsx b/frontend/src/b/Sheets.tsx index 8168ab9..7303ef3 100644 --- a/frontend/src/b/Sheets.tsx +++ b/frontend/src/b/Sheets.tsx @@ -14,9 +14,7 @@ import { listCommentsInfiniteOptions, listCommentsInfiniteQueryKey, listRegionsOptions, - loginMutation, meQueryKey, - signupMutation, unlikeCommentMutation, updateMeMutation, } from '../api/client/@tanstack/react-query.gen' @@ -35,6 +33,7 @@ import { useSky } from './skyContext' import { SHARE_SIZES, shareImage, type ShareSize } from './storyImage' import { SheetContext, useSheet, type SharePayload, type SheetState } from './sheetContext' import { HeartIcon } from './svg' +import { MyTalks } from './talk' import { Avatar, Ic, Skel, StateBox, TAP44, Thumb } from './ui' export function SheetProvider({ children }: { children: ReactNode }) { @@ -529,7 +528,7 @@ function ShareSheet({ share }: { share: SharePayload }) { const srcs = useRef([]) const [toast, setToast] = useState('') const image = images[size] - const text = `${share.title} · 날씨각 ${SITE_URL}` + const text = `${share.title} · 날씨각` // 고른 크기의 이미지를 미리 만들어 둔다. 누를 때 만들면 아이폰이 공유창을 막는다 useEffect(() => { @@ -558,14 +557,21 @@ function ShareSheet({ share }: { share: SharePayload }) { return () => list.forEach((s) => URL.revokeObjectURL(s)) }, []) - // 휴대폰은 공유창에 이미지와 링크를 같이 넘기고, 공유창이 없으면 이미지를 내려받고 링크를 복사한다 + // 휴대폰은 공유창에 이미지와 링크를 같이 넘기고, 이미지만 받는 앱이 있어 링크도 복사해 둔다. 공유창이 없으면 이미지를 내려받고 링크를 복사한다 const send = () => { if (!image) return const file = new File([image.blob], `nalssigak-${SHARE_SIZES[size].ratio.replace(':', 'x')}.png`, { type: 'image/png' }) - if (navigator.canShare?.({ files: [file], text })) { - navigator.share({ files: [file], title: share.title, text }).then( - () => { - setToast('보냈어요') + if (navigator.canShare?.({ files: [file], text, url: SITE_URL })) { + const copied = navigator.clipboard?.writeText(SITE_URL).then( + () => true, + (e: unknown) => { + console.error('[share] copy link', e) + return false + }, + ) + navigator.share({ files: [file], title: share.title, text, url: SITE_URL }).then( + async () => { + setToast((await copied) ? '보냈어요. 링크도 복사해 뒀어요' : '보냈어요') track('share', { content_type: 'image', item_id: share.title, method: 'share_sheet', ratio: SHARE_SIZES[size].ratio }) }, (e: unknown) => { @@ -585,7 +591,7 @@ function ShareSheet({ share }: { share: SharePayload }) { setToast('이미지를 내려받았어요') return } - navigator.clipboard.writeText(text).then( + navigator.clipboard.writeText(`${text} ${SITE_URL}`).then( () => setToast('이미지를 내려받고 링크를 복사했어요'), () => setToast('이미지를 내려받았어요. 링크 복사는 막혀 있어요'), ) @@ -715,8 +721,7 @@ function CommentRow({ c, postId }: { c: CommentData; postId: number }) { function CommentsSheet({ postId, draft }: { postId: number; draft?: string }) { const { region } = useRegion() - const { open } = useSheet() - const { loggedIn, me } = useAuth() + const { me } = useAuth() const queryClient = useQueryClient() const list = useInfiniteQuery({ ...listCommentsInfiniteOptions({ path: { post_id: postId } }), @@ -731,12 +736,11 @@ function CommentsSheet({ postId, draft }: { postId: number; draft?: string }) { const submit = (e: FormEvent) => { e.preventDefault() - if (!loggedIn) return open({ type: 'login', then: { type: 'comments', postId, draft: text } }) const body = text.trim() if (!body || add.isPending) return setAddFailed(false) add.mutate( - { path: { post_id: postId }, body: { body } }, + { path: { post_id: postId }, body: { body, region: region.code } }, { onSuccess: (res) => { setAddFailed(!res.result?.success) @@ -790,7 +794,7 @@ function CommentsSheet({ postId, draft }: { postId: number; draft?: string }) {

setText(e.target.value)} readOnly={add.isPending} maxLength={60} placeholder={me ? `${me.nickname}(으)로 댓글 달기…` : '댓글 달기…'} aria-label="댓글" className="min-w-0 flex-1 rounded-full border border-[#dfe5ee] bg-[#f7f9fc] px-3.5 py-2.5" /> -
@@ -799,74 +803,41 @@ function CommentsSheet({ postId, draft }: { postId: number; draft?: string }) { } /* ---------- 로그인 ---------- */ -const AUTH_ERRORS: Record = { - AUTH_FAILED: '아이디나 비밀번호가 맞지 않아요.', - AUTH_DUPLICATE_ID: '이미 쓰고 있는 아이디예요.', - INVALID_INPUT: '아이디는 영어 소문자·숫자·_ 4~20자, 비밀번호는 8~64자, 닉네임은 2~12자로 써 주세요.', -} - function LoginSheet({ onDone, onLoggedIn }: { onDone: () => void; onLoggedIn: () => void }) { const { me } = useAuth() - const [mode, setMode] = useState<'login' | 'signup'>('login') - const [loginId, setLoginId] = useState('') - const [password, setPassword] = useState('') - const [nickname, setNickname] = useState('') const [error, setError] = useState('') - const login = useMutation(loginMutation()) - const signup = useMutation(signupMutation()) - const pending = login.isPending || signup.isPending - const done = (res: ResAuth, method: 'id' | 'google' = 'id') => { + const done = (res: ResAuth) => { if (!res.result?.success || !res.access_token) { - setError(method === 'google' ? '구글로 로그인하지 못했어요. 다시 해 주세요.' : (AUTH_ERRORS[res.result?.desc ?? ''] ?? '잠시 뒤에 다시 해 주세요.')) + setError('구글로 로그인하지 못했어요. 다시 해 주세요.') return } setTokens(res.access_token, res.refresh_token ?? null) - track(method === 'google' ? 'login' : mode === 'login' ? 'login' : 'sign_up', { method }) + track('login', { method: 'google' }) onLoggedIn() } const fail = () => setError('서버에 닿지 못했어요. 잠시 뒤에 다시 해 주세요.') - const submit = (e: FormEvent) => { - e.preventDefault() - setError('') - if (mode === 'login') login.mutate({ body: { login_id: loginId.trim(), password } }, { onSuccess: (res) => done(res), onError: fail }) - else signup.mutate({ body: { login_id: loginId.trim(), password, nickname: nickname.trim() } }, { onSuccess: (res) => done(res), onError: fail }) - } - if (me) return - const field = 'w-full rounded-[14px] border border-[#dfe5ee] bg-[#f7f9fc] px-3.5 py-3' return ( -
-

글쓰기·댓글은 로그인한 뒤에 할 수 있어요.

- done(res, 'google')} onFail={fail} /> -
- {( - [ - ['login', '로그인'], - ['signup', '처음이에요'], - ] as const - ).map(([m, l]) => ( - - ))} -
- setLoginId(e.target.value)} autoComplete="username" required minLength={4} maxLength={20} placeholder="아이디" aria-label="아이디" className={field} /> - setPassword(e.target.value)} type="password" autoComplete={mode === 'login' ? 'current-password' : 'new-password'} required minLength={mode === 'signup' ? 8 : undefined} maxLength={64} placeholder={mode === 'signup' ? '비밀번호 (8자 이상)' : '비밀번호'} aria-label="비밀번호" className={field} /> - {mode === 'signup' && setNickname(e.target.value)} required minLength={2} maxLength={12} placeholder="닉네임 (2~12자)" aria-label="닉네임" className={field} />} +
+

글쓰기는 로그인한 뒤에 할 수 있어요.

+ { + setError('') + done(res) + }} + onFail={fail} + />

{error}

- - +
) } @@ -987,6 +958,7 @@ function MeSheet({ onDone }: { onDone: () => void }) {

{saving ? (saving.nickname == null ? '저장 중…' : '') : error}

+ + + + {( + [ + [false, '오늘'], + [true, '내일'], + ] as const + ).map(([v, l]) => ( + + ))} + + + {t.mo}월 {t.d}일 {WEEKDAYS[t.wd]}요일 + + + + {post && ( + <> + + + + )} + +
{CLOUDS.slice(0, CLOUD_N[weather]).map((c) => ( @@ -205,32 +367,47 @@ function Hero({ hero, today, ranked, all, feedLoad, todayLoad }: HeroProps) { ))}
- {/* 안 보이는 쪽을 덮어 오늘 밤 달 모양으로 */} - {moon && ( - - )} - - {failed(feedLoad) ? '점수를 못 불러왔어요' : `${slotScore != null && mode !== 'now' ? PREVIEW[mode].label : '지금'} 날씨 점수`} - {heroVal(feedLoad, score, 'w-[84px]')} - - {why && score != null && ( - - )} -
+ {/* 안 보이는 쪽을 덮어 오늘 밤 달 모양으로 */} + {moon && ( + + )} + + + {failed(feedLoad) ? '점수를 못 불러왔어요' : `${tmr && mode !== 'now' ? `내일 ${PREVIEW[mode].label}` : slotScore != null && mode !== 'now' ? PREVIEW[mode].label : '지금'} 날씨 점수`} + + {heroVal(feedLoad, score, 'w-[84px]')} + + {why && score != null && ( + + )} +
{top1 ? ( - ) : ( @@ -242,7 +419,11 @@ function Hero({ hero, today, ranked, all, feedLoad, todayLoad }: HeroProps) {

{status.map((x, i) => ( - {i > 0 && } + {i > 0 && ( + + )} {x.label} {x.value} @@ -253,14 +434,21 @@ function Hero({ hero, today, ranked, all, feedLoad, todayLoad }: HeroProps) {

{KINDS.map((k) => { - const isNow = k === nowKind + const isNow = !tmr && k === nowKind const s = slotOf(isNow ? 'now' : k) const on = k === kind return ( - ) })} @@ -281,12 +469,20 @@ function moonPath(pct: number, r: number, lit: boolean) { return `M0,${-r} A${r},${r} 0 0 ${lit ? 1 : 0} 0,${r} ${edge}` } -function GakCard({ items, place, at }: { items: TopIndex[]; place: string; at: string }) { +function GakCard({ items, post, place, at }: { items: TopIndex[]; post?: PostReaction | null; place: string; at: string }) { const { open } = useSheet() const tplRef = useRef(null) const top = items.filter((g) => g.active).slice(0, 5) return ( - 전체 보기} caption="누르면 계산 근거를 보여 줘요" shot={tplRef}> + 전체 보기} + caption="누르면 계산 근거를 보여 줘요" + shot={tplRef} + pinned={{ key: 'gak_post', post }} + >

@@ -368,6 +564,8 @@ function SeasonBand({ news }: { news: BandArticle[] }) { ) } +const TALK_EVERY = 3 + export function TodayPage() { const { region } = useRegion() const feed = useQuery(getFeedOptions({ query: { region: region.code } })) @@ -382,8 +580,19 @@ export function TodayPage() { const nowAt = f?.hero?.now_at const load = loadOf(feed) const [mine, setMine] = useState([]) - // 사람들이 쓴 글은 운영 포스트 3개마다 하나씩. 방금 올린 내 글은 글쓰기 칸 아래에 따로 있으니 빼고 - const talks = useFeedTalks().filter((t) => !mine.some((m) => m.talk_id === t.talk_id)) + // 사람들이 쓴 글은 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(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]) useEffect(() => { window.scrollTo({ top: 0 }) @@ -409,15 +618,15 @@ export function TodayPage() { return ( // 피드 칸은 전국 공통이라 지역이 바뀌어도 글 번호가 같다. 지역마다 새로 그려 넘긴 슬라이드·펼친 상태가 남지 않게 한다

- + setMine((m) => [t, ...m])} /> {mine.map((t) => ( - + setMine((m) => m.filter((x) => x.talk_id !== t.talk_id))} /> ))} {/* 실패 안내는 여기 한 번만, 각 카드 스켈레톤과 같은 크기로 */} {stories.some((g) => g.active) ? ( - + ) : load === 'loading' ? ( ) : ( @@ -434,11 +643,13 @@ export function TodayPage() { {i === 1 && } - {(i + 1) % 3 === 0 && talks[(i + 1) / 3 - 1] && } + {i > 0 && i % TALK_EVERY === 0 && talks[i / TALK_EVERY - 1] && } {bandAt.find(([at]) => at === i + 1)?.[1]} ))} {feed.isSuccess && bandAt.filter(([at]) => at > posts.length).map(([at, node]) => {node})} + {load !== 'loading' && talks.slice(between).map((t) => )} +
) diff --git a/frontend/src/b/b.css b/frontend/src/b/b.css index 072b849..b620123 100644 --- a/frontend/src/b/b.css +++ b/frontend/src/b/b.css @@ -553,13 +553,13 @@ html.b-sheet-open .b-app :is(.b-fall, .b-bob, .b-blob, .b-skystars i, .b-shoot, } } -/* 위·아래 바는 반투명으로 하늘이 비치게 */ +/* 위 바는 반투명으로 하늘이 비치게, 아래 탭 바는 홈 바 자리까지 글이 비치지 않게 불투명 */ .b-topbg { background: rgb(255 255 255 / 0.18); transition: background 1.4s ease; } .b-tabbar { - background: rgb(255 255 255 / 0.6); + background: #f7faff; overflow: visible; border-color: rgb(255 255 255 / 0.4); } @@ -567,7 +567,7 @@ html.b-sheet-open .b-app :is(.b-fall, .b-bob, .b-blob, .b-skystars i, .b-shoot, background: rgb(14 20 51 / 0.35); } .b-app[data-t='night'] .b-tabbar { - background: rgb(18 24 60 / 0.62); + background: #121838; border-color: rgb(255 255 255 / 0.08); } diff --git a/frontend/src/b/foliageMap.tsx b/frontend/src/b/foliageMap.tsx index 58628a8..290e61a 100644 --- a/frontend/src/b/foliageMap.tsx +++ b/frontend/src/b/foliageMap.tsx @@ -3,54 +3,42 @@ import data from '../../seo/foliage_2026.json' import { cx } from '../lib/utils' import { kst } from './lib' import { PostFrame } from './Post' +import { Ic } from './ui' -type Mountain = { name: string; region: string; lat: number; lon: number; peak: string } -type Stage = 'peak' | 'soon' | 'before' | 'after' +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' // 지도 그림(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 } -const PEAK_DAYS = 3 // 절정일 앞뒤 이만큼은 '지금 절정' -const SOON_DAYS = 7 +// 발표에 시작일이 없어 절정 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 = { - peak: { label: '지금 절정', dot: 'bg-[#ff5a36]' }, - soon: { label: '곧 절정', dot: 'bg-[#ffb02e]' }, - before: { label: '아직', dot: 'bg-[#7cc47a]' }, - after: { label: '절정 지남', dot: 'bg-[#b9a69a]' }, +const STAGE: Record = { + before: { label: '단풍 전', icon: 'size-3 opacity-60 grayscale' }, + first: { label: '첫 단풍', icon: 'size-3.5' }, + peak: { label: '절정', icon: 'size-[18px]' }, +} +const KIND: Record = { + maple: { label: '단풍', icon: 'maple' }, + ginkgo: { label: '은행', icon: 'ginkgo' }, } -const pos = (m: Mountain) => ({ +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}%`, }) -// 점이 붙은 곳은 이름을 점 왼쪽·위·아래로 돌려 겹치지 않게. 없으면 오른쪽 -type Side = 'left' | 'right' | 'top' | 'bottom' -const SIDE: Record = { - 광덕산: 'left', - 설악산: 'top', - 금원산: 'top', - 두륜산: 'left', - '한라산(1100도로)': 'left', -} -const LABEL_AT: Record = { - right: 'left-full top-1/2 -translate-y-1/2', - left: 'right-full top-1/2 -translate-y-1/2', - top: 'bottom-full left-1/2 -translate-x-1/2', - bottom: 'top-full left-1/2 -translate-x-1/2', -} -const short = (name: string) => name.replace(/\(.*\)$/, '') - const DAY = 86_400_000 const days = (from: string, to: string) => Math.round((Date.parse(to) - Date.parse(from)) / DAY) -function stage(m: Mountain, today: string): Stage { +function stage(m: Spot, today: string): Stage { const d = days(today, m.peak) - if (Math.abs(d) <= PEAK_DAYS) return 'peak' - if (d < 0) return 'after' - return d <= SOON_DAYS ? 'soon' : 'before' + 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))}` @@ -63,51 +51,57 @@ export function FoliageCard() { const [picked, setPicked] = useState(null) const mmdd = today.slice(5) if (mmdd < SEASON.from || mmdd > SEASON.to) return null - const mountains = (data.mountains as unknown as Mountain[]).map((m) => ({ ...m, stage: stage(m, today) })) - const peakNow = mountains.filter((m) => m.stage === 'peak').map((m) => m.name) - // 발표 지도에 서울 안 산은 없어 서울 시청에서 가장 가까운 산으로 - const seoul = mountains.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 = mountains.find((m) => m.name === picked) + 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) return ( - -
+ 5 ? ' 외' : ''}` : undefined}> +

단풍 지도 · {md(today)}

서울 근교 {seoul.name} 절정 예상 {md(seoul.peak)}

- 한반도 지도 - {mountains.map((m) => ( + 단풍 지도 + {spots.map((m) => ( ))} {sel && ( -

+

{sel.name} {sel.region}
- {STAGE[sel.stage].label} · 절정 예상 {md(sel.peak)} + {KIND[sel.kind].label} {STAGE[sel.stage].label} · 절정 예상 {md(sel.peak)} + {!sel.basis.startsWith('산림청') && 가까운 예측 지점 날짜예요}

)}
-
- {(Object.keys(STAGE) as Stage[]).map((s) => ( - - - {STAGE[s].label} +
+ {(Object.keys(KIND) as Kind[]).map((k) => ( + + + {KIND[k].label} + + ))} + + {(Object.keys(STAGE) as Stage[]).map((st) => ( + + + {STAGE[st].label} ))}

- 출처: 산림청 2026 단풍절정 예측 · 단풍나무 잎 절반이 물든 때 기준 + 출처: 산림청 2026 단풍절정 예측 · 잎 절반이 물든 때를 절정으로, 그 2주 전부터 첫 단풍으로 봐요

diff --git a/frontend/src/b/lib.ts b/frontend/src/b/lib.ts index ab21d2b..d4e3fc0 100644 --- a/frontend/src/b/lib.ts +++ b/frontend/src/b/lib.ts @@ -1,6 +1,6 @@ import type { CSSProperties } from 'react' -const SHARED = new Set(['bear', 'bike', 'bronze', 'camping', 'carwash', 'chimaek', 'cloud', 'coldwind', 'delivery', 'dog', 'garden', 'glasses', 'gold', 'hiking', 'iced_hot', 'jjamppong', 'laundry', 'letter', 'makeup', 'makgeolli', 'maple', 'moon', 'muggy', 'naengmyeon', 'photo', 'picnic', 'rabbit', 'rain', 'running', 'silver', 'snow', 'stars', 'sun_cloud', 'sun', 'sunset', 'taxi', 'umbrella', 'vent', 'walk', 'yajang', 'baseball', 'study', 'netflix', 'chestnut', 'peanut', 'tangerine', 'sweet_potato', 'fallen_leaf', 'kimchi', 'apple', 'mask', 'golf', 'jipkok', 'fishing', 'drive', 'kite', 'waterplay', 'riverwind', 'trot', 'pajeon', 'bingsu', 'blanket', 'indoordry', 'flower', 'bungeoppang', 'singing_rain', 'hangang', 'themepark', 'date', 'frizz', 'boiler', 'sunscreen', 'mosquito', 'tennis', 'hyodo', 'thanks', 'gift', 'party', 'game', 'selfie', 'sentimental']) +const SHARED = new Set(['bear', 'bike', 'bronze', 'camping', 'carwash', 'chimaek', 'cloud', 'coldwind', 'delivery', 'dog', 'garden', 'glasses', 'gold', 'hiking', 'iced_hot', 'jjamppong', 'laundry', 'letter', 'makeup', 'makgeolli', 'maple', 'moon', 'muggy', 'naengmyeon', 'photo', 'picnic', 'rabbit', 'rain', 'running', 'silver', 'snow', 'stars', 'sun_cloud', 'sun', 'sunset', 'taxi', 'umbrella', 'vent', 'walk', 'yajang', 'baseball', 'study', 'netflix', 'chestnut', 'peanut', 'tangerine', 'sweet_potato', 'fallen_leaf', 'kimchi', 'apple', 'mask', 'golf', 'jipkok', 'fishing', 'drive', 'kite', 'waterplay', 'riverwind', 'trot', 'pajeon', 'bingsu', 'blanket', 'indoordry', 'flower', 'bungeoppang', 'singing_rain', 'hangang', 'themepark', 'date', 'frizz', 'boiler', 'sunscreen', 'mosquito', 'tennis', 'hyodo', 'thanks', 'gift', 'party', 'game', 'selfie', 'sentimental', 'ginkgo']) const OWN = new Set(['fireworks', 'bulb', 'calendar', 'thermo', 'sheaf', 'popup', 'exhibition', 'concert']) /** 아이콘 이름 → 파일 경로 (공용 public/icons, B 전용 public/b/icons). 'none'(데이터 없는 칸)은 그림 없음 */ diff --git a/frontend/src/b/myGak.tsx b/frontend/src/b/myGak.tsx index a051042..d7071e2 100644 --- a/frontend/src/b/myGak.tsx +++ b/frontend/src/b/myGak.tsx @@ -1,10 +1,10 @@ import { useState, type ReactNode } from 'react' -import type { MyGakRule, MyGakScore } from '../api/client/types.gen' +import type { MyGakPreset, MyGakRule, MyGakScore } from '../api/client/types.gen' import { cx } from '../lib/utils' -import { gakName, shareUrl, SLOTS, type MyGak, type Slot, useMyGak, useMyGakScores } from './myGakState' +import { gakName, shareUrl, SLOTS, type MyGak, type Slot, useMyGak, useMyGakScores, usePresets } from './myGakState' import { useRegion } from './regionContext' import { useSheet } from './sheetContext' -import { Rail, Sec } from './ui' +import { Ic, Rail, Sec } from './ui' const SLOT_WORD = Object.fromEntries(SLOTS) as Record @@ -122,15 +122,49 @@ type Filled = { [K in keyof T]-?: NonNullable } const DEFAULT_RULE: Filled = { temp: [15, 25], rain: 'dry', wind_max: 4, air: 'normal', humidity: [30, 60], slots: ['morning', 'day', 'evening', 'night'] } type Cond = 'temp' | 'rain' | 'wind_max' | 'air' | 'humidity' +const condsOf = (r: MyGakRule): Record => ({ temp: !!r.temp, rain: !!r.rain, wind_max: r.wind_max != null, air: !!r.air, humidity: !!r.humidity }) + +/** 있는 각을 골라 그 각 조건으로 채운다 */ +function PresetPicker({ picked, onPick }: { picked: string | null; onPick: (p: MyGakPreset) => void }) { + const items = usePresets().data ?? [] + if (!items.length) return null + return ( +
+ 있는 각에서 불러오기 +
+ + {items.map((p) => ( + + ))} + +
+
+ ) +} + /** 내 각 만들기(이름과 조건)와 미리보기. shared 면 받은 각을 내 동네 점수로 보여 주고 가져오기만 */ export function MixSheet({ shared, onDone }: { shared?: MyGak; onDone: () => void }) { const { region } = useRegion() const { create, pending, failed } = useMyGak() const [name, setName] = useState(shared?.name ?? '') const [vals, setVals] = useState({ ...DEFAULT_RULE, ...(shared?.rule ?? {}) } as typeof DEFAULT_RULE) - const [on, setOn] = useState>( - shared ? { temp: !!shared.rule.temp, rain: !!shared.rule.rain, wind_max: shared.rule.wind_max != null, air: !!shared.rule.air, humidity: !!shared.rule.humidity } : { temp: true, rain: true, wind_max: false, air: false, humidity: false }, - ) + const [on, setOn] = useState>(shared ? condsOf(shared.rule) : { temp: true, rain: true, wind_max: false, air: false, humidity: false }) + const [picked, setPicked] = useState(null) + const pick = (p: MyGakPreset) => { + setPicked(p.code) + setName(p.name) + setVals({ ...DEFAULT_RULE, ...p.rule } as typeof DEFAULT_RULE) + setOn(condsOf(p.rule)) + } const set = (k: K, v: (typeof vals)[K]) => setVals((x) => ({ ...x, [k]: v })) const toggle = (k: Cond) => setOn((x) => ({ ...x, [k]: !x[k] })) const rule: MyGakRule = { slots: vals.slots, ...(Object.fromEntries((Object.keys(on) as Cond[]).filter((k) => on[k]).map((k) => [k, vals[k]])) as Partial) } @@ -144,10 +178,13 @@ export function MixSheet({ shared, onDone }: { shared?: MyGak; onDone: () => voi {shared ? (

친구가 보낸 각이에요. {region.name} 기준 점수예요

) : ( - + <> + + + )}
조건 diff --git a/frontend/src/b/myGakState.ts b/frontend/src/b/myGakState.ts index 82ae29d..673ff1d 100644 --- a/frontend/src/b/myGakState.ts +++ b/frontend/src/b/myGakState.ts @@ -1,7 +1,7 @@ import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query' import { useEffect, useSyncExternalStore } from 'react' import { SITE_URL } from '../api/setup' -import { addMyGakMutation, deleteMyGakMutation, listMyGakOptions, listMyGakQueryKey } from '../api/client/@tanstack/react-query.gen' +import { addMyGakMutation, deleteMyGakMutation, listMyGakOptions, listMyGakQueryKey, listPresetsOptions } from '../api/client/@tanstack/react-query.gen' import { scoreMyGak } from '../api/client/sdk.gen' import type { MyGakRule, MyGakScore } from '../api/client/types.gen' import { useAuth } from './authContext' @@ -89,6 +89,11 @@ export function useMyGakScores(rules: MyGakRule[]) { }) } +/** 공식 각을 내 각 조건으로 옮긴 목록 (내 각 만들기에서 골라 채우기) */ +export function usePresets() { + return useQuery({ ...listPresetsOptions(), staleTime: Infinity, select: (d) => d.items ?? [] }) +} + export function useMyGak() { const { loggedIn } = useAuth() const { open } = useSheet() diff --git a/frontend/src/b/pinnedLike.ts b/frontend/src/b/pinnedLike.ts new file mode 100644 index 0000000..71bf5aa --- /dev/null +++ b/frontend/src/b/pinnedLike.ts @@ -0,0 +1,38 @@ +import { useState } from 'react' +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 function usePinnedLike(key: PinnedKey, r?: PostReaction | null) { + const queryClient = useQueryClient() + const like = useMutation(likePostMutation()) + const unlike = useMutation(unlikePostMutation()) + const [failed, setFailed] = useState(false) + const liked = !!r?.liked + const count = r?.like_count ?? 0 + const patch = (values: Partial) => + queryClient.setQueriesData({ predicate: (q) => (q.queryKey[0] as { _id?: string } | undefined)?._id === 'getFeed' }, (feed) => + feed?.[key] && feed[key].post_id === r?.post_id ? { ...feed, [key]: { ...feed[key], ...values } } : feed, + ) + const toggle = () => { + if (!r || like.isPending || unlike.isPending) return + const on = !liked + setFailed(false) + patch({ liked: on, like_count: count + (on ? 1 : -1) }) + const revert = () => { + patch({ liked, like_count: count }) + setFailed(true) + } + ;(on ? like : unlike).mutate( + { path: { post_id: r.post_id } }, + { + onSuccess: (res) => (res.result?.success ? patch({ liked: res.liked ?? on, ...(res.like_count != null ? { like_count: res.like_count } : {}) }) : revert()), + onError: revert, + }, + ) + } + return { liked, count, failed, toggle } +} diff --git a/frontend/src/b/talk.tsx b/frontend/src/b/talk.tsx index 15f51c2..e442d4c 100644 --- a/frontend/src/b/talk.tsx +++ b/frontend/src/b/talk.tsx @@ -15,6 +15,7 @@ import { cx } from '../lib/utils' import { useAuth } from './authContext' import { ago, kst } from './lib' import { useRegion } from './regionContext' +import { useMyTalks } from './talkState' import { useSheet } from './sheetContext' import { HeartIcon } from './svg' import { Avatar, TAP44 } from './ui' @@ -44,7 +45,7 @@ function slotWord(iso: string) { function useRefreshTalks() { const queryClient = useQueryClient() - return () => queryClient.invalidateQueries({ queryKey: [{ _id: 'listTalks' }] }) + return () => queryClient.invalidateQueries({ predicate: (q) => ['listTalks', 'listMyTalks'].includes((q.queryKey[0] as { _id?: string } | undefined)?._id ?? '') }) } function Composer({ onDone }: { onDone?: (t: TalkData) => void }) { @@ -158,7 +159,8 @@ function Composer({ onDone }: { onDone?: (t: TalkData) => void }) { ) } -function TalkRow({ t }: { t: TalkData }) { +/** onGone: 내 글을 지웠을 때. 목록을 다시 받아도 빠지지 않는 곳(방금 쓴 글)에서 직접 뺀다 */ +function TalkRow({ t, onGone }: { t: TalkData; onGone?: () => void }) { const { loggedIn } = useAuth() const { open } = useSheet() const refresh = useRefreshTalks() @@ -225,7 +227,7 @@ function TalkRow({ t }: { t: TalkData }) { {menu === 'done' ? ( 처리했어요 ) : t.mine ? ( - ) : menu === 'report' ? ( @@ -270,10 +272,31 @@ export function FeedComposer({ onPosted }: { onPosted: (t: TalkData) => void }) } /** 피드에 끼우는 글 한 장 */ -export function TalkCard({ t }: { t: TalkData }) { +export function TalkCard({ t, onGone }: { t: TalkData; onGone?: () => void }) { return (
- +
) } + +/** 내 정보 창의 내가 쓴 글 */ +export function MyTalks() { + const { talks, loaded, more, loadMore } = useMyTalks() + if (!loaded) return null + return ( +
+

내 글

+ {talks.length ? ( + talks.map((t) => ) + ) : ( +

아직 쓴 글이 없어요

+ )} + {more && ( + + )} +
+ ) +} diff --git a/frontend/src/b/talkState.ts b/frontend/src/b/talkState.ts index 82fd87c..9614e73 100644 --- a/frontend/src/b/talkState.ts +++ b/frontend/src/b/talkState.ts @@ -1,12 +1,33 @@ import { useInfiniteQuery } from '@tanstack/react-query' -import { listTalksInfiniteOptions } from '../api/client/@tanstack/react-query.gen' +import { listMyTalksInfiniteOptions, listTalksInfiniteOptions } from '../api/client/@tanstack/react-query.gen' +import { useRegion } from './regionContext' -/** 사람들이 쓴 글. 오늘 피드에 운영 포스트 사이사이 섞는다 */ +/** 사람들이 쓴 글. 오늘 피드에 운영 포스트 사이사이 섞고, 남은 글은 피드 끝에 이어 붙인다 */ export function useFeedTalks() { + const { region } = useRegion() const list = useInfiniteQuery({ - ...listTalksInfiniteOptions(), + ...listTalksInfiniteOptions({ query: { region: region.code } }), initialPageParam: {}, getNextPageParam: (last) => last.next_cursor ?? undefined, }) - return list.data?.pages.flatMap((p) => p.talks ?? []) ?? [] + return { + talks: list.data?.pages.flatMap((p) => p.talks ?? []) ?? [], + more: list.hasNextPage && !list.isFetchingNextPage, + loadMore: list.fetchNextPage, + } +} + +/** 내가 쓴 글 (최신순) */ +export function useMyTalks() { + const list = useInfiniteQuery({ + ...listMyTalksInfiniteOptions(), + 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, + } }