Compare commits

..
Author SHA1 Message Date
minaChoi 03ad57bcaa Merge branch 'docs/todo-after-merge' — TODO 병합 상태 2026-10-28 15:28:48 +09:00
minaChoi 8a18ddc515 docs: TODO 오늘 타로·계정 레벨 병합 상태, 옛 날씨 사주 행 정리 2026-10-28 15:28:48 +09:00
minaChoi ab6959ee0f Merge branch 'feat/today-card' — 오늘 한 장(타로·행운·체크인), 오늘 탭 아이콘 줄, 계정 레벨(각) 2026-10-28 15:28:07 +09:00
minaChoi 71974dcf42 feat: 계정 레벨 — 날씨각에서 한 일로 각을 모아 레벨업, 레벨로 새 콘텐츠가 열림
- 각: 출석 10, 오늘 타로 10, 날씨 사주 10, 좋아요·댓글 5씩(하루 10), 동네 이야기 글 20, 저녁 체크인 10, 공유 10, 7일 연속 50. 같은 날 같은 대상은 한 번 (point_log)
- 레벨: 모은 총량으로 이슬 0 → 햇살 30 → 산들바람 100 → 무지개 200 → 노을 400 → 은하수 700 → 별똥별 1000. 지금 있는 기능은 잠그지 않음
- API: GET /v1/level/me, POST /v1/level/attend, POST /v1/level/share
- 화면: 헤더 아바타 레벨 배지, 내 정보 레벨 카드, 내 레벨 창(오늘 받을 각·레벨별로 열리는 것), 레벨이 오르면 축하 창
- 로그인한 사람만 쌓임 (기기 기록은 조작할 수 있어 받지 않음)
2026-10-28 14:45:44 +09:00
minaChoi 045d8d6cf0 feat: 오늘 탭 아이콘 줄 — 오늘 타로·오늘 코디는 창으로, 단풍 지도·쇼츠·동네 이야기는 페이지로, 내 각은 그 줄로
- 오늘 한 장 칸을 오늘 타로 창으로 옮김. 안 뽑았으면 빨간 점, 뽑았으면 n일째 (로그인 안 하면 기기 기록으로 계산)
- 오늘 코디: 오늘 피드에 올린 코디 카드를 창으로 (GET /v1/card/latest?template=ootd), 오늘 처음 보면 빨간 점
- 단풍 지도 아이콘은 단풍철에만, 아이콘 4개 추가 (Fluent 3D)
- GA4 today_icon
2026-10-28 14:37:55 +09:00
minaChoi 44146888d3 Merge branch 'docs/saju-rules' — TODO 날씨 사주 해석 기준 2026-10-28 14:32:58 +09:00
minaChoi 13bb3d9a02 docs: TODO 날씨 사주 해석 기준(사용자 위임) 기록 2026-10-28 14:32:58 +09:00
minaChoi 0a46fd71c2 Merge branch 'docs/level-decision' — TODO 계정 레벨·날씨 사주 2026-10-28 14:29:59 +09:00
minaChoi cbee7cd807 docs: TODO 계정 레벨 결정(레벨 제도, 단위 각)과 날씨 사주 남은 결정 2026-10-28 14:29:59 +09:00
minaChoi c37773f48f feat: 오늘 한 장 — 하루 한 장 날씨 카드(22장)·실제 날씨 행운·연속 도장·저녁 체크인
- 로그인 안 하면 기기에, 로그인하면 계정에 남기고 로그인할 때 기기 기록을 옮긴다 (표 fortune_draw·day_log)
- 행운 시간은 오늘 남은 구간 중 날씨 점수가 가장 높은 때, 장소는 날씨 맞춤 데이트 명소, 1위 각은 지금 순위
- 체크인은 해 지기 2시간 전부터: 기분·다녀온 곳(명소·노을 명소·지금 하는 행사에서 찾거나 직접)·카드 맞았나
- GA4 fortune_draw·day_log
2026-10-28 13:22:55 +09:00
minaChoi 52a4830b08 Merge branch 'docs/fortune-decision' — TODO 오늘 한 장 결정 2026-10-28 11:50:01 +09:00
minaChoi e154242c32 docs: TODO '오늘 한 장' 결정 — 뽑기+행운+기록, 저녁 체크인 최소판 2026-10-28 11:50:01 +09:00
minaChoi 728b24a0c9 feat: 새 기능 GA4 이벤트 — 창 열기·좋아요·댓글·신고·차단·약관 동의·이야기 글쓰기·히어로 오늘/내일·쇼츠·단풍 지도·내 각·토스 인트로·설치 띠 닫기 2026-10-28 11:25:58 +09:00
minaChoi 1489030c5f Merge branch 'docs/weather-fortune-1028' — TODO 날씨 운세 행 2026-10-28 11:21:04 +09:00
minaChoi 430f97131b docs: TODO '오늘 한 장' 행에 날씨 운세 추천 구성과 정할 것 2026-10-28 11:21:04 +09:00
minaChoi 1d6bb1e630 Merge branch 'docs/market-review-1028' — TODO 시장성 진단 7줄 2026-10-28 11:05:22 +09:00
minaChoi 001e163b2a docs: TODO 에 10/28 시장성 진단 결정 5건·첫 화면 기온 어긋남·GA4 측정 2026-10-28 11:05:16 +09:00
minaChoi 1ec87a82c1 feat: 인스타 장기 토큰을 갱신해 .env 에 넣고 backend·worker 를 다시 만드는 스크립트 (킹서버 cron 매달 1·15일) 2026-10-28 10:51:37 +09:00
minaChoi 5a1d464196 docs: 10/28 연애 타로 행운 포인트 고쳐 다시 게시 기록 2026-10-28 10:29:03 +09:00
minaChoi 571ff84b0c Merge remote-tracking branch 'origin/main' into sns 2026-10-28 10:21:00 +09:00
minaChoi ab9674eaa2 docs: 10/28 연애 타로 게시 기록 2026-10-28 10:19:50 +09:00
minaChoi 685a65faa5 Merge branch 'feat/youtube-shorts' — TODO 4줄 2026-10-28 09:49:16 +09:00
minaChoi 6ed6c14adc Merge branch 'fix/boot-retry' — 로딩 화면 멈춤 재시도 2026-10-28 09:41:53 +09:00
minaChoi ac16b098ba fix: 예전 탭을 다시 열면 '날씨 불러오는 중'에서 멈추던 문제 — 한 번만 새로고침하던 것을 첫 화면이 남아 있는 동안 계속(파일 실패·12초마다·탭 다시 볼 때·망 복구 때, 10초 간격) 다시 시도, 개발 서버 main.tsx 실패도 감지 2026-10-28 09:41:53 +09:00
minaChoi 5ee25551ea docs: 10/28 철회한 코디 포스트 4903 삭제 기록 2026-10-28 09:38:08 +09:00
minaChoi 1ae81ac25c docs: 10/28 세미정장 코디 다시 게시 기록 2026-10-28 09:33:58 +09:00
minaChoi 1ca680f006 feat: 그날 코디 — 미리 확인받은 picks.json 이 있으면 스냅을 다시 고르지 않고 그 코디로 그린다 2026-10-28 09:31:46 +09:00
minaChoi 9544674e7f Merge remote-tracking branch 'origin/main' into sns 2026-10-28 09:22:14 +09:00
minaChoi 3c81976998 docs: 10/27 단풍 카드뉴스·10/28 세미정장 코디 게시 기록 2026-10-28 09:22:11 +09:00
minaChoi 8709bfba2a docs: TODO 에 쇼츠 멈춤 버튼·토스 ait 브랜치·행사 주소·순서 의존 테스트 2026-10-28 08:56:43 +09:00
minaChoi 7f5441a512 Merge branch 'feat/youtube-shorts' — 사파리 쇼츠 시작 영상 2026-10-27 20:03:27 +09:00
minaChoi 694ea85ed3 fix: 아이폰 사파리에서 쇼츠를 누르면 첫 영상부터 열리던 문제 — 시작 영상으로 옮긴 뒤 한 번 더 맞추고, 옮기기 전엔 보이는 칸 변화를 무시 2026-10-27 20:03:27 +09:00
minaChoi ef61a5bf73 Merge branch 'feat/youtube-shorts' — 쇼츠 멈춤 없앰 2026-10-27 19:56:06 +09:00
minaChoi 74805aa829 fix: 쇼츠에서 멈춤 명령을 없앰 — 앞뒤 영상은 소리 없이 계속 틀어 두고 넘어오면 처음부터, 톡 누르면 릴스처럼 소리 켜기·끄기 (멈췄다 틀면 유튜브가 재생·멈춤 버튼을 띄워서) 2026-10-27 19:56:06 +09:00
minaChoi 5f79df1973 Merge branch 'feat/youtube-shorts' — 쇼츠 줄 재생 버튼 숨김 2026-10-27 19:45:41 +09:00
minaChoi 942b652e56 fix: 오늘 화면 쇼츠 줄 첫 카드도 재생이 시작된 뒤에만 영상을 보임 — 자동재생이 막히면 유튜브 재생 버튼 대신 표지 2026-10-27 19:45:41 +09:00
minaChoi f24e790bd7 Merge branch 'feat/youtube-shorts' — 쇼츠 토스판과 같은 코드 2026-10-27 19:30:15 +09:00
minaChoi d38cfc7229 fix: 쇼츠 코드를 토스판과 같게 — 토스도 앞뒤 미리 받기·소리 없이 자동재생, 재생 신호가 안 오는 토스만 1초 뒤 영상을 보임 (웹 동작은 그대로) 2026-10-27 19:30:15 +09:00
minaChoi b346af7fef Merge branch 'feat/youtube-shorts' — 단풍 지도 포스트 맨 앞 2026-10-27 19:05:34 +09:00
minaChoi 340b30cc8b fix: 단풍 지도를 피드 맨 위가 아니라 포스트 맨 앞으로 — 쇼츠·글쓰기·오늘의 각은 원래 자리 2026-10-27 19:05:33 +09:00
minaChoi fd67c2b45f Merge branch 'feat/youtube-shorts' — 내 각 개편, 이야기 내 글·무한 스크롤, 공유 이미지 얇은 띠, 행사 주소 2026-10-27 18:55:43 +09:00
minaChoi ffe6153148 feat: 내 각 아이콘·상세, 이야기 내 글·무한 스크롤, 공유 이미지 얇은 띠, 행사 주소 수집
- 내 각: 아이콘 고르기(my_gak.icon), 카드는 아이콘·점수·아쉬운 조건만, 눌러서 상세(시간대·조건별 점수), 공유는 공통 공유 창
- 이야기: 오늘 쓴 내 글 묶음, '내 글' 칩·탭, 무한 스크롤, 사진 카메라 버튼, 지우기 확인, ⋯ 메뉴 하트 옆, 글 시간 서버 계산(1일 전)
- 공유 이미지: 1:1·4:5 는 아래 얇은 띠 한 줄로 카드를 크게
- 행사: 수집 때 주소 저장(event.address), 행사 포스트에 장소·주소·기간
- 히어로 말풍선 '오늘 낮은 / 내일 낮은', 내일을 볼 때 배경도 따라감, 달 보름 순간이 낮이면 뜨는 시각으로
- 단풍 지도 피드 맨 위, 행사·계절 띠 포스트 틀 되돌림, 쇼츠 홈 버튼 가림·닫기 버튼, 하단 여백, 회색 글자 대비
- 토스 앱에선 쇼츠 플레이어를 하나만 띄움
2026-10-27 18:55:42 +09:00
minaChoi 3a249c509d Merge branch 'feat/youtube-shorts' — 각 포스트 오늘·내일·주말 점수, 밤 화면 포스트 색, 동네 글 묶음 1개부터 (1557ba4)
겹친 곳: 히어로 아이콘 간격은 main 방식(버튼 좌우 5px) 하나로, 달 포스트는 밤하늘·행사는 사진 있을 때만 밤하늘, 토스에선 첫 이야기 카드 숨김 유지
2026-10-27 16:26:31 +09:00
minaChoi 55edc037fb Merge branch 'revert/write-login-once' — 쓰기 버튼 로그인 창 누를 때마다 2026-10-27 15:48:37 +09:00
minaChoi a17cef201d fix: 쓰기 버튼 로그인 창을 다시 누를 때마다 띄우기 — '한 번만 띄우고 안내 흔들기'(0bc8ca0)를 되돌림 2026-10-27 15:47:14 +09:00
minaChoi 0414160520 Merge branch 'fix/write-login-once' — 쓰기 버튼 로그인 창은 한 번만 2026-10-27 15:41:58 +09:00
minaChoi 0bc8ca02a4 fix: 쓰기 버튼(쓰기 칸·사진·올리기·첫 이야기 카드)으로 뜨는 로그인 창은 이번 방문에 한 번만 — 닫은 뒤엔 '로그인하면 쓸 수 있어요'만 흔들어 알림 2026-10-27 15:41:57 +09:00
minaChoi 1557ba42c4 fix: 각 포스트·밤 화면·히어로 아이콘·동네 글 묶음 손봄
- 각 포스트: 각마다 같던 근거 표·요약 줄을 빼고 오늘·내일·주말 점수 칸(각 상세와 같은 값), 작은 화면에서 점수·그림 줄임
- 밤 화면에서도 포스트 본문은 낮 색 그대로, 어두운 각 배경(캠핑·별보기·산책)과 행사 밤하늘 배경 뺌
- 히어로 좋아요·댓글·보내기 간격·높이 맞춤
- 동네 사람들 묶음을 글 1개부터 보이게 (3개 미만이면 자기 글도 안 보이던 문제)
- QA 체크리스트에 쇼츠·각 포스트 결과, TODO 에 쇼츠 공유 링크 빈 화면
2026-10-27 15:20:35 +09:00
minaChoi 9af3407546 Merge branch 'fix/sheet-slide' — 아래 창 열기·닫기 애니메이션 2026-10-27 15:08:40 +09:00
minaChoi 117de90c3e fix: 아래 창(로그인 등)이 열리고 닫힐 때 버벅여 보이던 것 — 반투명으로 40px만 올라와 뒤 탭 바가 비쳤고 닫힐 땐 툭 사라지며 쓰기 칸 테두리가 번쩍였음, 불투명하게 아래에서 끝까지 올라오고 내려가며 닫히게 2026-10-27 15:08:40 +09:00
minaChoi be60551f49 Merge branch 'fix/composer-login-no-keyboard' — 로그인 전 쓰기 칸은 키보드 없이 로그인 창 2026-10-27 14:55:46 +09:00
minaChoi dcf2fe5a53 fix: 로그인 안 한 채 쓰기 칸을 누르면 로그인 창이 버벅이던 것 — 칸에 포커스가 가며 키보드가 떴다 내려갔음, 로그인 전엔 읽기 전용으로 두고 누르면 로그인 창 2026-10-27 14:55:46 +09:00
minaChoi 132301dc28 Merge branch 'fix/google-button-skeleton' — 로그인 창 구글 버튼 스켈레톤 2026-10-27 14:49:42 +09:00
minaChoi dd133c9d52 fix: 로그인 창 구글 버튼 자리에 스켈레톤 — 빈칸에 버튼이 늦게 툭 튀어나와 버벅이는 것처럼 보이던 것, 다 그려지면 부드럽게 바꿔 보임 2026-10-27 14:49:41 +09:00
minaChoi 5459b97ba0 Merge branch 'fix/foliage-card-slide2' — 단풍 카드 2번째 장 가림, 히어로 아이콘 간격, 로그인 창 첫 열기 버벅임, 토스 글 종류 필터 되돌림 2026-10-27 14:40:33 +09:00
minaChoi 1908433e46 fix: 토스에서 가리던 글 종류(카드뉴스 등) 다시 보이게 — 토스 번들이 업데이트돼 d3d872b 필터를 되돌림 2026-10-27 14:40:33 +09:00
minaChoi 7dcd6c6a4c fix: 로그인 창을 처음 열 때 버벅이던 것 줄임 — 구글 로그인 스크립트는 한가할 때 미리 받고, 구글 버튼과 뒤 화면 멈추기는 창이 다 올라온 뒤에 2026-10-27 14:39:41 +09:00
minaChoi 7d84226105 fix: 히어로 하트·댓글·보내기 간격이 숫자가 붙으면 어긋나던 문제 — 버튼마다 좌우 여백을 같게 2026-10-27 14:39:41 +09:00
minaChoi c45940c358 fix: 피드 단풍 지도 카드 2번째 장(지금 가기 좋은 곳) 왼쪽이 가려지던 문제 — 가운데 맞추려 민 지도가 옆 장을 덮었음, 1번째 장 밖은 자름 2026-10-27 14:29:34 +09:00
minaChoi 09e8b4734a Merge branch 'feat/app-moon-bot' — 앱 히어로·달 포스트 실제 달 모양, 캐릭터 댓글 표시 2026-10-27 14:05:03 +09:00
minaChoi a87f245547 feat: 앱도 웹과 같이 — 히어로·달 포스트를 오늘 밤 실제 달 모양으로(저녁엔 노을빛, 어두운 달이면 흰 점수), 캐릭터 댓글에 '날씨각' 표시·신고 메뉴 없음 2026-10-27 14:05:03 +09:00
minaChoi 197fafdc02 Merge branch 'fix/login-sheet-loop' — 로그인 안 한 채 쓰기 칸 누르면 로그인 창이 닫혀도 다시 열리던 문제 2026-10-27 13:25:43 +09:00
minaChoi 65fd9b8fb1 fix: 로그인 안 한 채 동네 이야기 쓰기 칸을 누르면 로그인 창이 닫혀도 다시 열리던 문제 — 창이 포커스를 쓰기 칸으로 돌려놓아 반복됐음, 열기 전에 포커스를 뺌 2026-10-27 13:20:14 +09:00
minaChoi 668377660c Merge branch 'feat/moon-bot-comments' — 달 포스트·히어로 실제 달 모양, 날씨각 캐릭터 댓글, 홈 화면 추가 띠, 남이섬 중복·날짜 테스트 2026-10-27 13:17:34 +09:00
minaChoi 694757b2fb feat: 서울 근교 단풍 TOP 10 카드뉴스 템플릿(foliage, 5장) — 관광공사 1유형 사진, 앱 단풍 지도 캡처, 날짜 대신 이번 주/다음 주 절정 2026-10-27 11:59:22 +09:00
132 changed files with 4266 additions and 447 deletions

No files matched your search

+24
View File
@@ -62,6 +62,11 @@
| [ ] | 오늘 화면 쇼츠 줄 — YouTube Data API 키(`YOUTUBE_API_KEY`) 발급해 운영 .env 에 넣기. 없으면 `youtube_shorts`(영상 ID 3개 고정)만 나와 새 쇼츠가 자동으로 안 붙음 (https://console.cloud.google.com/apis/library/youtube.googleapis.com) | 채널 RSS가 404라 키 없이 채널 목록을 못 받음 | `backend/config/settings.py`, `backend/services/shorts_service.py` |
| [ ] | **[결정 필요]** 쇼츠 문구 검토: '소리 켜기'/'소리 끄기' (줄 제목은 없앰) | 화면 문구 규칙 | `frontend/src/b/Shorts.tsx` |
| [ ] | 쇼츠를 올린 직후 목록 갱신(`ShortsService.refresh`) 부르기 — 지금은 워커가 07·12·18시 10분에만 받아 18시 넘어 올리면 다음 날 아침에 뜸. 자동 업로드면 끝난 뒤 호출, 손으로 올리면 관리자 갱신 API | 올리는 방식 확인 필요 | `backend/services/shorts_service.py`, `backend/worker_main.py` |
| [ ] | 쇼츠 API 실패·빈 목록일 때 공유 링크로 들어오면 남색 빈 화면만 보임 — 그 영상 ID 하나라도 띄우거나 × 버튼·안내 문구 보이기 | 10/27 QA 실패 (`items` 가 비면 빈 div 만 그림) | `frontend/src/b/Shorts.tsx` |
| [ ] | **[결정 필요]** 쇼츠 폰에서 유튜브 멈춤(\|\|) 버튼이 계속 남음 — 유튜브 플레이어 자체 버튼이라 코드로 못 지움. 우리 쇼츠 원본 mp4를 저장소에 올려 <video>로 틀지, 폰 연결해 유튜브로 더 시도할지 | 10/27 실기기 보고, 크롬·WebKit 흉내에선 재현 안 됨 | `frontend/src/b/Shorts.tsx` |
| [ ] | 토스 ait 는 `feat/apps-in-toss` 브랜치(~/orca/workspaces/o2o-weather/main-3)에서 만들기 — main 에는 토스 로그인·웹뷰 자동재생·쇼츠 토스 처리가 없음. 최신 ait 20:03 콘솔 업로드 필요 | 10/27 main 에서 만든 ait 로 쇼츠가 멈춰 보임 | `~/orca/workspaces/o2o-weather/main-3/frontend/nalssigak.ait` |
| [ ] | 운영 행사 주소(event.address) 채우기 — 팝가가 연속 요청을 막아(429) 로컬도 206개 중 80개만. 간격 두고 다시 | 10/27 주소 수집 추가 | `backend/scheduler/jobs.py` `refresh_popups` |
| [ ] | `test_watch_summary_flags_thunder_within_2_hours` 가 전체로 돌릴 때만 실패(따로 돌리면 통과) — 순서 의존 원인 찾기 | 10/27 전체 테스트 | `backend/tests/test_watch.py` |
| [ ] | 쇼츠 자동재생 아이폰 사파리 실기기 확인 — 소리 꺼도 자동재생을 막는다는 보고 있음 | 헤드리스 크롬에서만 확인 | `frontend/src/b/Shorts.tsx` |
| [x] | 단풍 명소 `남이섬`이 두 번 들어감(절정 10-25·10-27) — 10-27(화목원) 쪽 지움, 67곳 | 10/27 전체 점검 | `frontend/seo/foliage_2026.json` |
| [x] | 날짜 따라 깨지던 테스트 2개 — 노을 칸은 그날 해 지는 시각으로, 방위각은 한 해 범위(240~300°)로 확인 | 10/27 전체 점검 | `backend/tests/test_weather_today.py`, `backend/tests/test_sky_api.py` |
@@ -79,6 +84,21 @@
| [ ] | 익명 댓글이 링크·하루 제한에 걸려도 '댓글을 올리지 못했어요'만 나옴 — 이유별 안내 | 익명 댓글 작업 중 발견 | `frontend/src/b/Sheets.tsx` |
| [ ] | 매일 대표에게 진행 보고 (미완료 포함) | 10/21 회의 결정 | |
## 10/28 시장성 진단 (보고서는 채팅 첨부, 근거: 운영 DB 집계·첫 화면 캡처·회의록)
| 상태 | 할 일 | 이유 | 관련 파일 |
|---|---|---|---|
| [ ] | **[결정 필요]** 타깃을 2030 직장인으로 좁히기 — 기능은 지우지 않고 첫 화면·각 순서만 이 사람 기준으로. 9/29 '타깃 정하지 않음'을 바꾸는 일이라 대표 결정 | 콘텐츠가 2030·4050·반려인·동네 주민으로 흩어져 누구에게도 1순위가 아님 | `frontend/src/b/TodayPage.tsx`, `backend/services/feed_service.py` |
| [ ] | 오늘 타로(오늘 한 장) — main 병합(10/28): 오늘 탭 아이콘 줄 → 오늘 타로 창. 타로 22장 하루 1장 + 행운(시간·장소·색·1위 각) + 연속 도장 + 저녁 체크인. 남은 것: 배포(운영 init.sql 로 표 fortune_draw·day_log·point_log, users.points 생김), 토스 ait(`feat/apps-in-toss`에 main 합친 뒤) | 10/28 사용자 결정 | `frontend/src/b/fortune.tsx`, `frontend/src/b/todayIcons.tsx` |
| [ ] | **[결정 필요]** 아침 7시 웹 푸시 — 안드로이드 크롬은 바로, 아이폰은 홈 화면에 추가한 사람만(iOS 16.4+). 앱 위젯(10/21 결정)은 계속 | 다시 부르는 장치가 없음(코드에 웹 푸시 없음) → DAU가 쌓이지 않음 | `frontend/public/sw.js`, `frontend/src/b/install.ts` |
| [ ] | **[결정 필요]** 좋아요·댓글 0이면 숫자 숨기기, 동네 이야기는 그날 글이 몇 개 넘을 때만 위에 | 첫 화면 '좋아요 0개'·동네 글 1개가 "아무도 안 쓴다"는 신호 | `frontend/src/b/TodayPage.tsx`, `frontend/src/b/talk.tsx` |
| [ ] | **[결정 필요]** 4주 새 기능 동결 목록 — 후보: 나만의 각 피드 올리기, 동네 이야기 사진, 캐시워크·통신사 위젯, 새 각 추가, 지역 페이지 추가 확장(10/21 '모든 지역 추가'와 충돌) | 2명이 기능 폭을 넓히는 중, 바깥 사용자 반응은 거의 없음(계정 7개 대부분 팀 추정) | |
| [ ] | 첫 화면에 '지금 10°'(시간대 줄)와 '오전 10시 5°'(히어로 문장·오늘의 각)가 함께 보임 — 원인 확인(체감온도인지). 오늘의 각 5줄 설명도 모두 같은 문장 | 10/28 11시 운영 캡처(마포구), 숫자 어긋나면 첫 방문자 신뢰 잃음 | `frontend/src/b/TodayPage.tsx` |
| [ ] | GA4 사내 IP 제외 필터 + 주간 지표 4개(신규 방문, 1일·7일 재방문, 공유→방문, 홈 화면 추가→알림 허용) | 바깥 사용자 수를 아무도 모름, 이게 없으면 진단이 가설로 남음 | `docs/이벤트_추적.md` |
| [ ] | 계정 레벨 — main 병합(10/28, 배포 남음). 사용자 결정 10/28: **레벨 제도**(포인트 소비형 아님). 단위는 '각'(출석 +10각 등 서비스 전체 행동으로 적립), 레벨은 모은 총량 기준이라 나중에 각을 쓰는 기능을 붙여도 안 내려감. 지금 있는 기능·캐릭터·색·기분은 잠그지 않고, 새로 생기는 것(날씨 사주 연애운·궁합 등, 새 캐릭터·테두리, 댓글 레벨 배지)만 레벨로 열림. 내 정보는 기존 화면에 레벨·각만 더함. 정할 것: 레벨 이름·단계·필요 각, 행동별 각·하루 한도, 해금 목록 | 기획서 '계정 레벨(각)·날씨 사주 UI 기획'(10/28 채팅 첨부) | `frontend/src/b/Sheets.tsx` `MeSheet` |
| [ ] | 날씨 사주 해석 기준 — 사용자가 맡김(10/28 "니 알아서 하라"), 바꿀 수 있게 기록: 날씨 접목은 조후(한난조습) · 연애운은 열 때 성별 선택 입력(남/여/선택 안 함, 안 하면 도화·배우자궁만으로 본다고 표시) · 도화는 연지·일지 삼합 둘 다 · 홍염은 일간표(甲乙午 丙寅 丁未 戊己辰 庚戌 辛酉 壬子 癸申, 이견 있음 표시) · 합충형파해원진은 원국 네 지지 모두, 일지에 걸리면 연애 가중 · 절입 시각은 천문 계산식으로 1900~2100 표를 만들고 천문연 값으로 검증(패키지 안 씀) · 진태양시(출생지 경도)·서머타임 반영, 자시는 자정 기준(설정으로 변경) · 음력은 다음 단계(천문연 API) | 사용자 위임 10/28 | |
| [ ] | **[결정 필요]** 날씨 사주 화면·문구 — '내 기운'(계절·날씨 장면 16종), 점수 → 사주 풀이 → 계절·날씨 한 스푼, 하루 풀이를 '오늘의 결정 카드'(언제·미룰 것·입을 것/갈 곳·이번 주 날짜)로 줄지, 규칙별 의미 사전·문구 검토, 기운 장면 그림 | 사용자 피드백 10/28 | 기획서 '날씨 사주 기획 v2', '계정 레벨·날씨 사주 UI 기획' |
## 진행 순서
결정이 필요 없는 것부터, 사용자 눈에 틀린 정보가 보이는 것 → 기능 → 다듬기 순.
@@ -300,6 +320,10 @@
| [x] | 10/27 주식 타로(경제 전용 카드: 분할매수각·적금각·배당각) — 킹서버 카드 21→포스트 4591, 인스타 https://www.instagram.com/p/De-qodJAXp9/ | 사용자 요청 (10/27) | `admin/topics.json` |
| [x] | 10/27 스트릿 코디(철회: 겉옷 없는 사람 2명·남성적이라는 피드백, 포스트 4588 숨김 필요·인스타 앱에서 삭제 필요) — 킹서버 카드 16→포스트 4588, 인스타 https://www.instagram.com/p/De-hDoVge1N/. 참고 스냅 f20 https://www.musinsa.com/snap/1554718501896708736 · m20 https://www.musinsa.com/snap/1561558258020785611 · f40 https://www.musinsa.com/snap/1552178778683619999 · m40 https://www.musinsa.com/snap/1549383828670555308. 사용자 요청으로 옷은 스냅에 태그된 무신사 상품만(사진에만 보이는 f20 레드 니트집업·m40 백팩 뺌). 에이블리는 공개 API 없음. 카드 15(고치기 전)는 승인 대기로 남음. 인스타 게시 API가 'Application request limit reached'를 돌려줬지만 실제 게시는 됨 | 사용자 요청 (10/27) | `admin/scripts/outfit.mjs`, `snap.mjs` |
| [x] | 10/27 캐주얼 코디(스트릿 대체) — 킹서버 카드 19→포스트 4589, 인스타 https://www.instagram.com/p/De-oLGagZRB/. 참고 스냅 f20 https://www.musinsa.com/snap/1555508873710779888 · m20 https://www.musinsa.com/snap/1555156725005269012 · f40 https://www.musinsa.com/snap/1555157672544679299 · m40 https://www.musinsa.com/snap/1552193811640384198. 구간을 아침 체감·낮 최고 평균으로 정해 chilly, 쌀쌀한 날 겉옷 필수·미니·뮬/슬링백 제외, 여자 코디는 고프코어 감점. 카드 15·16·17·18은 버린 판 | 사용자 요청 (10/27) | `admin/scripts/snap.mjs`, `daily-ootd.mjs` |
| [x] | 10/27 서울 근교 단풍 TOP 10 카드뉴스(매주 목요일 시리즈 첫 회) — 킹서버 카드 22→포스트 4592, 인스타 https://www.instagram.com/p/De-1vM_gVN8/. 캡션 첫 줄에 제목이 두 번 나옴(서버가 제목을 붙이는데 캡션도 제목으로 시작), 인스타 API가 request limit을 돌려줘 ig_media_id 미기록 | 사용자 요청 (10/27) | `admin/src/cards/templates.tsx` |
| [x] | 10/28 세미정장 코디(철회: 20-30대 남자에 나팔바지라는 피드백, 포스트 4903 10/28 삭제함(deleted=true)·인스타 앱에서 삭제 필요) — 킹서버 카드 23→포스트 4903, 인스타 https://www.instagram.com/p/DfBIhUdAbbV/. 참고 스냅 f20 https://www.musinsa.com/snap/1560205304641814679 · m20 https://www.musinsa.com/snap/1551785083122597386 · f40 https://www.musinsa.com/snap/1551572173880406114 · m40 https://www.musinsa.com/snap/1556284432455808475. 4장 1:1 검수. 크롬이 2번째 장 렌더에서 멈춰 장마다 프로필을 따로 써서 다시 찍음, 인스타 API는 request limit을 돌려줬지만 실제 게시됨(ig_media_id 미기록) | 사용자 요청 (10/28) | `admin/scripts/card.mjs` |
| [x] | 10/28 세미정장 코디 다시(20-30대 남자만 교체: 오피서 코트·헨리넥 니트·다크 브라운 와이드 팬츠·헤비 부츠·토트백, 코디 구성을 먼저 확인받고 그림) — 킹서버 카드 24→포스트 4904, 인스타 https://www.instagram.com/p/DfBJ4SlAaok/. 참고 스냅 m20 https://www.musinsa.com/snap/1562338908609136514 (나머지 3명은 카드 23과 같음). 첫 그림은 상품 썸네일을 따라 바지가 베이지로 나와 스냅 색(브라운)으로 다시 그림 | 사용자 요청 (10/28) | `admin/scripts/daily-ootd.mjs` |
| [x] | 10/28 연애 타로(단풍각·데이트각·별보기각, 새 표지: 주제 배지 + 큰 질문) — 킹서버 카드 26→포스트 4906, 인스타 https://www.instagram.com/p/DfBQCW0ARgL/ (ig_media_id 17953447719320497). 처음 올린 카드 25→포스트 4905(인스타 DfBPIHJAR0m)는 행운 포인트가 날씨 정보뿐이라는 피드백으로 철회: 포스트 4905 deleted=true, 인스타 글은 앱에서 삭제됨. 행운 포인트를 "시각 · 행운 아이템"(리딩 속 행동에 쓰는 물건)으로 바꿔 다시 게시. 문구를 먼저 확인받음: 첫 기획의 행운 포인트(6시 1도·10시 바람)를 예보 slot 값으로 고치고, 연애와 관련 없는 카드(해돋이각·테니스각)를 데이트각·별보기각으로 바꿈. 5장 1:1 검수. 인스타 API는 두 번 다 request limit을 돌려줬지만 실제 게시됨(최신 글 확인 후 재시도 안 함) | 사용자 요청 (10/28) | `admin/src/cards/templates.tsx`, `admin/scripts/plan.mjs` |
| [x] | 각 카드 그림 미리 생성 — 가을에 나올 만한 28장(피크닉·캠핑·놀이공원·빨래·단풍·억새·테니스·골프·군고구마·붕어빵·군밤·사진산책·별보기·환기·세차·이불빨래·데이트·치맥·막걸리·파전·우산·넷플릭스·집콕·한강밤바람·멍뭉산책·센치·감성노래·낚시) + 기존 8 = 36/68. 여름·한겨울 전용 32장은 철 되면 생성 | 사용자 요청 (10/26) | `admin/src/assets/gak-card/` |
| [ ] | 카드 자동화 다음 단계 — ① 생성 직후 자동 검사(Claude 비전: 옷 개수·사람·글자·추가 옷, 불합격 1회 재생성) ② 승인 대기 카드 메일/Teams 알림 + 서명 토큰 승인 링크(`GET /v1/card/{id}/approve`) ③ 맥 launchd 매일 06:30 `claude -p "/daily-cards"` ④ 그림 세트가 차면 킹서버로 이전 | 사용자 요청 (10/26) | `backend/router/v1/card/card.py`, `admin/scripts/` |
| [ ] | 앱 헤더가 400~448px 폭에서 컨테이너를 넘쳐 로그인 버튼이 잘림(`frontend/src/b/BLayout.tsx` TopBar). 캡처는 456px로 찍어 피했지만 실제 폰(430·440px)에서도 잘릴 수 있음 | 10/24 캡처 중 발견 | `frontend/src/b/BLayout.tsx` |
+1 -1
View File
@@ -9,7 +9,7 @@ import { execFileSync } from 'node:child_process'
import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
import { resolve } from 'node:path'
const SLIDES = { tarot: 5, ootd: 4, intro: 8 }
const SLIDES = { tarot: 5, ootd: 4, intro: 8, foliage: 5 }
// 기본 문구가 서비스 데이터 그대로라 Claude 기획이 꼭 필요한 템플릿 (src/cards/templates.tsx autoPlan)
const AUTO_PLAN = ['tarot']
// src/cards/themes.ts THEMES 의 id
+4 -2
View File
@@ -1,6 +1,6 @@
// 그날 코디: 오늘 예보 → 무신사 인기 스냅에서 사람별 코디 선정 → Claude 가 옷 목록 추출 → Codex 가 참고 사진대로 플랫레이 그림 → 카드용 copy.
// 사용: node scripts/daily-ootd.mjs [--out out/<날짜>] (npm run card -- ootd --daily 가 부른다)
import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
import { join, resolve } from 'node:path'
import { drawWithCodex } from './codex-image.mjs'
import { extractOutfit } from './outfit.mjs'
@@ -63,7 +63,9 @@ export async function runDailyOotd({ outDir, style = 'minimal', log = console.lo
const weather = await weatherToday()
log(`오늘 ${weather.day}: 아침 ${weather.morningC}° · 낮 ${weather.maxC}° → 구간 ${weather.band} · 스타일 ${styleLabel}`)
mkdirSync(outDir, { recursive: true })
const picks = await pickSnaps({ band: weather.band, style, outDir: join(outDir, 'snaps'), log })
// 사용자가 먼저 확인한 코디(snap.mjs 가 쓴 picks.json)가 있으면 다시 고르지 않고 그대로 그린다
const picksFile = join(outDir, 'snaps', 'picks.json')
const picks = existsSync(picksFile) ? JSON.parse(readFileSync(picksFile, 'utf8')) : await pickSnaps({ band: weather.band, style, outDir: join(outDir, 'snaps'), log })
const dailyDir = resolve('public/daily')
mkdirSync(dailyDir, { recursive: true })
const outfits = []
Binary file not shown.

After

Width:  |  Height:  |  Size: 135 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 132 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 299 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 248 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 469 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 318 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 363 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 263 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 305 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 302 KiB

@@ -0,0 +1,125 @@
{
"source": "한국관광공사 관광사진(공공누리 제1유형, 출처표시)",
"spots": [
{
"file": "yongmunsa",
"name": "용문사 은행나무",
"region": "경기 양평",
"kind": "ginkgo",
"peak": "2026-10-29",
"photo": {
"title": "양평 용문사",
"by": "한국관광공사 김지호",
"shot": "2012.10"
}
},
{
"file": "namiseom",
"name": "남이섬",
"region": "강원 춘천",
"kind": "ginkgo",
"peak": "2026-10-27",
"photo": {
"title": "남이섬",
"by": "김효서",
"shot": "2023.11"
}
},
{
"file": "myeongnyundang",
"name": "성균관 명륜당",
"region": "서울 종로",
"kind": "ginkgo",
"peak": "2026-10-31",
"photo": {
"title": "성균관",
"by": "한국관광공사 박성근",
"shot": "2011.10"
}
},
{
"file": "gyeongbokgung",
"name": "경복궁",
"region": "서울 종로",
"kind": "maple",
"peak": "2026-11-02",
"photo": {
"title": "경복궁",
"by": "라이브스튜디오",
"shot": "2020.11"
}
},
{
"file": "namsan",
"name": "남산공원",
"region": "서울 중구",
"kind": "maple",
"peak": "2026-11-02",
"photo": {
"title": "남산성곽길",
"by": "한국관광공사 이범수",
"shot": "2011.11"
}
},
{
"file": "childrenpark",
"name": "어린이대공원",
"region": "서울 광진",
"kind": "maple",
"peak": "2026-11-02",
"photo": {
"title": "서울 어린이대공원",
"by": "최민희",
"shot": "2023.11"
}
},
{
"file": "changdeokgung",
"name": "창덕궁",
"region": "서울 종로",
"kind": "maple",
"peak": "2026-11-02",
"photo": {
"title": "창덕궁",
"by": "최린",
"shot": "2023.11"
}
},
{
"file": "deoksugung",
"name": "덕수궁 돌담길",
"region": "서울 중구",
"kind": "ginkgo",
"peak": "2026-11-04",
"photo": {
"title": "덕수궁",
"by": "한국관광공사 이범수",
"shot": "2019.11"
}
},
{
"file": "seoulforest",
"name": "서울숲",
"region": "서울 성동",
"kind": "ginkgo",
"peak": "2026-11-04",
"photo": {
"title": "서울숲",
"by": "임태원",
"shot": "2023.11"
}
},
{
"file": "mulhyanggi",
"name": "물향기수목원",
"region": "경기 오산",
"kind": "ginkgo",
"peak": "2026-11-06",
"photo": {
"title": "물향기수목원",
"by": "박아름",
"shot": "2025.10"
}
}
]
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 438 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 430 KiB

+48
View File
@@ -668,3 +668,51 @@
.intro-cta .intro-sub { top: 470px; font-size: 48px; color: var(--rust); }
.intro-cta .intro-note { left: 240px; right: 240px; text-align: center; }
.intro-cta .intro-note { top: 1250px; font-size: 36px; text-align: center; }
/* 서울 근교 단풍 TOP 10 */
.slide.foliage { background: #fff8eb; color: #322d32; }
.foliage .foliage-meta { position: absolute; top: 174px; left: 80px; color: #94694e; font-size: 32px; font-weight: 700; }
.foliage .foliage-title,
.foliage .foliage-list-title,
.foliage .foliage-cta-title { position: absolute; left: 80px; right: 80px; font-family: Jua, sans-serif; letter-spacing: -2px; }
.foliage .foliage-title { top: 222px; max-width: 920px; color: #b43e29; font-size: 96px; line-height: 1.04; }
.foliage .foliage-subtitle { position: absolute; top: 330px; left: 84px; right: 80px; color: #69584d; font-size: 38px; font-weight: 700; letter-spacing: -1px; }
.foliage-cover-panel,
.foliage-cta-panel { position: absolute; background: linear-gradient(140deg, #fbd0a0, #f5a96d 54%, #dd7657); border-radius: 64px; }
.foliage-cover-panel { left: 80px; right: 80px; top: 410px; bottom: 70px; }
.foliage .foliage-phone { position: absolute; overflow: hidden; box-sizing: content-box; width: 338px; aspect-ratio: 47 / 100; border: 15px solid #242327; border-radius: 53px; background: #fff; box-shadow: 0 28px 52px #59331c61, inset 0 0 0 2px #555; z-index: 2; }
.foliage .foliage-phone img { display: block; width: 100%; height: 100%; object-fit: contain; }
.foliage-cover .foliage-phone { top: 436px; left: 340px; width: 370px; transform: rotate(-4deg); }
.foliage .foliage-leaf { position: absolute; width: 110px; height: 110px; object-fit: contain; z-index: 1; filter: drop-shadow(0 12px 10px #963c2929); }
.foliage .foliage-leaf-a { top: 585px; left: 145px; transform: rotate(-21deg); }
.foliage .foliage-leaf-b { top: 725px; right: 150px; transform: rotate(18deg); }
.foliage .foliage-leaf-c { bottom: 132px; left: 165px; transform: rotate(15deg); }
.foliage .foliage-list-title { top: 229px; font-size: 80px; line-height: 1.05; }
.foliage .foliage-list-title em { font-style: normal; color: #c6462b; }
.foliage .foliage-board { position: absolute; left: 80px; right: 80px; top: 350px; bottom: 160px; display: grid; gap: 22px; }
.foliage-duo .foliage-board { grid-template-rows: repeat(2, minmax(0, 1fr)); }
.foliage-grid .foliage-board { grid-template-columns: repeat(2, minmax(0, 1fr)); grid-template-rows: repeat(2, minmax(0, 1fr)); }
.foliage .foliage-tile { position: relative; overflow: hidden; min-width: 0; border-radius: 38px; background: #aa7254; box-shadow: 0 12px 28px #5c382b26; }
.foliage .foliage-tile::after { content: ''; position: absolute; inset: 20% 0 0; background: linear-gradient(transparent 18%, #1c1719c4 76%, #120f11e8); }
.foliage .foliage-photo { display: block; width: 100%; height: 100%; object-fit: cover; }
.foliage .foliage-rank { position: absolute; top: 22px; left: 23px; z-index: 2; display: grid; place-items: center; width: 72px; height: 72px; border-radius: 22px; background: #fff9ec; color: #b43e29; font: 64px/1 Jua, sans-serif; box-shadow: 0 5px 15px #0003; }
.foliage .foliage-tile-copy { position: absolute; left: 28px; right: 20px; bottom: 24px; z-index: 2; color: #fff; }
.foliage .foliage-name { display: block; overflow: hidden; color: #fff; font: 72px/1.08 Jua, sans-serif; letter-spacing: -1.7px; white-space: nowrap; text-overflow: clip; }
.foliage-grid .foliage-name { font-size: 49px; letter-spacing: -2px; }
.foliage .foliage-facts { display: flex; align-items: center; gap: 12px; margin-top: 10px; color: #fff; font-size: 29px; font-weight: 750; white-space: nowrap; }
.foliage-grid .foliage-facts { gap: 7px; font-size: 22px; letter-spacing: -1px; }
.foliage .foliage-facts > span:not(:first-child)::before { content: '·'; margin-right: 12px; opacity: .8; }
.foliage-grid .foliage-facts > span:not(:first-child)::before { margin-right: 7px; }
.foliage .foliage-kind { display: inline-flex; align-items: center; gap: 3px; }
.foliage .foliage-kind img { width: 30px; height: 30px; object-fit: contain; }
.foliage-grid .foliage-kind img { width: 23px; height: 23px; }
.foliage .foliage-line { margin-top: 6px; color: #fff8ed; font-size: 30px; font-weight: 650; white-space: nowrap; }
.foliage .foliage-credit { position: absolute; left: 80px; right: 80px; bottom: 70px; color: #795e4d; font-size: 23px; font-weight: 600; line-height: 1.3; }
.foliage .foliage-cta-title { top: 220px; color: #b43e29; font-size: 82px; line-height: 1.1; }
.foliage .foliage-cta-body { position: absolute; left: 84px; right: 80px; top: 330px; color: #69584d; font-size: 36px; font-weight: 700; }
.foliage-cta-panel { left: 80px; right: 80px; top: 410px; bottom: 105px; }
.foliage-cta .foliage-phone { top: 440px; left: 124px; width: 330px; transform: rotate(-4deg); }
.foliage .foliage-actions { position: absolute; top: 790px; left: 460px; right: 112px; z-index: 3; display: flex; flex-direction: column; gap: 20px; }
.foliage .foliage-actions span { display: block; padding: 24px 18px; border-radius: 25px; background: #fffaf0; color: #a8402d; font-size: 31px; font-weight: 800; text-align: center; box-shadow: 0 8px 18px #703c252b; white-space: nowrap; }
.foliage .foliage-actions span + span { background: #a8402d; color: #fff; }
.foliage .foliage-source { position: absolute; left: 80px; right: 80px; bottom: 51px; color: #795e4d; font-size: 21px; font-weight: 600; }
+123 -1
View File
@@ -10,6 +10,7 @@ import { Frame, Lines } from './Frame'
import { tidy } from './text'
import { DEFAULT_STYLE, dailyOutfits, needsOuter, ootdBand, ootdOutfits, styleLabel } from './ootd'
import { gakArt, gakByCode } from './gaks'
import foliageData from '../assets/foliage/seoul-2026-10-29.json'
// 대주제(skin)마다 한 번 만든 배경 그림 (npm run gen-image -- tarot-bg <skin>). 없으면 민무늬 배경
const TAROT_BG = import.meta.glob<string>('../assets/tarot-bg/*.webp', { eager: true, import: 'default' })
@@ -39,6 +40,17 @@ export const hasTarotBg = (skin?: string) => !!tarotBg(skin)
import { iconUrl } from './icons'
import { toneVars } from './themes'
const FOLIAGE_IMAGES = import.meta.glob<string>('../assets/foliage/*.webp', { eager: true, import: 'default' })
const foliageImage = (file: string) => FOLIAGE_IMAGES[`../assets/foliage/${file}.webp`]
// 카드에 날짜 숫자는 쓰지 않는다: 오늘이 든 주(월~일) 안이면 '이번 주 절정', 그 뒤면 '다음 주 절정'
const foliagePeak = (date: string) => {
const today = new Date()
const sunday = new Date(today.getFullYear(), today.getMonth(), today.getDate() + ((7 - today.getDay()) % 7))
return new Date(`${date}T00:00:00`) <= sunday ? '이번 주 절정' : '다음 주 절정'
}
const foliageCredit = (spots: typeof foliageData.spots, firstRank: number) =>
`사진: 한국관광공사 · ${spots.map((spot, i) => `${firstRank + i}위 ${spot.photo.by.replace(/^한국관광공사\s*/, '')}`).join(' · ')}`
export type Copy = Record<string, string>
export type Field = { key: string; label: string }
@@ -266,6 +278,116 @@ const tarot: Template = {
const INTRO_GAK_CODES = ['walk', 'camping', 'fishing', 'chimaek', 'jjamppong', 'carwash', 'laundry', 'vent', 'stars', 'hiking', 'date', 'golf']
const foliage: Template = {
id: 'foliage',
name: '서울 근교 단풍 TOP 10',
about: '2026.10.29 기준 서울 근교 단풍 명소 10곳 · 사진 순위 5장',
how: [
'src/assets/foliage/seoul-2026-10-29.json의 순서가 1~10위다. 이름·지역·단풍 종류·절정 날짜와 사진 촬영자도 그 파일에서 가져온다.',
'1장은 앱 단풍 지도, 2~4장은 명소 사진 10장(1~2위는 크게, 3~10위는 4곳씩), 5장은 앱 명소 화면을 쓴다. 날씨 예보나 Claude 기획은 쓰지 않는다.',
'절정 날짜는 산림청 2026 단풍절정 예측 기준이다. 명소 사진은 한국관광공사 관광사진 공공누리 제1유형이므로 2~4장 아래에 촬영자와 함께 출처를 적는다.',
'모든 문구는 관리자 화면에서 직접 고칠 수 있다. 앱 안내는 토스 검색과 weather.o2o.kr을 함께 보여 준다.',
],
fields: [
{ key: 'date', label: '1장 날짜 줄' },
{ key: 'title', label: '1장 제목' },
{ key: 'subtitle', label: '1장 부제' },
{ key: 'heading2', label: '2장 제목' },
{ key: 'heading3', label: '3장 제목' },
{ key: 'heading4', label: '4장 제목' },
...foliageData.spots.flatMap((_, i) => {
const n = i + 1
return [
{ key: `name${n}`, label: `${n}위 이름` },
{ key: `region${n}`, label: `${n}위 지역` },
{ key: `kind${n}`, label: `${n}위 단풍/은행` },
{ key: `peak${n}`, label: `${n}위 절정 시기` },
]
}),
{ key: 'line1', label: '1위 한 줄' },
{ key: 'line2', label: '2위 한 줄' },
{ key: 'credit2', label: '2장 사진 출처' },
{ key: 'credit3', label: '3장 사진 출처' },
{ key: 'credit4', label: '4장 사진 출처' },
{ key: 'ctaTitle', label: '5장 제목' },
{ key: 'ctaBody', label: '5장 본문' },
{ key: 'button1', label: '5장 버튼 1' },
{ key: 'button2', label: '5장 버튼 2' },
{ key: 'source', label: '5장 출처' },
],
defaults: () => ({
date: '이번 주 단풍',
title: '서울 근교 단풍 TOP 10',
subtitle: '멀리 안 가도 돼요, 이번 주말 가볍게',
heading2: '1~2위', heading3: '3~6위', heading4: '7~10위',
...Object.fromEntries(foliageData.spots.flatMap((spot, i) => {
const n = i + 1
return [[`name${n}`, spot.name], [`region${n}`, spot.region], [`kind${n}`, spot.kind === 'ginkgo' ? '은행' : '단풍'], [`peak${n}`, foliagePeak(spot.peak)]]
})),
line1: '절 마당을 덮는 천연기념물 은행나무',
line2: '노란 잎이 깔린 메타세쿼이아·은행나무길',
credit2: foliageCredit(foliageData.spots.slice(0, 2), 1),
credit3: foliageCredit(foliageData.spots.slice(2, 6), 3),
credit4: foliageCredit(foliageData.spots.slice(6, 10), 7),
ctaTitle: '우리 동네 단풍은 지금 어디쯤?',
ctaBody: '전국 단풍 명소 68곳, 절정 날짜를 지도로 한눈에',
button1: "토스에서 '날씨각' 검색",
button2: 'weather.o2o.kr',
source: '절정 날짜: 산림청 2026 단풍절정 예측 · 사진: 한국관광공사',
}),
post: (_d, c) => ({
title: c.title,
caption: `${c.title} 🍁\n멀리 안 가도 돼요. 이번 주말 가볍게 다녀올 곳, 절정 시기 보고 골라요.\n\n전국 68곳 단풍 지도는 토스에서 '날씨각' 검색, 또는 weather.o2o.kr\n\n${c.source}\n${c.credit2}\n${c.credit3}\n${c.credit4}`,
hashtags: '#날씨각 #서울단풍 #단풍명소 #서울근교 #가을나들이 #단풍절정 #은행나무 #주말나들이',
}),
slides: (_d, c) => {
const frame = (page: number, className: string, children: ReactNode) =>
<Frame page={page} total={5} theme="sunset" className={`foliage foliage-${className}`} key={page}>{children}</Frame>
const phone = (file: string) => <div className="foliage-phone"><img src={foliageImage(file)} alt="날씨각 앱 단풍 지도 화면" /></div>
const tile = (i: number) => {
const spot = foliageData.spots[i]
const n = i + 1
const kind = c[`kind${n}`]
return <div className="foliage-tile" key={spot.file}>
<img className="foliage-photo" src={foliageImage(spot.file)} alt={c[`name${n}`]} />
<span className="foliage-rank">{n}</span>
<div className="foliage-tile-copy">
<strong className="foliage-name">{c[`name${n}`]}</strong>
<div className="foliage-facts"><span>{c[`region${n}`]}</span><span className="foliage-kind"><img src={iconUrl(kind === '은행' ? 'ginkgo' : 'maple')} alt="" />{kind}</span><span>{c[`peak${n}`]}</span></div>
{i < 2 && <p className="foliage-line">{c[`line${n}`]}</p>}
</div>
</div>
}
return [
frame(0, 'cover', <>
<p className="foliage-meta">{c.date}</p>
<h1 className="foliage-title">{c.title}</h1>
<p className="foliage-subtitle">{c.subtitle}</p>
<div className="foliage-cover-panel" />
{phone('app-map')}
<img className="foliage-leaf foliage-leaf-a" src={iconUrl('maple')} alt="" />
<img className="foliage-leaf foliage-leaf-b" src={iconUrl('ginkgo')} alt="" />
<img className="foliage-leaf foliage-leaf-c" src={iconUrl('fallen_leaf')} alt="" />
</>),
...[[0, 1], [2, 3, 4, 5], [6, 7, 8, 9]].map((indices, j) => frame(j + 1, j === 0 ? 'duo' : 'grid', <>
<p className="foliage-meta">{c.date}</p>
<h1 className="foliage-list-title">서울 근교 단풍 <em>{c[`heading${j + 2}`]}</em></h1>
<div className="foliage-board">{indices.map(tile)}</div>
<p className="foliage-credit">{c[`credit${j + 2}`]}</p>
</>)),
frame(4, 'cta', <>
<p className="foliage-meta">{c.date}</p>
<h1 className="foliage-cta-title">{c.ctaTitle}</h1>
<p className="foliage-cta-body">{c.ctaBody}</p>
<div className="foliage-cta-panel" />
{phone('app-spot')}
<div className="foliage-actions"><span>{c.button1}</span><span>{c.button2}</span></div>
<p className="foliage-source">{c.source}</p>
</>),
]
},
}
const intro: Template = {
id: 'intro',
name: '날씨각 소개',
@@ -381,6 +503,6 @@ const intro: Template = {
},
}
export const TEMPLATES: Template[] = [tarot, ootd, intro]
export const TEMPLATES: Template[] = [tarot, ootd, intro, foliage]
export const templateById = (id: string) => TEMPLATES.find((t) => t.id === id)
+38
View File
@@ -246,6 +246,7 @@ class Event(Base):
area: Mapped[Optional[str]] = mapped_column(String(20), nullable=True)
name: Mapped[str] = mapped_column(String(60))
place_name: Mapped[str] = mapped_column(String(60))
address: Mapped[Optional[str]] = mapped_column(String(120), nullable=True)
icon: Mapped[str] = mapped_column(String(30), default="fireworks")
start_date: Mapped[date] = mapped_column(Date)
end_date: Mapped[date] = mapped_column(Date)
@@ -362,6 +363,7 @@ class User(Base):
status: Mapped[int] = mapped_column(SmallInteger, default=1)
terms_agreed_at: Mapped[Optional[datetime]] = mapped_column(DateTime(timezone=True), nullable=True)
token_version: Mapped[int] = mapped_column(SmallInteger, default=1)
points: Mapped[int] = mapped_column(Integer, default=0)
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
deleted: Mapped[bool] = mapped_column(Boolean, default=False)
@@ -447,10 +449,46 @@ class MyGak(Base):
my_gak_id: Mapped[int] = mapped_column(BigInteger, primary_key=True)
user_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True))
name: Mapped[str] = mapped_column(String(12))
icon: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
rule: Mapped[dict] = mapped_column(JSONB)
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
class PointLog(Base):
__tablename__ = "point_log"
point_id: Mapped[int] = mapped_column(BigInteger, primary_key=True)
user_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True))
day: Mapped[date] = mapped_column(Date)
action: Mapped[str] = mapped_column(String(20))
ref: Mapped[str] = mapped_column(String(40), default="")
points: Mapped[int] = mapped_column(SmallInteger)
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
class FortuneDraw(Base):
__tablename__ = "fortune_draw"
user_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True)
day: Mapped[date] = mapped_column(Date, primary_key=True)
card_code: Mapped[str] = mapped_column(String(32))
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
class DayLog(Base):
__tablename__ = "day_log"
user_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True)
day: Mapped[date] = mapped_column(Date, primary_key=True)
mood: Mapped[int] = mapped_column(SmallInteger)
went_out: Mapped[bool] = mapped_column(Boolean)
place_name: Mapped[Optional[str]] = mapped_column(String(40), nullable=True)
place_ref: Mapped[Optional[str]] = mapped_column(String(40), nullable=True)
card_hit: Mapped[Optional[bool]] = mapped_column(Boolean, nullable=True)
region_code: Mapped[str] = mapped_column(String(10))
updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
class Talk(Base):
__tablename__ = "talk"
+7
View File
@@ -26,6 +26,13 @@ class CardCRUD:
"""만든 순서 역순. 올린 것·승인 대기·반려 모두."""
return list((await s.scalars(select(CardSet).order_by(CardSet.card_id.desc()).limit(limit))).all())
async def latest_published(self, s: AsyncSession, template: str) -> Optional[CardSet]:
"""그 틀로 가장 최근에 피드에 올린 카드뉴스"""
return await s.scalar(
select(CardSet).where(CardSet.template == template, CardSet.status == CardStatus.PUBLISHED.value, CardSet.post_id.is_not(None))
.order_by(CardSet.published_at.desc()).limit(1)
)
async def many(self, s: AsyncSession, card_ids: list[int]) -> list[CardSet]:
if not card_ids:
return []
+52
View File
@@ -0,0 +1,52 @@
import uuid
from datetime import date
from typing import Optional
from sqlalchemy import case, func, select
from sqlalchemy.dialects.postgresql import insert
from sqlalchemy.ext.asyncio import AsyncSession
from common.database.model.models import DayLog, Event, FortuneDraw, Place, SunsetSpot
def _near(region_col, sido: str):
return case((region_col.startswith(sido), 0), else_=1)
class FortuneCRUD:
async def draw_of(self, s: AsyncSession, user_id: uuid.UUID, day: date) -> Optional[FortuneDraw]:
return await s.get(FortuneDraw, (user_id, day))
async def add_draw(self, s: AsyncSession, user_id: uuid.UUID, day: date, card_code: str) -> FortuneDraw:
"""그날 이미 뽑았으면 그 카드를 그대로 돌려준다 (폰과 PC 에서 동시에 뽑아도 처음 카드 하나로)"""
await s.execute(insert(FortuneDraw).values(user_id=user_id, day=day, card_code=card_code).on_conflict_do_nothing())
return await s.scalar(select(FortuneDraw).where(FortuneDraw.user_id == user_id, FortuneDraw.day == day))
async def draw_days(self, s: AsyncSession, user_id: uuid.UUID, since: date) -> list[date]:
return list((await s.scalars(select(FortuneDraw.day).where(FortuneDraw.user_id == user_id, FortuneDraw.day >= since))).all())
async def log_of(self, s: AsyncSession, user_id: uuid.UUID, day: date) -> Optional[DayLog]:
return await s.get(DayLog, (user_id, day))
async def save_log(self, s: AsyncSession, user_id: uuid.UUID, day: date, values: dict) -> DayLog:
stmt = insert(DayLog).values(user_id=user_id, day=day, **values)
await s.execute(stmt.on_conflict_do_update(index_elements=[DayLog.user_id, DayLog.day], set_={**values, "updated_at": func.now()}))
return await s.scalar(select(DayLog).where(DayLog.user_id == user_id, DayLog.day == day).execution_options(populate_existing=True))
async def import_rows(self, s: AsyncSession, user_id: uuid.UUID, draws: list[tuple[date, str]], logs: list[tuple[date, dict]]) -> None:
"""기기에 있던 기록을 계정으로. 계정에 이미 있는 날은 계정 쪽을 둔다"""
if draws:
await s.execute(insert(FortuneDraw).values([{"user_id": user_id, "day": d, "card_code": c} for d, c in draws]).on_conflict_do_nothing())
if logs:
await s.execute(insert(DayLog).values([{"user_id": user_id, "day": d, **v} for d, v in logs]).on_conflict_do_nothing())
async def search_places(self, s: AsyncSession, q: str, sido: str, today: date, limit: int) -> list[tuple[str, str]]:
"""이름에 q 가 들어간 데이트 명소·노을 명소·지금 하는 행사. 같은 시도를 앞에. (place_ref, 이름)"""
like = "%" + q.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_") + "%"
places = (await s.execute(select(Place.place_id, Place.name).where(Place.name.ilike(like, escape="\\")).order_by(_near(Place.region_code, sido), Place.name).limit(limit))).all()
spots = (await s.execute(select(SunsetSpot.spot_id, SunsetSpot.name).where(SunsetSpot.name.ilike(like, escape="\\")).order_by(_near(SunsetSpot.region_code, sido), SunsetSpot.name).limit(limit))).all()
events = (await s.execute(
select(Event.event_id, Event.name).where(Event.name.ilike(like, escape="\\"), Event.start_date <= today, Event.end_date >= today)
.order_by(case((Event.sido_code == sido, 0), else_=1), Event.name).limit(limit)
)).all()
return [(f"place:{i}", n) for i, n in places] + [(f"spot:{i}", n) for i, n in spots] + [(f"event:{i}", n) for i, n in events]
+30
View File
@@ -0,0 +1,30 @@
import uuid
from datetime import date
from sqlalchemy import func, select, update
from sqlalchemy.dialects.postgresql import insert
from sqlalchemy.ext.asyncio import AsyncSession
from common.database.model.models import PointLog, User
class LevelCRUD:
async def earned(self, s: AsyncSession, user_id: uuid.UUID, day: date, action: str) -> int:
return await s.scalar(select(func.coalesce(func.sum(PointLog.points), 0)).where(PointLog.user_id == user_id, PointLog.day == day, PointLog.action == action))
async def add(self, s: AsyncSession, user_id: uuid.UUID, day: date, action: str, ref: str, points: int) -> int:
"""같은 날 같은 일·대상이면 넣지 않는다. 넣었으면 총량에 더하고 새 총량을 돌려준다 (안 넣었으면 0)"""
row = await s.scalar(insert(PointLog).values(user_id=user_id, day=day, action=action, ref=ref, points=points).on_conflict_do_nothing().returning(PointLog.point_id))
if row is None:
return 0
return await s.scalar(update(User).where(User.user_id == user_id).values(points=User.points + points).returning(User.points))
async def today(self, s: AsyncSession, user_id: uuid.UUID, day: date) -> dict[str, int]:
rows = (await s.execute(select(PointLog.action, func.sum(PointLog.points)).where(PointLog.user_id == user_id, PointLog.day == day).group_by(PointLog.action))).all()
return {a: int(p) for a, p in rows}
async def attend_days(self, s: AsyncSession, user_id: uuid.UUID, since: date) -> list[date]:
return list((await s.scalars(select(PointLog.day).where(PointLog.user_id == user_id, PointLog.action == "attend", PointLog.day >= since))).all())
async def points(self, s: AsyncSession, user_id: uuid.UUID) -> int:
return await s.scalar(select(User.points).where(User.user_id == user_id)) or 0
+3 -2
View File
@@ -1,4 +1,5 @@
import uuid
from typing import Optional
from sqlalchemy import delete, func, select
from sqlalchemy.ext.asyncio import AsyncSession
@@ -13,8 +14,8 @@ class MyGakCRUD:
async def count(self, s: AsyncSession, user_id: uuid.UUID) -> int:
return await s.scalar(select(func.count()).select_from(MyGak).where(MyGak.user_id == user_id))
async def add(self, s: AsyncSession, user_id: uuid.UUID, name: str, rule: dict) -> MyGak:
row = MyGak(user_id=user_id, name=name, rule=rule)
async def add(self, s: AsyncSession, user_id: uuid.UUID, name: str, rule: dict, icon: Optional[str] = None) -> MyGak:
row = MyGak(user_id=user_id, name=name, rule=rule, icon=icon)
s.add(row)
await s.flush()
return row
+3 -2
View File
@@ -48,11 +48,12 @@ class WeekCRUD:
if not rows:
return
# 출처마다 이름에 "&lt;" 같은 HTML 문자가 섞여 와서, 넣기 전에 푼다
rows = [{**r, "name": plain(r["name"]), "place_name": plain(r["place_name"])} for r in rows]
# 주소는 출처마다 있거나 없어서, 없는 행도 칸을 맞춰 넣는다
rows = [{**r, "name": plain(r["name"]), "place_name": plain(r["place_name"]), "address": r.get("address")} for r in rows]
stmt = insert(Event).values(rows)
await s.execute(stmt.on_conflict_do_update(
index_elements=["source_id"],
set_={k: stmt.excluded[k] for k in ("name", "place_name", "start_date", "end_date", "is_confirmed", "image_url", "lat", "lon", "kind", "icon")},
set_={k: stmt.excluded[k] for k in ("name", "place_name", "address", "start_date", "end_date", "is_confirmed", "image_url", "lat", "lon", "kind", "icon")},
))
async def replace_manual_events(self, s: AsyncSession, rows: list[dict]) -> None:
+38
View File
@@ -316,6 +316,43 @@ CREATE TABLE IF NOT EXISTS public.my_gak (
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE INDEX IF NOT EXISTS ix_my_gak_user ON public.my_gak (user_id);
ALTER TABLE public.my_gak ADD COLUMN IF NOT EXISTS icon VARCHAR(32) NULL; -- 고른 아이콘 (각 아이콘 이름, 없으면 기본)
-- 계정 레벨: 날씨각에서 한 일로 모은 각 (로그인한 사람만). 레벨은 모은 총량으로 정하고, 같은 날 같은 일·대상은 한 번만 준다
CREATE TABLE IF NOT EXISTS public.point_log (
point_id BIGSERIAL PRIMARY KEY,
user_id UUID NOT NULL,
day DATE NOT NULL,
action VARCHAR(20) NOT NULL, -- services/level_service.py ACTIONS
ref VARCHAR(40) NOT NULL DEFAULT '', -- 같은 날 같은 대상 중복 막기 (post:12 등)
points SMALLINT NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE UNIQUE INDEX IF NOT EXISTS uq_point_log ON public.point_log (user_id, day, action, ref);
ALTER TABLE public.users ADD COLUMN IF NOT EXISTS points INTEGER NOT NULL DEFAULT 0; -- 모은 각 총량 (point_log 합)
-- 오늘 한 장: 로그인한 사람이 그날 뽑은 카드 (하루 한 장, 로그인 안 하면 기기에만 남는다)
CREATE TABLE IF NOT EXISTS public.fortune_draw (
user_id UUID NOT NULL,
day DATE NOT NULL,
card_code VARCHAR(32) NOT NULL, -- 각 코드 (services/fortune_deck.json)
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
PRIMARY KEY (user_id, day)
);
-- 저녁 체크인: 그날 기분·다녀온 곳·카드가 맞았는지 (본인만 본다)
CREATE TABLE IF NOT EXISTS public.day_log (
user_id UUID NOT NULL,
day DATE NOT NULL,
mood SMALLINT NOT NULL, -- 1(가장 좋음)~5
went_out BOOLEAN NOT NULL,
place_name VARCHAR(40) NULL, -- 다녀온 곳 이름 (목록에서 고르거나 직접 씀)
place_ref VARCHAR(40) NULL, -- 목록에서 고른 곳: place:<id> · spot:<id> · event:<id>
card_hit BOOLEAN NULL, -- 오늘 카드 맞았나 (안 고르면 NULL)
region_code VARCHAR(10) NOT NULL,
updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
PRIMARY KEY (user_id, day)
);
-- 동네 이야기: 사용자가 쓴 짧은 글(전국에 보임). 쓸 때의 동네 날씨를 함께 남긴다
CREATE TABLE IF NOT EXISTS public.talk (
@@ -465,6 +502,7 @@ ALTER TABLE public.event ADD COLUMN IF NOT EXISTS image_url VARCHAR(500) NULL;
ALTER TABLE public.event ADD COLUMN IF NOT EXISTS lat NUMERIC(8,5) NULL;
ALTER TABLE public.event ADD COLUMN IF NOT EXISTS lon NUMERIC(8,5) NULL;
ALTER TABLE public.event ADD COLUMN IF NOT EXISTS kind SMALLINT NOT NULL DEFAULT 1;
ALTER TABLE public.event ADD COLUMN IF NOT EXISTS address VARCHAR(120) NULL; -- 도로명 주소 (출처에 있을 때만)
-- 공휴일 (주말·행사 탭의 "개천절").
CREATE TABLE IF NOT EXISTS public.holiday (
+4
View File
@@ -14,6 +14,8 @@ from router.v1.feed.feed import router as feed_router
from router.v1.image.image import router as image_router
from router.v1.index.index import router as index_router
from router.v1.my_gak.my_gak import router as my_gak_router
from router.v1.fortune.fortune import router as fortune_router
from router.v1.level.level import router as level_router
from router.v1.reaction.reaction import router as reaction_router
from router.v1.region.region import router as region_router
from router.v1.season.season import router as season_router
@@ -48,6 +50,8 @@ app.include_router(feed_router)
app.include_router(auth_router)
app.include_router(reaction_router)
app.include_router(my_gak_router)
app.include_router(fortune_router)
app.include_router(level_router)
app.include_router(talk_router)
app.include_router(watch_router)
app.include_router(image_router)
+11 -1
View File
@@ -14,7 +14,7 @@ from common.models.errors import error_info
from common.utils.kma_time import KST, kst_midnight, now_kst
from crud.card_crud import CardCRUD
from crud.feed_crud import FeedCRUD
from router.v1.card.protocol import CardItem, Req_CardCreate, Res_Card, Res_CardList
from router.v1.card.protocol import CardItem, Req_CardCreate, Res_Card, Res_CardList, Res_LatestCard
from services.bot_comment import fill_bot_comments
from services.external import instagram
from services.feed_service import _FEED_DAY_START, clear_feed_cache, feed_day
@@ -82,6 +82,16 @@ async def list_cards(limit: int = Query(50, ge=1, le=200)) -> Res_CardList:
])
@router.get("/latest", response_model=Res_LatestCard, response_model_exclude_none=True, summary="그 틀로 가장 최근에 피드에 올린 카드뉴스의 포스트 (오늘 탭 '오늘 코디' 아이콘)")
async def latest_card(template: str = Query(..., pattern=r"^[a-z_]{1,20}$")) -> Res_LatestCard:
err, card = await DB_SESSION_MNG.execute_lambda(lambda s: _crud.latest_published(s, template))
if err is not ErrorType.SUCCESS:
return Res_LatestCard(result=error_info(err))
if card is None:
return Res_LatestCard()
return Res_LatestCard(post_id=card.post_id, published_at=card.published_at.astimezone(KST) if card.published_at else None)
@router.post("", response_model=Res_Card, response_model_exclude_none=True, summary="카드뉴스 저장 (관리자). publish 면 바로 그날 피드에 올린다", dependencies=[Depends(require_admin)])
async def create_card(req: Req_CardCreate) -> Res_Card:
images = _jpegs(req.images)
+5
View File
@@ -18,6 +18,11 @@ class Req_CardCreate(WebPacketProtocol):
publish: bool = Field(default=False, description="true 면 만들자마자 그날 피드에 올린다. false 면 승인 대기")
class Res_LatestCard(Res_WebPacketProtocol):
post_id: Optional[int] = None
published_at: Optional[datetime] = None
class Res_Card(Res_WebPacketProtocol):
card_id: Optional[int] = None
status: Optional[CardStatus] = None
+2 -13
View File
@@ -1,10 +1,10 @@
from typing import Optional
from fastapi import APIRouter, Depends, Path, Query, Request
from fastapi import APIRouter, Depends, Path, Query
from common.auth import optional_user
from common.database.model.models import User
from common.enums import ErrorType, PostType
from common.enums import ErrorType
from common.liker import Liker, liker
from common.models.errors import error_info
from router.v1.feed.protocol import Res_Feed, Res_Post
@@ -13,26 +13,15 @@ from services.reaction_service import ReactionService
router = APIRouter(prefix="/v1/feed", tags=["feed"])
# 토스에 올라간 10/13 번들은 UV 까지만 알아서, 그 뒤에 생긴 글 종류(카드뉴스 등)가 오면 흰 화면이 된다
TOSS_KNOWN_MAX = PostType.UV.value
def _from_toss(request: Request) -> bool:
ref = request.headers.get("origin") or request.headers.get("referer") or ""
return "AppsInToss" in request.headers.get("user-agent", "") or ".tossmini.com" in ref
@router.get("", response_model=Res_Feed, response_model_exclude_none=True, summary="메인 피드: 하늘 영역, 오늘의 각, 오늘 포스트 전부, 띠")
async def get_feed(
request: Request,
region: str = Query(..., description="구 행정코드"), user: Optional[User] = Depends(optional_user), who: Liker = Depends(liker),
service: FeedService = Depends(), reactions: ReactionService = Depends(),
) -> Res_Feed:
err, feed = await service.feed(region)
if err is not ErrorType.SUCCESS:
return Res_Feed(result=error_info(err))
if _from_toss(request):
feed = feed.model_copy(update={"posts": [p for p in feed.posts if p.post_type.value <= TOSS_KNOWN_MAX]})
pinned = [x for x in (feed.hero_post, feed.gak_post, feed.foliage_post, feed.events_post, feed.season_post) if x is not None]
ids = [p.post_id for p in feed.posts] + [x.post_id for x in pinned]
counts = await reactions.counts(ids)
+2 -1
View File
@@ -5,6 +5,7 @@ from pydantic import Field
from common.enums import PostType, SkySituation, SlotTone
from common.models.gmodel import Res_WebPacketProtocol, WebPacketProtocol
from router.v1.index.protocol import TrendPoint
class Row(WebPacketProtocol):
@@ -51,8 +52,8 @@ class GakSlide(WebPacketProtocol):
score: int
line: str
summary: str
rows: list[Row] = Field(default=[], description="점수 근거: 비중 큰 날씨 조건부터 네 개와 지금 값 (기온 · 체감 18°)")
say: Optional[str] = Field(default=None, description="점수 구간 설명 문장 (seed sentences)")
trend: list[TrendPoint] = Field(default=[], description="오늘 · 내일 · 이번 주말 점수 (각 상세 날짜 칸과 같은 값)")
class Cut(WebPacketProtocol):
Whitespace-only changes.
+61
View File
@@ -0,0 +1,61 @@
from typing import Optional
from fastapi import APIRouter, Depends, Query
from common.auth import current_user, optional_user
from common.database.model.models import DayLog, User
from common.enums import ErrorType
from common.models.errors import error_info
from common.models.gmodel import Res_WebPacketProtocol
from router.v1.fortune.protocol import (
DayLogData, FortuneCard, FortuneLuck, FortunePlace, Req_DayLog, Req_FortuneDraw, Req_FortuneImport, Res_DayLog, Res_FortunePlaces, Res_FortuneToday,
)
from services.fortune_service import FortuneService, Today
router = APIRouter(prefix="/v1/fortune", tags=["fortune"])
def _log(g: Optional[DayLog]) -> Optional[DayLogData]:
if g is None:
return None
return DayLogData(day=g.day, mood=g.mood, went_out=g.went_out, place_name=g.place_name, place_ref=g.place_ref, card_hit=g.card_hit)
def _today(t: Today) -> Res_FortuneToday:
return Res_FortuneToday(
day=t.day, streak=t.streak, checkin_open=t.checkin_open, log=_log(t.log),
card=FortuneCard(**t.card.__dict__) if t.card else None, luck=FortuneLuck(**t.luck.__dict__) if t.luck else None,
)
@router.get("/today", response_model=Res_FortuneToday, response_model_exclude_none=True, summary="오늘 한 장: 로그인했으면 오늘 뽑은 카드·행운·체크인·연속 기록 (안 뽑았으면 카드 없이)")
async def get_fortune_today(region: str = Query(..., min_length=10, max_length=10), user: Optional[User] = Depends(optional_user), service: FortuneService = Depends()) -> Res_FortuneToday:
err, t = await service.today(region, user)
return Res_FortuneToday(result=error_info(err)) if err is not ErrorType.SUCCESS or t is None else _today(t)
@router.post("/draw", response_model=Res_FortuneToday, response_model_exclude_none=True, summary="오늘 카드 뽑기 (하루 한 장). 로그인 안 했으면 기기에 있는 오늘 카드를 넘기면 그 카드로 행운만 계산")
async def draw_fortune(req: Req_FortuneDraw, user: Optional[User] = Depends(optional_user), service: FortuneService = Depends()) -> Res_FortuneToday:
err, t = await service.draw(req.region_code, user, req.card_code, req.days)
return Res_FortuneToday(result=error_info(err)) if err is not ErrorType.SUCCESS or t is None else _today(t)
@router.put("/log", response_model=Res_DayLog, response_model_exclude_none=True, summary="오늘 저녁 체크인 저장 (로그인). 다시 보내면 고친다")
async def save_day_log(req: Req_DayLog, user: User = Depends(current_user), service: FortuneService = Depends()) -> Res_DayLog:
err, g = await service.save_log(user, req.region_code, req.mood, req.went_out, req.place_name, req.place_ref, req.card_hit)
return Res_DayLog(result=error_info(err)) if err is not ErrorType.SUCCESS or g is None else Res_DayLog(log=_log(g))
@router.post("/import", response_model=Res_WebPacketProtocol, response_model_exclude_none=True, summary="로그인할 때 기기에 있던 뽑은 카드·체크인을 계정으로 (계정에 있는 날은 계정 쪽을 둔다)")
async def import_fortune(req: Req_FortuneImport, user: User = Depends(current_user), service: FortuneService = Depends()) -> Res_WebPacketProtocol:
draws = [(d.day, d.card_code) for d in req.draws]
logs = [(g.day, g.model_dump(exclude={"day"})) for g in req.logs]
return Res_WebPacketProtocol(result=error_info(await service.import_local(user, draws, logs)))
@router.get("/places", response_model=Res_FortunePlaces, response_model_exclude_none=True, summary="체크인에서 다녀온 곳 찾기: 이름에 q 가 들어간 데이트 명소·노을 명소·지금 하는 행사")
async def search_fortune_places(region: str = Query(..., min_length=10, max_length=10), q: str = Query(..., max_length=20), service: FortuneService = Depends()) -> Res_FortunePlaces:
err, rows = await service.places(region, q)
if err is not ErrorType.SUCCESS:
return Res_FortunePlaces(result=error_info(err))
return Res_FortunePlaces(items=[FortunePlace(ref=r, name=n) for r, n in rows])
+83
View File
@@ -0,0 +1,83 @@
from datetime import date
from typing import Optional
from pydantic import Field
from common.models.gmodel import Req_WebPacketProtocol, Res_WebPacketProtocol, WebPacketProtocol
class FortuneCard(WebPacketProtocol):
code: str = Field(description="각 코드 (카드 그림은 /fortune/<code>.webp)")
name: str
icon: str
reading: str = Field(description="리딩 한 문장")
color: str = Field(description="행운 색 이름")
hex: str = Field(description="행운 색 #rrggbb")
class FortuneLuck(WebPacketProtocol):
time: Optional[str] = Field(None, description="행운 시간: 오늘 남은 구간 중 날씨가 가장 좋은 때 (예: 오후 4~7시)")
place: Optional[str] = Field(None, description="행운 장소: 날씨 맞춤 데이트 명소")
place_id: Optional[int] = None
top_gak: Optional[str] = Field(None, description="지금 1위 각 이름")
top_icon: Optional[str] = None
class DayLogData(WebPacketProtocol):
day: date
mood: int = Field(ge=1, le=5, description="1(가장 좋음)~5")
went_out: bool
place_name: Optional[str] = None
place_ref: Optional[str] = Field(None, description="목록에서 고른 곳: place:<id> · spot:<id> · event:<id>")
card_hit: Optional[bool] = Field(None, description="오늘 카드 맞았나")
class Res_FortuneToday(Res_WebPacketProtocol):
day: Optional[date] = None
card: Optional[FortuneCard] = Field(None, description="오늘 뽑은 카드. 아직 안 뽑았으면 없음")
luck: Optional[FortuneLuck] = None
streak: int = Field(0, description="이어 뽑은 날 수 (7일에 한 번 쉬는 날은 봐준다)")
checkin_open: bool = Field(False, description="저녁(해 지기 2시간 전)부터 체크인")
log: Optional[DayLogData] = Field(None, description="오늘 체크인 (로그인했을 때)")
class Req_FortuneDraw(Req_WebPacketProtocol):
region_code: str = Field(min_length=10, max_length=10)
card_code: Optional[str] = Field(None, max_length=32, description="로그인 안 했을 때 기기에 있는 오늘 카드 (없으면 새로 뽑음)")
days: list[date] = Field(default=[], max_length=60, description="로그인 안 했을 때 기기에 남은 뽑은 날 (연속 기록용)")
class Req_DayLog(Req_WebPacketProtocol):
region_code: str = Field(min_length=10, max_length=10)
mood: int = Field(ge=1, le=5)
went_out: bool
place_name: Optional[str] = Field(None, max_length=40)
place_ref: Optional[str] = Field(None, max_length=40)
card_hit: Optional[bool] = None
class Res_DayLog(Res_WebPacketProtocol):
log: Optional[DayLogData] = None
class LocalDraw(WebPacketProtocol):
day: date
card_code: str = Field(max_length=32)
class LocalLog(Req_DayLog):
day: date
class Req_FortuneImport(Req_WebPacketProtocol):
draws: list[LocalDraw] = Field(default=[], max_length=60)
logs: list[LocalLog] = Field(default=[], max_length=60)
class FortunePlace(WebPacketProtocol):
ref: str = Field(description="place:<id> · spot:<id> · event:<id>")
name: str
class Res_FortunePlaces(Res_WebPacketProtocol):
items: list[FortunePlace] = []
View File
Whitespace-only changes.
+35
View File
@@ -0,0 +1,35 @@
from fastapi import APIRouter, Depends
from common.auth import current_user
from common.database.model.models import User
from common.enums import ErrorType
from common.models.errors import error_info
from router.v1.level.protocol import LevelAction, LevelStep, LevelUnlock, Res_Level
from services.level_service import LEVELS, LevelService, Status
router = APIRouter(prefix="/v1/level", tags=["level"])
def _res(err: ErrorType, st: Status | None) -> Res_Level:
if err is not ErrorType.SUCCESS or st is None:
return Res_Level(result=error_info(err))
return Res_Level(
points=st.points, level=st.level, name=st.name, floor=st.floor, next_points=st.next_points, next_name=st.next_name, streak=st.streak,
today=[LevelAction(**a.__dict__) for a in st.today], unlocks=[LevelUnlock(level=lv, key=k, name=n) for lv, k, n in st.unlocks],
levels=[LevelStep(level=i + 1, name=n, points=p) for i, (p, n) in enumerate(LEVELS)],
)
@router.get("/me", response_model=Res_Level, response_model_exclude_none=True, summary="내 레벨: 모은 각, 다음 레벨, 오늘 받은 각, 레벨로 열리는 것")
async def my_level(user: User = Depends(current_user), service: LevelService = Depends()) -> Res_Level:
return _res(*await service.status(user))
@router.post("/attend", response_model=Res_Level, response_model_exclude_none=True, summary="출석 (하루 한 번 각). 7일 이어지면 보너스")
async def attend(user: User = Depends(current_user), service: LevelService = Depends()) -> Res_Level:
return _res(*await service.attend(user))
@router.post("/share", response_model=Res_Level, response_model_exclude_none=True, summary="공유를 마쳤을 때 (하루 한 번 각)")
async def shared(user: User = Depends(current_user), service: LevelService = Depends()) -> Res_Level:
return _res(*await service.share(user))
+38
View File
@@ -0,0 +1,38 @@
from typing import Optional
from pydantic import Field
from common.models.gmodel import Res_WebPacketProtocol, WebPacketProtocol
class LevelAction(WebPacketProtocol):
action: str
name: str
points: int = Field(description="한 번에 주는 각")
cap: int = Field(description="하루 한도")
earned: int = Field(description="오늘 받은 각")
class LevelUnlock(WebPacketProtocol):
level: int
key: str
name: str
class LevelStep(WebPacketProtocol):
level: int
name: str
points: int = Field(description="이 레벨이 되는 각 총량")
class Res_Level(Res_WebPacketProtocol):
points: int = Field(0, description="모은 각 총량")
level: int = 1
name: Optional[str] = None
floor: int = Field(0, description="지금 레벨이 시작하는 각")
next_points: Optional[int] = Field(None, description="다음 레벨에 필요한 총량 (마지막 레벨이면 없음)")
next_name: Optional[str] = None
streak: int = Field(0, description="이어 출석한 날")
today: list[LevelAction] = []
unlocks: list[LevelUnlock] = []
levels: list[LevelStep] = Field([], description="레벨 전체 (이름·필요한 각)")
+2 -2
View File
@@ -14,7 +14,7 @@ router = APIRouter(prefix="/v1/my-gak", tags=["my-gak"])
def _data(g: MyGak) -> MyGakData:
return MyGakData(my_gak_id=g.my_gak_id, name=g.name, rule=MyGakRule(**g.rule))
return MyGakData(my_gak_id=g.my_gak_id, name=g.name, icon=g.icon, rule=MyGakRule(**g.rule))
@router.get("", response_model=Res_MyGakList, response_model_exclude_none=True, summary="내 각 목록 (로그인하지 않았으면 빈 목록)")
@@ -29,7 +29,7 @@ async def list_my_gak(user: Optional[User] = Depends(optional_user), service: My
@router.post("", response_model=Res_MyGak, response_model_exclude_none=True, summary="이름과 날씨 조건으로 내 각 만들기")
async def add_my_gak(req: Req_MyGak, user: User = Depends(current_user), service: MyGakService = Depends()) -> Res_MyGak:
err, g = await service.add(user, req.name, req.rule.model_dump(exclude_none=True))
err, g = await service.add(user, req.name, req.rule.model_dump(exclude_none=True), req.icon)
return Res_MyGak(result=error_info(err)) if err is not ErrorType.SUCCESS or g is None else Res_MyGak(item=_data(g))
+3
View File
@@ -29,11 +29,13 @@ class MyGakRule(WebPacketProtocol):
class MyGakData(WebPacketProtocol):
my_gak_id: int
name: str
icon: Optional[str] = Field(None, description="고른 아이콘 (각 아이콘 이름)")
rule: MyGakRule
class Req_MyGak(Req_WebPacketProtocol):
name: str = Field(min_length=1, max_length=12, description="내 각 이름 (끝에 '각'이 없으면 붙인다)")
icon: Optional[str] = Field(None, pattern=r"^[a-z_]{1,32}$", description="고른 아이콘 (각 아이콘 이름)")
rule: MyGakRule
@@ -66,6 +68,7 @@ class MyGakScore(WebPacketProtocol):
slot: Optional[Slot] = Field(None, description="score 가 어느 시간대 점수인지")
slots: dict[str, int] = Field(default={}, description="고른 시간대별 점수 (아침·낮·저녁·밤 순)")
reasons: list[str] = Field(default=[], description="score 근거: 조건마다 그 시간대 실제 값")
factors: dict[str, int] = Field(default={}, description="조건별 점수 0~100 (temp·rain·wind·air·humidity, reasons 와 같은 순서)")
class Res_MyGakScore(Res_WebPacketProtocol):
+1
View File
@@ -22,6 +22,7 @@ class TalkData(WebPacketProtocol):
liked: bool
mine: bool
created_at: datetime
ago: str = Field(description="쓴 지 얼마나 됐는지 (방금 · 12분 전 · 3시간 전 · 1일 전 · 2주 전)")
class Req_Talk(Req_WebPacketProtocol):
+3 -2
View File
@@ -11,10 +11,10 @@ from common.enums import ErrorType, TalkTopic
from common.liker import Liker, liker
from common.models.errors import error_info
from common.models.gmodel import Res_WebPacketProtocol
from common.utils.kma_time import KST
from common.utils.kma_time import KST, now_kst
from router.v1.talk.protocol import Req_Talk, Req_TalkReport, Res_Talk, Res_TalkGroups, Res_TalkImage, Res_TalkLike, Res_TalkList, TalkData, TalkGroup
from services.talk_image import MAX_BYTES, URL_PREFIX, file_of, save
from services.talk_service import TalkService, TalkView
from services.talk_service import TalkService, TalkView, ago_text
router = APIRouter(prefix="/v1/talk", tags=["talk"])
@@ -24,6 +24,7 @@ def _data(v: TalkView) -> TalkData:
return TalkData(
talk_id=t.talk_id, nickname=u.nickname, character=u.character, color=u.color, mood=u.mood, region_name=v.region_name, weather=t.weather,
body=t.body, image=t.image, topic=TalkTopic(t.topic), like_count=t.like_count, liked=v.liked, mine=v.mine, created_at=t.created_at.astimezone(KST),
ago=ago_text(t.created_at, now_kst()),
)
+3 -2
View File
@@ -106,7 +106,8 @@ def parse_popup(page: str, popup_id: int, since: date) -> Optional[dict]:
if start is None or end is None or end < since:
return None
loc = ld.get("location") or {}
sido = sido_of((loc.get("address") or {}).get("streetAddress", ""))
address = html.unescape((loc.get("address") or {}).get("streetAddress") or "").strip()
sido = sido_of(address)
if sido is None:
return None
geo = loc.get("geo") or {}
@@ -115,7 +116,7 @@ def parse_popup(page: str, popup_id: int, since: date) -> Optional[dict]:
kind = EventKind.CONCERT
return {
"source_id": f"{SOURCE_PREFIX}{popup_id}", "sido_code": sido, "name": name[:60],
"place_name": place[:60], "start_date": start, "end_date": end, "is_confirmed": True,
"place_name": place[:60], "address": address[:120] or None, "start_date": start, "end_date": end, "is_confirmed": True,
"source_url": POPUP_URL.format(id=popup_id), "image_url": None,
"lat": _coord(geo.get("latitude")), "lon": _coord(geo.get("longitude")), "kind": kind, "icon": EVENT_ICON[kind],
}
+1 -1
View File
@@ -59,7 +59,7 @@ def parse_seoul_festivals(items: list[dict]) -> list[dict]:
continue
rows.append({
"source_id": f"{SOURCE_PREFIX}{it['cultcode']}", "sido_code": SEOUL, "name": name[:60],
"place_name": html.unescape(it.get("facName") or it.get("addr") or "")[:60], "start_date": start, "end_date": end, "is_confirmed": True,
"place_name": html.unescape(it.get("facName") or it.get("addr") or "")[:60], "address": html.unescape(it.get("addr") or "")[:120] or None, "start_date": start, "end_date": end, "is_confirmed": True,
"source_url": VIEW_URL.format(code=it["cultcode"]),
"image_url": IMAGE_URL.format(id=it["atchFileId"]) if it.get("atchFileId") else None,
# 이 목록은 xCoord 가 위도, yCoord 가 경도다
+1 -1
View File
@@ -35,7 +35,7 @@ def parse_festivals(items: list[dict], sido_code: str) -> list[dict]:
continue
rows.append({
"source_id": str(it["contentid"]), "sido_code": sido_code, "name": it.get("title", "")[:60],
"place_name": (it.get("addr1") or "")[:60], "start_date": start, "end_date": end, "is_confirmed": True,
"place_name": (it.get("addr1") or "")[:60], "address": (it.get("addr1") or "")[:120] or None, "start_date": start, "end_date": end, "is_confirmed": True,
"source_url": None, "image_url": (it.get("firstimage") or "").replace("http://", "https://", 1) or None,
"lat": _coord(it.get("mapy")), "lon": _coord(it.get("mapx")), "kind": EventKind.FESTIVAL, "icon": EVENT_ICON[EventKind.FESTIVAL],
})
+15 -31
View File
@@ -1,6 +1,5 @@
import asyncio
import random
import re
from dataclasses import dataclass, field
from datetime import date, datetime, time, timedelta
from typing import Optional
@@ -25,6 +24,7 @@ from router.v1.feed.protocol import (
BandArticle, BandEvent, Bands, Cut, GakSlide, Hero, HeroStat, HeroTomorrow, HourCell, HoursSlide, ImageSlide, PostData, PostReaction, Res_Feed, Row, RowsSlide, SunsetSlide,
PlanSlide, PlanStep, TopIndex, WeatherWhy, WeekDay, WeekGak, WeekSlide,
)
from router.v1.index.protocol import TrendPoint
from services.air_service import GRADE_LABEL as AIR_GRADE_LABEL
from services.air_service import pm10_grade, pm25_grade
from services.bot_comment import fill_bot_comments
@@ -34,7 +34,7 @@ from services.calc.moon import MoonNight, nearest, night, view_line
from services.calc.sky_score import GRADE_LABEL, sky_title
from services.calc.sun import sun_times
from services.hero_stats import UV_HIGH, HeroInput, discomfort_label, hero_stats, hero_status, uv_label, uv_level
from services.index_service import IndexBoard, IndexItem, IndexService
from services.index_service import IndexBoard, IndexItem, IndexService, slot_label
from services.now_service import NowService, NowWeather
from services.season_service import SeasonService
from services.sky_service import SkyService, SkyView, day_verdict
@@ -425,7 +425,7 @@ class FeedService:
cards.append(data)
gak_posts = sorted((p for p in posts or [] if PostType(p.post_type) is PostType.GAK), key=lambda p: p.index_rank or 0)
for p, item in zip(gak_posts, gak):
cards.append(self._gak(p, item))
cards.append(self._gak(p, item, board.day))
has_warning = bool(now_w and now_w.warnings)
# 오늘 이야기 줄엔 제철인 각만 (철 지난 각은 각 탭 목록 끝에만)
items = [i for i in board.items if i.in_season] if board else []
@@ -504,10 +504,11 @@ class FeedService:
return dict(post_id=p.post_id, post_type=PostType(p.post_type), like_count=p.like_count, comment_count=p.comment_count,
published_at=p.published_at.astimezone(KST))
def _gak(self, p: Post, i: IndexItem) -> PostData:
def _gak(self, p: Post, i: IndexItem, today: date) -> PostData:
d = i.definition
return PostData(**self._base(p), title=f"{d.name} {i.score.score}점", icon=d.icon, caption=_gak_caption(i),
slides=[GakSlide(kind="gak", index_id=d.index_id, code=d.code, name=d.name, rank=i.rank, score=i.score.score, line=d.description, summary=i.score.summary, rows=gak_rows(i), say=_band_sentence(d.sentences, i.score.score))],
slides=[GakSlide(kind="gak", index_id=d.index_id, code=d.code, name=d.name, rank=i.rank, score=i.score.score, line=d.description, summary=i.score.summary, say=_band_sentence(d.sentences, i.score.score),
trend=[TrendPoint(day=t.score_date, label=slot_label(t.score_date, today), score=t.score, estimated=t.estimated) for t in i.trend])],
share_messages=[f"오늘 {d.name} 어때? {d.name} {i.score.score}점이래"])
def _render(self, p: Post, c: "_Ctx") -> Optional[PostData]:
@@ -541,7 +542,11 @@ class FeedService:
if len(soon) < rank:
return None
e = soon[rank - 1]
rows = ([Row(label="장소", value=e.event.place_name, place=e.event.place_name)] if e.event.place_name else []) + [Row(label="기간", value=day_range(e.event.start_date, e.event.end_date))]
ev = e.event
# 장소 이름이 행사 이름과 같으면(출처에 장소가 비어 이름이 들어간 것) 빼고, 주소는 눌러서 지도로
rows = ([Row(label="장소", value=ev.place_name, place=ev.address or ev.place_name)] if ev.place_name and ev.place_name != ev.name else [])
rows += [Row(label="주소", value=ev.address, place=ev.address)] if ev.address and ev.address != ev.place_name else []
rows += [Row(label="기간", value=day_range(ev.start_date, ev.end_date))]
caption = _event_caption(e)
return PostData(**base, title=e.event.name, icon=e.event.icon, caption=caption,
slides=[RowsSlide(kind="rows", eyebrow=f"가까운 행사 · {e.status_label}", line=e.event.name, icon=e.event.icon, rows=rows, image=e.event.image_url, image_credit=image_credit(e.event))],
@@ -608,7 +613,10 @@ class FeedService:
share_messages=[f"오늘 밤은 {name}이래 🌙"])
when = f"{'내일 ' if at.date() > tonight.date() else ''}{at:%H:%M}"
if is_full:
line = f"오늘 밤 보름달,\n{when}에 가장 둥글어요"
# 가장 둥근 순간이 낮(달이 안 보일 때)이면 그 시각 대신 뜨는 시각을 알려 준다
daytime = 6 <= at.hour < 17
line = (f"오늘 밤 보름달,\n{when}에 가장 둥글어요" if not daytime
else f"오늘 밤 보름달,\n{_clock_word(m.rise_at)}에 떠요" if m.rise_at else "오늘 밤 보름달,\n저녁부터 밤새 떠 있어요")
caption = "구름 사이로 잠깐씩 보일 수 있어요." if view.startswith("흐려서") else "소원 빌기 딱 좋은 밤이에요 🌕"
return PostData(**base, title="오늘 밤 보름달", icon="moon", caption=caption,
slides=[RowsSlide(kind="rows", eyebrow=eyebrow, line=line, icon="moon", moon_pct=100, moon_waxing=False, rows=[Row(label="보이는지", value=view), *rows])],
@@ -779,30 +787,6 @@ def _band_sentence(sentences: Optional[dict], score: int) -> Optional[str]:
return sentences[str(lo)] if lo is not None else None
# 각 포스트에 보일 근거 줄 이름. 시간(요일·노을 점수)은 계산 방식 설명이라 뺀다
_AXIS_NAME = {"temp": "기온", "rain": "비", "wind": "바람", "humidity": "습도", "air": "미세먼지", "uv": "자외선", "sun": "햇볕", "view": "시야"}
_NOTE_HEAD = {"wind": "바람 ", "humidity": "습도 ", "air": "초미세먼지 "}
def gak_rows(i: IndexItem, n: int = 4) -> list[Row]:
"""비중이 큰 조건부터 n개와 지금 값. 점수에 안 쓰는 조건도 n개가 될 때까지 지금 날씨로 채운다. 값은 계산 근거 문구의 첫 마디 (체감 18°, 확률 20%, 초속 3m)."""
d, notes = i.definition, i.score.notes or {}
weighted = sorted((a for a in _AXIS_NAME if getattr(d, f"weight_{a}", 0) and notes.get(a)), key=lambda a: -getattr(d, f"weight_{a}"))
axes = weighted + [a for a in ("temp", "rain", "wind", "air", "humidity") if a not in weighted and notes.get(a)]
rows = []
for a in axes[:n]:
head, _, tail = notes[a].partition(", ")
prob = re.search(r"확률 \d+%", notes[a]) if a == "rain" else None
if prob:
value = prob.group(0)
elif a == "air" and tail:
value = tail
else:
value = head.removeprefix(_NOTE_HEAD.get(a, ""))
rows.append(Row(label=_AXIS_NAME[a], value=value))
return rows
def _gak_caption(i: IndexItem) -> str:
"""슬라이드에 없는 내일 점수(없으면 하기 좋은 시간). 점수 구간 설명 문장은 슬라이드에 있다."""
nxt = next((x for x in i.trend if x.score_date > i.score.score_date), None)
+26
View File
@@ -0,0 +1,26 @@
{
"cards": [
{ "code": "date", "reading": "미뤄 둔 약속, 오늘은 먼저 연락해 보세요.", "color": "코랄", "hex": "#ff7f6e" },
{ "code": "yajang", "reading": "퇴근길에 바깥 자리 하나 잡고 오늘 얘기를 풀어 보세요.", "color": "호박색", "hex": "#e9a23b" },
{ "code": "chimaek", "reading": "오늘 고생한 나한테 치킨 한 마리쯤은 괜찮아요.", "color": "머스터드", "hex": "#d9a400" },
{ "code": "sentimental", "reading": "마음이 몽글한 날이에요. 오래 못 본 사람에게 안부를 보내 보세요.", "color": "라벤더", "hex": "#b8a6e3" },
{ "code": "mood_song", "reading": "출근길 이어폰에 예전에 좋아하던 노래를 걸어 보세요.", "color": "네이비", "hex": "#25335c" },
{ "code": "jipkok", "reading": "오늘은 약속보다 이불이 반가운 날, 쉬는 것도 일이에요.", "color": "오트밀", "hex": "#e3d7c3" },
{ "code": "netflix", "reading": "찜만 해 둔 그 영화, 오늘 밤에 볼 차례예요.", "color": "버건디", "hex": "#7a1f2b" },
{ "code": "pajeon", "reading": "오늘은 혼자 먹는 것보다 둘이 나눠 먹는 게 더 맛있어요.", "color": "올리브", "hex": "#7d8a3a" },
{ "code": "bungeoppang", "reading": "주머니에 현금 한 장 챙겨 두면 길에서 작은 기쁨을 만나요.", "color": "브라운", "hex": "#8b5a2b" },
{ "code": "sweetpotato", "reading": "손 시린 사람에게 따뜻한 걸 건네면 오래 기억돼요.", "color": "테라코타", "hex": "#c8643c" },
{ "code": "iced_hot", "reading": "오늘은 차가운 것보다 따뜻한 한 잔이 머리를 맑게 해 줘요.", "color": "카멜", "hex": "#c19a6b" },
{ "code": "stars", "reading": "잠들기 전 하늘을 한 번 올려다보면 고민이 작아 보여요.", "color": "짙은 파랑", "hex": "#1f3a7a" },
{ "code": "riverwind", "reading": "저녁 바람 쐬며 걷다 보면 꼬였던 생각이 풀려요.", "color": "민트", "hex": "#9fdcc8" },
{ "code": "photo", "reading": "오늘 본 예쁜 장면 하나를 사진으로 남겨 두세요.", "color": "피치", "hex": "#ffc2a1" },
{ "code": "walk", "reading": "해 진 뒤 동네 한 바퀴가 생각 정리에 딱 좋아요.", "color": "세이지", "hex": "#a3b899" },
{ "code": "running", "reading": "짧게라도 뛰어 보세요. 움직인 만큼 내일 몸이 가벼워요.", "color": "라임", "hex": "#b5d334" },
{ "code": "picnic", "reading": "점심은 밖에서, 햇볕 아래 잠깐이 오후를 바꿔요.", "color": "버터 옐로", "hex": "#f6e27f" },
{ "code": "drive", "reading": "창문 열고 좋아하는 길로 한 바퀴 돌면 기분이 바뀌어요.", "color": "하늘색", "hex": "#8ec5f0" },
{ "code": "foliage", "reading": "지금 아니면 못 보는 것부터 챙기세요. 미루면 지나가요.", "color": "오렌지", "hex": "#f07a2a" },
{ "code": "camping", "reading": "주말 계획을 오늘 정해 두면 한 주가 가벼워져요.", "color": "숲 초록", "hex": "#2f5d3a" },
{ "code": "themepark", "reading": "오늘은 어른스럽지 않아도 돼요. 마음껏 웃어 보세요.", "color": "핫핑크", "hex": "#ff5fa2" },
{ "code": "dog", "reading": "오늘은 누군가와 나란히 걷는 시간이 행운이에요.", "color": "크림", "hex": "#f3ead8" }
]
}
+210
View File
@@ -0,0 +1,210 @@
import json
import random
import re
from dataclasses import dataclass
from datetime import date, timedelta
from pathlib import Path
from typing import Optional
from fastapi import Depends
from common.database.db_session_manager import DB_SESSION_MNG
from common.database.model.models import DayLog, User
from common.enums import ErrorType
from common.utils.kma_time import now_kst
from crud.fortune_crud import FortuneCRUD
from services.calc.day_slot import SLOTS, slot_hours
from services.calc.sun import sun_times
from services.index_service import IndexService, current_slot, shown_slot
from services.level_service import award
from services.week_service import WeekService
# 오늘 한 장 덱: 각 코드마다 리딩 한 문장과 행운 색. 이름·아이콘은 각 정의에서 가져온다
DECK: dict[str, dict] = {c["code"]: c for c in json.loads((Path(__file__).parent / "fortune_deck.json").read_text(encoding="utf-8"))["cards"]}
# 연속 기록은 이만큼 거슬러 올라가 센다. 기기에서 옮겨 오는 기록도 이 안쪽만 받는다
HISTORY_DAYS = 60
# 연속 기록에서 쉬는 날은 이 간격에 한 번만 봐준다
REST_EVERY_DAYS = 7
PLACE_LIMIT = 8
_PLACE_REF = re.compile(r"^(place|spot|event):\d{1,12}$")
def streak(days: set[date], today: date) -> int:
"""오늘(아직 안 뽑았으면 어제)부터 거꾸로 이어 뽑은 날 수. 하루 빠진 날은 7일에 한 번 쉬는 날로 봐준다."""
d = today if today in days else today - timedelta(days=1)
count, rests = 0, []
while True:
if d in days:
count += 1
elif d - timedelta(days=1) in days and all((r - d).days >= REST_EVERY_DAYS for r in rests):
rests.append(d)
else:
return count
d -= timedelta(days=1)
def hours_text(hours: set[int]) -> str:
"""구간 시각(24 이상은 다음 날)을 '오후 4~7시'처럼. 끝은 마지막 시각의 다음 정각."""
start, end = min(hours), max(hours) + 1
def part(h: int) -> tuple[str, int]:
h %= 24
word = "새벽" if h < 6 else "오전" if h < 12 else "오후"
return word, h % 12 or 12
(w1, h1), (w2, h2) = part(start), part(end)
return f"{w1} {h1}~{h2}시" if w1 == w2 else f"{w1} {h1}시~{w2} {h2}시"
@dataclass
class Card:
code: str
name: str
icon: str
reading: str
color: str
hex: str
@dataclass
class Luck:
time: Optional[str] # 오늘 남은 구간 중 날씨 점수가 가장 높은 때
place: Optional[str] # 날씨 맞춤 데이트 명소 첫 곳
place_id: Optional[int]
top_gak: Optional[str] # 지금 1위 각
top_icon: Optional[str]
@dataclass
class Today:
day: date
card: Optional[Card]
luck: Optional[Luck]
streak: int
checkin_open: bool # 저녁(해 지기 2시간 전)부터 체크인을 받는다
log: Optional[DayLog] = None
class FortuneService:
def __init__(self, crud: FortuneCRUD = Depends(FortuneCRUD), index: IndexService = Depends(IndexService), week: WeekService = Depends(WeekService)) -> None:
self.crud, self.index, self.week = crud, index, week
async def _card(self, code: str) -> Optional[Card]:
if code not in DECK:
return None
err, defs = await DB_SESSION_MNG.execute_lambda(lambda s: self.index.crud.definitions(s))
d = next((d for d in defs or [] if d.code == code), None)
if err is not ErrorType.SUCCESS or d is None:
return None
c = DECK[code]
return Card(code=code, name=d.name, icon=d.icon, reading=c["reading"], color=c["color"], hex=c["hex"])
async def _luck(self, region_code: str) -> tuple[ErrorType, Optional[Luck], bool]:
err, board = await self.index.board(region_code)
if err is not ErrorType.SUCCESS or board is None:
return err, None, False
now = now_kst()
sunset_at = sun_times(board.day, float(board.region.lat), float(board.region.lon)).sunset_at
cur = current_slot(now, sunset_at)
left = SLOTS[SLOTS.index(shown_slot(cur)):]
best = max((k for k in left if k in board.weather_slots), key=lambda k: board.weather_slots[k], default=None)
_, places, _, _ = await self.week.places(region_code, board.day, None)
place = next((p for p in places if p.is_good), places[0] if places else None)
top = board.ranked[0].definition if board.ranked else None
luck = Luck(
time=hours_text(slot_hours(board.day, sunset_at)[best]) if best else None,
place=place.place.name if place else None, place_id=place.place.place_id if place else None,
top_gak=top.name if top else None, top_icon=top.icon if top else None,
)
return ErrorType.SUCCESS, luck, cur in ("evening", "night")
async def _streak(self, user: User, today: date) -> tuple[ErrorType, int]:
err, days = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.draw_days(s, user.user_id, today - timedelta(days=HISTORY_DAYS)))
return err, streak(set(days or []), today)
async def today(self, region_code: str, user: Optional[User]) -> tuple[ErrorType, Optional[Today]]:
"""로그인했으면 오늘 뽑은 카드·체크인·연속 기록. 안 뽑았으면 카드 없이"""
today = now_kst().date()
if user is None:
return ErrorType.SUCCESS, Today(day=today, card=None, luck=None, streak=0, checkin_open=False)
err, row = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.draw_of(s, user.user_id, today))
if err is not ErrorType.SUCCESS:
return err, None
err, n = await self._streak(user, today)
if err is not ErrorType.SUCCESS:
return err, None
if row is None:
return ErrorType.SUCCESS, Today(day=today, card=None, luck=None, streak=n, checkin_open=False)
err, luck, open_ = await self._luck(region_code)
if err is not ErrorType.SUCCESS:
return err, None
err, log = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.log_of(s, user.user_id, today))
if err is not ErrorType.SUCCESS:
return err, None
return ErrorType.SUCCESS, Today(day=today, card=await self._card(row.card_code), luck=luck, streak=n, checkin_open=open_, log=log)
async def draw(self, region_code: str, user: Optional[User], card_code: Optional[str], days: list[date]) -> tuple[ErrorType, Optional[Today]]:
"""하루 한 장. 로그인했으면 그날 처음 뽑은 카드, 안 했으면 기기에 있는 오늘 카드(없으면 새로 뽑음)와 기기에 남은 뽑은 날로 연속 기록."""
today = now_kst().date()
fresh = random.choice(list(DECK))
if user is not None:
err, row = await DB_SESSION_MNG.execute_lambda_write(lambda s: self.crud.add_draw(s, user.user_id, today, fresh))
if err is not ErrorType.SUCCESS or row is None:
return err, None
code = row.card_code
await award(user.user_id, "tarot")
err, n = await self._streak(user, today)
if err is not ErrorType.SUCCESS:
return err, None
err, log = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.log_of(s, user.user_id, today))
if err is not ErrorType.SUCCESS:
return err, None
else:
code = card_code if card_code in DECK else fresh
n, log = streak({d for d in days if today - timedelta(days=HISTORY_DAYS) <= d < today} | {today}, today), None
card = await self._card(code)
if card is None:
return ErrorType.DB_ERROR, None
err, luck, open_ = await self._luck(region_code)
if err is not ErrorType.SUCCESS:
return err, None
return ErrorType.SUCCESS, Today(day=today, card=card, luck=luck, streak=n, checkin_open=open_, log=log)
async def save_log(self, user: User, region_code: str, mood: int, went_out: bool, place_name: Optional[str], place_ref: Optional[str], card_hit: Optional[bool]) -> tuple[ErrorType, Optional[DayLog]]:
values = clean_log(mood, went_out, place_name, place_ref, card_hit, region_code)
if values is None:
return ErrorType.INVALID_INPUT, None
today = now_kst().date()
err, log = await DB_SESSION_MNG.execute_lambda_write(lambda s: self.crud.save_log(s, user.user_id, today, values))
if err is ErrorType.SUCCESS:
await award(user.user_id, "checkin")
return err, log
async def import_local(self, user: User, draws: list[tuple[date, str]], logs: list[tuple[date, dict]]) -> ErrorType:
"""로그인할 때 기기에 있던 뽑은 카드·체크인을 계정으로. 최근 60일, 덱에 있는 카드, 형식이 맞는 체크인만"""
today = now_kst().date()
since = today - timedelta(days=HISTORY_DAYS)
ok_draws = [(d, c) for d, c in draws if since <= d <= today and c in DECK]
ok_logs = [(d, v) for d, raw in logs if since <= d <= today and (v := clean_log(**raw)) is not None]
err, _ = await DB_SESSION_MNG.execute_lambda_write(lambda s: self.crud.import_rows(s, user.user_id, ok_draws, ok_logs))
return err
async def places(self, region_code: str, q: str) -> tuple[ErrorType, list[tuple[str, str]]]:
q = " ".join(q.split())
if not q:
return ErrorType.SUCCESS, []
today = now_kst().date()
return await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.search_places(s, q, region_code[:2], today, PLACE_LIMIT))
def clean_log(mood: int, went_out: bool, place_name: Optional[str], place_ref: Optional[str], card_hit: Optional[bool], region_code: str) -> Optional[dict]:
"""체크인 값 확인. 안 나갔으면 다녀온 곳은 비운다"""
if not 1 <= mood <= 5 or not region_code:
return None
name = " ".join((place_name or "").split())[:40] or None
if place_ref is not None and not _PLACE_REF.match(place_ref):
return None
if not went_out:
name, place_ref = None, None
return {"mood": mood, "went_out": went_out, "place_name": name, "place_ref": place_ref if name else None, "card_hit": card_hit, "region_code": region_code[:10]}
+141
View File
@@ -0,0 +1,141 @@
import uuid
from dataclasses import dataclass
from datetime import date, timedelta
from typing import Optional
from fastapi import Depends
from common.database.db_session_manager import DB_SESSION_MNG
from common.database.model.models import User
from common.enums import ErrorType
from common.logger import LOG
from common.utils.kma_time import now_kst
from crud.level_crud import LevelCRUD
# 계정 레벨: 모은 각 총량으로 정한다 (쓰는 기능이 생겨도 레벨은 안 내려간다). 사용자 결정 10/28
LEVELS: list[tuple[int, str]] = [(0, "이슬"), (30, "햇살"), (100, "산들바람"), (200, "무지개"), (400, "노을"), (700, "은하수"), (1000, "별똥별")]
# 각을 주는 일: (한 번에 주는 각, 하루 한도, 이름). 로그인한 사람만 쌓인다
ACTIONS: dict[str, tuple[int, int, str]] = {
"attend": (10, 10, "출석"),
"tarot": (10, 10, "오늘 타로 뽑기"),
"saju": (10, 10, "날씨 사주 오늘 기운"),
"react": (5, 10, "좋아요·댓글"),
"talk": (20, 20, "동네 이야기 글쓰기"),
"checkin": (10, 10, "저녁 체크인"),
"share": (10, 10, "공유하기"),
"streak": (50, 50, "7일 연속 출석"),
}
STREAK_DAYS = 7
STREAK_LOOKBACK = 60
# 레벨로 열리는 것: 새로 생기는 것만 잠근다 (지금 있는 기능·캐릭터·색·기분은 그대로)
UNLOCKS: dict[int, list[tuple[str, str]]] = {
2: [("saju_week", "날씨 사주 이번 주 흐름")],
3: [("saju_money", "금전운 · 일운")],
4: [("saju_love", "연애운")],
5: [("saju_match", "궁합")],
6: [("saju_month", "이달 운")],
7: [("saju_year", "올해 운")],
}
def level_of(points: int) -> int:
return max(i + 1 for i, (need, _) in enumerate(LEVELS) if points >= need)
def unlock_level(key: str) -> int:
return next((lv for lv, items in UNLOCKS.items() if any(k == key for k, _ in items)), 1)
def is_unlocked(points: int, key: str) -> bool:
return level_of(points) >= unlock_level(key)
def streak(days: set[date], today: date) -> int:
"""오늘부터 거꾸로 이어 출석한 날 수"""
n = 0
while today - timedelta(days=n) in days:
n += 1
return n
async def award(user_id: uuid.UUID, action: str, ref: str = "") -> int:
"""각을 준다. 하루 한도·같은 대상 중복이면 주지 않는다. 본래 동작을 막지 않게 실패는 로그만 남긴다. 새 총량(안 줬으면 0)"""
per, cap, _ = ACTIONS[action]
day = now_kst().date()
crud = LevelCRUD()
err, earned = await DB_SESSION_MNG.execute_lambda(lambda s: crud.earned(s, user_id, day, action))
if err is not ErrorType.SUCCESS:
LOG.error(f"[level] 각 조회 실패 {action}")
return 0
if earned >= cap:
return 0
points = min(per, cap - earned)
err, total = await DB_SESSION_MNG.execute_lambda_write(lambda s: crud.add(s, user_id, day, action, ref, points))
if err is not ErrorType.SUCCESS:
LOG.error(f"[level] 각 적립 실패 {action}")
return 0
if action == "attend" and total:
err, days = await DB_SESSION_MNG.execute_lambda(lambda s: crud.attend_days(s, user_id, day - timedelta(days=STREAK_LOOKBACK)))
n = streak(set(days or []), day) if err is ErrorType.SUCCESS else 0
if n and n % STREAK_DAYS == 0:
more = await award(user_id, "streak", str(n))
total = more or total
return total or 0
@dataclass
class TodayAction:
action: str
name: str
points: int # 한 번에 주는 각
cap: int
earned: int
@dataclass
class Status:
points: int
level: int
name: str
floor: int # 지금 레벨이 시작하는 각
next_points: Optional[int] # 다음 레벨까지 필요한 총량 (마지막 레벨이면 없음)
next_name: Optional[str]
streak: int
today: list[TodayAction]
unlocks: list[tuple[int, str, str]] # (레벨, 키, 이름)
class LevelService:
def __init__(self, crud: LevelCRUD = Depends(LevelCRUD)) -> None:
self.crud = crud
async def status(self, user: User) -> tuple[ErrorType, Optional[Status]]:
day = now_kst().date()
err, points = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.points(s, user.user_id))
if err is not ErrorType.SUCCESS:
return err, None
err, today = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.today(s, user.user_id, day))
if err is not ErrorType.SUCCESS:
return err, None
err, days = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.attend_days(s, user.user_id, day - timedelta(days=STREAK_LOOKBACK)))
if err is not ErrorType.SUCCESS:
return err, None
lv = level_of(points)
floor, name = LEVELS[lv - 1]
nxt = LEVELS[lv] if lv < len(LEVELS) else None
return ErrorType.SUCCESS, Status(
points=points, level=lv, name=name, floor=floor, next_points=nxt[0] if nxt else None, next_name=nxt[1] if nxt else None,
streak=streak(set(days), day),
today=[TodayAction(action=a, name=n, points=p, cap=c, earned=(today or {}).get(a, 0)) for a, (p, c, n) in ACTIONS.items() if a != "streak"],
unlocks=[(lv_, k, n) for lv_, items in UNLOCKS.items() for k, n in items],
)
async def attend(self, user: User) -> tuple[ErrorType, Optional[Status]]:
await award(user.user_id, "attend")
return await self.status(user)
async def share(self, user: User) -> tuple[ErrorType, Optional[Status]]:
await award(user.user_id, "share")
return await self.status(user)
+3 -2
View File
@@ -40,7 +40,7 @@ class MyGakService:
err, rows = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.of_user(s, user.user_id))
return err, rows or []
async def add(self, user: User, name: str, rule: dict) -> tuple[ErrorType, Optional[MyGak]]:
async def add(self, user: User, name: str, rule: dict, icon: Optional[str] = None) -> tuple[ErrorType, Optional[MyGak]]:
name = gak_name(name)
if name is None:
return ErrorType.INVALID_INPUT, None
@@ -49,7 +49,7 @@ class MyGakService:
return err, None
if n >= MAX_PER_USER:
return ErrorType.INVALID_INPUT, None
return await DB_SESSION_MNG.execute_lambda_write(lambda s: self.crud.add(s, user.user_id, name, rule))
return await DB_SESSION_MNG.execute_lambda_write(lambda s: self.crud.add(s, user.user_id, name, rule, icon))
async def delete(self, user: User, my_gak_id: int) -> ErrorType:
err, found = await DB_SESSION_MNG.execute_lambda_write(lambda s: self.crud.delete(s, user.user_id, my_gak_id))
@@ -79,5 +79,6 @@ class MyGakService:
"score": res.score if res else None, "slot": key if res else None,
"slots": {k: v.score for k, v in picked.items()},
"reasons": [res.notes[a] for a in axes(r) if res.notes.get(a)] if res else [],
"factors": {a: res.factors[a] for a in axes(r) if res.notes.get(a) and a in res.factors} if res else {},
})
return ErrorType.SUCCESS, (now_slot, out)
+6 -1
View File
@@ -14,6 +14,7 @@ from crud.feed_crud import FeedCRUD
from crud.reaction_crud import ReactionCRUD
from crud.region_crud import RegionCRUD
from services.bot_comment import BOT_COLORS, BOT_NAMES
from services.level_service import award
from services.talk_service import _LINK, _PHONE
COMMENT_MAX = 60
@@ -55,7 +56,10 @@ class ReactionService:
err = await self._post_exists(post_id)
if err is not ErrorType.SUCCESS:
return err, None
return await DB_SESSION_MNG.execute_lambda_write(lambda s: self.crud.toggle_post_like(s, post_id, who, on))
err, count = await DB_SESSION_MNG.execute_lambda_write(lambda s: self.crud.toggle_post_like(s, post_id, who, on))
if err is ErrorType.SUCCESS and on and who.user_id is not None:
await award(who.user_id, "react", f"post:{post_id}")
return err, count
async def save_post(self, post_id: int, user: User, on: bool) -> ErrorType:
err = await self._post_exists(post_id)
@@ -139,6 +143,7 @@ class ReactionService:
return err, None
if user is None:
return err, self._view(c, None, None, None, None, False, who)
await award(user.user_id, "react", f"comment:{c.comment_id}")
return err, self._view(c, user.nickname, user.character, user.color, user.mood, False, who)
async def delete_comment(self, comment_id: int, who: Liker) -> ErrorType:
+16
View File
@@ -14,6 +14,7 @@ from common.utils.kma_time import kst_midnight, now_kst
from crud.region_crud import RegionCRUD
from crud.talk_crud import TalkCRUD
from crud.weather_crud import WeatherCRUD
from services.level_service import award
from services.talk_image import is_ours
BODY_MAX = 100
@@ -66,6 +67,20 @@ def group_age(t: Talk, region_code: Optional[str], now: datetime) -> float:
return age - near - LIKE_H * math.log2(1 + t.like_count)
def ago_text(at: datetime, now: datetime) -> str:
"""글 시간: 방금 · N분 전 · N시간 전 · N일 전 · N주 전 (하루가 넘으면 시간 대신 날로)"""
minutes = max(0, int((now - at).total_seconds() // 60))
if minutes < 5:
return "방금"
if minutes < 60:
return f"{minutes}분 전"
hours = minutes // 60
if hours < 24:
return f"{hours}시간 전"
days = hours // 24
return f"{days}일 전" if days < 7 else f"{days // 7}주 전"
def pick_group(views: list["TalkView"], region_code: Optional[str], now: datetime) -> list["TalkView"]:
"""한 사람 한 장, 최대 GROUP_MAX 장. 첫 장은 신고 받은 적 없는 글"""
out: list[TalkView] = []
@@ -190,6 +205,7 @@ class TalkService:
err, t = await DB_SESSION_MNG.execute_lambda_write(lambda s: self.crud.add(s, user.user_id, region_code, body, weather, image, topic.value))
if err is not ErrorType.SUCCESS or t is None:
return err, None
await award(user.user_id, "talk", str(t.talk_id))
return ErrorType.SUCCESS, TalkView(talk=t, author=user, region_name=region.short_name, liked=False, mine=True)
async def delete(self, user: User, talk_id: int) -> ErrorType:
+13
View File
@@ -142,3 +142,16 @@ async def test_instagram_requires_token(offline, admin_key, monkeypatch):
made = (await c.post("/v1/card", json=body(), headers=admin_key)).json()
res = (await c.post(f"/v1/card/{made['card_id']}/instagram", headers=admin_key)).json()
assert res["result"]["success"] is False and "INSTAGRAM" in res["msg"]
@pytest.mark.anyio
async def test_latest_card_by_template_is_public(offline, admin_key):
async with client() as c:
assert "post_id" not in (await c.get("/v1/card/latest", params={"template": "ootd"})).json()
ootd = (await c.post("/v1/card", json=body(template="ootd", title="오늘 코디", publish=True), headers=admin_key)).json()
await c.post("/v1/card", json=body(template="ootd", title="승인 대기 코디"), headers=admin_key)
await c.post("/v1/card", json=body(publish=True), headers=admin_key)
# 그 틀로 피드에 올린 것 중 가장 최근 (승인 대기·다른 틀은 빼고)
latest = (await c.get("/v1/card/latest", params={"template": "ootd"})).json()
assert latest["post_id"] == ootd["post_id"] and latest["published_at"]
assert (await c.get("/v1/card/latest", params={"template": "../x"})).status_code == 422
-15
View File
@@ -416,18 +416,3 @@ def test_uv_post_only_when_moderate_or_higher():
assert FeedService._uv_post(None, base, ctx([(9, 1.0), (12, 2.5)])) is None
assert FeedService._uv_post(None, base, ctx([])) is None
def test_gak_rows_shows_heaviest_conditions_with_short_values():
from types import SimpleNamespace
from services.feed_service import gak_rows
d = SimpleNamespace(weight_temp=30, weight_rain=25, weight_wind=10, weight_humidity=0, weight_air=15, weight_uv=0, weight_sun=0, weight_view=0, weight_time=20)
notes = {"temp": "체감 18°, 편한 범위 15~25° 안", "rain": "비 확률 20%", "wind": "바람 초속 3.1m", "air": "초미세먼지 16㎍/㎥, 좋음", "time": "수요일"}
item = SimpleNamespace(definition=d, score=SimpleNamespace(notes=notes))
assert [(r.label, r.value) for r in gak_rows(item, 3)] == [("기온", "체감 18°"), ("비", "확률 20%"), ("미세먼지", "좋음")]
# 점수에 안 쓰는 조건은 뒤에 지금 날씨로 채운다
d.weight_wind = 0
assert [r.label for r in gak_rows(item)] == ["기온", "비", "미세먼지", "바람"]
item.score.notes = {**notes, "rain": "비 소식, 내일까지 비 확률 70%"}
assert gak_rows(item)[1].value == "확률 70%"
-18
View File
@@ -1,18 +0,0 @@
from starlette.requests import Request
from common.enums import PostType
from router.v1.feed.feed import TOSS_KNOWN_MAX, _from_toss
def _req(headers: dict) -> Request:
return Request({"type": "http", "headers": [(k.lower().encode(), v.encode()) for k, v in headers.items()]})
def test_from_toss_by_referer_or_user_agent():
assert _from_toss(_req({"referer": "https://nalssigak.apps.tossmini.com/"}))
assert _from_toss(_req({"user-agent": "Mozilla/5.0 ... AppsInToss TossApp/5.282.1"}))
assert not _from_toss(_req({"referer": "https://weather.o2o.kr/", "user-agent": "Mozilla/5.0 Safari"}))
def test_card_is_hidden_from_old_toss_bundle():
assert PostType.CARD.value > TOSS_KNOWN_MAX >= PostType.UV.value
+128
View File
@@ -0,0 +1,128 @@
from datetime import date, timedelta
import pytest
from httpx import ASGITransport, AsyncClient
from common.utils.kma_time import now_kst
from router.router import app
from services.fortune_service import DECK, clean_log, hours_text, streak
REGION = "1144000000"
D = date(2026, 10, 28)
def client():
return AsyncClient(transport=ASGITransport(app=app), base_url="http://test")
async def _login(c, login_id: str) -> dict:
body = (await c.post("/v1/auth/signup", json={"login_id": login_id, "password": "password1", "nickname": login_id})).json()
return {"Authorization": f"Bearer {body['access_token']}"}
def _days(*back: int) -> set[date]:
return {D - timedelta(days=b) for b in back}
def test_deck_is_22_cards_with_reading_and_color():
assert len(DECK) == 22
assert all(c["reading"] and c["color"] and c["hex"].startswith("#") for c in DECK.values())
def test_streak_counts_back_from_today_or_yesterday():
assert streak(set(), D) == 0
assert streak(_days(0, 1, 2), D) == 3
# 오늘 아직 안 뽑았으면 어제까지 센다
assert streak(_days(1, 2), D) == 2
def test_streak_forgives_one_rest_day_a_week():
# 하루 빠진 날(2일 전)은 쉬는 날로 봐준다
assert streak(_days(0, 1, 3, 4), D) == 4
# 이틀 연속 빠지면 끊긴다
assert streak(_days(0, 3, 4), D) == 1
# 쉬는 날이 7일 안에 두 번이면 두 번째에서 끊긴다
assert streak(_days(0, 2, 4, 5), D) == 2
# 7일 넘게 떨어져 있으면 두 번 다 봐준다
assert streak(_days(0, 2, 3, 4, 5, 6, 7, 8, 10), D) == 9
def test_hours_text():
assert hours_text({16, 17, 18}) == "오후 4~7시"
assert hours_text({11, 12, 13, 14}) == "오전 11시~오후 3시"
assert hours_text(set(range(19, 29))) == "오후 7시~새벽 5시"
def test_clean_log_drops_place_when_stayed_home_and_rejects_bad_ref():
v = clean_log(2, False, "하늘공원", "spot:3", True, REGION)
assert v["place_name"] is None and v["place_ref"] is None and v["card_hit"] is True
assert clean_log(2, True, " 하늘 공원 ", "spot:3", None, REGION)["place_name"] == "하늘 공원"
assert clean_log(2, True, "하늘공원", "../x", None, REGION) is None
assert clean_log(6, True, None, None, None, REGION) is None
@pytest.mark.anyio
async def test_anon_draw_keeps_device_card_and_counts_device_days(offline):
today = now_kst().date()
async with client() as c:
first = (await c.post("/v1/fortune/draw", json={"region_code": REGION})).json()
assert first["card"]["code"] in DECK and first["card"]["name"].endswith("각")
assert first["luck"]["time"] and first["luck"]["top_gak"]
assert first["streak"] == 1
# 기기에 있는 오늘 카드를 넘기면 그 카드 그대로, 기기에 남은 뽑은 날로 연속 기록
again = (await c.post("/v1/fortune/draw", json={"region_code": REGION, "card_code": first["card"]["code"], "days": [str(today - timedelta(days=1)), str(today - timedelta(days=2))]})).json()
assert again["card"]["code"] == first["card"]["code"] and again["streak"] == 3
# 덱에 없는 카드면 새로 뽑는다
assert (await c.post("/v1/fortune/draw", json={"region_code": REGION, "card_code": "laundry"})).json()["card"]["code"] in DECK
# 로그인 안 했으면 오늘 보기는 카드 없이, 체크인은 못 한다
assert "card" not in (await c.get("/v1/fortune/today", params={"region": REGION})).json()
assert (await c.put("/v1/fortune/log", json={"region_code": REGION, "mood": 1, "went_out": False})).status_code == 401
@pytest.mark.anyio
async def test_login_draws_one_card_a_day_and_saves_checkin(offline):
async with client() as c:
h = await _login(c, "fortune_01")
assert "card" not in (await c.get("/v1/fortune/today", params={"region": REGION}, headers=h)).json()
first = (await c.post("/v1/fortune/draw", json={"region_code": REGION}, headers=h)).json()["card"]["code"]
# 다시 뽑아도, 기기 카드를 넘겨도 그날 처음 카드
other = next(k for k in DECK if k != first)
assert (await c.post("/v1/fortune/draw", json={"region_code": REGION, "card_code": other}, headers=h)).json()["card"]["code"] == first
today = (await c.get("/v1/fortune/today", params={"region": REGION}, headers=h)).json()
assert today["card"]["code"] == first and today["streak"] == 1 and "log" not in today
saved = (await c.put("/v1/fortune/log", json={"region_code": REGION, "mood": 2, "went_out": True, "place_name": "하늘공원", "place_ref": "spot:2", "card_hit": True}, headers=h)).json()
assert saved["log"]["place_name"] == "하늘공원" and saved["log"]["card_hit"] is True
# 다시 보내면 고친다
fixed = (await c.put("/v1/fortune/log", json={"region_code": REGION, "mood": 4, "went_out": False}, headers=h)).json()["log"]
assert fixed["mood"] == 4 and "place_name" not in fixed
assert (await c.get("/v1/fortune/today", params={"region": REGION}, headers=h)).json()["log"]["mood"] == 4
assert (await c.put("/v1/fortune/log", json={"region_code": REGION, "mood": 9, "went_out": False}, headers=h)).status_code == 422
@pytest.mark.anyio
async def test_import_moves_device_records_but_keeps_account_days(offline):
today = now_kst().date()
async with client() as c:
h = await _login(c, "fortune_02")
mine = (await c.post("/v1/fortune/draw", json={"region_code": REGION}, headers=h)).json()["card"]["code"]
other = next(k for k in DECK if k != mine)
body = {
"draws": [{"day": str(today), "card_code": other}, {"day": str(today - timedelta(days=1)), "card_code": other}, {"day": str(today - timedelta(days=90)), "card_code": other}],
"logs": [{"day": str(today - timedelta(days=1)), "region_code": REGION, "mood": 1, "went_out": False}],
}
assert (await c.post("/v1/fortune/import", json=body, headers=h)).json()["result"]["success"] is True
t = (await c.get("/v1/fortune/today", params={"region": REGION}, headers=h)).json()
# 오늘은 계정에서 뽑은 카드 그대로, 어제 기록이 더해져 2일째. 60일보다 오래된 날은 받지 않는다
assert t["card"]["code"] == mine and t["streak"] == 2
assert (await c.post("/v1/fortune/import", json=body)).status_code == 401
@pytest.mark.anyio
async def test_place_search_finds_spots_by_name():
async with client() as c:
items = (await c.get("/v1/fortune/places", params={"region": REGION, "q": "하늘공원"})).json()["items"]
assert any(i["name"] == "하늘공원" and i["ref"].startswith("spot:") for i in items)
# LIKE 기호는 글자 그대로 찾는다
assert (await c.get("/v1/fortune/places", params={"region": REGION, "q": "%"})).json()["items"] == []
assert (await c.get("/v1/fortune/places", params={"region": REGION, "q": " "})).json()["items"] == []
+104
View File
@@ -0,0 +1,104 @@
from datetime import timedelta
import pytest
from httpx import ASGITransport, AsyncClient
from sqlalchemy import select
from common.database.db_session_manager import DB_SESSION_MNG
from common.database.model.models import PointLog, User
from common.utils.kma_time import now_kst
from router.router import app
from services.level_service import LEVELS, is_unlocked, level_of
REGION = "1144000000"
pytestmark = pytest.mark.usefixtures("no_bot_comments")
def client():
return AsyncClient(transport=ASGITransport(app=app), base_url="http://test")
async def _login(c, login_id: str) -> dict:
body = (await c.post("/v1/auth/signup", json={"login_id": login_id, "password": "password1", "nickname": login_id})).json()
h = {"Authorization": f"Bearer {body['access_token']}"}
await c.post("/v1/auth/terms", headers=h)
return h
def _earned(level: dict, action: str) -> int:
return next(a["earned"] for a in level["today"] if a["action"] == action)
def test_level_thresholds_and_unlocks():
assert [need for need, _ in LEVELS] == [0, 30, 100, 200, 400, 700, 1000]
assert level_of(0) == 1 and level_of(29) == 1 and level_of(30) == 2 and level_of(199) == 3 and level_of(200) == 4 and level_of(5000) == 7
assert not is_unlocked(199, "saju_love") and is_unlocked(200, "saju_love")
assert not is_unlocked(399, "saju_match") and is_unlocked(400, "saju_match")
@pytest.mark.anyio
async def test_actions_award_once_and_respect_daily_caps(offline):
async with client() as c:
assert (await c.get("/v1/level/me")).status_code == 401
h = await _login(c, "level_01")
me = (await c.get("/v1/level/me", headers=h)).json()
assert me["points"] == 0 and me["level"] == 1 and me["name"] == "이슬" and me["next_points"] == 30
# 출석은 하루 한 번
assert (await c.post("/v1/level/attend", headers=h)).json()["points"] == 10
assert (await c.post("/v1/level/attend", headers=h)).json()["points"] == 10
# 좋아요·댓글은 5각씩 하루 10각, 같은 글을 다시 눌러도 더 안 줌
posts = [p["post_id"] for p in (await c.get("/v1/feed", params={"region": REGION})).json()["posts"][:3]]
await c.post(f"/v1/reaction/post/{posts[0]}/like", headers=h)
await c.delete(f"/v1/reaction/post/{posts[0]}/like", headers=h)
await c.post(f"/v1/reaction/post/{posts[0]}/like", headers=h)
assert _earned((await c.get("/v1/level/me", headers=h)).json(), "react") == 5
await c.post(f"/v1/reaction/post/{posts[1]}/comment", json={"body": "오늘 노을 기대돼요"}, headers=h)
await c.post(f"/v1/reaction/post/{posts[2]}/like", headers=h)
me = (await c.get("/v1/level/me", headers=h)).json()
assert _earned(me, "react") == 10 and me["points"] == 20
# 오늘 타로는 하루 한 번, 동네 이야기 글 20각 → 50각이면 Lv.2
await c.post("/v1/fortune/draw", json={"region_code": REGION}, headers=h)
await c.post("/v1/fortune/draw", json={"region_code": REGION}, headers=h)
await c.post("/v1/talk", json={"region_code": REGION, "body": "오늘 하늘 맑아요"}, headers=h)
me = (await c.get("/v1/level/me", headers=h)).json()
assert _earned(me, "tarot") == 10 and _earned(me, "talk") == 20
assert me["points"] == 50 and me["level"] == 2 and me["name"] == "햇살" and me["floor"] == 30 and me["next_points"] == 100
# 저녁 체크인·공유도 하루 한 번
await c.put("/v1/fortune/log", json={"region_code": REGION, "mood": 2, "went_out": False}, headers=h)
await c.put("/v1/fortune/log", json={"region_code": REGION, "mood": 3, "went_out": False}, headers=h)
await c.post("/v1/level/share", headers=h)
assert (await c.post("/v1/level/share", headers=h)).json()["points"] == 70
# 로그인 안 한 좋아요는 각이 없다 (다른 사람 계정에도 안 쌓임)
await c.post(f"/v1/reaction/post/{posts[0]}/like", headers={"X-Forwarded-For": "203.0.113.50"})
assert (await c.get("/v1/level/me", headers=h)).json()["points"] == 70
@pytest.mark.anyio
async def test_seven_day_attendance_bonus(offline):
async with client() as c:
h = await _login(c, "level_02")
await c.post("/v1/level/attend", headers=h)
today = now_kst().date()
async def backfill(s):
uid = await s.scalar(select(User.user_id).where(User.login_id == "level_02"))
s.add_all([PointLog(user_id=uid, day=today - timedelta(days=d), action="attend", ref="", points=10) for d in range(1, 7)])
await DB_SESSION_MNG.execute_lambda_write(backfill)
# 오늘 출석이 이미 있으니 다시 불러도 보너스가 생기지 않는다 → 다음 날처럼 오늘 기록을 지우고 다시 출석
async def drop_today(s):
uid = await s.scalar(select(User.user_id).where(User.login_id == "level_02"))
row = await s.scalar(select(PointLog).where(PointLog.user_id == uid, PointLog.day == today))
await s.delete(row)
user = await s.get(User, uid)
user.points -= 10
await DB_SESSION_MNG.execute_lambda_write(drop_today)
me = (await c.post("/v1/level/attend", headers=h)).json()
# 지난 6일은 장부만 넣어 총량엔 없다: 오늘 출석 10 + 7일 연속 50
assert me["streak"] == 7 and me["points"] == 60
+2 -1
View File
@@ -34,7 +34,8 @@ def _moon_post(now: datetime):
def test_moon_post_every_night_with_full_and_new_moon_stories():
full = _moon_post(datetime(2025, 10, 7, 20, 0, tzinfo=KST)) # 보름 10.07 12:47
assert full.title == "오늘 밤 보름달" and "12:4" in full.slides[0].line
# 가장 둥근 순간(12:47)이 낮이라 그 시각 대신 뜨는 시각·밤새 떠 있음을 말한다
assert full.title == "오늘 밤 보름달" and "12:4" not in full.slides[0].line and ("떠요" in full.slides[0].line or "밤새" in full.slides[0].line)
new = _moon_post(datetime(2024, 4, 9, 1, 0, tzinfo=KST)) # 삭 04.09 03:21, 자정 넘긴 새벽에도 그 밤
assert new.title == "오늘 밤 달 없는 밤"
plain = _moon_post(datetime(2025, 10, 4, 20, 0, tzinfo=KST)) # 보름 사흘 전
+5
View File
@@ -72,6 +72,11 @@ async def test_add_list_delete_and_limits():
item = (await c.post("/v1/my-gak", json={"name": "소맥", "rule": RULE}, headers=h)).json()["item"]
assert item["name"] == "소맥각" and item["rule"]["temp"] == [15, 25] and item["rule"]["slots"] == ["evening", "night"]
assert [g["my_gak_id"] for g in (await c.get("/v1/my-gak", headers=h)).json()["items"]] == [item["my_gak_id"]]
# 고른 아이콘을 저장하고, 아이콘 이름 꼴이 아니면 받지 않는다
picnic = (await c.post("/v1/my-gak", json={"name": "피크닉", "icon": "picnic", "rule": RULE}, headers=h)).json()["item"]
assert picnic["icon"] == "picnic"
assert (await c.post("/v1/my-gak", json={"name": "피크닉", "icon": "../x", "rule": RULE}, headers=h)).status_code == 422
await c.delete(f"/v1/my-gak/{picnic['my_gak_id']}", headers=h)
assert (await c.delete(f"/v1/my-gak/{item['my_gak_id']}", headers=h)).json()["result"]["success"] is True
assert (await c.delete(f"/v1/my-gak/{item['my_gak_id']}", headers=h)).json()["result"]["desc"] == "NOT_FOUND"
for i in range(MAX_PER_USER):
+1 -1
View File
@@ -22,7 +22,7 @@ def _page(popup_id: int, kind: str, start: str, end: str, address: str = "서울
def test_parse_popup_maps_store():
row = parse_popup(_page(501, "STORE", "2026-10-02", "2026-10-11"), 501, date(2026, 10, 1))
assert row == {
"source_id": "popga:501", "sido_code": "11", "name": "테스트 팝업 & 굿즈", "place_name": "테스트 빌딩 1F",
"source_id": "popga:501", "sido_code": "11", "name": "테스트 팝업 & 굿즈", "place_name": "테스트 빌딩 1F", "address": "서울 성동구 테스트로 1",
"start_date": date(2026, 10, 2), "end_date": date(2026, 10, 11), "is_confirmed": True,
"source_url": "https://popga.co.kr/popup/501", "image_url": None, "lat": 37.54461, "lon": 127.05575, "kind": EventKind.POPUP, "icon": "popup",
}
+14
View File
@@ -191,3 +191,17 @@ def test_pick_group_orders_near_fresh_first_one_per_person_clean_first():
assert [v.talk.talk_id for v in pick_group([far, same_sido, same_gu, old_popular, again], REGION, now)] == [5, 2, 1, 4]
reported = _view(6, "e", REGION, 0, reports=1)
assert pick_group([reported, far], REGION, now)[0].talk.talk_id == 1
def test_ago_text_switches_to_days_after_a_day():
from datetime import datetime, timedelta
from services.talk_service import ago_text
now = datetime(2026, 10, 27, 18, 0)
assert ago_text(now - timedelta(minutes=2), now) == "방금"
assert ago_text(now - timedelta(minutes=12), now) == "12분 전"
assert ago_text(now - timedelta(hours=23, minutes=59), now) == "23시간 전"
assert ago_text(now - timedelta(hours=24), now) == "1일 전"
assert ago_text(now - timedelta(hours=140), now) == "5일 전"
assert ago_text(now - timedelta(days=15), now) == "2주 전"
+26
View File
@@ -152,3 +152,29 @@
- [ ] 작은 버튼이 잘 눌리는지: 포스트 하트·댓글·보내기, 댓글 하트, 시트 ×
- [ ] 댓글 입력칸을 누르면 키보드 위로 입력칸·게시 버튼이 보인다 (확인)
- [ ] 로그인 시트 비밀번호 칸·버튼, 지역 검색 목록이 키보드에 가려지지 않는다 (확인)
## 17. 오늘 탭: 쇼츠 줄·쇼츠 페이지
10/27 헤드리스 크롬(iPhone 13·SE·데스크톱 1280)으로 자동 점검한 결과. `[x]` 통과, `[ ]` 실패·미확인.
- [x] 히어로 바로 아래 세로 카드 줄(3개), 제목 줄 없음
- [x] 줄이 화면에 보이면 첫 카드만 소리 없이 재생, 화면 밖으로 나가면 플레이어를 내림
- [x] 카드 누름 → `/shorts/영상ID`, 영상이 헤더·버튼 줄과 하단 탭 사이에 9:16으로 맞고, 앞뒤 영상까지 3개만 띄움
- [x] 쇼츠 페이지에선 뒤 페이지가 스크롤되지 않고, 닫으면 다시 스크롤됨
- [x] '소리 켜기' 누름 → '소리 끄기'로 바뀜
- [x] 위아래로 넘기면 주소가 그 영상으로 바뀜(뒤로 가기 기록은 안 쌓임 → 뒤로 가기 한 번에 오늘 화면)
- [x] 영상 탭 → 일시정지, 다시 탭 → 재생 (모바일·마우스 둘 다)
- [x] × · Esc · 하단 탭 누름 → 쇼츠 페이지를 닫고 이동
- [x] 공유 링크로 바로 들어오면 그 영상부터, 닫으면 오늘 화면으로(뒤로 가기에 남지 않음)
- [x] 목록에 없는 영상 ID 링크 → 그 영상을 맨 앞에 붙여 보임 / `/shorts`(ID 없음) → 첫 영상부터 / 새로고침해도 그대로
- [x] 마우스로 20px 끌면 제자리, 30px 넘게 끌면 다음·이전, 첫 영상에서 아래로 끌면 그대로
- [x] 마우스 휠·키보드 ↓로도 넘어감
- [x] 쇼츠 API 실패·빈 목록 → 오늘 화면에서 줄이 통째로 숨음
- [ ] **실패** 쇼츠 API 실패·빈 목록일 때 공유 링크(`/shorts/영상ID`)로 들어오면 남색 빈 화면만 계속 보임. 영상·× 버튼·안내 문구 없음(하단 탭으로만 나갈 수 있음)
- [ ] 미확인: 밤 테마에서 쇼츠 카드 그림·영상이 남색 판에 가려지지 않는지 (자동 캡처가 다른 곳을 찍음, 눈으로 확인 필요)
- [ ] 미확인: 아이폰 사파리 실기기 자동재생, 손가락으로 위아래 넘길 때 한 장씩 딱 멈추는지 (헤드리스는 터치 스크롤 재현 불가)
## 18. 각 포스트 카드
- [x] 아이폰 13·SE에서 점수·각 이름·'계산 근거 보기' 버튼이 카드 밖으로 잘리지 않는다 (10/27 근거 표·요약 줄 뺀 뒤, SE는 점수 글씨를 작게)
- [x] 카드마다 같은 내용이 반복되지 않는다: 기온·비·바람·미세먼지 표와 '오전 10시 13°, 바람 조금' 줄 없음, 말풍선 문장은 각마다 다름
+22 -1
View File
@@ -1,6 +1,6 @@
# 이벤트 추적 (GA4)
기준: `frontend/index.html`, `frontend/src/lib/analytics.ts`, `frontend/src/b/Sheets.tsx`, `frontend/src/b/region.tsx`, `frontend/src/b/install.ts`, `frontend/src/b/installBanner.tsx`, `frontend/src/main.tsx` (2026-10-21)
기준: `frontend/index.html`, `frontend/src/lib/analytics.ts`, `frontend/src/b/Sheets.tsx`, `frontend/src/b/region.tsx`, `frontend/src/b/install.ts`, `frontend/src/b/installBanner.tsx`, `frontend/src/main.tsx`, 2026-10-28 추가분은 `Post.tsx`·`pinnedLike.ts`·`talk.tsx`·`TodayPage.tsx`·`Shorts.tsx`·`FoliagePage.tsx`·`foliageMap.tsx`·`myGakState.ts`·`tossIntro.tsx` (2026-10-21, 2026-10-28)
## 한 줄 요약
@@ -34,8 +34,29 @@ GA4 태그(`gtag.js`, 측정 ID `G-D378J4X373`)를 `index.html`에 심고, 화
| `install_choice` | 설치창에서 고름 (안드로이드·PC Chrome·Edge) | `outcome: 'accepted' \| 'dismissed'` | `install.ts` `promptInstall` |
| `install_done` | 설치 완료 (브라우저가 `appinstalled`를 줄 때만. 아이폰은 오지 않음) | 없음 | `install.ts` |
| `app_launch` | 홈 화면 아이콘(설치한 앱)으로 엶 | `mode: 'standalone'` | `main.tsx` |
| `sheet_open` | 아래에서 올라오는 창이 열림 (각·글·보내기·댓글·로그인·내 정보·지역·내 각·홈 화면 추가·점수 근거·이야기 등) | `sheet`(창 종류: `gak`·`article`·`share`·`comments`·`login`·`me`·`region`·`mix`·`myGak`·`install`·`weatherWhy`·`talk`·`seasonWeek`) | `Sheets.tsx` `SheetProvider` `open` |
| `like` | 좋아요 성공 (취소는 안 보냄) | `content_type: 'post' \| 'comment' \| 'talk' \| 'hero_post' \| 'gak_post' \| 'foliage_post' \| 'events_post' \| 'season_post'`, `item_id`(포스트·댓글·글 번호) | `Post.tsx` `FullCard`, `pinnedLike.ts`, `Sheets.tsx` `CommentRow`, `talk.tsx` |
| `comment` | 댓글 올리기 성공 | `post_id` | `Sheets.tsx` `CommentsSheet` `send` |
| `terms_agree` | 댓글 쓰기 전 이용약관 동의 성공 | 없음 | `Sheets.tsx` `CommentsSheet` `agreeAndSend` |
| `report` | 신고 성공 | `content_type: 'comment' \| 'talk'`, `reason`(신고 이유 번호) | `Sheets.tsx` `CommentMenu`, `talk.tsx` |
| `block` | 차단 성공 | `content_type: 'comment' \| 'talk'` | `Sheets.tsx` `CommentMenu`, `talk.tsx` |
| `talk_post` | 이야기 글 올리기 성공 | `topic`(주제 번호), `with_image` | `talk.tsx` 글쓰기 `submit` |
| `hero_day_switch` | 히어로 오늘/내일 스위치를 바꿈 | `day: 'today' \| 'tomorrow'` | `TodayPage.tsx` |
| `shorts_open` | 쇼츠 페이지(/shorts/영상ID)로 들어옴 (오늘 화면 쇼츠 줄·공유 링크) | `video_id` | `Shorts.tsx` `ShortsPage` |
| `shorts_view` | 쇼츠를 넘겨 다른 영상으로 감 | `video_id`, `index`(목록 순서) | `Shorts.tsx` `ShortsPage` |
| `shorts_sound` | 쇼츠 소리 켜기·끄기 | `on` | `Shorts.tsx` `toggleSound` |
| `foliage_open` | 단풍 지도 페이지(/foliage)를 엶 | 없음 | `FoliagePage.tsx` |
| `foliage_spot` | 단풍 명소를 고름 | `spot_name`, `from: 'page' \| 'card'`(지도 페이지·오늘 화면 카드) | `FoliagePage.tsx`, `foliageMap.tsx` |
| `my_gak_save` | 내 각 만들기 성공 (로그인 전엔 기기에 저장) | `gak_name` | `myGakState.ts` `create` |
| `toss_intro_start` | 토스판 첫 소개 화면에서 '시작하기' | 없음 | `tossIntro.tsx` |
| `install_banner_close` | '홈 화면에 추가' 띠를 × 로 닫음 | 없음 | `installBanner.tsx` |
| `fortune_draw` | 오늘 한 장에서 카드를 뽑음 (하루 한 번, 다시 열 때는 안 보냄) | `card`(각 코드) | `fortune.tsx` `useTodayCard` |
| `day_log` | 저녁 체크인을 적어 둠 (고쳐 적어도 보냄). 다녀온 곳 이름은 보내지 않음 | `mood`(1~5), `went_out`, `card_hit`(맞았어요 true·글쎄요 false·안 고름 null) | `fortune.tsx` `useTodayCard` |
| `today_icon` | 오늘 탭 아이콘 줄에서 아이콘을 누름 | `icon`(`tarot`·`ootd`·`foliage`·`shorts`·`myGak`·`talk`) | `todayIcons.tsx` `TodayIcons` |
- 공유창에서 사용자가 취소하면 `share`를 보내지 않는다.
- 토스판은 로그인이 없어 `login` `toss`는 나가지 않는다. `id`·`sign_up`도 지금 화면에 아이디 가입이 없어 나가지 않는다.
- 점수 근거·댓글창 열기처럼 창으로 여는 기능은 따로 이벤트를 두지 않고 `sheet_open`의 `sheet`로 나눠 본다.
- `region_change`의 `location`은 처음 온 사람의 자동 위치 맞춤도 포함한다.
- 설치는 카드 노출 → 누름 → 설치 완료 → 홈 화면 실행 순서로 본다. 아이폰은 설치 완료를 알 수 없어 `app_launch`로 대신 본다.
- 새 이벤트는 `analytics.ts`의 `Events` 타입에 먼저 더한다. 타입에 없는 이름은 빌드에서 걸린다.
+14 -6
View File
@@ -12,13 +12,15 @@
</script>
<script>
// 이미 열었던 탭을 다시 열면 브라우저가 예전 HTML 을 다시 쓰고, 그 HTML 이 부르는 예전 빌드 파일은 배포로 지워져 첫 화면에서 멈춘다.
// 빌드 파일을 못 받았거나 12초 지나도 첫 화면이 그대로면 한 번만 새로 불러온다 (30초 안에 또 하지는 않는다)
// 돌아왔을 때 망이 아직 안 붙어 다시 불러온 것까지 실패하기도 하니, 첫 화면이 남아 있는 동안은 계속 다시 시도한다:
// 빌드 파일을 못 받았을 때, 12초마다, 탭을 다시 볼 때, 망이 다시 붙을 때 (10초 안에 또 하지는 않는다)
(function () {
var KEY = 'nalssigak.bootReload'
function reloadOnce() {
function retry() {
if (!document.getElementById('boot') || document.hidden) return
try {
var last = Number(sessionStorage.getItem(KEY) || 0)
if (Date.now() - last < 30000) return
if (Date.now() - last < 10000) return
sessionStorage.setItem(KEY, String(Date.now()))
} catch (e) {
console.error('[boot] storage', e)
@@ -27,11 +29,17 @@
}
window.addEventListener('error', function (e) {
var el = e.target
if (el && (el.tagName === 'SCRIPT' || el.tagName === 'LINK') && /\/assets\//.test(el.src || el.href || '')) reloadOnce()
if (el && (el.tagName === 'SCRIPT' || el.tagName === 'LINK') && (el.src || el.href || '').indexOf(location.origin + '/') === 0) retry()
}, true)
setTimeout(function () {
if (document.getElementById('boot')) reloadOnce()
var timer = setInterval(function () {
if (document.getElementById('boot')) retry()
else clearInterval(timer)
}, 12000)
document.addEventListener('visibilitychange', retry)
window.addEventListener('online', retry)
window.addEventListener('pageshow', function (e) {
if (e.persisted) retry()
})
})()
</script>
<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-4414665130371841" crossorigin="anonymous"></script>
Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 21 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 26 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 21 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 24 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 26 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 29 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 28 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 32 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 27 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 27 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 36 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 26 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 26 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 29 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 33 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 27 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 31 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 28 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 26 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 24 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 31 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 27 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 29 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 30 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 29 KiB

+17 -4
View File
@@ -1,7 +1,7 @@
import { useCallback, useEffect, useMemo, useState, type ReactNode } from 'react'
import { NavLink, Outlet, useLocation, useNavigationType } from 'react-router'
import { useIsFetching, useQuery } from '@tanstack/react-query'
import { getSeasonWeekOptions } from '@nalssigak/shared/api/client/@tanstack/react-query.gen'
import { useIsFetching, useQuery, useQueryClient } from '@tanstack/react-query'
import { authConfigOptions, getSeasonWeekOptions } from '@nalssigak/shared/api/client/@tanstack/react-query.gen'
import { IS_TOSS } from '../lib/platform'
import { cx } from '../lib/utils'
import { kindOfHour, kst, seasonOf, type TimeKind } from '@nalssigak/shared/lib'
@@ -9,6 +9,8 @@ import './b.css'
import { AuthProvider } from './auth'
import { RegionProvider } from './region'
import { useAuth } from './authContext'
import { preloadGoogle } from './googleScript'
import { LevelBadge, LevelWatcher } from './level'
import { useRegion } from './regionContext'
import { useSheet } from './sheetContext'
import { SheetProvider } from './Sheets'
@@ -47,7 +49,16 @@ function TopBar() {
const { region, locateStatus } = useRegion()
const { open } = useSheet()
const { me, mePending } = useAuth()
const queryClient = useQueryClient()
const tab = TABS.find((t) => t.to !== '/' && pathname.startsWith(t.to))
const loggedOut = !IS_TOSS && !mePending && !me
// 로그인 창을 처음 열 때 버벅이지 않게 구글 로그인 준비물을 미리 받아 둔다
useEffect(() => {
if (!loggedOut) return
void queryClient.prefetchQuery({ ...authConfigOptions(), staleTime: Infinity })
return preloadGoogle()
}, [loggedOut, queryClient])
return (
<header className="sticky top-0 z-20 flex h-[calc(54px+env(safe-area-inset-top,0px))] items-center justify-between gap-2 px-4 pt-[env(safe-area-inset-top,0px)]">
@@ -65,8 +76,9 @@ function TopBar() {
{IS_TOSS ? null : mePending ? (
<Skel shape className="size-9 shrink-0 rounded-full" />
) : me ? (
<button type="button" onClick={() => open({ type: 'me' })} aria-label={`내 정보, ${me.nickname}`} className="shrink-0 cursor-pointer rounded-full shadow-[0_6px_12px_rgb(40_48_74/0.12)]">
<button type="button" onClick={() => open({ type: 'me' })} aria-label={`내 정보, ${me.nickname}`} className="relative shrink-0 cursor-pointer rounded-full shadow-[0_6px_12px_rgb(40_48_74/0.12)]">
<Avatar character={me.character} color={me.color} mood={me.mood} size={36} />
<LevelBadge />
</button>
) : (
<button type="button" onClick={() => open({ type: 'login' })} className="shrink-0 cursor-pointer rounded-full bg-(--ink) px-3 py-1.5 text-[13px] font-extrabold text-white">
@@ -254,7 +266,7 @@ function Shell() {
{/* 위·아래 바: 띠는 화면 끝까지, 내용은 가운데 440px 안 */}
<div className="b-topbg fixed inset-x-0 top-0 z-[19] h-[calc(54px+env(safe-area-inset-top,0px))] backdrop-blur-md" aria-hidden="true" />
<div className="fixed inset-x-0 top-0 z-[19] h-[env(safe-area-inset-top,0px)] transition-colors duration-1400" style={{ backgroundColor: NOTCH_BG[kind] }} aria-hidden="true" />
<div className="relative mx-auto min-h-dvh max-w-[440px] overflow-x-clip pb-[calc(70px+env(safe-area-inset-bottom,0px))]">
<div className="relative mx-auto min-h-dvh max-w-[440px] overflow-x-clip pb-[calc(104px+env(safe-area-inset-bottom,0px))]">
<TopBar />
<main className="relative z-[1]">
<Outlet />
@@ -308,6 +320,7 @@ export function BLayout() {
<SheetProvider>
<Shell />
<TossIntro />
<LevelWatcher />
</SheetProvider>
</RegionProvider>
</AuthProvider>
+5
View File
@@ -6,6 +6,7 @@ import { useSheet } from './sheetContext'
import { FoliageMapShare, FoliageSpotShare } from './shareCards'
import { SendIcon } from './svg'
import { Chips, Ic, TAP44 } from './ui'
import { track } from '../lib/analytics'
type View = { s: number; tx: number; ty: number }
type Filter = 'all' | Kind
@@ -66,6 +67,10 @@ export function FoliagePage() {
const spotShotRef = useRef<HTMLDivElement>(null)
const mapShotRef = useRef<HTMLDivElement>(null)
const shown = useMemo(() => spots.filter((m) => filter === 'all' || m.kind === filter), [spots, filter])
useEffect(() => track('foliage_open', {}), [])
useEffect(() => {
if (sel) track('foliage_spot', { spot_name: sel, from: 'page' })
}, [sel])
const vpRef = useRef<HTMLDivElement>(null)
const [box, setBox] = useState({ W: 0, H: 0 })
+32 -20
View File
@@ -15,6 +15,7 @@ import { CommentIcon, HeartIcon, SendIcon } from './svg'
import { useCarousel } from './carousel'
import { MoonArt } from './moon'
import { Arrows, Credit, Ic, Rows, Skel, TAP44, Thumb } from './ui'
import { track } from '../lib/analytics'
const ACCOUNTS: Record<PostType, readonly [string, string]> = {
[PostType.WEATHER]: ['오늘 날씨', 'sun'],
@@ -53,7 +54,8 @@ function slideBg(post: PostData, slide: Slide): SlideBg {
if (slide.kind === 'plan') return slide.eyebrow.startsWith('일') ? 'peach' : 'butter'
if (slide.kind === 'gak') return GAK_BG[post.post_id % GAK_BG.length]
if (slide.kind === 'image') return 'sky'
if (post.post_type === PostType.EVENT || post.post_type === PostType.MOON) return 'night'
if (post.post_type === PostType.MOON) return 'night'
if (post.post_type === PostType.EVENT) return slide.image ? 'night' : 'peach'
if (post.post_type === PostType.TIP) return 'sky'
if (post.post_type === PostType.AIR) return slide.icon === 'vent' ? 'mint' : 'lilac'
if (post.post_type === PostType.DAY_TRIP) return slide.image ? 'night' : 'mint'
@@ -63,18 +65,16 @@ function slideBg(post: PostData, slide: Slide): SlideBg {
const DARK = new Set<SlideBg>(['dusk', 'night'])
// 그림 배경이 있는 각(code)과 장 수. 여러 장이면 글마다 돌려 쓴다
const BG_IMAGES: Record<string, number> = { bike: 4, picnic: 1, hiking: 1, camping: 1, stars: 1, walk: 1, hangang: 1 }
const EVENT_BG_N = 4
const BG_IMAGES: Record<string, number> = { bike: 4, picnic: 1, hiking: 1, hangang: 1 }
function bgImage(name: string, n: number, seed: number): CSSProperties {
const file = n > 1 ? `${name}-${'abcd'[seed % n]}` : name
return { backgroundImage: `url(/post-bg/${file}.webp)`, backgroundSize: 'cover', backgroundPosition: 'center' }
}
/** 그림 배경: 각은 각마다, 사진 없는 행사는 행사용. 없으면 색 배경만 */
/** 그림 배경: 각은 각마다. 없으면 색 배경만 */
function slideImage(post: PostData, slide: Slide): CSSProperties | undefined {
if (slide.kind === 'gak') return BG_IMAGES[slide.code] ? bgImage(slide.code, BG_IMAGES[slide.code], post.post_id) : undefined
if (post.post_type === PostType.EVENT && slide.kind === 'rows' && !slide.image) return bgImage('event', EVENT_BG_N, post.post_id)
return undefined
}
@@ -164,17 +164,28 @@ function SlideView({ slide, bg, img }: { slide: Slide; bg: SlideBg; img?: CSSPro
<div className={cx(slideBase, `b-bg-${bg}`)} style={img}>
<Eyebrow>오늘의 각 · {slide.rank}위</Eyebrow>
<Big>{slide.line}</Big>
<Pic name={slide.code} />
<Pic name={slide.code} className="[@media(max-height:700px)]:top-[26%] [@media(max-height:700px)]:w-[34%]" />
{slide.say && <p className="relative z-[1] m-0 mt-2.5 w-[56%] rounded-[16px] rounded-tl-[4px] bg-white/80 px-3 py-2 text-[14px] leading-snug font-bold">{slide.say}</p>}
{/* 점수 근거: 비중 큰 조건과 지금 값. 오른쪽 아이콘과 겹치지 않게 왼쪽 반만 */}
{!!slide.rows?.length && (
<div className="relative z-[1] mt-2 w-[56%] rounded-[16px] bg-white/70 px-3 text-[14px] [&_b]:text-[15px] [&>div>div]:py-1.5 [&>div]:mt-0">
<Rows rows={slide.rows} />
{/* 오른쪽 아래 빈 곳에 오늘·내일·주말 점수 (각 상세 날짜 칸과 같은 값) */}
<div className="relative z-[1] mt-auto flex items-end justify-between gap-3">
<div>
<b className="block font-bagel text-[82px] leading-[0.9] font-normal text-(--orange) [@media(max-height:700px)]:text-[64px]">{slide.score}</b>
<p className="m-0 font-jua text-[29px] leading-tight">{slide.name}</p>
</div>
)}
<b className="mt-auto font-bagel text-[82px] leading-[0.9] font-normal text-(--orange)">{slide.score}</b>
<p className="m-0 font-jua text-[29px] leading-tight">{slide.name}</p>
<Eyebrow className="mt-1">{slide.summary}</Eyebrow>
{!!slide.trend?.length && (
<div className="grid w-[46%] grid-cols-2 gap-1.5">
{slide.trend.map((t) => (
<div key={t.day} className="rounded-xl bg-white/80 px-1 py-1.5 text-center">
<small className="block text-[11px] font-extrabold whitespace-nowrap text-(--ink2)">
{t.label}
{t.estimated && ' 예상'}
</small>
<b className="block font-bagel text-lg leading-tight font-normal text-(--orange)">{t.score}</b>
</div>
))}
</div>
)}
</div>
<button type="button" onClick={() => open({ type: 'gak', indexId: slide.index_id })} className="mt-3 cursor-pointer self-start rounded-full bg-(--orange) px-4 py-[9px] font-jua text-[15px] text-white shadow-[inset_0_-5px_0_var(--orange-deep)]">
계산 근거 보기
</button>
@@ -406,10 +417,11 @@ function FullCard({ post }: PostProps) {
;(on ? like : unlike).mutate(
{ path: { post_id: post.post_id } },
{
onSuccess: (res) =>
res.result?.success
? patch({ liked: res.liked ?? on, ...(res.like_count != null ? { like_count: res.like_count } : {}) })
: revert(),
onSuccess: (res) => {
if (!res.result?.success) return revert()
patch({ liked: res.liked ?? on, ...(res.like_count != null ? { like_count: res.like_count } : {}) })
if (on) track('like', { content_type: 'post', item_id: post.post_id })
},
onError: revert,
},
)
@@ -438,7 +450,7 @@ function FullCard({ post }: PostProps) {
<small className="text-xs font-semibold text-(--ink2)">{account}</small>
</span>
</div>
<div className="relative aspect-[4/5] overflow-hidden" onClick={onTap}>
<div className="b-day relative aspect-[4/5] overflow-hidden" onClick={onTap}>
{n > 1 && (
<span data-noshot className="absolute top-3 right-3 z-[2] rounded-full bg-[rgb(30_36_56/0.55)] px-[9px] py-[3px] text-xs font-extrabold text-white" aria-hidden="true">
{index + 1}/{n}
@@ -548,7 +560,7 @@ export function PostFrame({ title, account, avatar, caption, more, shot, pinned,
<small className="text-xs font-semibold text-(--ink2)">{account}</small>
</span>
</div>
<div ref={bodyRef}>{children}</div>
<div ref={bodyRef} className="b-day">{children}</div>
<div className="flex items-center gap-3.5 px-3 pt-2.5 pb-1 [&_svg]:size-[26px] [&_svg]:stroke-[1.9]">
{postId != null && (
<>
+69 -30
View File
@@ -34,8 +34,11 @@ import { ago, articleMeta, AVATAR_COLORS, cardBg, CHARACTERS, dateRange, loadOf,
import { GoogleButton } from './googleLogin'
import { useInstall, useInstallable } from './install'
import { InstallSheet } from './installBanner'
import { ARTICLE_CAT } from './lib'
import { MixSheet } from './myGak'
import { ARTICLE_CAT, SHEET_CLOSE_MS, SHEET_OPEN_MS } from './lib'
import { MixSheet, MyGakSheet } from './myGak'
import { TarotSheet } from './fortune'
import { OotdSheet } from './todayIcons'
import { LevelCard, LevelSheet, LevelUpSheet, useShareReward } from './level'
import { ownPage, useRegion } from './regionContext'
import { WeatherWhySheet } from './weatherWhy'
import { useSky } from './skyContext'
@@ -54,6 +57,7 @@ export function SheetProvider({ children }: { children: ReactNode }) {
window.history.pushState({ ...window.history.state, sheet: true }, '')
pushed.current = true
}
track('sheet_open', { sheet: s.type })
setState(s)
}, [])
const close = useCallback(() => {
@@ -85,7 +89,7 @@ export function SheetProvider({ children }: { children: ReactNode }) {
)
}
const TITLES = { article: '읽을거리', seasonWeek: '이번 주 특집', share: '보내기', comments: '댓글', login: '로그인', me: '내 정보', region: '지역 바꾸기', install: '홈 화면에 추가', weatherWhy: '날씨 점수는 이렇게 나와요', talk: '이야기' } as const
const TITLES = { article: '읽을거리', seasonWeek: '이번 주 특집', share: '보내기', comments: '댓글', login: '로그인', me: '내 정보', region: '지역 바꾸기', install: '홈 화면에 추가', weatherWhy: '날씨 점수는 이렇게 나와요', talk: '이야기', tarot: '오늘 타로', ootd: '오늘 코디', level: '내 레벨', levelUp: '레벨이 올랐어요' } as const
/** 아래에서 올라오는 창: 네이티브 <dialog>라 ESC·포커스 가두기·포커스 되돌리기가 기본으로 된다 */
function SheetHost({ state, onClose }: { state: SheetState; onClose: () => void }) {
@@ -95,11 +99,25 @@ function SheetHost({ state, onClose }: { state: SheetState; onClose: () => void
const [gakTitle, setGakTitle] = useState('')
const [articleTitle, setArticleTitle] = useState('')
// 닫히는 동안에도 내려가는 창에 내용이 남아 있게, 마지막으로 연 창을 들고 있는다
const [shown, setShown] = useState<SheetState>(state)
if (state && state !== shown) setShown(state)
const closing = !state && shown != null
useEffect(() => {
const el = ref.current
if (!el) return
if (state && !el.open) el.showModal()
if (!state && el.open) el.close()
if (state) {
if (!el.open) el.showModal()
return
}
if (!el.open) return
// 내려가는 애니메이션이 끝난 뒤에 실제로 닫는다
const t = setTimeout(() => {
el.close()
setShown(null)
}, SHEET_CLOSE_MS)
return () => clearTimeout(t)
}, [state])
// 창이 열려 있는 동안 뒤 페이지는 스크롤되지 않게 잠근다
@@ -109,15 +127,17 @@ function SheetHost({ state, onClose }: { state: SheetState; onClose: () => void
const root = document.documentElement
const before = root.style.overflow
root.style.overflow = 'hidden'
root.classList.add('b-sheet-open')
// 뒤 화면 움직임 멈추기는 페이지 전체 스타일을 다시 계산하게 해서, 창이 다 올라온 뒤에 한다
const pause = setTimeout(() => root.classList.add('b-sheet-open'), SHEET_OPEN_MS)
return () => {
clearTimeout(pause)
root.style.overflow = before
root.classList.remove('b-sheet-open')
}
}, [isOpen])
const then = state?.type === 'login' ? state.then : undefined
const title = !state ? '' : state.type === 'gak' ? gakTitle : state.type === 'article' ? articleTitle || TITLES.article : state.type === 'mix' ? (state.shared ? '받은 각' : '내 각 만들기') : TITLES[state.type]
const then = shown?.type === 'login' ? shown.then : undefined
const title = !shown ? '' : shown.type === 'gak' ? gakTitle : shown.type === 'article' ? articleTitle || TITLES.article : shown.type === 'mix' ? (shown.shared ? '받은 각' : '내 각 만들기') : shown.type === 'myGak' ? '내 각' : TITLES[shown.type]
return (
<dialog
@@ -125,12 +145,17 @@ function SheetHost({ state, onClose }: { state: SheetState; onClose: () => void
aria-label={title}
data-t={kind}
onClose={onClose}
// ESC 도 바로 닫지 않고 내려가며 닫히게
onCancel={(e) => {
e.preventDefault()
onClose()
}}
onClick={(e) => {
if (e.target === e.currentTarget) onClose()
}}
className="b-sheet-dialog b-app fixed inset-x-0 top-auto bottom-0 m-0 mx-auto max-h-[86dvh] w-full max-w-[440px] overflow-visible bg-transparent p-0 text-(--ink)"
className={cx('b-sheet-dialog b-app fixed inset-x-0 top-auto bottom-0 m-0 mx-auto max-h-[86dvh] w-full max-w-[440px] overflow-visible bg-transparent p-0 text-(--ink)', closing && 'b-sheet-closing')}
>
{state && (
{shown && (
<div className="b-sheet flex max-h-[86dvh] flex-col rounded-t-[22px] bg-white pb-[env(safe-area-inset-bottom,0px)]">
<div className="relative border-b border-(--line) px-4 pt-2 pb-2.5 text-center">
<div className="mx-auto mb-2.5 h-1 w-10 rounded-full bg-(--line)" aria-hidden="true" />
@@ -139,21 +164,26 @@ function SheetHost({ state, onClose }: { state: SheetState; onClose: () => void
×
</button>
</div>
{state.type === 'gak' && <GakSheet indexId={state.indexId} onTitle={setGakTitle} />}
{state.type === 'article' && <ArticleSheet articleId={state.articleId} onTitle={setArticleTitle} />}
{state.type === 'seasonWeek' && <SeasonWeekSheet />}
{state.type === 'share' && <ShareSheet share={state.share} />}
{state.type === 'comments' && <CommentsSheet postId={state.postId} draft={state.draft} />}
{state.type === 'login' && <LoginSheet onDone={onClose} onLoggedIn={then ? () => open(then) : onClose} />}
{state.type === 'me' && <MeSheet onDone={onClose} />}
{state.type === 'region' && <RegionSheet onDone={onClose} />}
{state.type === 'mix' && <MixSheet shared={state.shared} onDone={onClose} />}
{state.type === 'install' && <InstallSheet />}
{state.type === 'weatherWhy' && <WeatherWhySheet d={state.why} />}
{state.type === 'talk' && <TalkSheet talk={state.talk} />}
{shown.type === 'gak' && <GakSheet indexId={shown.indexId} onTitle={setGakTitle} />}
{shown.type === 'article' && <ArticleSheet articleId={shown.articleId} onTitle={setArticleTitle} />}
{shown.type === 'seasonWeek' && <SeasonWeekSheet />}
{shown.type === 'share' && <ShareSheet share={shown.share} />}
{shown.type === 'comments' && <CommentsSheet postId={shown.postId} draft={shown.draft} />}
{shown.type === 'login' && <LoginSheet onDone={onClose} onLoggedIn={then ? () => open(then) : onClose} />}
{shown.type === 'me' && <MeSheet onDone={onClose} />}
{shown.type === 'region' && <RegionSheet onDone={onClose} />}
{shown.type === 'mix' && <MixSheet shared={shown.shared} onDone={onClose} />}
{shown.type === 'myGak' && <MyGakSheet gak={shown.gak} shot={shown.shot} onDone={onClose} />}
{shown.type === 'install' && <InstallSheet />}
{shown.type === 'weatherWhy' && <WeatherWhySheet d={shown.why} />}
{shown.type === 'tarot' && <TarotSheet />}
{shown.type === 'ootd' && <OotdSheet />}
{shown.type === 'level' && <LevelSheet />}
{shown.type === 'levelUp' && <LevelUpSheet level={shown.level} />}
{shown.type === 'talk' && <TalkSheet talk={shown.talk} />}
</div>
)}
{!state && <RegionLinks />}
{!shown && <RegionLinks />}
</dialog>
)
}
@@ -531,6 +561,7 @@ const SIZE_KEYS = Object.keys(SHARE_SIZES) as ShareSize[]
function ShareSheet({ share }: { share: SharePayload }) {
const { region } = useRegion()
const reward = useShareReward()
const { kind } = useSky()
const [size, setSize] = useState<ShareSize>('story')
const [images, setImages] = useState<Partial<Record<ShareSize, { blob: Blob; src: string }>>>({})
@@ -539,6 +570,7 @@ function ShareSheet({ share }: { share: SharePayload }) {
const [toast, setToast] = useState('')
const image = images[size]
const text = `${share.title} · 날씨각`
const url = share.url ?? SITE_URL
// 고른 크기의 이미지를 미리 만들어 둔다. 누를 때 만들면 아이폰이 공유창을 막는다
useEffect(() => {
@@ -576,6 +608,7 @@ function ShareSheet({ share }: { share: SharePayload }) {
(r) => {
setToast(r === 'saved' ? '이미지를 저장하고 링크를 보냈어요' : '링크를 보냈어요')
track('share', { content_type: 'image', item_id: share.title, method: 'share_sheet', ratio: SHARE_SIZES[size].ratio })
reward()
},
(e: unknown) => {
console.error('[share] toss', e)
@@ -584,18 +617,19 @@ function ShareSheet({ share }: { share: SharePayload }) {
)
return
}
if (navigator.canShare?.({ files: [file], text, url: SITE_URL })) {
const copied = navigator.clipboard?.writeText(SITE_URL).then(
if (navigator.canShare?.({ files: [file], text, url })) {
const copied = navigator.clipboard?.writeText(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(
navigator.share({ files: [file], title: share.title, text, url }).then(
async () => {
setToast((await copied) ? '보냈어요. 링크도 복사해 뒀어요' : '보냈어요')
track('share', { content_type: 'image', item_id: share.title, method: 'share_sheet', ratio: SHARE_SIZES[size].ratio })
reward()
},
(e: unknown) => {
if (e instanceof DOMException && e.name === 'AbortError') return
@@ -614,7 +648,7 @@ function ShareSheet({ share }: { share: SharePayload }) {
setToast('이미지를 내려받았어요')
return
}
navigator.clipboard.writeText(`${text} ${SITE_URL}`).then(
navigator.clipboard.writeText(`${text} ${url}`).then(
() => setToast('이미지를 내려받고 링크를 복사했어요'),
() => setToast('이미지를 내려받았어요. 링크 복사는 막혀 있어요'),
)
@@ -669,9 +703,10 @@ function CommentMenu({ c, postId, onNotice }: { c: CommentData; postId: number;
const block = useMutation(blockAuthorMutation())
const pending = report.isPending || block.isPending
const finish = (notice: string) => ({
const finish = (notice: string, done: () => void) => ({
onSuccess: (res: { result?: { success?: boolean } }) => {
if (!res.result?.success) return setFailed(true)
done()
setStep('closed')
onNotice(notice)
queryClient.invalidateQueries({ predicate: isCommentList })
@@ -705,14 +740,14 @@ function CommentMenu({ c, postId, onNotice }: { c: CommentData; postId: number;
)}
{step === 'report' &&
REPORT_REASONS.map(([reason, label]) => (
<button key={reason} type="button" disabled={pending} className={btn} onClick={() => report.mutate({ path: { comment_id: c.comment_id }, body: { reason } }, finish('신고했어요. 확인하고 조치할게요.'))}>
<button key={reason} type="button" disabled={pending} className={btn} onClick={() => report.mutate({ path: { comment_id: c.comment_id }, body: { reason } }, finish('신고했어요. 확인하고 조치할게요.', () => track('report', { content_type: 'comment', reason })))}>
{label}
</button>
))}
{step === 'block' && (
<>
<span className="w-full text-[13px] font-bold text-(--ink)">{c.nickname}님 댓글을 더는 안 볼까요?</span>
<button type="button" disabled={pending} className={cx(btn, 'bg-(--heart) text-white')} onClick={() => block.mutate({ path: { comment_id: c.comment_id } }, finish('차단했어요. 내 정보에서 풀 수 있어요.'))}>
<button type="button" disabled={pending} className={cx(btn, 'bg-(--heart) text-white')} onClick={() => block.mutate({ path: { comment_id: c.comment_id } }, finish('차단했어요. 내 정보에서 풀 수 있어요.', () => track('block', { content_type: 'comment' })))}>
차단하기
</button>
<button type="button" disabled={pending} className={btn} onClick={() => go('closed')}>
@@ -759,6 +794,7 @@ function CommentRow({ c, postId, onNotice }: { c: CommentData; postId: number; o
if (res.result?.success) {
setLiked(!!res.liked)
if (res.like_count != null) setCount(res.like_count)
if (next) track('like', { content_type: 'comment', item_id: c.comment_id })
return
}
revert()
@@ -860,6 +896,7 @@ function CommentsSheet({ postId, draft }: { postId: number; draft?: string }) {
if (res.result?.desc === 'TERMS_REQUIRED') return setAskTerms(true)
setAddFailed(!res.result?.success)
if (!res.result?.success) return
track('comment', { post_id: postId })
setText('')
queryClient.invalidateQueries({ queryKey: listCommentsInfiniteQueryKey({ path: { post_id: postId } }) })
queryClient.invalidateQueries({ queryKey: getFeedQueryKey({ query: { region: region.code } }) })
@@ -882,6 +919,7 @@ function CommentsSheet({ postId, draft }: { postId: number; draft?: string }) {
{
onSuccess: (res) => {
if (!res.result?.success) return setAddFailed(true)
track('terms_agree', {})
queryClient.setQueryData(meQueryKey(), res)
setAskTerms(false)
send()
@@ -1131,6 +1169,7 @@ function MeSheet({ onDone }: { onDone: () => void }) {
<Avatar character={me.character} color={me.color} mood={me.mood} size={64} />
<p className="m-0 text-center text-sm font-semibold text-(--ink2)">{me.provider === AuthProvider.TOSS ? '토스로 로그인했어요' : me.provider === AuthProvider.GOOGLE ? '구글 계정으로 로그인했어요' : `${me.login_id}(으)로 로그인했어요`}</p>
</div>
<LevelCard />
{installable && (
<button type="button" onClick={() => install('menu')} className="cursor-pointer rounded-2xl bg-[#fff4ec] py-2.5 font-jua text-[15.5px] text-(--orange)">
📲 홈 화면에 추가
+87 -30
View File
@@ -3,8 +3,11 @@ import { type CSSProperties, type PointerEvent as ReactPointerEvent, useEffect,
import { Link, useNavigate, useParams } from 'react-router'
import { listShortsOptions } from '@nalssigak/shared/api/client/@tanstack/react-query.gen'
import type { ShortItem } from '@nalssigak/shared/api/client'
import { IS_TOSS } from '../lib/platform'
import { cx } from '../lib/utils'
import { CloseIcon } from './svg'
import { Rail, Skel, SkelRail, TAP44 } from './ui'
import { track } from '../lib/analytics'
// 유튜브는 플레이어가 200×200 이상이어야 해서, 카드 안 미리보기는 200px 너비로 띄우고 줄여 보인다.
// 위 로고·아래 제목 줄이 작은 카드에서 겹쳐 보이지 않게 가운데를 1.4배로 키워 위아래를 잘라 낸다
@@ -15,13 +18,18 @@ const SCALE = (CARD_W / PLAYER_W) * 1.4
// 쇼츠 페이지의 영상 칸: 위 헤더(54px)·버튼 줄(48px)과 아래 탭 바(--shorts-tab) 사이 높이와 화면 너비 안에 9:16으로 맞춘다
const FIT = { width: 'min(100vw, calc((100dvh - env(safe-area-inset-top, 0px) - 54px - 48px - var(--shorts-tab, 0px)) * 9 / 16))', aspectRatio: '9 / 16' }
/** 아래 탭 바 높이 (기기마다 안전 영역이 달라 실제로 잰다) */
/** 아래 탭 바가 가리는 높이: 탭 바 위로 솟은 가운데 홈 동그라미까지 (기기마다 안전 영역이 달라 실제로 잰다) */
function useTabBarHeight() {
const [h, setH] = useState(0)
useLayoutEffect(() => {
const nav = document.querySelector<HTMLElement>('nav.b-tabbar')
if (!nav) return
const ro = new ResizeObserver(() => setH(nav.offsetHeight))
const measure = () => {
const bar = nav.getBoundingClientRect()
const bump = nav.querySelector('.b-tab-main > *')?.getBoundingClientRect().top ?? bar.top
setH(Math.round(bar.bottom - Math.min(bar.top, bump)))
}
const ro = new ResizeObserver(measure)
ro.observe(nav)
return () => ro.disconnect()
}, [])
@@ -30,6 +38,11 @@ function useTabBarHeight() {
const YT_ORIGIN = 'https://www.youtube-nocookie.com'
// 토스 웹뷰에는 플레이어가 보내는 재생 상태가 오지 않는다. 그래서 토스는 첫 장면이 나왔는지를 시간으로 보고 표지를 걷는다 (나머지는 웹과 같다)
const PLAIN = IS_TOSS
// 토스는 재생 상태가 안 오므로, 플레이어 문서가 뜨고 이만큼 지나면 첫 장면이 나왔다고 보고 표지를 걷는다 (그 전엔 플레이어의 검은 화면 대신 표지)
const PLAIN_SHOW_MS = 1000
function embed(id: string) {
const q = new URLSearchParams({
autoplay: '1', mute: '1', playsinline: '1', loop: '1', playlist: id, controls: '0', rel: '0', modestbranding: '1',
@@ -38,7 +51,7 @@ function embed(id: string) {
return `${YT_ORIGIN}/embed/${id}?${q}`
}
type Func = 'playVideo' | 'pauseVideo' | 'seekTo' | 'mute' | 'unMute'
type Func = 'playVideo' | 'seekTo' | 'mute' | 'unMute'
/** 이미 띄운 플레이어에 명령 (IFrame API 메시지) */
function command(frame: HTMLIFrameElement | null | undefined, func: Func, args: unknown[] = []) {
@@ -85,7 +98,8 @@ export function ShortsRail() {
<section ref={ref} aria-label="날씨각 쇼츠">
<Rail label="쇼츠 목록">
{items.map((s, i) => (
<ShortCard key={s.id} s={s} playing={i === 0 && visible} />
// 토스 앱 웹뷰는 유튜브 플레이어가 무거워, 줄에선 표지만 보이고 누르면 재생
<ShortCard key={s.id} s={s} playing={!IS_TOSS && i === 0 && visible} />
))}
</Rail>
</section>
@@ -93,16 +107,35 @@ export function ShortsRail() {
}
function ShortCard({ s, playing }: { s: ShortItem; playing: boolean }) {
// 재생이 시작된 뒤에만 플레이어를 보인다: 자동재생이 막히면(아이폰 절전 등) 유튜브 재생 버튼 대신 표지 그대로
const [started, setStarted] = useState(false)
const frame = useRef<HTMLIFrameElement>(null)
useEffect(() => {
if (!playing) return
const onMessage = (e: MessageEvent) => {
if (e.origin !== YT_ORIGIN || typeof e.data !== 'string' || e.source !== frame.current?.contentWindow) return
try {
if ((JSON.parse(e.data) as { info?: { playerState?: number } }).info?.playerState === PLAYING) setStarted(true)
} catch {
return
}
}
window.addEventListener('message', onMessage)
return () => window.removeEventListener('message', onMessage)
}, [playing])
return (
<Link to={`/shorts/${s.id}`} aria-label={`${s.title} 보기`} className="relative block aspect-[9/16] w-[120px] cursor-pointer overflow-hidden rounded-xl bg-[#1d2233] p-0 text-left text-white">
<img src={`https://i.ytimg.com/vi/${s.id}/hqdefault.jpg`} alt="" loading="lazy" className="absolute inset-0 size-full object-cover" />
{playing && (
<iframe
ref={frame}
src={embed(s.id)}
title={s.title}
allow="autoplay; encrypted-media; picture-in-picture"
tabIndex={-1}
className="pointer-events-none absolute top-1/2 left-1/2 border-0"
// 재생 상태를 받으려면 플레이어에 먼저 '듣고 있다'고 알린다
onLoad={(e) => e.currentTarget.contentWindow?.postMessage(JSON.stringify({ event: 'listening', id: s.id }), YT_ORIGIN)}
className={cx('pointer-events-none absolute top-1/2 left-1/2 border-0 transition-opacity duration-200', !started && 'opacity-0')}
style={{ width: PLAYER_W, height: (PLAYER_W * 16) / 9, transform: `translate(-50%, -50%) scale(${SCALE})` }}
/>
)}
@@ -124,9 +157,16 @@ export function ShortsPage() {
const start = Math.max(0, items.findIndex((s) => s.id === firstId))
// 앱 안에서 들어왔으면 뒤로, 링크로 바로 들어왔으면 오늘 화면으로
const close = () => ((window.history.state as { idx?: number } | null)?.idx ? navigate(-1) : navigate('/', { replace: true }))
useEffect(() => {
if (firstId) track('shorts_open', { video_id: firstId })
}, [firstId])
const at = (s: ShortItem) => {
track('shorts_view', { video_id: s.id, index: items.indexOf(s) })
navigate(`/shorts/${s.id}`, { replace: true })
}
if (!items.length) return <div className="fixed inset-0 z-[70] bg-[#1d2233]" aria-busy={q.isPending} />
return <ShortsViewer items={items} start={start} onClose={close} onAt={(s) => navigate(`/shorts/${s.id}`, { replace: true })} />
return <ShortsViewer items={items} start={start} onClose={close} onAt={at} />
}
/**
@@ -139,22 +179,37 @@ function ShortsViewer({ items, start, onClose, onAt }: { items: ShortItem[]; sta
const tabH = useTabBarHeight()
// 첫 장면을 받은 플레이어. 그 전엔 플레이어의 검은 화면 대신 표지를 보인다
const [ready, setReady] = useState<ReadonlySet<number>>(new Set())
// 토스: 표지를 걷은 플레이어들. 다음 영상도 미리 띄워 두므로 여럿
const [plainShown, setPlainShown] = useState<ReadonlySet<number>>(new Set())
const plainTimers = useRef(new Set<number>())
useEffect(() => {
const timers = plainTimers.current
return () => timers.forEach((t) => window.clearTimeout(t))
}, [])
const frames = useRef(new Map<number, HTMLIFrameElement>())
const atRef = useRef(start)
const soundRef = useRef(false)
// 누르기로 멈춘 상태. 다른 영상으로 넘어가면 다시 재생 중으로
const paused = useRef(false)
// 처음 한 번: 시작 영상으로 맞추고, 뒤 페이지 스크롤을 잠근다
const startRef = useRef(start)
useEffect(() => {
// scrollIntoView 는 바깥 칸까지 굴려 버튼 줄이 헤더 밑으로 숨으므로 목록만 옮긴다
// 시작 영상으로 옮기기 전엔 보이는 칸이 바뀐 것으로 치지 않는다 (사파리는 처음 그릴 때 맨 위 칸이 먼저 보여 첫 영상으로 바뀌던 것)
const placed = useRef(false)
useLayoutEffect(() => {
// scrollIntoView 는 바깥 칸까지 굴려 버튼 줄이 헤더 밑으로 숨으므로 목록만 옮긴다. 사파리는 첫 그림 전에 옮긴 값을 되돌려 한 번 더
const box = list.current
if (box) box.scrollTop = box.clientHeight * startRef.current
const place = () => {
if (box) box.scrollTop = box.clientHeight * startRef.current
}
place()
const raf = requestAnimationFrame(() => {
place()
placed.current = true
})
const root = document.documentElement
const before = root.style.overflow
root.style.overflow = 'hidden'
return () => {
cancelAnimationFrame(raf)
root.style.overflow = before
}
}, [])
@@ -170,6 +225,7 @@ function ShortsViewer({ items, start, onClose, onAt }: { items: ShortItem[]; sta
if (!box) return
const io = new IntersectionObserver(
(entries) => {
if (!placed.current) return
for (const e of entries) if (e.isIntersecting) setAt(Number((e.target as HTMLElement).dataset.i))
},
{ root: box, threshold: 0.6 },
@@ -178,7 +234,7 @@ function ShortsViewer({ items, start, onClose, onAt }: { items: ShortItem[]; sta
return () => io.disconnect()
}, [])
// 미리 띄운 영상이 재생되기 시작하면(첫 장면을 받음) 보이는 영상이 아닐 때 멈추고 처음으로
// 플레이어가 재생을 시작하면(첫 장면을 받음) 보이게 한다. 앞뒤 영상은 멈추지 않는다: 멈췄다 다시 틀면 유튜브가 재생·멈춤 버튼을 영상 위에 띄운다
useEffect(() => {
const onMessage = (e: MessageEvent) => {
if (e.origin !== YT_ORIGIN || typeof e.data !== 'string') return
@@ -192,9 +248,6 @@ function ShortsViewer({ items, start, onClose, onAt }: { items: ShortItem[]; sta
for (const [i, f] of frames.current) {
if (f.contentWindow !== e.source) continue
setReady((r) => (r.has(i) ? r : new Set(r).add(i)))
if (i === atRef.current) continue
command(f, 'pauseVideo')
command(f, 'seekTo', [0, true])
}
}
window.addEventListener('message', onMessage)
@@ -205,27 +258,21 @@ function ShortsViewer({ items, start, onClose, onAt }: { items: ShortItem[]; sta
useEffect(() => {
if (atRef.current !== at) moved(items[at])
atRef.current = at
paused.current = false
// 앞뒤 영상은 소리 없이 계속 돌고 있으니, 넘어온 영상만 처음부터 다시 틀고 소리를 맞춘다 (멈춤 명령은 쓰지 않는다)
for (const [i, f] of frames.current) {
if (i === at) {
command(f, 'seekTo', [0, true])
command(f, soundRef.current ? 'unMute' : 'mute')
command(f, 'playVideo')
} else {
command(f, 'pauseVideo')
command(f, 'mute')
}
} else command(f, 'mute')
}
}, [at, items])
// 마우스로도 끌어 넘긴다: 영상 위는 유튜브 iframe 이 마우스를 가져가서, 그 위에 투명한 판을 깔고 끈 만큼 목록을 옮긴다.
// 손가락은 브라우저 스크롤에 맡기고, 끌지 않고 누르기만 하면 재생·일시정지
// 손가락은 브라우저 스크롤에 맡기고, 끌지 않고 누르기만 하면 릴스처럼 소리 켜기·끄기 (멈추면 유튜브 버튼이 떠서)
const drag = useRef<{ y: number; top: number; moved: boolean } | null>(null)
const lastPointer = useRef('')
const [dragging, setDragging] = useState(false)
const togglePause = () => {
paused.current = !paused.current
command(frames.current.get(atRef.current), paused.current ? 'pauseVideo' : 'playVideo')
}
const onPointerDown = (e: ReactPointerEvent<HTMLDivElement>) => {
lastPointer.current = e.pointerType
const box = list.current
@@ -248,7 +295,7 @@ function ShortsViewer({ items, start, onClose, onAt }: { items: ShortItem[]; sta
drag.current = null
setDragging(false)
if (!d || !box) return
if (!d.moved) return togglePause()
if (!d.moved) return toggleSound()
// 30px 만 끌어도 다음·이전 영상으로, 그보다 덜 끌면 제자리로
const h = box.clientHeight
const dy = e.clientY - d.y
@@ -261,6 +308,7 @@ function ShortsViewer({ items, start, onClose, onAt }: { items: ShortItem[]; sta
const on = !sound
soundRef.current = on
setSound(on)
track('shorts_sound', { on })
command(frames.current.get(at), on ? 'unMute' : 'mute')
}
@@ -282,8 +330,9 @@ function ShortsViewer({ items, start, onClose, onAt }: { items: ShortItem[]; sta
/>
<div className="absolute inset-0 bg-black/35" aria-hidden="true" />
<div className="relative mx-auto flex h-12 w-full max-w-[440px] shrink-0 items-center justify-between px-3">
<button type="button" onClick={onClose} aria-label="닫기" className={cx('relative grid size-9 cursor-pointer place-items-center rounded-full bg-white/15 text-xl text-white', TAP44)}>
×
{/* 글자 '×'는 글꼴마다 아래로 처져 그림으로 */}
<button type="button" onClick={onClose} aria-label="닫기" className={cx('relative grid size-9 cursor-pointer place-items-center rounded-full bg-white/15 text-white', TAP44)}>
<CloseIcon className="size-[18px]" />
</button>
<button type="button" onClick={toggleSound} aria-pressed={sound} className="h-9 cursor-pointer rounded-full bg-white/15 px-3.5 text-[13px] font-bold text-white">
{sound ? '소리 끄기' : '소리 켜기'}
@@ -294,6 +343,7 @@ function ShortsViewer({ items, start, onClose, onAt }: { items: ShortItem[]; sta
<div key={s.id} data-i={i} className="relative grid h-full snap-start place-items-center">
<div className="relative" style={FIT}>
<img src={`https://i.ytimg.com/vi/${s.id}/hqdefault.jpg`} alt="" className="absolute inset-0 size-full object-cover" />
{/* 릴스처럼 앞뒤 영상을 소리 없이 미리 받아 둔다 */}
{Math.abs(i - at) <= 1 && (
<iframe
ref={(f) => {
@@ -305,6 +355,13 @@ function ShortsViewer({ items, start, onClose, onAt }: { items: ShortItem[]; sta
allow="autoplay; encrypted-media; picture-in-picture"
// 재생 상태를 받으려면 플레이어에 먼저 '듣고 있다'고 알린다
onLoad={(e) => {
if (PLAIN) {
const t = window.setTimeout(() => {
plainTimers.current.delete(t)
setPlainShown((r) => (r.has(i) ? r : new Set(r).add(i)))
}, PLAIN_SHOW_MS)
plainTimers.current.add(t)
}
e.currentTarget.contentWindow?.postMessage(JSON.stringify({ event: 'listening', id: s.id }), YT_ORIGIN)
// 앞뒤 밖으로 밀려나 내려갔다 다시 뜬 플레이어는 첫 장면을 새로 받을 때까지 다시 숨긴다
setReady((r) => {
@@ -314,7 +371,7 @@ function ShortsViewer({ items, start, onClose, onAt }: { items: ShortItem[]; sta
return next
})
}}
className={cx('absolute inset-0 size-full border-0 transition-opacity duration-200', !ready.has(i) && 'opacity-0')}
className={cx('absolute inset-0 size-full border-0 transition-opacity duration-200', (PLAIN ? !plainShown.has(i) : !ready.has(i)) && 'opacity-0')}
/>
)}
<div
@@ -326,7 +383,7 @@ function ShortsViewer({ items, start, onClose, onAt }: { items: ShortItem[]; sta
drag.current = null
setDragging(false)
}}
onClick={() => lastPointer.current !== 'mouse' && togglePause()}
onClick={() => lastPointer.current !== 'mouse' && toggleSound()}
className={cx('absolute inset-0 touch-pan-y select-none', dragging ? 'cursor-grabbing' : 'cursor-grab')}
/>
</div>
+58 -26
View File
@@ -1,44 +1,76 @@
import { useEffect, useEffectEvent, useRef } from 'react'
import { useSearchParams } from 'react-router'
import type { TalkTopic } from '@nalssigak/shared/api/client/types.gen'
import { cx } from '../lib/utils'
import { TalkCard } from './talk'
import { TOPICS, useTopicTalks } from './talkState'
import { Sec } from './ui'
import { useAuth } from './authContext'
import { useSheet } from './sheetContext'
import { FeedComposer, TalkCard } from './talk'
import { TOPICS, useMyTalks, useTopicTalks } from './talkState'
import { Rail, Sec } from './ui'
/** 주제별 사람 글: 위 주제 탭, 아래 글 목록. 피드 묶음의 '전체 보기'가 ?topic= 으로 연다 */
type Tab = TalkTopic | 'all' | 'mine'
/** 목록 끝이 화면 아래 600px 안에 들어오면 다음 쪽을 받는다 (글이 많아도 버튼 없이 이어서) */
function MoreOnScroll({ onMore }: { onMore: () => void }) {
const ref = useRef<HTMLDivElement>(null)
const more = useEffectEvent(onMore)
useEffect(() => {
const el = ref.current
if (!el) return
const io = new IntersectionObserver(([e]) => e.isIntersecting && more(), { rootMargin: '0px 0px 600px 0px' })
io.observe(el)
return () => io.disconnect()
}, [])
return <div ref={ref} className="h-px" aria-hidden="true" />
}
/** 주제별 사람 글: 위 주제 탭(한 줄 가로로 밀기, 끝에 '내 글'), 아래 글 목록. 피드 묶음의 '전체 보기'가 ?topic= · ?mine=1 로 연다 */
export function TalkPage() {
const [params, setParams] = useSearchParams()
const { loggedIn } = useAuth()
const { open } = useSheet()
const raw = Number(params.get('topic'))
const topic = TOPICS.some(([k]) => k === raw) ? (raw as TalkTopic) : undefined
const { talks, loaded, more, loadMore } = useTopicTalks(topic)
const tabs: (readonly [TalkTopic | undefined, string])[] = [[undefined, '전체'], ...TOPICS]
const tab: Tab = params.get('mine') ? 'mine' : TOPICS.some(([k]) => k === raw) ? (raw as TalkTopic) : 'all'
const topicList = useTopicTalks(tab === 'all' || tab === 'mine' ? undefined : tab)
const mineList = useMyTalks(tab === 'mine' && loggedIn)
const { talks, loaded, more, loadMore } = tab === 'mine' ? mineList : topicList
const tabs: (readonly [Tab, string])[] = [['all', '전체'], ...TOPICS, ['mine', '내 글']]
const go = (k: Tab) => setParams(k === 'mine' ? { mine: '1' } : k === 'all' ? {} : { topic: String(k) }, { replace: true })
return (
<section aria-label="동네 사람들 글">
<Sec title="동네 사람들 글" sub="가까운 동네 글부터 보여요" />
<div className="flex flex-wrap gap-1.5 px-4 pb-1" role="tablist" aria-label="글 주제">
{tabs.map(([k, label]) => (
<button
key={label}
type="button"
role="tab"
aria-selected={topic === k}
onClick={() => setParams(k ? { topic: String(k) } : {}, { replace: true })}
className={cx('cursor-pointer rounded-full px-3 py-1.5 text-[13px] font-extrabold', topic === k ? 'bg-(--ink) text-white' : 'bg-white text-(--ink2)')}
>
{label}
</button>
))}
<div role="tablist" aria-label="글 주제">
<Rail className="gap-1.5 pt-0">
{tabs.map(([k, label]) => (
<button
key={label}
type="button"
role="tab"
aria-selected={tab === k}
onClick={() => go(k)}
className={cx('cursor-pointer rounded-full px-3 py-1.5 text-[13px] font-extrabold whitespace-nowrap', tab === k ? 'bg-(--ink) text-white' : 'bg-white text-(--ink2)')}
>
{label}
</button>
))}
</Rail>
</div>
{loaded && !talks.length && <p className="mx-4 mt-6 text-center text-[14px] font-semibold text-(--ink3)">아직 이 주제 글이 없어요. 오늘 탭에서 첫 글을 써 주세요.</p>}
<FeedComposer />
{tab === 'mine' && !loggedIn ? (
<p className="mx-4 mt-6 text-center text-[14px] font-semibold text-(--ink3)">
로그인하면 내가 쓴 글을 모아 볼 수 있어요.{' '}
<button type="button" onClick={() => open({ type: 'login' })} className="cursor-pointer font-extrabold text-(--orange)">
로그인
</button>
</p>
) : (
loaded && !talks.length && <p className="mx-4 mt-6 text-center text-[14px] font-semibold text-(--ink3)">{tab === 'mine' ? '아직 쓴 글이 없어요. 위 칸에서 첫 글을 써 주세요.' : '아직 이 주제 글이 없어요. 위 칸에서 첫 글을 써 주세요.'}</p>
)}
{talks.map((t) => (
<TalkCard key={`${t.talk_id}:${t.liked}:${t.like_count}`} t={t} />
))}
{more && (
<button type="button" onClick={() => loadMore()} className="mx-3 mt-3 w-[calc(100%-1.5rem)] cursor-pointer rounded-[14px] bg-white py-2.5 text-[13.5px] font-extrabold text-(--ink2)">
더 보기
</button>
)}
{more && <MoreOnScroll onMore={() => loadMore()} />}
</section>
)
}
Loaded 100 of 132 files, more files were not shown because too many files have changed in this diff. Show more