Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2627dd2685 | ||
|
|
f9988855d3 | ||
|
|
a3271a827b | ||
|
|
872d68e738 | ||
|
|
90773081c2 | ||
|
|
e22564bc20 | ||
|
|
fb2e6c4fac | ||
|
|
512ae6b591 | ||
|
|
01263f4149 | ||
|
|
387929683c | ||
|
|
a875dfabe6 | ||
|
|
096d1effb0 | ||
|
|
928e9053cf | ||
|
|
e1b5efc01b | ||
|
|
a6251db762 | ||
|
|
814e64931d | ||
|
|
0144a64b42 | ||
|
|
9b1e32d620 | ||
|
|
91837ff8e9 | ||
|
|
2400957657 | ||
|
|
84212099e6 | ||
|
|
fdf8498a56 | ||
|
|
a646d1b26a | ||
|
|
7f2cbc13c9 | ||
|
|
ea5376820c | ||
|
|
e180d9651c | ||
|
|
7dcb40df78 | ||
|
|
07290597a0 | ||
|
|
7451599727 |
No files matched your search
@@ -1,16 +1,16 @@
|
||||
---
|
||||
description: 오늘 날씨 타로·코디 카드를 만들어 검수하고 킹서버에 승인 대기로 저장한다 (올리지는 않는다)
|
||||
argument-hint: <타로 주제> <코디 스타일: casual|semi|formal|street|minimal>
|
||||
description: 오늘 날씨 타로·코디 카드를 둘 다 만들어 검수하고 날씨각 피드와 인스타에 올린다 (/daily-tarot + /daily-ootd)
|
||||
argument-hint: "<타로 주제> <코디 스타일> 예) 건강 운동 minimal"
|
||||
---
|
||||
|
||||
오늘 인스타 카드를 만든다. 인자: `$ARGUMENTS` (앞은 타로 주제, 마지막 단어는 코디 스타일. 비어 있으면 타로 주제는 비우고 코디는 casual).
|
||||
재확인 질문 없이 순서대로 진행하고, 막히면 그 자리에서 보고하고 멈춘다. **인스타·날씨각 피드에 올리지 않는다** — 승인 대기 저장까지만.
|
||||
오늘 인스타 카드를 만든다. 인자: `$ARGUMENTS` — 앞은 타로 주제(비어 있으면 Claude 가 오늘 날씨에 맞는 주제를 고른다), 마지막 단어가 casual·semi·formal·street·minimal 중 하나면 코디 스타일(없으면 minimal=꾸안꾸). 코디 포스트 하나는 스타일 하나: 네 사람 모두 같은 스타일.
|
||||
재확인 질문 없이 순서대로 진행하고, 막히면 그 자리에서 보고하고 멈춘다. 타로는 `/daily-tarot` 의 순서대로, 코디는 `/daily-ootd` 의 순서대로 각각 만들고 검수한 뒤 올린다(두 명령 파일의 단계를 그대로 따른다).
|
||||
|
||||
1. 관리자 서버: `curl -s http://localhost:5175/api/targets` 에 `king` 이 있어야 한다. 없으면 `admin/` 에서 백그라운드로 켠다 (`admin/AGENTS.md` '켜기', 킹서버 키는 `ssh King_admin` 의 `~/proj/o2o-weather/.env` `ADMIN_API_KEY`, 값은 출력하지 않는다).
|
||||
2. 예보: `curl -s "https://weather.o2o.kr/v1/weather/today?region=1114000000"` 의 `day` 가 오늘인지 보고 slots 의 기온·하늘·비 확률을 적어 둔다.
|
||||
3. 타로: `cd admin && VITE_API_BASE_URL=https://weather.o2o.kr ADMIN_URL=http://localhost:5175 npm run card -- tarot --topic "<주제>" --color sky --post-wait`.
|
||||
출력된 기획 문구를 2의 예보와 대조한다(숫자·하늘 묘사가 틀리면 `--copy <값> --feedback "실제 수치…"` 로 한 번만 다시). "일부 그림을 못 만들어" 가 나오면 멈추고 보고한다. 크롬이 한 장에서 45초 넘게 멈추면 그 프로세스를 죽이고 그 장만 다시 찍는다.
|
||||
4. 코디: `{"style":"<스타일>","theme":"sky"}` 를 base64url 로 만들어 `npm run card -- ootd --copy <값> --post-wait`. 빠진 그림은 자동 생성된다(장당 1~5분).
|
||||
5. 검수(예외 없음): 만든 JPEG 전부를 **한 장씩 원본 크기로** Read 로 연다. 축소 시트로 판단하지 않는다. 볼 것: 글자 잘림·겹침, 그림 누락, 그림 속 사람·얼굴·글자, 코디는 옷 목록 줄의 옷이 그림에 전부 있고 추가 옷이 없는지, 날씨 줄 수치가 예보와 맞는지. 틀리면 고치고 다시 찍어 다시 본다.
|
||||
6. 새 그림이 생겼으면 `git add admin/src/assets/gak-card admin/src/assets/ootd admin/src/assets/tarot-bg` 후 `feat: <날짜> 카드 그림(…)` 로 커밋한다 (Claude 서명 없이).
|
||||
7. 보고(한국어, 짧게): 킹서버 카드 번호 2개(승인 대기), 만든 JPEG 경로, 새 그림 수, 검수에서 고친 것, 남은 이슈. 올리는 건 사용자가 관리자 '만든 카드' 탭이나 "올려" 로 한다.
|
||||
4. 코디(그날 코디): `npm run card -- ootd --daily --style <스타일> --color sky --post-wait`. 무신사 인기 스냅 중 그 스타일 태그(꾸안꾸·오피스룩·캐주얼·스트릿·정장)가 붙은 것에서 사람 4명(20-30대·40대~ 여·남) 코디를 고르고, Claude 가 옷 목록을 뽑고, Codex 가 참고 사진대로 플랫레이 그림을 그린다(사람당 2~4분). 고른 스냅 주소와 옷 목록이 출력된다. "스냅이 없어요"·"저장하지 못했어요" 가 나오면 멈추고 보고한다.
|
||||
5. 검수(예외 없음): 만든 JPEG 전부를 **한 장씩 원본 크기로** Read 로 연다. 축소 시트로 판단하지 않는다. 볼 것: 글자 잘림·겹침, 그림 누락, 그림 속 사람·얼굴·글자, 코디는 그림 아래 옷 목록의 옷이 그림에 전부 있고 추가 옷이 없는지, 스냅 사진(`out/<날짜>/snaps/<사람>/snap.jpg`)과 옷·색이 같은지, 날씨 줄 수치가 예보와 맞는지. 틀리면 고치고 다시 찍어 다시 본다.
|
||||
6. 새 타로 그림이 생겼으면 `git add admin/src/assets/gak-card admin/src/assets/tarot-bg` 후 `feat: <날짜> 각 카드 그림(…)` 로 커밋한다 (Claude 서명 없이). 코디 그림(`admin/public/daily`)은 커밋하지 않는다.
|
||||
7. 보고(한국어, 짧게): 킹서버 카드 번호 2개(승인 대기), 만든 JPEG 경로, 참고한 스냅 주소 4개, 검수에서 고친 것, 남은 이슈. 올리는 건 사용자가 관리자 '만든 카드' 탭이나 "올려" 로 한다.
|
||||
@@ -0,0 +1,15 @@
|
||||
---
|
||||
description: 오늘의 코디 카드 4장(20-30대·40대~ 여·남, 스타일 하나)을 무신사 인기 스냅으로 만들어 검수하고 날씨각 피드와 인스타에 올린다
|
||||
argument-hint: "<스타일> minimal(꾸안꾸)·casual·semi(오피스)·formal·street (비우면 minimal)"
|
||||
---
|
||||
|
||||
오늘의 코디 카드를 만들어 올린다. 인자: `$ARGUMENTS` — 코디 스타일 하나(minimal=꾸안꾸, casual=캐주얼, semi=세미정장·오피스, formal=정장, street=스트릿). 비어 있으면 minimal. 포스트 하나는 스타일 하나: 네 사람 모두 같은 스타일.
|
||||
재확인 질문 없이 순서대로 진행하고, 막히면 그 자리에서 보고하고 멈춘다. 검수를 통과한 뒤에만 올린다(올린 건 되돌릴 수 없다).
|
||||
|
||||
1. 관리자 서버: `curl -s http://localhost:5175/api/targets` 에 `king` 이 있어야 한다. 없으면 `admin/` 에서 백그라운드로 켠다 (`admin/AGENTS.md` '켜기', 킹서버 키는 `ssh King_admin` 의 `~/proj/o2o-weather/.env` `ADMIN_API_KEY`, 값은 출력하지 않는다).
|
||||
2. 만들기(승인 대기로 저장까지): `cd admin && VITE_API_BASE_URL=https://weather.o2o.kr ADMIN_URL=http://localhost:5175 npm run card -- ootd --daily --style <스타일> --color sky --post-wait`. 출력 끝의 `카드 N` 번호를 적어 둔다.
|
||||
무신사 인기 스냅 중 그 스타일 태그가 붙은 것에서 사람 4명 코디를 고르고(최근 14일에 쓴 스냅 제외), Claude 가 옷 목록을 뽑고, Codex 가 스냅 사진·상품 썸네일을 참고해 플랫레이 그림을 그린다(사람당 2~4분, 총 10~15분). 고른 스냅 주소·옷 목록이 출력된다. "스냅이 없어요"·"저장하지 못했어요"·"Codex 실행이 실패" 가 나오면 멈추고 보고한다. 로그의 `rmcp … AuthRequired` 는 Codex 내부 경고라 무시한다. 크롬이 한 장에서 45초 넘게 멈추면 그 프로세스를 죽이고 그 장만 다시 찍는다.
|
||||
3. 검수(예외 없음): 만든 JPEG 4장을 **한 장씩 원본 크기로** Read 로 연다. 축소 시트로 판단하지 않는다. 볼 것: 그림이 비어 있지 않은지, 그림 아래 옷 목록의 옷이 그림에 전부 있고 추가 옷이 없는지, 그림 속 사람·얼굴·글자, 스냅 사진(`admin/out/<날짜>/snaps/<사람>/snap.jpg`)과 옷·색이 같은지, 이름표 줄이 날씨 줄과 겹치지 않는지, 날씨 줄 수치가 예보(`https://weather.o2o.kr/v1/weather/today?region=1114000000`)와 맞는지. 틀리면 고치고 다시 만들어(2번, 새 카드 번호) 다시 본다. 못 고치면 올리지 말고 보고한다.
|
||||
4. 올리기(검수 통과 시): `curl -s -X POST "http://localhost:5175/api/cards/<카드 N>/publish?target=king"` → `post_id` 확인, 이어서 `curl -s -X POST --max-time 600 "http://localhost:5175/api/cards/<카드 N>/instagram?target=king"` → `ig_media_id`. 인스타 링크: `~/projects/o2o-weather/.env` 의 `INSTAGRAM_ACCESS_TOKEN` 으로 `GET https://graph.instagram.com/v24.0/<ig_media_id>?fields=permalink` (토큰 값은 출력하지 않는다).
|
||||
5. TODO.md 인스타 홍보 표에 한 줄(카드·포스트 번호, 인스타 링크, 참고 스냅 4개) 적고 `docs:` 커밋, `git push origin sns:main`. 코디 그림(`admin/public/daily`)은 커밋하지 않는다.
|
||||
6. 보고(한국어, 짧게): 인스타 링크, 킹서버 카드·포스트 번호, 참고한 스냅 주소 4개, 검수에서 고친 것, 남은 이슈.
|
||||
@@ -0,0 +1,16 @@
|
||||
---
|
||||
description: 오늘의 날씨 타로 카드 5장을 만들어 검수하고 날씨각 피드와 인스타에 올린다
|
||||
argument-hint: "<타로 주제> 예) 건강 운동 · 연애 썸 · 경제 주식 (비우면 Claude가 고름)"
|
||||
---
|
||||
|
||||
오늘의 날씨 타로 카드를 만들어 올린다. 인자: `$ARGUMENTS` — 타로 주제(대주제 소주제). 비어 있으면 Claude 가 오늘 날씨에 맞는 주제를 고른다.
|
||||
재확인 질문 없이 순서대로 진행하고, 막히면 그 자리에서 보고하고 멈춘다. 검수를 통과한 뒤에만 올린다(올린 건 되돌릴 수 없다).
|
||||
|
||||
1. 관리자 서버: `curl -s http://localhost:5175/api/targets` 에 `king` 이 있어야 한다. 없으면 `admin/` 에서 백그라운드로 켠다 (`admin/AGENTS.md` '켜기', 킹서버 키는 `ssh King_admin` 의 `~/proj/o2o-weather/.env` `ADMIN_API_KEY`, 값은 출력하지 않는다).
|
||||
2. 예보: `curl -s "https://weather.o2o.kr/v1/weather/today?region=1114000000"` 의 `day` 가 오늘인지 보고 slots 의 기온·하늘·비 확률을 적어 둔다.
|
||||
3. 만들기(승인 대기로 저장까지): `cd admin && VITE_API_BASE_URL=https://weather.o2o.kr ADMIN_URL=http://localhost:5175 npm run card -- tarot --topic "<주제>" --color sky --post-wait` (주제가 없으면 `--topic` 없이). 출력 끝의 `카드 N` 번호를 적어 둔다.
|
||||
출력된 기획 문구를 2의 예보와 대조한다(숫자·하늘 묘사가 틀리면 `--copy <값> --feedback "실제 수치…"` 로 한 번만 다시). 빠진 각 카드 그림은 Codex 가 자동으로 만든다(장당 1~5분). "일부 그림을 못 만들어" 가 나오면 멈추고 보고한다. 크롬이 한 장에서 45초 넘게 멈추면 그 프로세스를 죽이고 그 장만 다시 찍는다.
|
||||
4. 검수(예외 없음): 만든 JPEG 5장을 **한 장씩 원본 크기로** Read 로 연다. 축소 시트로 판단하지 않는다. 볼 것: 글자 잘림·겹침, 카드 그림 누락, 그림 속 사람·글자, 리딩 문구의 수치·하늘 묘사가 예보와 맞는지, 말투(3문장, "~할 수 있어요" 남발·덕담 금지). 틀리면 고치고 다시 만들어(3번, 새 카드 번호) 다시 본다. 못 고치면 올리지 말고 보고한다.
|
||||
5. 올리기(검수 통과 시): `curl -s -X POST "http://localhost:5175/api/cards/<카드 N>/publish?target=king"` → `post_id` 확인, 이어서 `curl -s -X POST --max-time 600 "http://localhost:5175/api/cards/<카드 N>/instagram?target=king"` → `ig_media_id`. 인스타 링크: `~/projects/o2o-weather/.env` 의 `INSTAGRAM_ACCESS_TOKEN` 으로 `GET https://graph.instagram.com/v24.0/<ig_media_id>?fields=permalink` (토큰 값은 출력하지 않는다).
|
||||
6. 새 그림이 생겼으면 `git add admin/src/assets/gak-card admin/src/assets/tarot-bg` 후 `feat: <날짜> 각 카드 그림(…)` 로 커밋한다 (Claude 서명 없이). TODO.md 인스타 홍보 표에 한 줄(카드·포스트 번호, 인스타 링크) 적고 `docs:` 커밋, `git push origin sns:main`.
|
||||
7. 보고(한국어, 짧게): 인스타 링크, 킹서버 카드·포스트 번호, 새 그림 수, 검수에서 고친 것, 남은 이슈.
|
||||
@@ -32,6 +32,13 @@ GOOGLE_CLIENT_ID=
|
||||
JWT_ACCESS_SECRET=
|
||||
JWT_REFRESH_SECRET=
|
||||
|
||||
# ── 백엔드: 앱인토스 토스 로그인. 인증서·키는 저장소 최상위 secrets/toss/ 에 두고(커밋 안 함) 컨테이너 안 경로를 적는다
|
||||
# compose 는 secrets/toss 를 backend 의 /run/secrets/toss 에 읽기 전용으로 붙인다
|
||||
TOSS_MTLS_CERT=/run/secrets/toss/nalssigak_public.crt
|
||||
TOSS_MTLS_KEY=/run/secrets/toss/nalssigak_private.key
|
||||
# 연결 끊기 콜백 Basic Auth "아이디:비밀번호" — 콘솔에 넣은 값과 같게. 비우면 콜백을 모두 거절한다
|
||||
TOSS_UNLINK_AUTH=
|
||||
|
||||
# ── 배포(compose): 비우면 로컬 기본값. 킹서버 예: FRONT_PORT=30040, API_BIND=127.0.0.1:9810, PG_BIND=127.0.0.1:5440, REDIS_BIND=127.0.0.1:6390
|
||||
FRONT_PORT=
|
||||
API_BIND=
|
||||
|
||||
@@ -24,3 +24,8 @@ backend/uploads/
|
||||
.impeccable/
|
||||
|
||||
/zzz
|
||||
# 인증서·키: 서버와 각자 PC 에만 둔다 (토스 mTLS 등)
|
||||
secrets/
|
||||
*.pem
|
||||
*.key
|
||||
*.crt
|
||||
@@ -0,0 +1,34 @@
|
||||
# 날씨각
|
||||
|
||||
날씨를 보면 오늘 할 일을 알려 주는 서비스. https://weather.o2o.kr
|
||||
|
||||
| 폴더 | 내용 | 문서 |
|
||||
|---|---|---|
|
||||
| `backend/` | FastAPI 백엔드 (날씨·각 점수·피드·카드 API) | `backend/docs/README.md` |
|
||||
| `frontend/` | React 서비스 화면 | `frontend/README.md` |
|
||||
| `admin/` | 관리자: 인스타 카드(날씨 타로·오늘의 코디) 제작 | `admin/AGENTS.md` |
|
||||
| `docs/` | 기획·설계·운영 문서 | 아래 |
|
||||
|
||||
## 인스타 카드 올리기
|
||||
|
||||
Claude Code에서 한 줄:
|
||||
|
||||
```
|
||||
/daily-tarot 건강 운동 ← 날씨 타로 5장
|
||||
/daily-ootd minimal ← 오늘의 코디 4장
|
||||
```
|
||||
|
||||
만들고 검수하고 날씨각 피드·인스타까지 올린 뒤 링크를 보고한다. 자세한 건 [docs/인스타_카드_사용법.md](docs/인스타_카드_사용법.md).
|
||||
|
||||
## 주요 문서
|
||||
|
||||
- [서비스 동작 안내](docs/서비스_동작_안내.md) — 날씨를 언제 받고 점수를 어떻게 매기나
|
||||
- [각 계산 기준](docs/각_계산기준.md) · [점수 계산식](docs/점수_계산식.md)
|
||||
- [피드 동작 방식](docs/피드_동작방식.md) · [콘텐츠 설계서](docs/콘텐츠_설계서.md)
|
||||
- [인스타 카드 사용법](docs/인스타_카드_사용법.md)
|
||||
- [TODO](TODO.md) — 결정 필요·미해결 항목
|
||||
- 회의록: `docs/meetings/`
|
||||
|
||||
## 배포
|
||||
|
||||
킹서버에서 `./deploy.sh` (init.sql 재실행, docker compose). 운영 `.env`는 서버에 따로 있다.
|
||||
@@ -207,6 +207,15 @@
|
||||
| [x] | 좋아요·댓글이 전국 공통 — 포스트가 (날짜, 자리) 하나로 전국에 하나뿐이라, 구마다 내용이 다른 카드(오늘 날씨·각 1~3위·노을·미세먼지·행사)도 댓글·좋아요를 전국이 같이 씀. 예: 강남의 "1위 산책각"과 부산의 "1위 빨래각"이 같은 댓글창. 안: 지역 데이터 카드만 시도(17) 단위로 나누고 계절·상식·명언은 전국 공통 유지 | 사용자 질문 (10/8) | `backend/postgres-init/init.sql` (`uq_post_feed`), `backend/services/feed_service.py` (`build_day`, `_gak`) |
|
||||
| [ ] | **[결정 필요]** 포스트 시도 단위가 17이 아니라 16 — `region.code` 앞 2자리에서 광주·전남이 둘 다 `12`(전남광주통합특별시)라 같은 댓글창을 씀. 그대로 둘지, 이름 앞머리로 광주·전남을 나눌지 | 포스트 시도 나누기 (10/8) | `backend/services/feed_service.py` (`sido_of`), `backend/seed/region.csv` |
|
||||
| [ ] | 광주·전남 구는 행사가 안 잡힐 수 있음 — 구 코드 시도는 `12`인데 행사 수집·`event.sido_code`는 `29`(광주)·`46`(전남). 좌표 없는 행사는 `is_nearby`·`nearby_sidos`에서 빠짐 | 포스트 시도 나누기 중 발견 (10/8) | `backend/services/week_service.py:125,144`, `backend/services/external/culture_api.py:28` |
|
||||
| [ ] | **[결정 필요]** 앱인토스 입점 여부 — 검토안은 "웹 출시 후 보기 전용 토스판으로 시험, 첫 달 포인트·알림 20~30만 원, 5주차에 포인트 없는 주의 7일 재방문율 20%를 기준으로 계속/중단" (https://claude.ai/artifact/QgA7iq3CCesTRYcFyZck71) | 앱인토스 검토 | |
|
||||
| [ ] | **[결정 필요]** 토스판 광고 — 앱인토스 수익은 토스 광고·인앱결제뿐인데 웹은 '광고 없음'으로 정함. 안 붙이면 토스판은 비용만 드는 홍보 채널 | 앱인토스 검토 | |
|
||||
| [ ] | 앱인토스 사전 확인 — 시간대별 밤 배경이 '라이트 모드' 규칙에 걸리는지, 네이버 지도 링크가 '단순 정보 확인' 예외인지 채널톡 문의 | 앱인토스 검토 | `frontend/src/b/BLayout.tsx`, `frontend/src/b/ui.tsx` |
|
||||
| [ ] | **[결정 필요]** 각 34개 정리 — 계절 밖 각(10월 물놀이·냉면) 노출 막기(각별 '보여 줄 달'), 나쁜 일 예고 각(택시대란·배달폭주·김서림·화장붕괴)을 순위에서 빼고 '조심' 카드로, 날씨 관계 약한 재미 각(공부·넷플릭스·짬뽕·막걸리·뜨아·군밤·집콕) 축소 또는 '재미' 표시 (https://claude.ai/artifact/4WgpUjdNqdSNnMN4ASB4BB) | 토스판 전략 검토 | `backend/seed/index_definition.json`, `backend/services/index_service.py` |
|
||||
| [ ] | 글 재고 부족 — 25편(한 문장 8·시 3·상식 4·계절 9)이라 매일 보면 1~2주 안에 반복, 계절 글은 10월분뿐. 기획의 'AI 주 1회 생성'이 스케줄러에 없음. 8주치 재고 또는 생성·검토 파이프라인 | 토스판 전략 검토 | `backend/seed/article.json`, `backend/scheduler/jobs.py` |
|
||||
| [ ] | **[결정 필요]** 노을 알림 재검토 — 10/2에 제외했지만 토스 알림은 정보성만 허용돼 "오늘 노을 좋음"이 가장 맞는 알림. 토스판 핵심 후보 | 토스판 전략 검토 | |
|
||||
| [ ] | **[결정 필요]** 히어로 숫자 5개(기온·체감·불쾌지수·날씨 점수·1위 각 점수) — 불쾌지수 여름만, 날씨 점수 유지 여부 | 토스판 전략 검토 | `frontend/src/b/TodayPage.tsx` |
|
||||
| [x] | 토스판 방식 — WebView로 결정(10/12). 별도 프로젝트 없이 `frontend/`에 토스 빌드 모드 추가, RN은 독립 앱만 | 토스판 전략 검토 | `frontend/` |
|
||||
| [x] | 앱인토스 appName 정식 이름으로 교체 — 콘솔 앱 `nalssigak`으로 맞춤(10/13). 정식 앱 등록 후 두 곳을 같이 바꾸고 `npm run build:toss` 다시 실행 | 콘솔 테스트 앱으로 먼저 등록 | `frontend/apps-in-toss.config.ts`, `frontend/src/lib/platform.ts` |
|
||||
| [x] | 전체 날씨 점수 기준 강화 — 100점은 '1년에 하루' 수준으로만 → 각과 같은 계산에 기준만 좁힘(체감 21±0.5°·습도 45~55%·해 90%↑·바람 1m/s↓·초미세먼지 10↓, 사용자 결정 '기준만 좁히기'). 실제 연 몇 번 나오는지는 미확인 (`docs/점수_계산식.md` 3) | 10/8 회의 결정 | `backend/services/index_service.py:203` |
|
||||
| [x] | 각 점수를 아침·낮·저녁·밤 시간대별로 → 지금 구간 점수로 순위, 안 겹치는 각은 순위·피드에서 빼고 스토리·전체엔 '지금 아님'. 히어로는 '지금 날씨 점수'(지금 구간). 운영 DB에 `index_score.slots` 칸 추가 필요(배포 때 `init.sql`의 ALTER) | 10/8 회의 결정 | `backend/services/calc/index_calc.py:297` |
|
||||
| [x] | 히어로에 습도·불쾌지수 항상 표시 → 4칸(지금·습도·불쾌지수·상황 1칸, 사용자 결정). 불쾌지수 75 이상이면 경고 색, 상황 칸 후보에서 불쾌지수 뺌 | 10/8 회의 결정 | `frontend/src/b/TodayPage.tsx` (`HeroStat`) |
|
||||
@@ -218,6 +227,13 @@
|
||||
| [ ] | **[결정 필요]** 각 순위가 점수 순이 아니라 보임 — 순위가 점수 × 중요도라 환기각 92점(하)이 5위, 골프각 89점이 3위, 빨래각 83점이 2위. 각 탭 받침대·스토리에서 높은 점수가 뒤에 있어 어색함. 점수를 순위대로 보여줄지, 중요도 가중을 줄일지 | 화면 직접 확인 중 발견 (10/12) | `backend/services/calc/index_calc.py` (`PRIORITY_WEIGHT`), `frontend/src/b/GakPage.tsx` |
|
||||
| [x] | 노을 점수 29점(잿빛)인데 결론 '나가 볼 만해요' — 결론이 구름 분포만 보고 공기 보정(가시거리·습도)을 안 봤음 → 공기 보정 0.7배 미만이면 결론 한 단계 낮추고 이유에 공기 표시, '해 질 무렵(N시) 예보 기준' 표시. 운영 DB에 `sky_score.air` 칸 추가 필요(배포 때 `init.sql`의 ALTER) | 사용자 지적 (10/12, 분당구) | `backend/services/sky_service.py` (`day_verdict`, `build_plan`), `backend/services/calc/sky_score.py` (`air_note`) |
|
||||
| [x] | 노을 탭 다시 짜기 → 시안 A(사용자 선택): 히어로 '오늘은 애매해요 / 18:10쯤 가장 붉어요 / 쉬운 이유', 내일 안내 바로 아래, 숫자는 '자세히', 시간표에 가장 붉을 때 — 처음 보면 '그래서 가?'에서 멈춤: 히어로 18:00이 무슨 시각인지 없음, 결론 카드가 좋은 말·나쁜 말을 섞음, 구름 %·예보 모델 수 같은 전문 용어, '가장 붉을 때'가 시간표에 없음, '내일이 더 나아요'가 맨 아래. 시안 먼저 보고 결정 | 사용자 지적 (10/12) | `frontend/src/b/SkyPage.tsx`, `backend/services/calc/sky_score.py` (`reason`) |
|
||||
| [ ] | 토스 로그인 운영 설정 — 서버 `secrets/toss/` 인증서·키, `.env` `TOSS_*` 세 줄은 넣음(10/14). 남은 것: 정산정보 등록(대표님), 배포, 콘솔 약관 링크·콜백, `4050 인증서버에 등록된 미니앱이 아닙니다` 재확인 | 토스 로그인 구현(10/14) | `compose.yaml`, `.env.example`, `backend/config/settings.py` |
|
||||
| [ ] | 토스 번들 다시 만들기 — 로그인(4050) 풀린 뒤 `npm run build:toss`로 한 번에. 지금 콘솔 번들엔 로그인·GA `platform` 값이 없음. 로그인 실패 상태로 검수 올리면 반려 위험 | 로그인 미완성이라 미룸(10/14) | `frontend/` |
|
||||
| [ ] | **[결정 필요]** 토스 연결 끊기 처리 — 지금은 UNLINK·탈퇴 모두 토큰만 무효로 함. 토스 탈퇴(`WITHDRAWAL_TOSS`·`WITHDRAWAL_TERMS`) 때 계정·댓글을 지울지 | 토스 로그인 구현(10/14) | `backend/services/auth_service.py` |
|
||||
| [ ] | 토스 로그인 문구 검토 — '토스로 로그인', '토스로 로그인했어요', '토스 로그인을 마치지 못했어요. 한 번 더 눌러 주세요.', 기본 닉네임 '토스1234'(userKey 끝 4자리), 로그인 창 '날씨각 로그인'·'로그인하면 동네 이야기를 쓰고 내 각을 저장할 수 있어요', 인트로 '오늘 날씨에 맞는 일을 점수로 알려 줘요'·'세차·빨래·러닝 각 점수'·'오늘 노을이 예쁜 시간'·'이번 주말 가까운 행사'·'시작하기'(10/24) | 토스 로그인 구현(10/14) | `frontend/src/b/Sheets.tsx`, `backend/services/auth_service.py` |
|
||||
| [ ] | 토스판 첫 실행에 인트로와 위치 권한 창이 같이 뜸 — 위치 권한은 앱이 뜨자마자 물어서 인트로 위에 겹칠 수 있음. '시작하기' 뒤로 미룰지 토스 앱에서 확인 | 인트로 추가 (10/24) | `frontend/src/b/region.tsx`, `frontend/src/b/tossIntro.tsx` |
|
||||
| [ ] | 메뉴의 '로그인하면 좋아요·댓글을 쓸 수 있어요' — 좋아요·댓글은 로그인 없이 됨(10/21 결정)이라 문구가 틀림 | 인트로 추가 중 발견 (10/24) | `frontend/src/b/Sheets.tsx:1117` |
|
||||
| [ ] | 댓글 신고·차단 — 앱인토스 필수 아님(신고·차단 필수는 채팅·만남·중고거래만, 서비스 오픈 정책·서비스별 주의사항). 만들지 않기로 함(10/14). 검수에서 요청이 오면 만든다 | 토스 로그인 구현(10/14) | |
|
||||
| [x] | 각 늘리기 53→68 — 리서치로 고른 8개(한강·놀이공원·데이트·곱슬머리·보일러·선크림·모기·테니스) + 감성 7개(효도·감사·선물·파티·게임·셀카·센치), 아이콘 15개(Codex) | 사용자 요청 (10/20, 리서치 https://claude.ai/artifact/3ZQbtGKRLVZViRRC5voBzY) | `backend/seed/index_definition.json`, `frontend/public/icons/`, `frontend/src/b/lib.ts` |
|
||||
| [ ] | **[결정 필요]** 한강각·놀이공원각이 강·놀이공원 없는 동네에도 나옴 — 각을 지역별로 가려 보여 주는 기능이 없음(한강밤바람각도 같음). 서울·한강 인접 구만 보일지 | 새 각 추가 중 발견 (10/20) | `backend/seed/index_definition.json`, `backend/services/index_service.py` |
|
||||
| [ ] | **[결정 필요]** 기존 각과 겹침 — 센치↔감성노래, 게임↔넷플릭스·집콕, 곱슬머리↔화장붕괴, 효도↔트로트, 셀카↔사진산책. 둘 다 둘지 합칠지 | 새 각 추가 중 발견 (10/20) | `backend/seed/index_definition.json` |
|
||||
@@ -268,7 +284,12 @@
|
||||
| [ ] | 인스타 릴스(20초, 2.5D: Codex 3D 렌더풍 배경 + 카메라 패럴랙스, 무료 BGM, API로 업로드) — 백엔드에 mp4 공개 주소 + REELS 게시 추가 필요 | 사용자 요청 (10/24) | `backend/services/external/instagram.py` |
|
||||
| [ ] | 인스타에 올라간 불량 게시물 삭제(앱에서만 가능): 소개 카드 De3SUTtoDGR·De3ycbAIPVw(스샷 잘림)·De31G7VIBEc(7·8번 장 치우침), 릴스 18152745022535272(폰 잘림), 10/25 꾸안꾸 코디 De58VfXINy0(20-30대와 40대~ 옷이 같음)·De5-8gboL-c(40대 여자 롱가디건·여름 옷)·De6B2gwIMXF(이름표 자리 어긋남) — 킹서버 포스트 3961·3962·3963은 deleted=true로 숨김 | 10/24·10/25 검수 실패 | — |
|
||||
| [ ] | 소개 카드 최종본(`admin/out/2026-10-24/소개카드_1~8.jpg`, 10/24 21:54 — 8장 1:1 검수 완료, 모서리 캐릭터는 1번만·4·6·8번은 3D 스틸 안 캐릭터)과 3D 릴스(`admin/out/2026-10-24/릴스_3D.mp4`·표지 `릴스_3D_표지.jpg`, 21프레임 검수 완료) — 사용자가 "올려"라고 할 때만 올림. 릴스 음악은 HeyGen 로그인(`~/.local/bin/heygen auth login --oauth`) 뒤 `npx hyperframes media-use resolve --type bgm` | 10/24 | `admin/reels/intro3d/` |
|
||||
| [ ] | 코디 옷 데이터 — 세미정장·정장·스트릿·꾸안꾸 4스타일은 7개 기온 구간 전부 20-30대와 40대~ 옷이 같음(캐주얼만 다름, warm·꾸안꾸는 10/25 고침). 40대~ 여/남 옷 목록 54개를 새로 써서 검토받고 반영 | 10/25 발견 | `admin/image-prompts/ootd.json` |
|
||||
| [x] | 코디 옷 데이터 — 세미정장·정장·스트릿·꾸안꾸 4스타일은 7개 기온 구간 전부 20-30대와 40대~ 옷이 같음(캐주얼만 다름, warm·꾸안꾸는 10/25 고침). 40대~ 여/남 옷 목록 54개를 새로 써서 검토받고 반영 — 10/26 그날 코디(--daily)로 대체해 고정 데이터는 예비용만 | 10/25 발견 | `admin/image-prompts/ootd.json` |
|
||||
| [x] | 코디 카드 매일 다르게 — 고정 옷 데이터 대신 무신사 스냅 공개 API에서 오늘 구간 인기 코디를 사람별(40대~ 단정 태그 우선)로 골라 Claude가 옷 목록 추출, Codex가 참고 사진 첨부로 플랫레이 생성(`npm run card -- ootd --daily`, `/daily-cards`). 10/26 4장 검수 통과. 에이블리는 공개 API 없음(앱 전용)이라 미사용 | 사용자 요청 (10/26) | `admin/scripts/daily-ootd.mjs`, `snap.mjs`, `outfit.mjs`, `codex-image.mjs` |
|
||||
| [x] | 10/26 세미정장 코디(그날 코디 첫 게시) — 킹서버 카드 12→포스트 4275, 인스타 https://www.instagram.com/p/De8O2kqATrl/. 무신사 스냅 4개 참고, 4장 1:1 검수 | 사용자 요청 (10/26) | `admin/scripts/daily-ootd.mjs` |
|
||||
| [x] | 10/26 몸 컨디션 타로(건강: 등산각·자전거각·산책각) — 킹서버 카드 13→포스트 4276, 인스타 https://www.instagram.com/p/De8Zw7MIEVW/. 기획에서 3번 산책각 비 시점 틀린 것 피드백으로 고침. card.mjs --post-wait 가 ECONNRESET 으로 두 번 실패해 post-king.py 로 저장 | 사용자 요청 (10/26) | `admin/scripts/card.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` |
|
||||
| [ ] | `npm run card`가 크롬 멈춤에 시간 제한이 없음 — 10/24 소개 카드 7번 장에서 헤드리스 크롬이 75분 멈춰 있었음(`--virtual-time-budget`만으론 안 끝남). `execFileSync`에 `timeout`(예: 60초) 주고 실패 시 그 장만 재시도 | 10/24 렌더 중 발견 | `admin/scripts/card.mjs` |
|
||||
| [x] | 10/25 건강·운동 타로(킹서버 카드 7→포스트 3960, 인스타 https://www.instagram.com/p/De5iLg4AS_M/)·꾸안꾸 코디는 처음 올린 카드 8→포스트 3961(인스타 De58VfXINy0)이 40대~ 옷이 20-30대와 같아 숨기고, 40대~ 옷을 새로 써서 카드 9→포스트 3962(인스타 De5-8gboL-c)로 재게시했으나 40대 여자 그림에 롱가디건이 끼고 전체가 여름 옷으로 보여 다시 숨김. 일교차 8도 이상이면 겉옷을 5번째 옷으로 넣게 고쳐 카드 10→포스트 3963(인스타 De6B2gwIMXF)으로 올렸으나 그림 배치와 이름표 자리가 어긋나 숨김. 프롬프트에 옷 자리를 적고 다시 그려 카드 11→포스트 3964, 인스타 https://www.instagram.com/p/De6JRIkoKbT/ 로 최종 게시. 07:52 예약(세션 크론)이 세션 종료로 안 돌아 09:46 수동 실행. 코디는 사용자 결정으로 사람 구분을 20-30대·40대~ 4장으로 바꿈(f30·m30 그림 파일 8장은 남아 있으나 미사용). 새 그림 8장(러닝각·자전거각·warm 꾸안꾸 6) | 사용자 요청 (10/24) | `admin/image-prompts/ootd.json`, `admin/scripts/card.mjs` |
|
||||
|
||||
@@ -25,3 +25,6 @@ dist-ssr
|
||||
|
||||
# npm run card 결과
|
||||
out
|
||||
|
||||
# 그날 코디 그림 (scripts/daily-ootd.mjs 가 만들고 카드가 /daily/... 로 읽는다)
|
||||
public/daily
|
||||
@@ -33,6 +33,10 @@ VITE_API_BASE_URL=http://localhost:9810 npm run dev # http://localhost:5175
|
||||
- **카드**: 날씨각 각 카드(`../backend/seed/index_definition.json`, 53장). 오늘 점수가 높은 각 중 질문과 엮이는 3장을 고르고, 각 카드로 질문을 리딩한다. 카드 그림은 그 각의 아이콘.
|
||||
- 대주제·소주제·아이콘을 늘리려면 `topics.json`만 고친다. 새 꾸밈 모양은 CSS와 `image-prompts/tarot.json`에 같이 더한다.
|
||||
|
||||
## 매일 올리기 (슬래시 명령)
|
||||
|
||||
사용자용 안내는 `docs/인스타_카드_사용법.md`. Claude Code에서 `/daily-tarot <주제>`, `/daily-ootd <스타일>`, `/daily-cards <주제> <스타일>` 을 치면 만들기 → 장마다 검수 → 킹서버 피드·인스타 게시 → 링크 보고까지 한 번에 한다. 명령 정의는 `.claude/commands/`.
|
||||
|
||||
## 대화로 만들 때 (Claude·Codex)
|
||||
|
||||
사용자가 "오늘 주식 날씨 타로 만들어 줘"처럼 말하면 아래 명령을 실행한다. 관리자 화면(`npm run dev`)이 켜져 있어야 한다.
|
||||
@@ -55,6 +59,25 @@ VITE_API_BASE_URL=http://localhost:9810 npm run card -- tarot --topic 주식 [--
|
||||
- 관리자 서버가 비밀값을 `/api/post`·`/api/cards`에서만 붙인다. 브라우저엔 안 나간다. 킹서버 키는 킹서버 `.env`의 `ADMIN_API_KEY`와 같은 값.
|
||||
- 켜는 예: `VITE_API_BASE_URL=http://localhost:9810 ADMIN_API_KEY=… KING_ADMIN_API_KEY=… npm run dev`
|
||||
|
||||
## 그날 코디 (무신사 인기 스냅 → 옷 추출 → 참고 사진대로 그림)
|
||||
|
||||
코디 카드는 고정 데이터(`image-prompts/ootd.json` 구간×스타일 옷) 대신 **그날 무신사 인기 스냅**으로 만든다. 같은 날씨라도 매일 다른 코디가 나온다.
|
||||
|
||||
```bash
|
||||
VITE_API_BASE_URL=https://weather.o2o.kr npm run card -- ootd --daily --style minimal --color sky --post-wait
|
||||
```
|
||||
|
||||
포스트 하나는 스타일 하나(`--style`, 기본 minimal=꾸안꾸): 네 사람 모두 그 스타일 태그(`scripts/snap.mjs STYLE_TAGS`)가 붙은 스냅에서 고르고 제목도 그 스타일로 통일한다.
|
||||
|
||||
흐름(`scripts/daily-ootd.mjs`):
|
||||
1. 오늘 예보로 기온 구간을 정한다(`scripts/daily-ootd.mjs weatherToday`).
|
||||
2. `scripts/snap.mjs`: 무신사 스냅 공개 API에서 구간에 맞는 태그(가을코디·간절기코디·겨울코디…)와 단정 키워드(오피스룩·댄디룩…)로 인기 스냅을 모으고, 상품 카테고리로 상의·하의·신발이 다 있는 것만 남긴 뒤 사람별(40대~ 먼저, 단정 태그 가산점)로 하나씩 고른다. 45일 지난 스냅, 구간에 안 맞는 아우터(패딩·코트 등)·반바지는 뺀다. 사진·상품 썸네일은 `out/<날짜>/snaps/<사람>/`에 참고용으로만 받고 어디에도 올리지 않는다.
|
||||
3. `scripts/outfit.mjs`: Claude CLI(sonnet, Read 로 사진을 봄)가 자리별(top·outer·bottom·shoes·bag) 한글 이름표와 영어 그림 설명을 뽑는다.
|
||||
4. `scripts/codex-image.mjs`: Codex 에 스냅 사진·상품 썸네일을 첨부(`-i`)해 같은 옷·색으로 우리 플랫레이 스타일 그림을 그린다 → `public/daily/<날짜>-<사람>.webp` (git 에 넣지 않음).
|
||||
5. 카드는 `copy.outfits`(JSON 문자열)로 이름표·그림 주소를 받는다(`src/cards/ootd.ts dailyOutfits`). 제목은 Claude 가 정한 스타일 한 단어(꾸안꾸·오피스룩…).
|
||||
|
||||
에이블리는 공개 API가 없어 쓰지 않는다(앱 전용). 고정 데이터 방식(`--daily` 없이)은 그대로 남아 있다.
|
||||
|
||||
## 카드 그림 만들기 (Codex 이미지 생성)
|
||||
|
||||
**그림은 그날 만드는 카드에 필요한 것만 그때 만든다.** 조합(기온 구간 × 스타일 × 사람, 타로 78장)을 미리 일괄로 만들지 않는다. Codex 사용량이 한정돼 있다.
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
// --post 면 다 그린 뒤 날씨각 오늘 피드에 바로 올리고, --post-wait 면 승인 대기로 저장한다 (관리자 서버 /api/post).
|
||||
// 지역은 고르지 않는다. 카드는 서울 예보로 만들고 카드에 지역 이름은 나가지 않는다 (src/cards/data.ts BASE_REGION)
|
||||
import { execFileSync } from 'node:child_process'
|
||||
import { existsSync, mkdirSync, readFileSync, rmSync } from 'node:fs'
|
||||
import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
|
||||
import { resolve } from 'node:path'
|
||||
|
||||
const SLIDES = { tarot: 5, ootd: 4, intro: 8 }
|
||||
@@ -34,11 +34,14 @@ let copy = flag('--copy')
|
||||
const topic = flag('--topic')
|
||||
const feedback = flag('--feedback')
|
||||
const color = flag('--color')
|
||||
const styleArg = flag('--style')
|
||||
const outArg = flag('--out')
|
||||
const take = (name) => args.includes(name) && args.splice(args.indexOf(name), 1).length > 0
|
||||
const noImages = take('--no-images')
|
||||
let noImages = take('--no-images')
|
||||
const postNow = take('--post')
|
||||
const postWait = take('--post-wait')
|
||||
// --daily: 코디를 고정 데이터 대신 그날 무신사 인기 스냅에서 뽑아 그린다 (scripts/daily-ootd.mjs)
|
||||
const daily = take('--daily')
|
||||
const [template] = args
|
||||
|
||||
if (!SLIDES[template]) fail(`사용: npm run card -- <${Object.keys(SLIDES).join('|')}> [--topic 주제] [--feedback 피드백] [--color ${THEMES.join('|')}] [--copy 값] [--out 폴더]`)
|
||||
@@ -62,6 +65,16 @@ if (topic !== null || feedback !== null || (!copy && AUTO_PLAN.includes(template
|
||||
console.log(`주제: ${body.topic}`)
|
||||
for (const [k, v] of Object.entries(body.copy)) console.log(` ${k}: ${v.replaceAll('\n', ' / ')}`)
|
||||
copy = Buffer.from(JSON.stringify({ ...current, ...body.copy })).toString('base64url')
|
||||
// 타로: 오늘 고른 각을 적어 두면 다음 7일은 다른 각이 나온다 (scripts/plan.mjs recentCodes)
|
||||
if (template === 'tarot') {
|
||||
const file = resolve('out/tarot-history.json')
|
||||
const today = new Date(Date.now() + 9 * 3600_000).toISOString().slice(0, 10)
|
||||
const history = existsSync(file) ? JSON.parse(readFileSync(file, 'utf8')) : {}
|
||||
const codes = ['c1', 'c2', 'c3'].map((k) => body.copy[k]).filter(Boolean)
|
||||
history[today] = [...new Set([...(history[today] ?? []), ...codes])]
|
||||
mkdirSync(resolve('out'), { recursive: true })
|
||||
writeFileSync(file, JSON.stringify(history, null, 1))
|
||||
}
|
||||
}
|
||||
|
||||
{
|
||||
@@ -72,6 +85,19 @@ if (topic !== null || feedback !== null || (!copy && AUTO_PLAN.includes(template
|
||||
console.log(`다시 그리거나 피드백할 때: --copy ${copy}`)
|
||||
}
|
||||
|
||||
const day = new Date(Date.now() + 9 * 3600_000).toISOString().slice(0, 10)
|
||||
const outDir = resolve(outArg ?? `out/${day}`)
|
||||
|
||||
if (daily) {
|
||||
if (template !== 'ootd') fail('--daily 는 ootd 템플릿에서만 써요.')
|
||||
const { runDailyOotd, toCardOutfits } = await import('./daily-ootd.mjs')
|
||||
// 포스트 하나는 스타일 하나: --style <casual|semi|formal|street|minimal>, 없으면 --copy 의 style, 그것도 없으면 꾸안꾸
|
||||
const style = styleArg ?? decode(copy).style ?? 'minimal'
|
||||
const { outfits } = await runDailyOotd({ outDir, style })
|
||||
copy = Buffer.from(JSON.stringify({ ...decode(copy), style, outfits: JSON.stringify(toCardOutfits(outfits)) })).toString('base64url')
|
||||
noImages = true
|
||||
}
|
||||
|
||||
// 그날 카드에 필요한 그림 중 없는 것만 Codex로 만든다 (관리자 서버 /api/gen-image, 한 장씩)
|
||||
if (!noImages) {
|
||||
const start = await fetch(`${ADMIN_URL}/api/gen-image`, {
|
||||
@@ -94,8 +120,6 @@ if (!noImages) {
|
||||
}
|
||||
}
|
||||
|
||||
const day = new Date(Date.now() + 9 * 3600_000).toISOString().slice(0, 10)
|
||||
const outDir = resolve(outArg ?? `out/${day}`)
|
||||
mkdirSync(outDir, { recursive: true })
|
||||
|
||||
const files = []
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
// Codex CLI의 이미지 생성 도구로 그림 한 장을 만들어 webp 로 저장한다. gen-image.mjs(고정 데이터 그림)와 daily-ootd.mjs(그날 코디 그림)가 같이 쓴다.
|
||||
import { execFileSync } from 'node:child_process'
|
||||
import { mkdtempSync, readdirSync, rmSync } from 'node:fs'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
|
||||
// 그림은 이미지 생성 도구가 만들고 Codex 는 도구를 부르고 결과를 저장하는 역할뿐이라 중간 모델·낮은 추론으로 고정한다 (가장 싼 gpt-6-luna 는 결과를 파일로 저장하지 못하고, 기본 설정의 gpt-6-astra·xhigh 는 한도를 금방 소진한다)
|
||||
export const IMAGE_MODEL = process.env.CODEX_IMAGE_MODEL ?? 'gpt-6-sol'
|
||||
|
||||
/**
|
||||
* @param {{ id: string, prompt: string, outPath: string, images?: string[], log?: (s: string) => void }} job
|
||||
* images: 참고 사진(그 옷·색을 따라 그리게 할 때). 결과는 outPath(webp, 가로 1024).
|
||||
* @returns {'ok' | 'not-saved'} 실패(한도·로그인)는 throw
|
||||
*/
|
||||
export function drawWithCodex({ id, prompt, outPath, images = [], log = console.log }) {
|
||||
const work = mkdtempSync(join(tmpdir(), `gen-${id}-`))
|
||||
const task = [
|
||||
images.length
|
||||
? '첨부한 참고 사진(코디 사진·상품 사진)의 옷·색·소재·실루엣을 그대로 따르되, 아래 프롬프트의 스타일로 새 그림을 내장 이미지 생성 도구로 만든다 (사진을 복사하지 말고, 사람은 절대 그리지 않는다).'
|
||||
: '내장 이미지 생성 도구로 아래 프롬프트 그대로 이미지를 만든다 (비율은 프롬프트를 따른다).',
|
||||
'만든 이미지를 직접 열어 확인한다: 사람 얼굴·손·마네킹·글자·숫자·로고가 있거나, 프롬프트의 물건이 빠지거나 잘렸으면 한 번만 다시 만든다 (사용량을 아끼려고 최대 2장).',
|
||||
'통과한 한 장만 이 폴더에 result.png 로 저장한다. 다른 파일은 만들지 않는다.',
|
||||
'',
|
||||
prompt,
|
||||
].join('\n')
|
||||
log(`${id}: Codex로 그리는 중…${images.length ? ` (참고 사진 ${images.length}장)` : ''}`)
|
||||
try {
|
||||
// -i 는 파일을 여러 개 받아서 뒤의 프롬프트까지 파일로 읽는다 → 프롬프트는 stdin 으로 준다
|
||||
const imageArgs = images.flatMap((p) => ['-i', p])
|
||||
execFileSync('codex', ['exec', '--skip-git-repo-check', '-C', work, '-s', 'workspace-write', '-m', IMAGE_MODEL, '-c', 'model_reasoning_effort="low"', ...imageArgs], { input: task, stdio: ['pipe', 'ignore', 'inherit'] })
|
||||
} catch (e) {
|
||||
rmSync(work, { recursive: true, force: true })
|
||||
throw new Error(`${id}: Codex 실행이 실패했어요 (${e.message}). 사용 한도나 로그인을 확인하세요.`)
|
||||
}
|
||||
const png = readdirSync(work).find((f) => f === 'result.png') ?? readdirSync(work).find((f) => f.endsWith('.png'))
|
||||
if (!png) {
|
||||
log(`${id}: Codex가 그림을 저장하지 않았어요. 작업 폴더: ${work}`)
|
||||
return 'not-saved'
|
||||
}
|
||||
execFileSync('cwebp', ['-quiet', '-q', '88', '-resize', '1024', '0', join(work, png), '-o', outPath])
|
||||
rmSync(work, { recursive: true, force: true })
|
||||
log(`${id}: ${outPath}`)
|
||||
return 'ok'
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
// 그날 코디: 오늘 예보 → 무신사 인기 스냅에서 사람별 코디 선정 → Claude 가 옷 목록 추출 → Codex 가 참고 사진대로 플랫레이 그림 → 카드용 copy.
|
||||
// 사용: node scripts/daily-ootd.mjs [--out out/<날짜>] (npm run card -- ootd --daily 가 부른다)
|
||||
import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'
|
||||
import { join, resolve } from 'node:path'
|
||||
import { drawWithCodex } from './codex-image.mjs'
|
||||
import { extractOutfit } from './outfit.mjs'
|
||||
import { pickSnaps } from './snap.mjs'
|
||||
|
||||
const API_URL = process.env.VITE_API_BASE_URL ?? 'http://localhost:9810'
|
||||
const REGION = '1114000000' // 서울 중구 (src/cards/data.ts BASE_REGION)
|
||||
const spec = JSON.parse(readFileSync(resolve('image-prompts/ootd.json'), 'utf8'))
|
||||
const PERSONA_ORDER = ['f20', 'm20', 'f40', 'm40']
|
||||
const COUNT_WORD = { 3: 'three', 4: 'four', 5: 'five' }
|
||||
|
||||
/** 오늘 예보 → 아침·낮 기온, 기온 구간 (src/cards/data.ts temps 와 같은 계산) */
|
||||
export async function weatherToday() {
|
||||
const res = await fetch(`${API_URL}/v1/weather/today?region=${REGION}`)
|
||||
const d = await res.json()
|
||||
if (d.result?.success === false || !d.slots?.length) throw new Error(`오늘 예보를 받지 못했어요 (${d.result?.desc ?? '응답 없음'})`)
|
||||
const hour = (s) => new Date(s.at).getHours()
|
||||
const withTemp = d.slots.filter((s) => s.temp_c != null)
|
||||
const day = withTemp.filter((s) => hour(s) >= 6 && hour(s) <= 21)
|
||||
const t = day.length ? day : withTemp
|
||||
const maxC = Math.round(Math.max(...t.map((s) => s.temp_c)))
|
||||
const morningC = Math.round((t.find((s) => hour(s) === 6) ?? t[0]).temp_c)
|
||||
const band = spec.bands.find((b) => maxC >= b.from) ?? spec.bands[spec.bands.length - 1]
|
||||
return { day: d.day, morningC, maxC, band: band.id, layering: band.layering ?? '' }
|
||||
}
|
||||
|
||||
// 카드 이름표 순서(상의·겉옷·하의·신발·가방)와 그림 번호 순서(1 상의·2 하의·3 신발·4 가방·5 겉옷)는 다르다
|
||||
const LABEL_ORDER = ['top', 'outer', 'bottom', 'shoes', 'bag']
|
||||
const DRAW_ORDER = ['top', 'bottom', 'shoes', 'bag', 'outer']
|
||||
|
||||
function layoutFor(slots) {
|
||||
const has = (s) => slots.includes(s)
|
||||
const topRow = has('outer') ? '(1) top-left, the outer layer in the top center, (2) top-right' : '(1) top-left, (2) top-right'
|
||||
const bottomRow = has('bag') ? '(3) bottom-left and (4) bottom-right' : '(3) bottom-center'
|
||||
return `top row: ${topRow}; bottom row: ${bottomRow}. Clearly separate spots, nothing else in between.`
|
||||
}
|
||||
|
||||
function buildPrompt(persona, outfit, weather) {
|
||||
const by = Object.fromEntries(outfit.items.map((it) => [it.slot, it]))
|
||||
const drawn = DRAW_ORDER.filter((s) => by[s])
|
||||
const items = drawn.map((s, i) => `(${i + 1}) ${by[s].prompt}${s === 'outer' ? ' as the outer layer' : ''}`).join(', ')
|
||||
return spec.style
|
||||
.replace('{items}', items)
|
||||
.replace('{count}', COUNT_WORD[drawn.length] ?? String(drawn.length))
|
||||
.replace('{layout}', layoutFor(drawn))
|
||||
.replace('{persona}', spec.personas[persona].prompt)
|
||||
.replace('{style}', outfit.style)
|
||||
.replace('{trend}', 'follow the attached reference photos (the outfit photo and the product thumbnails): the same garments, colors, materials and silhouettes')
|
||||
.replace('{layering}', weather.layering)
|
||||
}
|
||||
|
||||
/** 포스트 하나는 스타일 하나(기본 꾸안꾸). 네 사람 모두 그 스타일 스냅에서 고르고 제목도 같은 스타일로 간다.
|
||||
* @returns {Promise<{ weather: object, outfits: { persona: string, label: string, style: string, labels: string[], image: string, source: string, items: object[] }[] }>} */
|
||||
export async function runDailyOotd({ outDir, style = 'minimal', log = console.log }) {
|
||||
if (!spec.styles[style]) throw new Error(`스타일은 ${Object.keys(spec.styles).join(', ')} 중 하나예요: ${style}`)
|
||||
const styleLabel = spec.styles[style].label
|
||||
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 })
|
||||
const dailyDir = resolve('public/daily')
|
||||
mkdirSync(dailyDir, { recursive: true })
|
||||
const outfits = []
|
||||
for (const persona of PERSONA_ORDER) {
|
||||
const pick = picks[persona]
|
||||
log(`${persona}: Claude가 옷 목록을 뽑는 중… (${pick.url})`)
|
||||
const outfit = await extractOutfit(pick, persona, weather)
|
||||
// 제목은 Claude 가 본 분위기가 아니라 포스트 스타일로 통일한다
|
||||
outfit.style = styleLabel
|
||||
const by = Object.fromEntries(outfit.items.map((it) => [it.slot, it]))
|
||||
const labels = LABEL_ORDER.filter((s) => by[s]).map((s) => by[s].label)
|
||||
log(` ${outfit.style}: ${labels.join(' · ')}`)
|
||||
const id = `${weather.day}-${persona}`
|
||||
const outPath = join(dailyDir, `${id}.webp`)
|
||||
const images = [pick.files.image, ...pick.files.thumbs.slice(0, 4).map((t) => t.path)]
|
||||
const prompt = buildPrompt(persona, outfit, weather)
|
||||
let result = drawWithCodex({ id, prompt, outPath, images, log })
|
||||
if (result !== 'ok') result = drawWithCodex({ id, prompt, outPath, images, log })
|
||||
if (result !== 'ok') throw new Error(`${id}: 그림을 두 번 다 저장하지 못했어요`)
|
||||
outfits.push({ persona, label: spec.personas[persona].label, style: outfit.style, labels, image: `/daily/${id}.webp`, source: pick.url, items: outfit.items })
|
||||
}
|
||||
writeFileSync(join(outDir, 'outfits.json'), JSON.stringify({ weather, outfits }, null, 1))
|
||||
return { weather, outfits }
|
||||
}
|
||||
|
||||
/** 카드(copy.outfits)에 넣는 꼴: 사람·제목·스타일·이름표·그림 주소 */
|
||||
export const toCardOutfits = (outfits) => outfits.map(({ persona, label, style, labels, image }) => ({ persona, label, style, labels, image }))
|
||||
|
||||
if (process.argv[1]?.endsWith('daily-ootd.mjs')) {
|
||||
const args = process.argv.slice(2)
|
||||
const flag = (n) => (args.includes(n) ? args[args.indexOf(n) + 1] : null)
|
||||
const outArg = flag('--out')
|
||||
const style = flag('--style') ?? 'minimal'
|
||||
const day = new Date(Date.now() + 9 * 3600_000).toISOString().slice(0, 10)
|
||||
const { outfits } = await runDailyOotd({ outDir: resolve(outArg ?? `out/${day}`), style })
|
||||
const copy = Buffer.from(JSON.stringify({ outfits: JSON.stringify(toCardOutfits(outfits)), style, theme: 'sky' })).toString('base64url')
|
||||
console.log(`카드 그리기: npm run card -- ootd --no-images --copy ${copy}`)
|
||||
}
|
||||
@@ -1,12 +1,9 @@
|
||||
// 카드 그림을 프롬프트 템플릿(image-prompts/<종류>.json)대로 Codex 이미지 생성으로 만들어 src/assets/<종류>/<id>.webp 에 넣는다.
|
||||
// 넣은 그림은 카드에 자동으로 붙는다. 사용: npm run gen-image -- ootd <구간|스타일|구간-사람-스타일|missing> [스타일] [--force]
|
||||
// 예: ootd cool casual (12~16도 캐주얼 6명) · ootd semi (세미정장 전 구간) · ootd cool-f20-casual · ootd missing formal
|
||||
import { execFileSync } from 'node:child_process'
|
||||
import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync } from 'node:fs'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { existsSync, mkdirSync, readFileSync } from 'node:fs'
|
||||
import { join, resolve } from 'node:path'
|
||||
|
||||
const IMAGE_MODEL = process.env.CODEX_IMAGE_MODEL ?? 'gpt-6-sol'
|
||||
import { drawWithCodex } from './codex-image.mjs'
|
||||
|
||||
function fail(message) {
|
||||
console.error(message)
|
||||
@@ -77,33 +74,14 @@ for (const band of bands) {
|
||||
console.log(`${band.id}: 이미 있어요 (다시 만들려면 --force)`)
|
||||
continue
|
||||
}
|
||||
const prompt = band.prompt
|
||||
const work = mkdtempSync(join(tmpdir(), `gen-${kind}-${band.id}-`))
|
||||
const task = [
|
||||
'내장 이미지 생성 도구로 아래 프롬프트 그대로 이미지를 만든다 (비율은 프롬프트를 따른다).',
|
||||
'만든 이미지를 직접 열어 확인한다: 사람 얼굴·손·마네킹·글자·숫자·로고가 있거나, 프롬프트의 물건이 빠지거나 잘렸으면 한 번만 다시 만든다 (사용량을 아끼려고 최대 2장).',
|
||||
`통과한 한 장만 이 폴더에 result.png 로 저장한다. 다른 파일은 만들지 않는다.`,
|
||||
'',
|
||||
prompt,
|
||||
].join('\n')
|
||||
console.log(`${band.id}: Codex로 그리는 중…`)
|
||||
let result
|
||||
try {
|
||||
// 그림은 이미지 생성 도구가 만들고 Codex 는 도구를 부르고 결과를 저장하는 역할뿐이라 중간 모델·낮은 추론으로 고정한다 (가장 싼 gpt-6-luna 는 결과를 파일로 저장하지 못하고, 기본 설정의 gpt-6-astra·xhigh 는 한도를 금방 소진한다)
|
||||
execFileSync('codex', ['exec', '--skip-git-repo-check', '-C', work, '-s', 'workspace-write', '-m', IMAGE_MODEL, '-c', 'model_reasoning_effort="low"', task], { stdio: ['ignore', 'ignore', 'inherit'] })
|
||||
result = drawWithCodex({ id: band.id, prompt: band.prompt, outPath: outPath(band.id) })
|
||||
} catch (e) {
|
||||
rmSync(work, { recursive: true, force: true })
|
||||
fail(`${band.id}: Codex 실행이 실패했어요 (${e.message}). 사용 한도나 로그인을 확인하세요.`)
|
||||
fail(e.message)
|
||||
}
|
||||
const png = readdirSync(work).find((f) => f === 'result.png') ?? readdirSync(work).find((f) => f.endsWith('.png'))
|
||||
// 저장을 빼먹는 건 그 한 장 문제라 나머지는 계속 만들고 끝에 모아서 알린다 (한도·로그인 실패는 위에서 바로 멈춤)
|
||||
if (!png) {
|
||||
console.error(`${band.id}: Codex가 그림을 저장하지 않았어요. 작업 폴더: ${work}`)
|
||||
failed.push(band.id)
|
||||
continue
|
||||
}
|
||||
execFileSync('cwebp', ['-quiet', '-q', '88', '-resize', '1024', '0', join(work, png), '-o', outPath(band.id)])
|
||||
rmSync(work, { recursive: true, force: true })
|
||||
console.log(`${band.id}: ${outPath(band.id)}`)
|
||||
if (result !== 'ok') failed.push(band.id)
|
||||
}
|
||||
|
||||
if (failed.length) fail(`못 만든 그림: ${failed.join(", ")} — 다시: npm run gen-image -- ${kind} ${failed.join(" ")}`)
|
||||
@@ -0,0 +1,75 @@
|
||||
// 고른 스냅(사진 + 입은 상품 목록)에서 카드에 쓸 옷 목록을 Claude CLI로 뽑는다: 자리별 한글 이름표와 그림용 영어 설명.
|
||||
import { execFile } from 'node:child_process'
|
||||
import { tmpdir } from 'node:os'
|
||||
|
||||
const SLOT_ORDER = ['top', 'outer', 'bottom', 'shoes', 'bag']
|
||||
const PERSONA_TEXT = { f20: '20-30대 여자', m20: '20-30대 남자', f40: '40대 이상 여자', m40: '40대 이상 남자' }
|
||||
|
||||
const schema = {
|
||||
type: 'object',
|
||||
properties: {
|
||||
style: { type: 'string', description: '이 코디를 한 단어로 (예: 꾸안꾸, 오피스룩, 캐주얼, 미니멀, 스트릿, 데일리)' },
|
||||
items: {
|
||||
type: 'array',
|
||||
minItems: 4,
|
||||
maxItems: 5,
|
||||
items: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
slot: { type: 'string', enum: SLOT_ORDER },
|
||||
label: { type: 'string', description: '카드 이름표. 한글 2~7자 (예: 스트라이프 티, 와이드 슬랙스, 로퍼)' },
|
||||
prompt: { type: 'string', description: '그림용 영어 설명 한 구절: 색(대문자)·소재·실루엣 (예: a CHARCOAL wool single-breasted blazer)' },
|
||||
},
|
||||
required: ['slot', 'label', 'prompt'],
|
||||
additionalProperties: false,
|
||||
},
|
||||
},
|
||||
},
|
||||
required: ['style', 'items'],
|
||||
additionalProperties: false,
|
||||
}
|
||||
|
||||
function buildPrompt(pick, persona, weather) {
|
||||
const goods = pick.goods.map((g, i) => `${i + 1}. [${g.category1} > ${g.category2}] ${g.brand} ${g.name}`).join('\n')
|
||||
const files = [pick.files.image, ...pick.files.thumbs.map((t) => t.path)]
|
||||
return [
|
||||
`무신사 스냅 코디 사진과 그 코디에 태그된 상품 목록이다. ${PERSONA_TEXT[persona]} 카드에 쓸 옷 목록을 만든다.`,
|
||||
`오늘 서울 날씨: 아침 ${weather.morningC}도, 낮 최고 ${weather.maxC}도.`,
|
||||
'',
|
||||
'먼저 Read 도구로 이 파일들을 본다(첫 파일이 코디 사진, 나머지는 상품 썸네일):',
|
||||
...files.map((f) => `- ${f}`),
|
||||
'',
|
||||
'태그된 상품:',
|
||||
goods,
|
||||
'',
|
||||
'규칙:',
|
||||
'- 자리(slot)는 top·bottom·shoes 는 반드시, 사진에서 겉옷(outer)을 입거나 걸쳤으면 outer 도, 가방이 있으면 bag 도 넣는다. 최대 5개, 자리마다 하나.',
|
||||
'- 원피스면 top 으로 넣고 bottom 은 생략하지 말고 같은 원피스를 bottom 에 다시 넣지 않는다 → 원피스는 top, bottom 자리에는 사진의 다른 하의가 없으면 shoes·bag 으로 4개를 채운다.',
|
||||
'- 상품 목록에 있는 옷은 그 상품명 기준으로, 없는 옷은 사진에서 보이는 대로. 색은 사진 기준.',
|
||||
'- label 은 카드 이름표라 짧고 쉬운 한글(브랜드·영어 금지). prompt 는 영어 한 구절, 색은 대문자.',
|
||||
'- style 은 코디 분위기 한 단어.',
|
||||
'JSON 으로만 답한다.',
|
||||
].join('\n')
|
||||
}
|
||||
|
||||
/** @returns {Promise<{ style: string, items: { slot: string, label: string, prompt: string }[] }>} */
|
||||
export function extractOutfit(pick, persona, weather) {
|
||||
const args = ['-p', buildPrompt(pick, persona, weather), '--output-format', 'json', '--json-schema', JSON.stringify(schema), '--tools', 'Read', '--allowedTools', 'Read', '--no-session-persistence', '--model', 'sonnet']
|
||||
return new Promise((done, fail) => {
|
||||
execFile('claude', args, { cwd: tmpdir(), timeout: 240_000, maxBuffer: 10 * 1024 * 1024 }, (err, stdout) => {
|
||||
if (err) return fail(new Error(`Claude CLI 실행 실패: ${err.message}. 터미널에서 claude 로그인 상태를 확인하세요.`))
|
||||
let out
|
||||
try {
|
||||
out = JSON.parse(stdout)
|
||||
} catch {
|
||||
return fail(new Error(`Claude 답을 읽지 못했어요: ${stdout.slice(0, 300)}`))
|
||||
}
|
||||
const result = out.structured_output ?? (typeof out.result === 'string' ? JSON.parse(out.result) : null)
|
||||
if (out.is_error || !result?.items?.length) return fail(new Error(`Claude가 옷 목록을 주지 못했어요: ${String(out.result ?? '').slice(0, 300)}`))
|
||||
const seen = new Set()
|
||||
const items = result.items.filter((it) => SLOT_ORDER.includes(it.slot) && !seen.has(it.slot) && seen.add(it.slot))
|
||||
items.sort((a, b) => SLOT_ORDER.indexOf(a.slot) - SLOT_ORDER.indexOf(b.slot))
|
||||
done({ style: String(result.style ?? '').trim() || '데일리', items })
|
||||
})
|
||||
})
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
// 카드 문구 기획: 템플릿 칸·오늘 날씨·주제·피드백을 Claude CLI(claude -p)에 넘겨 칸별 문구를 받는다.
|
||||
// 관리자 서버(/api/plan)와 npm run card --topic 이 같이 쓴다. API 키 없이 이 맥에 로그인된 Claude Code를 쓴다.
|
||||
import { execFile } from 'node:child_process'
|
||||
import { readdirSync, readFileSync } from 'node:fs'
|
||||
import { existsSync, readdirSync, readFileSync } from 'node:fs'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { resolve } from 'node:path'
|
||||
|
||||
@@ -20,6 +20,19 @@ const questionOf = (topic) => {
|
||||
}
|
||||
// 날씨 타로 카드 = 날씨각 각 카드 (서비스와 같은 각 목록)
|
||||
const DECK = JSON.parse(readFileSync(resolve(import.meta.dirname, '../../backend/seed/index_definition.json'), 'utf8')).map((g) => ({ id: g.code, name: g.name, icon: g.icon, meaning: g.description }))
|
||||
// 최근에 쓴 각은 빼서 매일 같은 카드가 나오지 않게 한다 (card.mjs 가 기획할 때마다 적는다)
|
||||
const HISTORY_FILE = resolve(import.meta.dirname, '../out/tarot-history.json')
|
||||
const HISTORY_DAYS = 7
|
||||
function recentCodes() {
|
||||
if (!existsSync(HISTORY_FILE)) return []
|
||||
try {
|
||||
const history = JSON.parse(readFileSync(HISTORY_FILE, 'utf8'))
|
||||
const cutoff = Date.now() - HISTORY_DAYS * 86400_000
|
||||
return [...new Set(Object.entries(history).filter(([day]) => new Date(day).getTime() >= cutoff).flatMap(([, codes]) => codes))]
|
||||
} catch {
|
||||
return []
|
||||
}
|
||||
}
|
||||
const categoryOf = (topic) => TOPICS.find((c) => topic.includes(c.name) || c.subtopics.some((s) => topic.includes(s)))
|
||||
|
||||
const RULES = [
|
||||
@@ -56,15 +69,25 @@ const TAROT_TONE = [
|
||||
'키워드(k)는 4~8자 명사구("같이 걷는 시간", "먼저 보내는 한 줄"). 행운 포인트(l)는 시간·날씨·행동 한 줄 22자 이내("저녁 8시, 17도로 걷기 딱 좋아요").',
|
||||
]
|
||||
|
||||
function tarotSection(topic) {
|
||||
/** 오늘 고를 수 있는 각: 최근 7일에 쓴 각은 뺀다 (관리자가 고정한 카드는 남긴다) */
|
||||
function availableDeck(fixed = {}) {
|
||||
const recent = new Set(recentCodes())
|
||||
const keep = new Set(fixed.cards ?? [])
|
||||
return DECK.filter((c) => !recent.has(c.id) || keep.has(c.id))
|
||||
}
|
||||
|
||||
function tarotSection(topic, fixed = {}) {
|
||||
const deck = availableDeck(fixed)
|
||||
const excluded = DECK.filter((c) => !deck.includes(c)).map((c) => c.name)
|
||||
return [
|
||||
'',
|
||||
'## 각 카드 (이 목록에서만 고른다. card1·card2·card3에 서로 다른 code)',
|
||||
questionOf(topic) ? `표지 질문(question)은 이것을 쓴다(피드백이 바꾸라고 하면 바꾼다): ${questionOf(topic)}` : '표지 질문(question)은 주제에 맞는 "오늘 ~할까요?" 꼴 질문 하나를 쓴다.',
|
||||
'오늘 날씨 데이터의 오늘_각_점수에서 점수가 높은 각(오늘 실제로 하기 좋은 각) 가운데 질문과 엮을 수 있는 것을 고른다. 세 장은 서로 다른 답(하나는 긍정, 하나는 조건부, 하나는 기다리기 같은 식)이 되게 고르고, 되도록 아침·낮·저녁(밤) 각에서 하나씩 골라 세 장이 하루로 이어지게 한다.',
|
||||
'오늘 날씨 데이터의 오늘_각_점수에서 점수가 높은 편(상위 15개 안)인 각 가운데 질문과 엮을 수 있는 것을 고른다. 매일 같은 야외 운동 각(산책·자전거·등산·드라이브)만 반복하지 말고 먹거리·계절·집·동네 각도 섞어 날마다 다른 카드가 나오게 한다. 세 장은 서로 다른 답(하나는 긍정, 하나는 조건부, 하나는 기다리기 같은 식)이 되게 고르고, 되도록 아침·낮·저녁(밤) 각에서 하나씩 골라 세 장이 하루로 이어지게 한다.',
|
||||
excluded.length ? `최근 7일에 쓴 각이라 오늘은 고를 수 없음(목록에서 뺐다): ${excluded.join(', ')}` : '',
|
||||
...TAROT_TONE,
|
||||
'',
|
||||
...DECK.map((c) => `- ${c.id}: ${c.name} — ${c.meaning}`),
|
||||
...deck.map((c) => `- ${c.id}: ${c.name} — ${c.meaning}`),
|
||||
]
|
||||
}
|
||||
|
||||
@@ -86,23 +109,23 @@ function buildPrompt(ctx, { topic, feedback, fixed = {} }) {
|
||||
topic ? `## 주제: ${topic}` : `## 주제: 없음 — 다음 대주제·소주제 중 오늘 날씨와 어울리는 것을 하나 골라 topic에 "대주제 소주제"로 적고 그 주제로 쓴다: ${TOPICS.map((c) => `${c.name}(${c.subtopics.join('·')})`).join(', ')}`,
|
||||
feedback ? `## 피드백 (반드시 반영): ${feedback}` : '',
|
||||
'',
|
||||
...(isTarot(ctx) ? tarotSection(topic) : []),
|
||||
...(isTarot(ctx) ? tarotSection(topic, fixed) : []),
|
||||
fixed.question ? `## 질문은 관리자가 정했다(그대로 쓴다): ${fixed.question}` : '',
|
||||
fixed.cards?.length ? `## 카드는 관리자가 골랐다(card1·card2·card3 순서 그대로): ${fixed.cards.join(', ')}` : '',
|
||||
'모든 칸을 채운 JSON으로만 답한다. topic에는 쓴 주제를 짧게 적는다.',
|
||||
].join('\n')
|
||||
}
|
||||
|
||||
function schema(ctx) {
|
||||
function schema(ctx, fixed = {}) {
|
||||
const properties = { topic: { type: 'string' } }
|
||||
for (const f of ctx.fields) if (!(isTarot(ctx) && DECK_KEY.test(f.key))) properties[f.key] = { type: 'string' }
|
||||
if (isTarot(ctx)) for (const k of ['card1', 'card2', 'card3']) properties[k] = { type: 'string', enum: DECK.map((c) => c.id) }
|
||||
if (isTarot(ctx)) for (const k of ['card1', 'card2', 'card3']) properties[k] = { type: 'string', enum: availableDeck(fixed).map((c) => c.id) }
|
||||
return { type: 'object', properties, required: Object.keys(properties), additionalProperties: false }
|
||||
}
|
||||
|
||||
/** @returns {Promise<{ topic: string, copy: Record<string, string> }>} */
|
||||
export function runPlan(ctx, { topic = '', feedback = '', fixed = {} } = {}) {
|
||||
const args = ['-p', buildPrompt(ctx, { topic, feedback, fixed }), '--output-format', 'json', '--json-schema', JSON.stringify(schema(ctx)), '--tools', '', '--no-session-persistence', '--model', 'sonnet']
|
||||
const args = ['-p', buildPrompt(ctx, { topic, feedback, fixed }), '--output-format', 'json', '--json-schema', JSON.stringify(schema(ctx, fixed)), '--tools', '', '--no-session-persistence', '--model', 'sonnet']
|
||||
return new Promise((done, fail) => {
|
||||
execFile('claude', args, { cwd: tmpdir(), timeout: 180_000, maxBuffer: 10 * 1024 * 1024 }, (err, stdout) => {
|
||||
if (err) return fail(new Error(`Claude CLI 실행 실패: ${err.message}. 터미널에서 claude 로그인 상태를 확인하세요.`))
|
||||
|
||||
@@ -0,0 +1,233 @@
|
||||
// 무신사 스냅(공개 API)에서 오늘 날씨에 맞는 인기 코디를 사람별로 하나씩 고른다. 사진·상품 썸네일은 그림 참고용으로만 내려받고 어디에도 올리지 않는다.
|
||||
// 사용(확인용): node scripts/snap.mjs --band mild --out out/2026-10-26/snaps
|
||||
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
|
||||
import { join, resolve } from 'node:path'
|
||||
|
||||
// 최근에 쓴 스냅은 다시 고르지 않는다 (스타일이 달라도 같은 코디가 또 나오지 않게)
|
||||
const HISTORY_FILE = resolve('out/snap-history.json')
|
||||
const HISTORY_DAYS = 14
|
||||
function loadHistory() {
|
||||
if (!existsSync(HISTORY_FILE)) return {}
|
||||
try {
|
||||
return JSON.parse(readFileSync(HISTORY_FILE, 'utf8'))
|
||||
} catch {
|
||||
return {}
|
||||
}
|
||||
}
|
||||
function recentIds(history) {
|
||||
const cutoff = Date.now() - HISTORY_DAYS * 86400_000
|
||||
return new Set(Object.entries(history).filter(([day]) => new Date(day).getTime() >= cutoff).flatMap(([, ids]) => ids))
|
||||
}
|
||||
|
||||
const LIST_URL = 'https://content.musinsa.com/api2/content/snap/v1/snaps'
|
||||
const GOODS_URL = (no) => `https://goods-detail.musinsa.com/api2/goods/${no}`
|
||||
const IMAGE_HOST = 'https://image.msscdn.net'
|
||||
const HEADERS = { 'User-Agent': 'Mozilla/5.0', Accept: 'application/json' }
|
||||
|
||||
/** 카드 사람(페르소나) → 성별과 "40대~"면 단정한 코디를 고르는 기준 */
|
||||
export const PERSONAS = {
|
||||
f20: { gender: 'WOMEN', mature: false },
|
||||
m20: { gender: 'MEN', mature: false },
|
||||
f40: { gender: 'WOMEN', mature: true },
|
||||
m40: { gender: 'MEN', mature: true },
|
||||
}
|
||||
|
||||
// 기온 구간(image-prompts/ootd.json bands 의 id)별로 찾는 태그와 걸러 낼 아우터
|
||||
const HEAVY = /패딩|푸퍼|다운|롱코트|울코트|무스탕|플리스|기모|헤비|퍼 /i
|
||||
const MID = /코트|자켓|재킷|점퍼|블루종|집업/i
|
||||
const SHORTS = /쇼츠|반바지|shorts|숏팬츠|버뮤다/i
|
||||
const SHORT_SLEEVE = /반팔|하프 슬리브|half sleeve|슬리브리스|민소매|sleeveless/i
|
||||
const BAND = {
|
||||
hot: { tags: ['여름코디', '간절기코디'], rejectGoods: [HEAVY, MID], rejectTags: [/겨울|패딩|코트/] },
|
||||
warm: { tags: ['간절기코디', '가을코디'], rejectGoods: [HEAVY, MID], rejectTags: [/겨울|패딩|코트/] },
|
||||
mild: { tags: ['가을코디', '간절기코디'], rejectGoods: [HEAVY, SHORTS], rejectTags: [/겨울|패딩/] },
|
||||
cool: { tags: ['가을코디', '가을아우터'], rejectGoods: [HEAVY, SHORTS, SHORT_SLEEVE], rejectTags: [/겨울/] },
|
||||
chilly: { tags: ['가을코디', '겨울코디'], rejectGoods: [/롱패딩|헤비/, SHORTS, SHORT_SLEEVE], rejectTags: [] },
|
||||
cold: { tags: ['겨울코디'], rejectGoods: [SHORTS, SHORT_SLEEVE], rejectTags: [/여름|반팔/] },
|
||||
freezing: { tags: ['겨울코디', '롱패딩'], rejectGoods: [SHORTS, SHORT_SLEEVE], rejectTags: [/여름|반팔|가을/] },
|
||||
}
|
||||
// 철 지난 스냅은 뺀다
|
||||
const MAX_AGE_DAYS = 45
|
||||
// 포스트 하나는 스타일 하나: 네 사람 모두 이 태그가 붙은 스냅에서 고른다 (image-prompts/ootd.json styles 의 id)
|
||||
export const STYLE_TAGS = {
|
||||
casual: ['데일리룩', '캐주얼룩', '캐주얼'],
|
||||
semi: ['오피스룩', '출근룩', '비즈니스캐주얼'],
|
||||
formal: ['정장', '수트', '포멀룩'],
|
||||
street: ['스트릿', '스트릿룩', '스트릿패션'],
|
||||
minimal: ['꾸안꾸', '미니멀룩', '미니멀'],
|
||||
}
|
||||
// 40대~ 는 단정한 코디 태그로 한 번 더 모은다
|
||||
const MATURE_KEYWORDS = { WOMEN: ['오피스룩', '출근룩', '미니멀룩'], MEN: ['오피스룩', '댄디룩', '비즈니스캐주얼'] }
|
||||
const MATURE_TAG = /오피스|출근|미니멀|클래식|단정|하객|댄디|비즈니스|포멀|꾸안꾸/
|
||||
const YOUNG_ONLY = /캠퍼스|학생|스트릿|스트리트|힙합|Y2K|고프코어|테크웨어/i
|
||||
|
||||
/** 상품 카테고리 → 카드 자리 */
|
||||
export function slotOf(goods) {
|
||||
const c = `${goods.category1 ?? ''} ${goods.category2 ?? ''}`
|
||||
if (/원피스/.test(c)) return 'onepiece'
|
||||
if (/아우터|가디건|자켓|재킷|코트|점퍼|패딩|블루종/.test(c)) return 'outer'
|
||||
if (/상의|티셔츠|셔츠|니트|블라우스|후드/.test(c)) return 'top'
|
||||
if (/바지|스커트|팬츠|슬랙스|데님|하의/.test(c)) return 'bottom'
|
||||
if (/신발|스니커즈|구두|부츠|로퍼|샌들|슈즈/.test(c)) return 'shoes'
|
||||
if (/가방|백팩|토트|숄더|크로스/.test(c)) return 'bag'
|
||||
if (/모자|액세서리|주얼리|시계|양말|벨트|안경|스카프|머플러|캡/.test(c)) return 'acc'
|
||||
return 'other'
|
||||
}
|
||||
|
||||
async function getJson(url) {
|
||||
const res = await fetch(url, { headers: HEADERS })
|
||||
if (!res.ok) throw new Error(`${res.status} ${url}`)
|
||||
return res.json()
|
||||
}
|
||||
|
||||
/** 태그·키워드로 인기 스냅 목록 (한 번에 100개, 상품 번호·성별·태그·좋아요 포함) */
|
||||
async function listSnaps(params, pages) {
|
||||
const out = []
|
||||
for (let page = 1; page <= pages; page++) {
|
||||
const q = new URLSearchParams({ sort: 'POPULAR', size: '100', page: String(page), ...params })
|
||||
const body = await getJson(`${LIST_URL}?${q}`)
|
||||
const list = body.data?.list ?? []
|
||||
for (const d of list) {
|
||||
out.push({
|
||||
id: d.id,
|
||||
url: `https://www.musinsa.com/snap/${d.id}`,
|
||||
gender: d.model?.gender ?? '',
|
||||
age: d.model?.age ?? null,
|
||||
likes: d.aggregations?.likeCount ?? 0,
|
||||
tags: (d.tags ?? []).map((t) => t.name),
|
||||
text: (d.detail?.content ?? '').slice(0, 200),
|
||||
image: d.medias?.find((m) => m.type === 'IMAGE')?.path ?? d.thumbnailUrl ?? '',
|
||||
createdAt: d.createdAt ?? '',
|
||||
goodsNos: (d.goods ?? []).map((g) => g.goodsNo).filter(Boolean),
|
||||
})
|
||||
}
|
||||
if (list.length < 100) break
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
async function goodsDetail(no) {
|
||||
const d = (await getJson(GOODS_URL(no))).data
|
||||
const thumb = d.thumbnailImageUrl ?? ''
|
||||
const g = {
|
||||
no,
|
||||
name: d.goodsNm ?? '',
|
||||
brand: typeof d.brand === 'object' ? (d.brand?.name ?? '') : (d.brand ?? ''),
|
||||
category1: d.category?.categoryDepth1Title ?? '',
|
||||
category2: d.category?.categoryDepth2Title ?? '',
|
||||
thumb: thumb ? (thumb.startsWith('http') ? thumb : IMAGE_HOST + thumb) : '',
|
||||
}
|
||||
return { ...g, slot: slotOf(g) }
|
||||
}
|
||||
|
||||
async function withGoods(snap) {
|
||||
const goods = []
|
||||
for (const no of snap.goodsNos.slice(0, 8)) {
|
||||
try {
|
||||
goods.push(await goodsDetail(no))
|
||||
} catch {
|
||||
// 품절·삭제된 상품은 빼고 간다
|
||||
}
|
||||
}
|
||||
return { ...snap, goods }
|
||||
}
|
||||
|
||||
function fits(snap, band) {
|
||||
const rule = BAND[band] ?? BAND.mild
|
||||
if (snap.createdAt && Date.now() - new Date(snap.createdAt).getTime() > MAX_AGE_DAYS * 86400_000) return false
|
||||
const blob = snap.goods.map((g) => `${g.name} ${g.category2}`).join(' | ')
|
||||
if (rule.rejectGoods.some((re) => re.test(blob))) return false
|
||||
if (rule.rejectTags.some((re) => snap.tags.some((t) => re.test(t)))) return false
|
||||
const slots = new Set(snap.goods.map((g) => g.slot))
|
||||
const hasTop = slots.has('top') || slots.has('onepiece')
|
||||
const hasBottom = slots.has('bottom') || slots.has('onepiece')
|
||||
return hasTop && hasBottom && slots.has('shoes') && !!snap.image
|
||||
}
|
||||
|
||||
function score(snap, persona) {
|
||||
let s = Math.log10(snap.likes + 10)
|
||||
const tagBlob = snap.tags.join(' ')
|
||||
const goods = snap.goods ?? []
|
||||
if (PERSONAS[persona].mature) {
|
||||
if (MATURE_TAG.test(tagBlob)) s += 1.5
|
||||
if (YOUNG_ONLY.test(tagBlob)) s -= 2
|
||||
if (goods.some((g) => /슬랙스|로퍼|니트|블라우스|코트|자켓|재킷|셔츠/.test(g.name + g.category2))) s += 0.5
|
||||
if (goods.some((g) => /카고|후드|조거|스웨트/.test(g.name + g.category2))) s -= 1
|
||||
} else if (MATURE_TAG.test(tagBlob) && !/꾸안꾸|데일리/.test(tagBlob)) s -= 0.3
|
||||
return s
|
||||
}
|
||||
|
||||
async function download(url, path) {
|
||||
const res = await fetch(url, { headers: { 'User-Agent': 'Mozilla/5.0' } })
|
||||
if (!res.ok) throw new Error(`${res.status} ${url}`)
|
||||
writeFileSync(path, Buffer.from(await res.arrayBuffer()))
|
||||
}
|
||||
|
||||
/** 사람별로 스냅 하나씩: { f20: {...snap, files: { image, thumbs[] }}, ... }. style 을 주면 네 사람 모두 그 스타일 태그가 붙은 스냅에서 고른다 */
|
||||
export async function pickSnaps({ band, style, outDir, pages = 2, log = console.log }) {
|
||||
mkdirSync(outDir, { recursive: true })
|
||||
const rule = BAND[band] ?? BAND.mild
|
||||
const styleTags = STYLE_TAGS[style] ?? []
|
||||
const pool = new Map()
|
||||
const add = (list) => list.forEach((s) => s.goodsNos.length >= 3 && !pool.has(s.id) && pool.set(s.id, s))
|
||||
for (const tag of styleTags) add(await listSnaps({ tags: tag }, pages))
|
||||
for (const tag of rule.tags) add(await listSnaps({ tags: tag }, pages))
|
||||
for (const gender of ['WOMEN', 'MEN']) for (const kw of MATURE_KEYWORDS[gender]) add(await listSnaps({ keyword: kw }, 1))
|
||||
const hasStyle = (s) => styleTags.length === 0 || s.tags.some((t) => styleTags.some((st) => t.includes(st)))
|
||||
log(`무신사 스냅 후보 ${pool.size}개 (구간 ${band}${styleTags.length ? ` · 스타일 #${styleTags.join(' #')} ${[...pool.values()].filter(hasStyle).length}개` : ''}). 상품 정보를 받아 거르는 중…`)
|
||||
|
||||
const picks = {}
|
||||
const history = loadHistory()
|
||||
const used = recentIds(history)
|
||||
// 40대~ 를 먼저 골라야 단정한 코디가 남는다. 좋아요 순으로 상품 정보를 받아 보며 맞는 첫 코디를 고른다
|
||||
for (const persona of ['f40', 'm40', 'f20', 'm20']) {
|
||||
const { gender } = PERSONAS[persona]
|
||||
// 스타일 태그가 붙은 스냅을 먼저, 모자라면 나머지 (스타일 태그 없는 스냅은 뒤로)
|
||||
const candidates = [...pool.values()]
|
||||
.filter((s) => s.gender === gender && !used.has(s.id))
|
||||
.sort((a, b) => Number(hasStyle(b)) - Number(hasStyle(a)) || score(b, persona) - score(a, persona))
|
||||
.slice(0, 25)
|
||||
let best = null
|
||||
for (const c of candidates) {
|
||||
const full = c.goods ? c : await withGoods(c)
|
||||
pool.set(full.id, full)
|
||||
if (fits(full, band)) {
|
||||
best = full
|
||||
break
|
||||
}
|
||||
}
|
||||
if (!best) throw new Error(`${persona} 에 맞는 스냅이 없어요 (성별 ${gender}, 구간 ${band})`)
|
||||
used.add(best.id)
|
||||
const dir = join(outDir, persona)
|
||||
mkdirSync(dir, { recursive: true })
|
||||
const image = join(dir, 'snap.jpg')
|
||||
await download(best.image, image)
|
||||
const thumbs = []
|
||||
for (const [i, g] of best.goods.entries()) {
|
||||
if (!g.thumb || g.slot === 'other') continue
|
||||
const p = join(dir, `goods-${i + 1}.jpg`)
|
||||
try {
|
||||
await download(g.thumb, p)
|
||||
thumbs.push({ path: p, goods: g })
|
||||
} catch {
|
||||
// 썸네일 없으면 상품명만 쓴다
|
||||
}
|
||||
}
|
||||
picks[persona] = { ...best, styled: hasStyle(best), files: { image, thumbs } }
|
||||
log(` ${persona}: ${best.url} ♥${best.likes}${styleTags.length && !hasStyle(best) ? ' (스타일 태그 없음, 대체)' : ''} #${best.tags.slice(0, 3).join(' #')} | ${best.goods.map((g) => g.name).join(' / ').slice(0, 90)}`)
|
||||
}
|
||||
writeFileSync(join(outDir, 'picks.json'), JSON.stringify(picks, null, 1))
|
||||
const today = new Date(Date.now() + 9 * 3600_000).toISOString().slice(0, 10)
|
||||
history[today] = [...new Set([...(history[today] ?? []), ...Object.values(picks).map((p) => p.id)])]
|
||||
mkdirSync(resolve('out'), { recursive: true })
|
||||
writeFileSync(HISTORY_FILE, JSON.stringify(history, null, 1))
|
||||
return picks
|
||||
}
|
||||
|
||||
if (process.argv[1]?.endsWith('snap.mjs')) {
|
||||
const args = process.argv.slice(2)
|
||||
const flag = (n) => (args.includes(n) ? args[args.indexOf(n) + 1] : null)
|
||||
const band = flag('--band') ?? 'mild'
|
||||
const outDir = flag('--out') ?? `out/${new Date(Date.now() + 9 * 3600_000).toISOString().slice(0, 10)}/snaps`
|
||||
await pickSnaps({ band, style: flag('--style') ?? undefined, outDir, pages: Number(flag('--pages') ?? 2) })
|
||||
}
|
||||
|
After Width: | Height: | Size: 204 KiB |
|
After Width: | Height: | Size: 201 KiB |
|
After Width: | Height: | Size: 214 KiB |
|
After Width: | Height: | Size: 228 KiB |
|
After Width: | Height: | Size: 245 KiB |
|
After Width: | Height: | Size: 227 KiB |
|
After Width: | Height: | Size: 280 KiB |
|
After Width: | Height: | Size: 203 KiB |
|
After Width: | Height: | Size: 218 KiB |
|
After Width: | Height: | Size: 255 KiB |
|
After Width: | Height: | Size: 221 KiB |
|
After Width: | Height: | Size: 227 KiB |
|
After Width: | Height: | Size: 214 KiB |
|
After Width: | Height: | Size: 273 KiB |
|
After Width: | Height: | Size: 220 KiB |
|
After Width: | Height: | Size: 174 KiB |
|
After Width: | Height: | Size: 348 KiB |
|
After Width: | Height: | Size: 210 KiB |
|
After Width: | Height: | Size: 244 KiB |
|
After Width: | Height: | Size: 217 KiB |
|
After Width: | Height: | Size: 194 KiB |
|
After Width: | Height: | Size: 219 KiB |
|
After Width: | Height: | Size: 232 KiB |
|
After Width: | Height: | Size: 236 KiB |
|
After Width: | Height: | Size: 237 KiB |
|
After Width: | Height: | Size: 204 KiB |
|
After Width: | Height: | Size: 260 KiB |
|
After Width: | Height: | Size: 219 KiB |
@@ -133,7 +133,7 @@
|
||||
top: 350px;
|
||||
left: 80px;
|
||||
width: 920px;
|
||||
height: 800px;
|
||||
height: 760px;
|
||||
border-radius: 44px;
|
||||
overflow: hidden;
|
||||
background: var(--stage);
|
||||
@@ -141,7 +141,7 @@
|
||||
.ootd-stage > img {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
object-fit: cover;
|
||||
object-fit: contain;
|
||||
}
|
||||
.ootd-labels {
|
||||
position: absolute;
|
||||
@@ -159,7 +159,7 @@
|
||||
/* 그림 아래 옷 목록: 그림 속 위치에 기대지 않고 따로 적는다 */
|
||||
.ootd-items {
|
||||
position: absolute;
|
||||
top: 1168px;
|
||||
top: 1126px;
|
||||
left: 80px;
|
||||
right: 80px;
|
||||
margin: 0;
|
||||
@@ -168,13 +168,14 @@
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
justify-content: center;
|
||||
gap: 10px;
|
||||
align-content: flex-start;
|
||||
gap: 8px;
|
||||
}
|
||||
.ootd-items li {
|
||||
padding: 8px 18px;
|
||||
padding: 7px 16px;
|
||||
border-radius: 99px;
|
||||
background: #fff;
|
||||
font-size: 28px;
|
||||
font-size: 26px;
|
||||
font-weight: 700;
|
||||
box-shadow: 0 6px 16px #28304a1f;
|
||||
white-space: nowrap;
|
||||
|
||||
@@ -3,7 +3,7 @@ import spec from '../../image-prompts/ootd.json'
|
||||
/** 낮 최고기온 구간 × 스타일 × 사람별 옷. 옷 목록·카드 글자는 image-prompts/ootd.json 한 곳에서 정한다.
|
||||
* 그림은 src/assets/ootd/<구간>-<사람>-<스타일>.webp 가 있으면 자동으로 붙는다 (npm run gen-image -- ootd <구간|스타일>).
|
||||
* 일교차가 크면(OUTER_GAP_C 이상) 겉옷을 5번째 옷으로 그린 <구간>-<사람>-<스타일>-outer.webp 를 쓰고 이름표에도 겉옷을 더한다 */
|
||||
export type Outfit = { persona: string; label: string; labels: string[]; outer: string; imageId: string; image?: string }
|
||||
export type Outfit = { persona: string; label: string; style?: string; labels: string[]; outer: string; imageId: string; image?: string }
|
||||
export type OotdBand = { id: string; from: number }
|
||||
|
||||
const IMAGES = import.meta.glob<string>('../assets/ootd/*.webp', { eager: true, import: 'default' })
|
||||
@@ -27,6 +27,17 @@ export function ootdBand(maxC: number) {
|
||||
return OOTD_BANDS.find((b) => maxC >= b.from) ?? OOTD_BANDS[OOTD_BANDS.length - 1]
|
||||
}
|
||||
|
||||
/** 그날 무신사 스냅에서 뽑은 코디 (scripts/daily-ootd.mjs 가 copy.outfits 에 JSON 문자열로 넣는다). 없으면 undefined */
|
||||
export function dailyOutfits(copy: Record<string, string>): Outfit[] | undefined {
|
||||
if (!copy.outfits) return undefined
|
||||
try {
|
||||
const list = JSON.parse(copy.outfits) as { persona: string; label: string; style?: string; labels: string[]; image: string }[]
|
||||
return list.map((o) => ({ persona: o.persona, label: o.label, style: o.style, labels: o.labels, outer: '', imageId: o.image, image: o.image }))
|
||||
} catch {
|
||||
return undefined
|
||||
}
|
||||
}
|
||||
|
||||
/** 그 구간·스타일의 사람별 옷. bandId 를 주면 기온 대신 그 구간 (예시 카드용). withOuter 면 겉옷 포함 그림·이름표 */
|
||||
export function ootdOutfits(maxC: number, style?: string, bandId?: string, withOuter = false): Outfit[] {
|
||||
const band = spec.bands.find((b) => b.id === (bandId || ootdBand(maxC).id))!
|
||||
|
||||
@@ -8,7 +8,7 @@ import stillNight from '../assets/intro/still-night.webp'
|
||||
import type { CardData } from './data'
|
||||
import { Frame, Lines } from './Frame'
|
||||
import { tidy } from './text'
|
||||
import { DEFAULT_STYLE, needsOuter, ootdBand, ootdOutfits, styleLabel } from './ootd'
|
||||
import { DEFAULT_STYLE, dailyOutfits, needsOuter, ootdBand, ootdOutfits, styleLabel } from './ootd'
|
||||
import { gakArt, gakByCode } from './gaks'
|
||||
|
||||
// 대주제(skin)마다 한 번 만든 배경 그림 (npm run gen-image -- tarot-bg <skin>). 없으면 민무늬 배경
|
||||
@@ -65,6 +65,7 @@ const ootd: Template = {
|
||||
hashtags: '#날씨각 #오늘의코디 #OOTD #데일리룩 #옷차림 #코디추천 #날씨 #오늘날씨 #서울날씨 #일상',
|
||||
}),
|
||||
warnings: (d, c) => {
|
||||
if (dailyOutfits(c)) return []
|
||||
const missing = ootdOutfits(d.maxC, c.style, undefined, needsOuter(d.maxC, d.morningC)).filter((o) => !o.image)
|
||||
const id = `${ootdBand(d.maxC).id}`
|
||||
return missing.length
|
||||
@@ -72,11 +73,11 @@ const ootd: Template = {
|
||||
: []
|
||||
},
|
||||
slides: (d, c) =>
|
||||
ootdOutfits(d.maxC, c.style, c.band, needsOuter(d.maxC, d.morningC)).map((o, i, all) => (
|
||||
(dailyOutfits(c) ?? ootdOutfits(d.maxC, c.style, c.band, needsOuter(d.maxC, d.morningC))).map((o, i, all) => (
|
||||
<Frame page={i} total={all.length} theme={c.theme} className="ootd" key={o.persona}>
|
||||
<p className="meta">{d.dateLabel} · 오늘의 코디</p>
|
||||
<h1 className="ootd-title">
|
||||
<Lines text={`*${o.label}* ${styleLabel(c.style)}${c.title ? ` ${c.title}` : ''}`} />
|
||||
<Lines text={`*${o.label}* ${o.style ?? styleLabel(c.style)}${c.title ? ` ${c.title}` : ''}`} />
|
||||
</h1>
|
||||
<div className="ootd-stage">
|
||||
{o.image ? (
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import { spawn } from 'node:child_process'
|
||||
import { createReadStream, existsSync } from 'node:fs'
|
||||
import type { IncomingMessage, ServerResponse } from 'node:http'
|
||||
import { basename, resolve } from 'node:path'
|
||||
import tailwindcss from '@tailwindcss/vite'
|
||||
import react from '@vitejs/plugin-react'
|
||||
import { defineConfig, type Plugin } from 'vite'
|
||||
@@ -171,9 +173,26 @@ function postApi(): Plugin {
|
||||
}
|
||||
}
|
||||
|
||||
/** GET /daily/<날짜>-<사람>.webp → public/daily (scripts/daily-ootd.mjs 가 만든 그날 코디 그림). publicDir 는 프론트 아이콘용이라 따로 서빙 */
|
||||
function dailyImages(): Plugin {
|
||||
return {
|
||||
name: 'daily-images',
|
||||
configureServer(server) {
|
||||
server.middlewares.use('/daily', (req, res, next) => {
|
||||
const name = basename((req.url ?? '').split('?')[0])
|
||||
const file = resolve(import.meta.dirname, 'public/daily', name)
|
||||
if (!name.endsWith('.webp') || !existsSync(file)) return next()
|
||||
res.setHeader('Content-Type', 'image/webp')
|
||||
res.setHeader('Cache-Control', 'no-cache')
|
||||
createReadStream(file).pipe(res)
|
||||
})
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// 각 아이콘·캐릭터는 서비스와 같은 파일을 쓴다 (/icons/*.png)
|
||||
export default defineConfig({
|
||||
plugins: [react(), tailwindcss(), planApi(), imageApi(), postApi()],
|
||||
plugins: [react(), tailwindcss(), planApi(), imageApi(), postApi(), dailyImages()],
|
||||
publicDir: '../frontend/public',
|
||||
server: { port: 5175, strictPort: true },
|
||||
})
|
||||
@@ -191,3 +191,4 @@ class CardStatus(CodeEnum):
|
||||
class AuthProvider(CodeEnum):
|
||||
LOCAL = 1
|
||||
GOOGLE = 2
|
||||
TOSS = 3
|
||||
@@ -59,6 +59,13 @@ class Settings(BaseSettings):
|
||||
jwt_access_minutes: int = 60
|
||||
jwt_refresh_days: int = 30
|
||||
|
||||
# 앱인토스 토스 로그인. 인증서·키는 저장소 밖(secrets/toss)에 두고 경로만 받는다
|
||||
toss_api_base: str = "https://apps-in-toss-api.toss.im"
|
||||
toss_mtls_cert: str = ""
|
||||
toss_mtls_key: str = ""
|
||||
# 연결 끊기 콜백의 Basic Auth 값 "아이디:비밀번호". 콘솔에 넣은 값과 같아야 한다
|
||||
toss_unlink_auth: str = ""
|
||||
|
||||
@field_validator("data_go_kr_service_key")
|
||||
@classmethod
|
||||
def _decode_service_key(cls, v: str) -> str:
|
||||
|
||||
@@ -12,6 +12,9 @@ class UserCRUD:
|
||||
async def by_login_id(self, s: AsyncSession, login_id: str) -> Optional[User]:
|
||||
return await s.scalar(select(User).where(User.login_id == login_id, User.deleted.is_(False)))
|
||||
|
||||
async def by_provider_uid(self, s: AsyncSession, provider: int, provider_uid: str) -> Optional[User]:
|
||||
return await s.scalar(select(User).where(User.provider == provider, User.provider_uid == provider_uid, User.deleted.is_(False)))
|
||||
|
||||
async def get(self, s: AsyncSession, user_id: uuid.UUID) -> Optional[User]:
|
||||
user = await s.get(User, user_id)
|
||||
return user if user is not None and not user.deleted else None
|
||||
@@ -22,6 +25,12 @@ class UserCRUD:
|
||||
await s.flush()
|
||||
return user
|
||||
|
||||
async def create_social(self, s: AsyncSession, provider: int, provider_uid: str, login_id: str, nickname: str) -> User:
|
||||
user = User(login_id=login_id, password=None, provider_uid=provider_uid, nickname=nickname, provider=provider)
|
||||
s.add(user)
|
||||
await s.flush()
|
||||
return user
|
||||
|
||||
async def create_google(self, s: AsyncSession, sub: str, nickname: str) -> User:
|
||||
user = User(login_id=f"google_{sub}", provider_uid=sub, nickname=nickname, provider=2)
|
||||
s.add(user)
|
||||
|
||||
@@ -206,13 +206,13 @@ CREATE TABLE IF NOT EXISTS public.card_image (
|
||||
|
||||
-- 사람·반응 (좋아요·저장·댓글은 로그인 필요, 보내기는 누구나)
|
||||
|
||||
-- 사용자. 일반(아이디·비밀번호) 또는 구글 로그인. 이름·전화번호는 받지 않는다.
|
||||
-- 사용자. 일반(아이디·비밀번호), 구글, 토스(앱인토스) 로그인. 이름·전화번호는 받지 않는다.
|
||||
CREATE TABLE IF NOT EXISTS public.users (
|
||||
user_id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
provider SMALLINT NOT NULL DEFAULT 1, -- AuthProvider: 1=일반 2=구글
|
||||
login_id VARCHAR(64) NOT NULL, -- 일반은 아이디, 구글은 google_<sub>
|
||||
provider SMALLINT NOT NULL DEFAULT 1, -- AuthProvider: 1=일반 2=구글 3=토스
|
||||
login_id VARCHAR(64) NOT NULL, -- 일반은 아이디, 구글은 google_<sub>, 토스는 toss_<userKey>
|
||||
password VARCHAR(255) NULL, -- bcrypt 해시. 구글 계정은 NULL
|
||||
provider_uid VARCHAR(255) NULL, -- 구글 sub. 일반 계정은 NULL
|
||||
provider_uid VARCHAR(255) NULL, -- 구글 sub 또는 토스 userKey. 일반 계정은 NULL
|
||||
nickname VARCHAR(30) NOT NULL, -- 댓글에 보이는 이름
|
||||
character VARCHAR(20) NOT NULL DEFAULT 'rabbit', -- 프로필 캐릭터: rabbit·bear·dog·sun·moon·cloud
|
||||
color VARCHAR(20) NOT NULL DEFAULT 'orange', -- 프로필 배경색: orange·blue·green·purple·pink·brown
|
||||
@@ -225,6 +225,7 @@ CREATE TABLE IF NOT EXISTS public.users (
|
||||
);
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS uq_users_login_id ON public.users (login_id) WHERE deleted = FALSE;
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS uq_users_google ON public.users (provider_uid) WHERE provider = 2 AND deleted = FALSE;
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS uq_users_toss ON public.users (provider_uid) WHERE provider = 3 AND deleted = FALSE;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS public.post_like (
|
||||
post_id BIGINT NOT NULL,
|
||||
|
||||
@@ -1,11 +1,17 @@
|
||||
from fastapi import APIRouter, Depends
|
||||
import base64
|
||||
import binascii
|
||||
import secrets
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import APIRouter, Depends, Header, HTTPException
|
||||
|
||||
from common.auth import current_user
|
||||
from common.database.model.models import User
|
||||
from common.enums import AuthProvider, ErrorType
|
||||
from common.logger import LOG
|
||||
from common.models.errors import error_info
|
||||
from config.settings import settings
|
||||
from router.v1.auth.protocol import Me, Req_Google, Req_Login, Req_Refresh, Req_Signup, Req_UpdateMe, Res_Auth, Res_AuthConfig, Res_Logout, Res_Me
|
||||
from router.v1.auth.protocol import Me, Req_Google, Req_Login, Req_Refresh, Req_Signup, Req_TossLogin, Req_TossUnlink, Req_UpdateMe, Res_Auth, Res_AuthConfig, Res_Logout, Res_Me, Res_TossUnlink
|
||||
from services.auth_service import AuthService
|
||||
|
||||
router = APIRouter(prefix="/v1/auth", tags=["auth"])
|
||||
@@ -34,6 +40,32 @@ async def login(req: Req_Login, service: AuthService = Depends()) -> Res_Auth:
|
||||
return _auth(err, user, service)
|
||||
|
||||
|
||||
@router.post("/toss", response_model=Res_Auth, response_model_exclude_none=True, summary="토스 로그인 (앱인토스 TossAuth.login 의 authorizationCode·referrer)")
|
||||
async def toss(req: Req_TossLogin, service: AuthService = Depends()) -> Res_Auth:
|
||||
err, user = await service.toss_login(req.authorization_code, req.referrer)
|
||||
return _auth(err, user, service)
|
||||
|
||||
|
||||
def _check_toss_basic(authorization: Optional[str]) -> None:
|
||||
"""콘솔에 넣은 "아이디:비밀번호" 와 같은지 본다. 값이 비어 있으면 모두 거절한다."""
|
||||
given = ""
|
||||
if authorization and authorization.startswith("Basic "):
|
||||
try:
|
||||
given = base64.b64decode(authorization.removeprefix("Basic "), validate=True).decode()
|
||||
except (binascii.Error, UnicodeDecodeError):
|
||||
given = ""
|
||||
if not settings.toss_unlink_auth or not secrets.compare_digest(given.encode(), settings.toss_unlink_auth.encode()):
|
||||
raise HTTPException(status_code=401, detail=ErrorType.AUTH_FAILED.name)
|
||||
|
||||
|
||||
@router.post("/toss/unlink", response_model=Res_TossUnlink, response_model_exclude_none=True, summary="토스 연결 끊기 콜백 (토스 서버가 Basic Auth 로 부름)")
|
||||
async def toss_unlink(req: Req_TossUnlink, authorization: Optional[str] = Header(None), service: AuthService = Depends()) -> Res_TossUnlink:
|
||||
_check_toss_basic(authorization)
|
||||
LOG.info(f"[auth] toss unlink: {req.referrer}")
|
||||
err = await service.toss_unlink(str(req.userKey))
|
||||
return Res_TossUnlink() if err is ErrorType.SUCCESS else Res_TossUnlink(result=error_info(err))
|
||||
|
||||
|
||||
@router.post("/google", response_model=Res_Auth, response_model_exclude_none=True, summary="구글 로그인 (처음이면 자동 닉네임으로 가입)")
|
||||
async def google_login(req: Req_Google, service: AuthService = Depends()) -> Res_Auth:
|
||||
err, user = await service.google(req.credential)
|
||||
|
||||
@@ -17,6 +17,15 @@ class Req_Login(Req_WebPacketProtocol):
|
||||
password: str
|
||||
|
||||
|
||||
class Req_TossLogin(Req_WebPacketProtocol):
|
||||
authorization_code: str
|
||||
referrer: str
|
||||
|
||||
|
||||
class Req_TossUnlink(Req_WebPacketProtocol):
|
||||
"""토스가 보내는 모양 그대로 (camelCase)"""
|
||||
userKey: int
|
||||
referrer: str
|
||||
class Req_Google(Req_WebPacketProtocol):
|
||||
credential: str = Field(min_length=20, max_length=4096, description="구글 로그인 버튼이 준 ID 토큰")
|
||||
|
||||
@@ -47,6 +56,10 @@ class Res_Auth(Res_WebPacketProtocol):
|
||||
me: Optional[Me] = None
|
||||
|
||||
|
||||
class Res_TossUnlink(Res_WebPacketProtocol):
|
||||
pass
|
||||
|
||||
|
||||
class Res_Logout(Res_WebPacketProtocol):
|
||||
pass
|
||||
|
||||
|
||||
@@ -14,7 +14,7 @@ async def get_today_page(sido: str = Path(..., pattern=_SLUG), place: str = Path
|
||||
err, html = await service.page(f"today/{sido}/{place}")
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return HTMLResponse("not found", status_code=404)
|
||||
return HTMLResponse(html, headers={"Cache-Control": "no-cache"})
|
||||
return HTMLResponse(html, headers={"Cache-Control": "no-store"})
|
||||
|
||||
|
||||
@router.get("/today/{sido}/{place}/{gu}", response_class=HTMLResponse, summary="구로 나뉜 시의 구 페이지 (/today/gyeonggi/seongnam/bundang)")
|
||||
@@ -22,7 +22,7 @@ async def get_today_gu_page(sido: str = Path(..., pattern=_SLUG), place: str = P
|
||||
err, html = await service.page(f"today/{sido}/{place}/{gu}")
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return HTMLResponse("not found", status_code=404)
|
||||
return HTMLResponse(html, headers={"Cache-Control": "no-cache"})
|
||||
return HTMLResponse(html, headers={"Cache-Control": "no-store"})
|
||||
|
||||
|
||||
@router.get("/tomorrow/{sido}/{place}", response_class=HTMLResponse, summary="지역 내일 날씨 페이지: 정적 HTML 에 내일 예보를 채운다 (nginx 가 /tomorrow/... 를 넘김)")
|
||||
@@ -30,7 +30,7 @@ async def get_tomorrow_page(sido: str = Path(..., pattern=_SLUG), place: str = P
|
||||
err, html = await service.page(f"tomorrow/{sido}/{place}")
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return HTMLResponse("not found", status_code=404)
|
||||
return HTMLResponse(html, headers={"Cache-Control": "no-cache"})
|
||||
return HTMLResponse(html, headers={"Cache-Control": "no-store"})
|
||||
|
||||
|
||||
@router.get("/tomorrow/{sido}/{place}/{gu}", response_class=HTMLResponse, summary="구로 나뉜 시의 구 내일 날씨 페이지")
|
||||
@@ -38,4 +38,4 @@ async def get_tomorrow_gu_page(sido: str = Path(..., pattern=_SLUG), place: str
|
||||
err, html = await service.page(f"tomorrow/{sido}/{place}/{gu}")
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return HTMLResponse("not found", status_code=404)
|
||||
return HTMLResponse(html, headers={"Cache-Control": "no-cache"})
|
||||
return HTMLResponse(html, headers={"Cache-Control": "no-store"})
|
||||
@@ -9,9 +9,11 @@ from common.auth import PASSWORD_MAX_BYTES, decode, hash_password, issue_tokens,
|
||||
from common.database.db_session_manager import DB_SESSION_MNG
|
||||
from common.google_id import verify as verify_google
|
||||
from common.database.model.models import User
|
||||
from common.enums import ErrorType
|
||||
from common.enums import AuthProvider, ErrorType
|
||||
from common.logger import LOG
|
||||
from config.settings import settings
|
||||
from crud.user_crud import UserCRUD
|
||||
from services.external import toss_login
|
||||
|
||||
LOGIN_ID = re.compile(r"^[a-z0-9_]{4,20}$")
|
||||
PASSWORD_MIN = 8
|
||||
@@ -19,6 +21,7 @@ NICKNAME = re.compile(r"^\S.{0,10}\S$")
|
||||
CHARACTERS = ("rabbit", "bear", "dog", "sun", "moon", "cloud")
|
||||
COLORS = ("orange", "blue", "green", "purple", "pink", "brown")
|
||||
MOODS = ("clear", "partly", "cloudy", "rain", "thunder", "snow", "fog", "rainbow")
|
||||
TOSS_REFERRERS = ("DEFAULT", "SANDBOX")
|
||||
|
||||
|
||||
_NICK_WORDS = ("맑은", "포근한", "산들", "반짝", "느긋한", "보슬", "선선한", "따끈한")
|
||||
@@ -58,6 +61,32 @@ class AuthService:
|
||||
return ErrorType.AUTH_FAILED, None
|
||||
return ErrorType.SUCCESS, user
|
||||
|
||||
async def toss_login(self, authorization_code: str, referrer: str) -> tuple[ErrorType, Optional[User]]:
|
||||
"""토스 userKey 로 계정을 찾고, 없으면 만든다. 이름·전화번호 같은 개인정보는 받지 않는다."""
|
||||
if not authorization_code or referrer not in TOSS_REFERRERS:
|
||||
return ErrorType.INVALID_INPUT, None
|
||||
try:
|
||||
key = str(await toss_login.user_key(authorization_code, referrer))
|
||||
except toss_login.TossLoginError as e:
|
||||
LOG.error(f"[auth] toss login: {e}")
|
||||
return ErrorType.AUTH_FAILED, None
|
||||
provider = AuthProvider.TOSS.value
|
||||
err, user = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.by_provider_uid(s, provider, key))
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return err, None
|
||||
if user is None:
|
||||
err, user = await DB_SESSION_MNG.execute_lambda_write(
|
||||
lambda s: self.crud.create_social(s, provider, key, f"toss_{key}", f"토스{key[-4:]}")
|
||||
)
|
||||
if err is not ErrorType.SUCCESS:
|
||||
# 같은 사람이 동시에 두 번 들어온 경우 먼저 만든 계정을 쓴다
|
||||
err, user = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.by_provider_uid(s, provider, key))
|
||||
if err is not ErrorType.SUCCESS or user is None:
|
||||
return err if err is not ErrorType.SUCCESS else ErrorType.DB_ERROR, None
|
||||
if user.status != 1:
|
||||
return ErrorType.AUTH_FAILED, None
|
||||
return ErrorType.SUCCESS, user
|
||||
|
||||
async def google(self, credential: str) -> tuple[ErrorType, Optional[User]]:
|
||||
"""구글 ID 토큰으로 로그인. 처음이면 자동 닉네임으로 계정을 만든다. 구글 이름·이메일은 저장하지 않는다."""
|
||||
sub = await verify_google(credential)
|
||||
@@ -78,6 +107,13 @@ class AuthService:
|
||||
return ErrorType.AUTH_FAILED, None
|
||||
return ErrorType.SUCCESS, user
|
||||
|
||||
async def toss_unlink(self, user_key: str) -> ErrorType:
|
||||
"""토스에서 연결을 끊으면 그 계정의 모든 토큰을 무효로 만든다. 계정이 없어도 성공으로 본다."""
|
||||
err, user = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.by_provider_uid(s, AuthProvider.TOSS.value, user_key))
|
||||
if err is not ErrorType.SUCCESS or user is None:
|
||||
return err
|
||||
return await self.logout(user)
|
||||
|
||||
async def refresh(self, refresh_token: str) -> tuple[ErrorType, Optional[User]]:
|
||||
claims = decode(refresh_token, settings.jwt_refresh_secret, "refresh")
|
||||
if claims is None:
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
import ssl
|
||||
from functools import lru_cache
|
||||
|
||||
import httpx
|
||||
|
||||
from common.logger import LOG
|
||||
from config.settings import settings
|
||||
|
||||
TIMEOUT_SEC = 10.0
|
||||
_PATH = "/api-partner/v1/apps-in-toss/user/oauth2"
|
||||
|
||||
|
||||
class TossLoginError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
@lru_cache(maxsize=1)
|
||||
def _mtls() -> ssl.SSLContext:
|
||||
if not settings.toss_mtls_cert or not settings.toss_mtls_key:
|
||||
raise TossLoginError("TOSS_MTLS_CERT / TOSS_MTLS_KEY is empty")
|
||||
ctx = ssl.create_default_context()
|
||||
ctx.load_cert_chain(settings.toss_mtls_cert, settings.toss_mtls_key)
|
||||
return ctx
|
||||
|
||||
|
||||
def _success(res: httpx.Response, step: str) -> dict:
|
||||
"""토스는 업무 오류도 HTTP 200 + resultType=FAIL 로 준다. 로그에 토큰·개인정보를 남기지 않는다."""
|
||||
res.raise_for_status()
|
||||
body = res.json()
|
||||
if body.get("resultType") != "SUCCESS":
|
||||
err = body.get("error")
|
||||
code = err.get("errorCode") if isinstance(err, dict) else err
|
||||
raise TossLoginError(f"{step} failed: {code}")
|
||||
return body["success"]
|
||||
|
||||
|
||||
async def user_key(authorization_code: str, referrer: str) -> int:
|
||||
"""앱에서 받은 인가 코드로 토스 토큰을 받고, 그 토큰으로 이 앱 전용 사용자 키(userKey)만 읽는다."""
|
||||
try:
|
||||
async with httpx.AsyncClient(base_url=settings.toss_api_base, verify=_mtls(), timeout=TIMEOUT_SEC, follow_redirects=False) as client:
|
||||
token = _success(
|
||||
await client.post(f"{_PATH}/generate-token", json={"authorizationCode": authorization_code, "referrer": referrer}),
|
||||
"generate-token",
|
||||
)
|
||||
me = _success(
|
||||
await client.get(f"{_PATH}/login-me", headers={"Authorization": f"Bearer {token['accessToken']}"}),
|
||||
"login-me",
|
||||
)
|
||||
return int(me["userKey"])
|
||||
except (httpx.HTTPError, ssl.SSLError, OSError, KeyError, ValueError) as e:
|
||||
LOG.error(f"[toss] login failed: {type(e).__name__}")
|
||||
raise TossLoginError(type(e).__name__) from None
|
||||
@@ -0,0 +1,87 @@
|
||||
import base64
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
from httpx import ASGITransport, AsyncClient
|
||||
|
||||
from config.settings import settings
|
||||
from router.router import app
|
||||
from services.external import toss_login
|
||||
|
||||
|
||||
def client():
|
||||
return AsyncClient(transport=ASGITransport(app=app), base_url="http://test")
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def toss(monkeypatch):
|
||||
"""토스 서버 대신 코드별로 정해 둔 userKey 를 돌려준다."""
|
||||
keys = {"code-a": 1234567, "code-b": 7654321}
|
||||
|
||||
async def fake_user_key(code: str, referrer: str) -> int:
|
||||
if code not in keys:
|
||||
raise toss_login.TossLoginError("generate-token failed: invalid_grant")
|
||||
return keys[code]
|
||||
|
||||
monkeypatch.setattr(toss_login, "user_key", fake_user_key)
|
||||
monkeypatch.setattr(settings, "toss_unlink_auth", "toss:unlink-secret")
|
||||
|
||||
|
||||
def _basic(value: str) -> dict:
|
||||
return {"Authorization": "Basic " + base64.b64encode(value.encode()).decode()}
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_toss_login_creates_once_and_reuses(toss):
|
||||
async with client() as c:
|
||||
first = (await c.post("/v1/auth/toss", json={"authorization_code": "code-a", "referrer": "SANDBOX"})).json()
|
||||
again = (await c.post("/v1/auth/toss", json={"authorization_code": "code-a", "referrer": "DEFAULT"})).json()
|
||||
other = (await c.post("/v1/auth/toss", json={"authorization_code": "code-b", "referrer": "DEFAULT"})).json()
|
||||
me = (await c.get("/v1/auth/me", headers={"Authorization": f"Bearer {first['access_token']}"})).json()
|
||||
assert first["result"]["success"] is True and first["me"]["provider"] == 3
|
||||
assert first["me"]["login_id"] == again["me"]["login_id"] == "toss_1234567"
|
||||
assert other["me"]["login_id"] == "toss_7654321"
|
||||
assert me["me"]["login_id"] == "toss_1234567"
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_toss_login_rejects_bad_code_and_referrer(toss):
|
||||
async with client() as c:
|
||||
bad_code = (await c.post("/v1/auth/toss", json={"authorization_code": "nope", "referrer": "DEFAULT"})).json()
|
||||
bad_ref = (await c.post("/v1/auth/toss", json={"authorization_code": "code-a", "referrer": "WEB"})).json()
|
||||
assert bad_code["result"]["desc"] == "AUTH_FAILED"
|
||||
assert bad_ref["result"]["desc"] == "INVALID_INPUT"
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_toss_unlink_needs_basic_auth_and_kills_tokens(toss):
|
||||
async with client() as c:
|
||||
login = (await c.post("/v1/auth/toss", json={"authorization_code": "code-a", "referrer": "DEFAULT"})).json()
|
||||
body = {"userKey": 1234567, "referrer": "UNLINK"}
|
||||
assert (await c.post("/v1/auth/toss/unlink", json=body)).status_code == 401
|
||||
assert (await c.post("/v1/auth/toss/unlink", json=body, headers=_basic("toss:wrong"))).status_code == 401
|
||||
ok = await c.post("/v1/auth/toss/unlink", json=body, headers=_basic("toss:unlink-secret"))
|
||||
unknown = await c.post("/v1/auth/toss/unlink", json={"userKey": 1, "referrer": "WITHDRAWAL_TOSS"}, headers=_basic("toss:unlink-secret"))
|
||||
me = await c.get("/v1/auth/me", headers={"Authorization": f"Bearer {login['access_token']}"})
|
||||
assert ok.status_code == 200 and ok.json()["result"]["success"] is True
|
||||
assert unknown.status_code == 200
|
||||
assert me.status_code == 401
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_toss_unlink_rejects_all_when_not_configured(toss, monkeypatch):
|
||||
monkeypatch.setattr(settings, "toss_unlink_auth", "")
|
||||
async with client() as c:
|
||||
r = await c.post("/v1/auth/toss/unlink", json={"userKey": 1, "referrer": "UNLINK"}, headers=_basic(":"))
|
||||
assert r.status_code == 401
|
||||
|
||||
|
||||
def test_success_reads_toss_wrapper():
|
||||
ok = httpx.Response(200, json={"resultType": "SUCCESS", "success": {"userKey": 1}}, request=httpx.Request("GET", "https://x"))
|
||||
fail = httpx.Response(200, json={"resultType": "FAIL", "error": {"errorCode": "4050", "reason": "x"}}, request=httpx.Request("GET", "https://x"))
|
||||
grant = httpx.Response(200, json={"error": "invalid_grant"}, request=httpx.Request("GET", "https://x"))
|
||||
assert toss_login._success(ok, "login-me") == {"userKey": 1}
|
||||
with pytest.raises(toss_login.TossLoginError, match="4050"):
|
||||
toss_login._success(fail, "login-me")
|
||||
with pytest.raises(toss_login.TossLoginError, match="invalid_grant"):
|
||||
toss_login._success(grant, "generate-token")
|
||||
@@ -44,6 +44,7 @@ services:
|
||||
ports:
|
||||
- "${API_BIND:-9810}:9800"
|
||||
volumes:
|
||||
- ./secrets/toss:/run/secrets/toss:ro
|
||||
- uploads:/app/uploads # 사람 글 사진
|
||||
depends_on:
|
||||
postgres:
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
# 앱인토스 진행 계획
|
||||
|
||||
기준: 2026-10-12. 근거 문서는 [입점 검토](https://claude.ai/artifact/QgA7iq3CCesTRYcFyZck71), [토스판 전략](https://claude.ai/artifact/4WgpUjdNqdSNnMN4ASB4BB).
|
||||
|
||||
## 정한 것
|
||||
|
||||
- 토스판은 **WebView**로 만든다. React Native(Granite)는 쓰지 않는다. RN은 토스와 무관한 독립 앱으로만 진행한다.
|
||||
- 프로젝트를 따로 만들지 않는다. 지금 `frontend/` 하나에서 **웹 빌드**와 **토스 빌드** 두 가지를 낸다.
|
||||
- 웹을 먼저 출시하고, 토스판은 그 뒤에 낸다.
|
||||
- 토스판 1차부터 **토스 로그인**을 넣는다(10/14 결정). 좋아요·댓글도 웹과 같이 켠다. 아이디 로그인은 토스판에서 쓰지 않는다.
|
||||
|
||||
## 구조
|
||||
|
||||
```
|
||||
frontend/
|
||||
apps-in-toss.config.ts 토스 앱 설정 (appName, brand, permissions, navigationBar, webBundleDir=dist-toss)
|
||||
.env.toss 로컬 전용, 커밋 안 함. VITE_API_BASE_URL·VITE_SITE_URL=https://weather.o2o.kr
|
||||
src/lib/platform.ts 웹/토스 차이를 모으는 유일한 곳
|
||||
```
|
||||
|
||||
- 빌드: 웹은 `npm run build`, 토스는 `npm run build:toss`. 토스 빌드는 `vite build --mode toss --outDir dist-toss`를 돌린 뒤 `ait build`로 `weather-gak-test.ait`를 만든다. 지금 appName은 테스트용 `weather-gak-test`다. 정식 앱으로 바꿀 때는 `apps-in-toss.config.ts`와 `src/lib/platform.ts`(`intoss://` 주소) 두 곳을 같이 고친다.
|
||||
- SDK 3.x는 설정 파일이 `apps-in-toss.config.ts`다. 문서에 나오는 `granite.config.ts`는 2.x 방식이다.
|
||||
- 토스 빌드에서 `.env.toss`에 HTTPS 주소가 없으면 `vite.config.ts`가 빌드를 멈춘다.
|
||||
- `platform.ts`는 `import.meta.env.MODE === 'toss'`로 갈린다. SDK는 토스 모드에서만 동적으로 import하므로 웹 번들에는 들어가지 않는다. 웹 빌드 결과에 SDK 조각이 없는 것을 확인했다.
|
||||
- 화면 코드는 `platform.ts`의 함수만 부른다. 화면 곳곳에 `if (토스)`를 두지 않는다.
|
||||
- 백엔드는 고치지 않는다. CORS는 이미 전부 허용(`backend/router/router.py:34`)이고, API 주소는 `VITE_API_BASE_URL`로 받는다(`frontend/src/api/setup.ts:4`).
|
||||
|
||||
## 웹과 토스가 다른 점
|
||||
|
||||
| 기능 | 웹 | 토스 | 파일 |
|
||||
|---|---|---|---|
|
||||
| 공유 | `navigator.share` (이미지 카드 + 링크) | 이미지는 기기에 저장(`File.saveBase64`), 링크는 `Share.createLink` + `Share.sendMessage`. SDK 공유는 글만 보낼 수 있다 | `frontend/src/b/Sheets.tsx` |
|
||||
| 위치 | `navigator.geolocation` | `Device.getLocation`. 처음 들어올 때는 권한 창을 띄우지 않고, 이미 허용한 사람만 위치로 맞춘다. '내 위치' 버튼을 누를 때 권한 창을 띄운다 | `frontend/src/b/region.tsx` |
|
||||
| 로그인 | 아이디·비밀번호 | 토스 로그인(`TossAuth.login` → `POST /v1/auth/toss`). 토스가 주는 개인정보는 받지 않고 `userKey`만 저장한다 | `frontend/src/b/Sheets.tsx` (`TossLoginSheet`), `backend/services/external/toss_login.py` |
|
||||
| 좋아요·댓글 | 있음 | 있음. 신고·차단은 필수가 아니라 만들지 않는다(검수에서 요청하면 만든다) | `frontend/src/b/Post.tsx`, `frontend/src/b/Sheets.tsx` |
|
||||
| 네이버 지도 링크 | 있음 | 장소 이름만 표시. Q4 답이 '예외 해당'이면 되돌린다 | `frontend/src/b/ui.tsx` (`MapLink`) |
|
||||
| 밤 배경 | 어두운 남색 | Q3 답 보고 결정 | `frontend/src/b/BLayout.tsx` |
|
||||
| GA4 | `index.html`에 태그 | Q2 답 보고 결정 | `frontend/index.html`, `frontend/src/lib/analytics.ts` |
|
||||
| 라우터 | `BrowserRouter` | Q1 답 보고 결정 (안 되면 `HashRouter`) | `frontend/src/App.tsx` |
|
||||
| AI 글 표시 | 없음 | 계절 소식 등에 표시 (문구는 검토받은 뒤) | 글 시트 |
|
||||
|
||||
## 토스에 물어볼 것 (채널톡 · 개발자 커뮤니티)
|
||||
|
||||
| # | 질문 | 답 |
|
||||
|---|---|---|
|
||||
| Q1 | WebView에서 `BrowserRouter`(주소 경로)로 화면을 나눠도 되는가 | |
|
||||
| Q2 | 미니앱 안에서 GA4(`gtag.js`)를 써도 되는가 | |
|
||||
| Q3 | 시간대에 따라 밤에 어두운 배경을 쓰면 '라이트 모드' 규칙에 걸리는가 | |
|
||||
| Q4 | 장소 이름을 누르면 네이버 지도로 가는 링크가 '단순 정보 확인' 예외에 해당하는가 | |
|
||||
| Q5 | 공유창으로 이미지 파일(공유 카드)을 보낼 수 있는가 | SDK 기준 불가(`Share.sendMessage`는 글만). 지금은 이미지를 저장하고 링크를 보낸다 |
|
||||
| Q6 | TDS는 '강력 권장'인데 React 19 프로젝트도 TDS 없이 검수를 통과하는가 (TDS는 React 18 필요) | |
|
||||
| Q7 | 카테고리 목록. '나들이·여가' 같은 분류가 있는가 | |
|
||||
|
||||
## 단계
|
||||
|
||||
각 단계가 끝나면 확인을 받고 다음 단계로 간다. 작업 브랜치는 `feat/apps-in-toss`.
|
||||
|
||||
### 0. 사전 준비 — 사람이 할 일
|
||||
|
||||
- [ ] 앱인토스 콘솔 가입, 앱 등록 → `appName` 확정 (https://apps-in-toss.toss.im)
|
||||
- [ ] 사업자 정보 등록 (영업일 기준 약 1일)
|
||||
- [ ] 위 Q1~Q7 문의
|
||||
- [ ] 샌드박스 앱을 테스트 폰에 설치
|
||||
|
||||
### 1. 토스 빌드 뼈대
|
||||
|
||||
- [x] `@apps-in-toss/web-framework@3.8.0` 설치 (버전 고정)
|
||||
- [x] `apps-in-toss.config.ts`, `.env.toss`(로컬), `package.json`에 `build:toss` 추가 → `weather-gak-test.ait` 생성 확인
|
||||
- [ ] 샌드박스 앱에서 피드가 뜨는지 확인 — 콘솔 앱 등록·샌드박스 설치 뒤
|
||||
|
||||
완료 기준: 웹 빌드 결과가 바뀌지 않고, 샌드박스에서 피드가 열린다.
|
||||
|
||||
### 2. 플랫폼 분기
|
||||
|
||||
- [x] `src/lib/platform.ts`: `IS_TOSS`, `SOCIAL`, `tossShare`, `tossLocation`
|
||||
- [x] 공유·위치·지도 링크를 토스에서 분기
|
||||
- [x] 토스 로그인: 백엔드 `POST /v1/auth/toss`, 연결 끊기 콜백 `POST /v1/auth/toss/unlink`, 프론트 `TossLoginSheet` (10/14)
|
||||
- [ ] 운영 서버에 mTLS 인증서 두기, `.env`에 `TOSS_MTLS_CERT`·`TOSS_MTLS_KEY`·`TOSS_UNLINK_AUTH`, compose 마운트
|
||||
- [ ] 콘솔: 토스 로그인 약관 동의·동의 항목·연결 끊기 콜백 등록
|
||||
- [ ] Q1~Q3 답에 따라 라우터·GA4·밤 배경을 처리한다 (지금은 웹과 같음)
|
||||
|
||||
완료 기준: 웹은 지금과 똑같이 동작한다. 토스에서는 토스 로그인으로만 로그인한다.
|
||||
|
||||
### 3. 토스판 피드 줄이기 — 결정 대기
|
||||
|
||||
TODO.md의 '각 34개 정리', '히어로 숫자 5개'가 결정되면 진행한다. 목표는 피드 8~10칸, 첫 화면에 한 줄 판정이다. 문구는 목록으로 검토받은 뒤 반영한다.
|
||||
|
||||
### 4. 검증
|
||||
|
||||
- [x] `npm run lint`, `npm run build`, `npm run build:toss` 모두 통과 (10/12)
|
||||
- [ ] 샌드박스 실기기 확인: 첫 화면 뒤로가기를 누르면 앱이 닫힌다, 진입하자마자 바텀시트가 뜨지 않는다, 상단 바 버튼이 1개다, 위치 권한을 거부해도 지역 선택으로 쓸 수 있다
|
||||
- [ ] [비게임 검수 체크리스트](https://developers-apps-in-toss.toss.im/checklist/app-nongame.md)와 항목별로 대조
|
||||
- [ ] 토스 공식 `project-validator` 스킬로 점검 (https://github.com/toss/apps-in-toss-skills)
|
||||
|
||||
### 5. 출시
|
||||
|
||||
- [ ] 웹 출시가 끝났는지 확인
|
||||
- [ ] `.ait` 번들을 콘솔에 올리고 검수 요청 (3~5영업일, 반려 시 다시 3~5일)
|
||||
|
||||
### 6. 출시 후 — 별도 결정
|
||||
|
||||
- 스마트 발송(알림): 금요일 주말 판정, 노을 좋은 날. 노을 알림은 TODO.md에서 결정 대기 중이다.
|
||||
- 포인트: 출시 후 2주만 쓰고 끊는다. 포인트를 끊은 주의 재방문율로 계속할지 판단한다.
|
||||
@@ -12,6 +12,7 @@ GA4 태그(`gtag.js`, 측정 ID `G-D378J4X373`)를 `index.html`에 심고, 화
|
||||
```
|
||||
|
||||
- 왜 GTM이 아니라 GA4 직접인가: 이벤트를 코드(`analytics.ts`)에서 정하므로, GTM을 쓰면 이벤트마다 트리거·태그를 한 번 더 만들어야 한다. 광고 픽셀도, 마케터가 직접 손볼 일도 아직 없다.
|
||||
- 모든 이벤트에 `platform: 'web' | 'toss'`가 붙는다. `index.html`의 `gtag('config')`에서 빌드 모드(`%MODE%`)로 정한다. GA4에서 보려면 맞춤 측정기준(이벤트 범위, `platform`)을 한 번 등록한다.
|
||||
- 개발 서버(`npm run dev`)에서는 `track()`이 이벤트를 보내지 않는다. 단 `index.html`의 페이지 조회(`page_view`)는 개발 서버에서도 나가므로 GA4에서 `localhost`를 걸러 본다.
|
||||
- 이벤트 이름은 영어 snake_case. GA4 추천 이벤트(`share`, `login`, `sign_up`, `select_content`)는 이름을 그대로 써야 GA4 기본 보고서에 잡힌다.
|
||||
- 값은 사람이 읽을 수 있게 한글 그대로 둔다 (예: `gak_name: '야장각'`).
|
||||
@@ -25,7 +26,7 @@ GA4 태그(`gtag.js`, 측정 ID `G-D378J4X373`)를 `index.html`에 심고, 화
|
||||
| `view_gak` | 각 상세 시트가 열려 데이터가 뜸 (같은 각은 한 번만) | `index_id`, `gak_name`, `score`, `rank` | `Sheets.tsx` `GakSheet` |
|
||||
| `select_content` | 글 시트가 열려 데이터가 뜸 (같은 글은 한 번만) | `content_type: 'article'`, `item_id`(글 번호), `category`(분류 이름) | `Sheets.tsx` `ArticleSheet` |
|
||||
| `share` | 공유창으로 보내기 성공, 또는 이미지 내려받기 | `content_type: 'image'`, `item_id`(공유 제목), `method: 'share_sheet' \| 'download'`, `ratio`(이미지 비율) | `Sheets.tsx` `ShareSheet` `send` |
|
||||
| `login` | 로그인 성공 (구글로 처음 들어와 자동 가입된 경우도 `login`) | `method: 'id' \| 'google'` | `Sheets.tsx` `LoginSheet` `done` |
|
||||
| `login` | 로그인 성공 (구글로 처음 들어와 자동 가입된 경우도 `login`) | `method: 'id' \| 'google' \| 'toss'`(앱인토스) | `Sheets.tsx` `LoginSheet` `done`, `TossLoginSheet` |
|
||||
| `sign_up` | 가입 성공 | `method: 'id'` | `Sheets.tsx` `LoginSheet` `done` |
|
||||
| `region_change` | 지역 목록에서 고름, 또는 위치로 가까운 구를 찾음 | `region_name`, `method: 'list' \| 'location'` | `Sheets.tsx` `RegionSheet`, `region.tsx` `findNearest` |
|
||||
| `install_banner_view` | 오늘 탭의 '홈 화면에 추가' 카드가 보임 (설치할 수 있는 곳에서, 닫은 지 2주 안 지났으면 안 보임) | 없음 | `installBanner.tsx` `InstallBanner` |
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
# 인스타 카드 사용법 (날씨 타로 · 오늘의 코디)
|
||||
|
||||
Claude Code에서 명령 한 줄을 치면 카드를 만들고, 장마다 검수하고, 날씨각 피드와 인스타(@nalssigak)에 올린 뒤 링크를 보고한다. 중간에 묻지 않는다.
|
||||
|
||||
## 명령
|
||||
|
||||
저장소 폴더에서 Claude Code를 열고:
|
||||
|
||||
| 명령 | 만드는 것 | 뒤에 적는 것 |
|
||||
|---|---|---|
|
||||
| `/daily-tarot 건강 운동` | 날씨 타로 5장 | 타로 주제 "대주제 소주제". 비우면 Claude가 오늘 날씨에 맞는 주제를 고름 |
|
||||
| `/daily-ootd minimal` | 오늘의 코디 4장 | 스타일 하나. 비우면 minimal |
|
||||
| `/daily-cards 건강 운동 minimal` | 둘 다 | 타로 주제 + 마지막 단어가 코디 스타일 |
|
||||
|
||||
타로 주제 예: `연애 썸`, `연애 데이트`, `경제 주식`, `경제 재테크`, `건강 운동`, `일·공부`, `관계`. 목록(`admin/topics.json`)에 없는 말도 된다.
|
||||
|
||||
코디 스타일: `minimal`(꾸안꾸) · `casual`(캐주얼) · `semi`(세미정장·오피스) · `formal`(정장) · `street`(스트릿). 포스트 하나는 스타일 하나로, 네 사람(20-30대·40대~ 여·남) 모두 같은 스타일.
|
||||
|
||||
## 무엇이 일어나나
|
||||
|
||||
1. 관리자 서버(`http://localhost:5175`)가 켜져 있는지 확인하고, 꺼져 있으면 켠다.
|
||||
2. 오늘 서울(중구) 예보를 받는다.
|
||||
3. **타로**: Claude가 주제·예보로 문구를 기획하고 각 카드 3장을 고른다(최근 7일에 쓴 각은 제외). 그림이 없는 각은 Codex가 그린다(장당 1~5분, 가을 각 36장은 이미 있음). 문구의 수치·하늘 묘사를 예보와 대조해 틀리면 한 번 다시 기획한다.
|
||||
**코디**: 무신사 인기 스냅에서 오늘 기온 구간과 스타일 태그에 맞는 코디를 사람별로 하나씩 고른다(최근 14일에 쓴 스냅 제외). Claude가 사진·태그된 상품으로 옷 목록을 뽑고, Codex가 스냅 사진·상품 썸네일을 참고해 같은 옷·색으로 플랫레이 그림을 그린다(사람당 2~4분).
|
||||
4. 카드를 1080×1350 JPEG로 찍어 `admin/out/<날짜>/`에 둔다.
|
||||
5. **검수**: 장마다 원본 크기로 열어 글자 잘림·그림 누락·사람·글자·수치 오류를 본다. 틀리면 고쳐서 다시 만들고, 못 고치면 올리지 않고 보고한다.
|
||||
6. 킹서버 피드에 게시 → 인스타 캐러셀 게시 → 인스타 링크·카드/포스트 번호를 보고하고 `TODO.md`에 한 줄 적는다.
|
||||
|
||||
걸리는 시간: 타로 3~10분, 코디 10~15분.
|
||||
|
||||
## 조건
|
||||
|
||||
- 맥(윈도우는 아직 안 됨). Node, Chrome, `cwebp`.
|
||||
- 이 맥에 Claude CLI·Codex CLI가 로그인돼 있을 것(플랜 계정, API 키 없음). 그림은 `gpt-6-sol`로 고정.
|
||||
- 킹서버 관리자 키에 접근 가능할 것(`ssh King_admin`). 관리자 서버 켜는 법은 `admin/AGENTS.md` '켜기'.
|
||||
- 인스타 토큰은 킹서버 `.env`에 있고 60일마다 갱신(`TODO.md` 참고).
|
||||
|
||||
## 올린 뒤
|
||||
|
||||
- 인스타 글은 API로 지울 수 없다. 잘못 올라갔으면 앱에서 직접 지운다. 킹서버 쪽은 포스트를 숨길 수 있다.
|
||||
- 다시 올리고 싶으면 명령을 한 번 더 치면 새 카드가 만들어진다(이전 것은 그대로 남음).
|
||||
|
||||
## 터미널에서만 (Claude 없이)
|
||||
|
||||
승인 대기 저장까지만 한다. 올리는 건 관리자 화면 '만든 카드' 탭에서.
|
||||
|
||||
```bash
|
||||
cd admin
|
||||
VITE_API_BASE_URL=https://weather.o2o.kr npm run card -- tarot --topic "건강 운동" --color sky --post-wait
|
||||
VITE_API_BASE_URL=https://weather.o2o.kr npm run card -- ootd --daily --style minimal --color sky --post-wait
|
||||
```
|
||||
|
||||
## 어디에 있나
|
||||
|
||||
- 명령 정의: `.claude/commands/daily-tarot.md`, `daily-ootd.md`, `daily-cards.md` (git에 있어 `git pull`만 하면 팀원도 같은 명령이 보임. Claude Code는 시작할 때 읽으므로 받은 뒤 새로 열기)
|
||||
- 스크립트: `admin/scripts/card.mjs`(카드), `plan.mjs`(타로 기획), `daily-ootd.mjs`·`snap.mjs`·`outfit.mjs`(그날 코디), `codex-image.mjs`·`gen-image.mjs`(그림)
|
||||
- 각 카드 그림: `admin/src/assets/gak-card/` (36/68장). 코디 그림: `admin/public/daily/` (git에 안 넣음)
|
||||
- 만드는 규칙 전체: `admin/AGENTS.md`
|
||||
@@ -5,3 +5,6 @@ dist
|
||||
.DS_Store
|
||||
Dockerfile
|
||||
.dockerignore
|
||||
dist-toss
|
||||
*.ait
|
||||
.env.toss
|
||||
@@ -22,3 +22,6 @@ dist-ssr
|
||||
*.njsproj
|
||||
*.sln
|
||||
*.sw?
|
||||
|
||||
dist-toss
|
||||
*.ait
|
||||
@@ -0,0 +1,10 @@
|
||||
import { defineConfig } from '@apps-in-toss/web-framework/config'
|
||||
|
||||
// appName 은 앱인토스 콘솔에 등록한 이름과 같아야 한다
|
||||
export default defineConfig({
|
||||
appName: 'nalssigak',
|
||||
brand: { primaryColor: '#ff7a45' },
|
||||
permissions: [{ name: 'geolocation', access: 'access' }],
|
||||
navigationBar: { withBackButton: true, withHomeButton: true },
|
||||
webBundleDir: 'dist-toss',
|
||||
})
|
||||
@@ -8,7 +8,7 @@
|
||||
function gtag(){dataLayer.push(arguments);}
|
||||
gtag('js', new Date());
|
||||
|
||||
gtag('config', 'G-D378J4X373');
|
||||
gtag('config', 'G-D378J4X373', { platform: '%MODE%' === 'toss' ? 'toss' : 'web' });
|
||||
</script>
|
||||
<script>
|
||||
// 이미 열었던 탭을 다시 열면 브라우저가 예전 HTML 을 다시 쓰고, 그 HTML 이 부르는 예전 빌드 파일은 배포로 지워져 첫 화면에서 멈춘다.
|
||||
|
||||
@@ -8,9 +8,11 @@
|
||||
"build": "tsc -b && vite build",
|
||||
"lint": "oxlint",
|
||||
"preview": "vite preview",
|
||||
"api": "openapi-ts"
|
||||
"api": "openapi-ts",
|
||||
"build:toss": "tsc -b && vite build --mode toss --outDir dist-toss && ait build"
|
||||
},
|
||||
"dependencies": {
|
||||
"@apps-in-toss/web-framework": "3.8.0",
|
||||
"@tailwindcss/vite": "^4.3.3",
|
||||
"@tanstack/react-query": "^5.104.0",
|
||||
"embla-carousel-react": "^8.6.0",
|
||||
|
||||
@@ -19,15 +19,16 @@
|
||||
<body>
|
||||
<main>
|
||||
<h1>개인정보처리방침</h1>
|
||||
<p class="muted">시행일: 2026년 10월 13일</p>
|
||||
<p class="muted">시행일: 2026년 10월 14일</p>
|
||||
|
||||
<p>AIO2O(이하 "회사")는 날씨각 웹 서비스(이하 "웹")와 날씨각 Wear OS 앱(이하 "워치 앱")을 운영하며, 「개인정보 보호법」에 따라 이용자의 개인정보를 다음과 같이 처리합니다.</p>
|
||||
<p>AIO2O(이하 "회사")는 날씨각 웹 서비스(이하 "웹"), 토스 앱 안의 날씨각 미니앱(이하 "토스 미니앱"), 날씨각 Wear OS 앱(이하 "워치 앱")을 운영하며, 「개인정보 보호법」에 따라 이용자의 개인정보를 다음과 같이 처리합니다.</p>
|
||||
|
||||
<h2>1. 수집하는 개인정보와 목적</h2>
|
||||
<table>
|
||||
<tr><th>구분</th><th>항목</th><th>목적</th></tr>
|
||||
<tr><td>웹 회원가입·로그인</td><td>아이디, 비밀번호(암호화 저장), 닉네임 / Google 로그인 시 Google 계정 고유 식별자</td><td>회원 식별, 좋아요·저장·댓글 기능 제공</td></tr>
|
||||
<tr><td>웹·워치 앱 위치</td><td>대략적인 위치(위도·경도)</td><td>가장 가까운 지역(구)의 날씨와 주변 축제를 보여주기 위해 사용합니다. 위치 좌표는 지역을 찾는 데만 쓰고 서버에 저장하지 않습니다.</td></tr>
|
||||
<tr><td>토스 미니앱 로그인</td><td>토스 로그인 시 토스가 주는 이용자 식별값(이 서비스에서만 쓰는 값), 닉네임</td><td>회원 식별, 좋아요·저장·댓글 기능 제공. 토스에서 동의받은 이름 등 다른 정보는 받아 저장하지 않습니다.</td></tr>
|
||||
<tr><td>웹·토스 미니앱·워치 앱 위치</td><td>대략적인 위치(위도·경도)</td><td>가장 가까운 지역(구)의 날씨와 주변 축제를 보여주기 위해 사용합니다. 위치 좌표는 지역을 찾는 데만 쓰고 서버에 저장하지 않습니다.</td></tr>
|
||||
<tr><td>서비스 이용</td><td>접속 기록(IP 주소, 접속 시각, 브라우저 정보), 선택한 지역</td><td>서비스 운영, 오류 확인, 이용 통계</td></tr>
|
||||
</table>
|
||||
<p>위치 권한은 선택 사항입니다. 허용하지 않아도 지역을 직접 골라 이용할 수 있습니다. 워치 앱은 회원가입이나 로그인 없이 이용할 수 있습니다.</p>
|
||||
@@ -42,7 +43,7 @@
|
||||
<p>보유 기간이 끝나거나 목적이 달성된 개인정보는 지체 없이 복구할 수 없는 방법으로 삭제합니다.</p>
|
||||
|
||||
<h2>5. 이용자의 권리</h2>
|
||||
<p>이용자는 언제든지 자신의 개인정보 열람, 정정, 삭제, 처리 정지와 회원 탈퇴를 요청할 수 있습니다. 아래 연락처로 요청하시면 지체 없이 처리합니다. 워치 앱의 위치 권한은 기기 설정에서 언제든지 끌 수 있습니다.</p>
|
||||
<p>이용자는 언제든지 자신의 개인정보 열람, 정정, 삭제, 처리 정지와 회원 탈퇴를 요청할 수 있습니다. 아래 연락처로 요청하시면 지체 없이 처리합니다. 워치 앱의 위치 권한은 기기 설정에서 언제든지 끌 수 있습니다. 토스 미니앱 회원은 토스 앱에서 날씨각과의 연결을 끊을 수 있으며, 연결을 끊으면 로그인이 풀립니다.</p>
|
||||
|
||||
<h2>6. 안전성 확보 조치</h2>
|
||||
<p>비밀번호는 암호화하여 저장하고, 개인정보에 접근할 수 있는 인원을 최소한으로 제한합니다.</p>
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
<!doctype html>
|
||||
<html lang="ko">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>이용약관 - 날씨각</title>
|
||||
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
|
||||
<style>
|
||||
body { margin: 0; padding: 32px 20px 64px; font: 15px/1.7 -apple-system, BlinkMacSystemFont, "Apple SD Gothic Neo", "Malgun Gothic", sans-serif; color: #28304a; background: #f1f8ff; }
|
||||
main { max-width: 720px; margin: 0 auto; }
|
||||
h1 { font-size: 26px; margin: 0 0 4px; }
|
||||
h2 { font-size: 18px; margin: 32px 0 8px; }
|
||||
ul { padding-left: 20px; }
|
||||
.muted { color: #5a6380; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<main>
|
||||
<h1>이용약관</h1>
|
||||
<p class="muted">시행일: 2026년 10월 14일</p>
|
||||
|
||||
<p>이 약관은 AIO2O(이하 "회사")가 제공하는 날씨각 서비스의 이용 조건과 절차, 회사와 이용자의 권리·의무를 정합니다.</p>
|
||||
|
||||
<h2>1. 용어</h2>
|
||||
<ul>
|
||||
<li>서비스: 회사가 웹(weather.o2o.kr), 토스 앱 안의 미니앱(이하 "토스 미니앱"), Wear OS 워치 앱으로 제공하는 날씨각과 그에 딸린 날씨·각 점수·노을·주말·행사·계절 정보, 좋아요·댓글·저장 기능</li>
|
||||
<li>이용자: 서비스를 이용하는 모든 사람</li>
|
||||
<li>회원: 웹에서 아이디·비밀번호로 가입했거나, 토스 미니앱에서 토스 로그인으로 로그인한 이용자</li>
|
||||
<li>게시물: 회원이 서비스에 올린 댓글</li>
|
||||
</ul>
|
||||
|
||||
<h2>2. 약관의 효력과 변경</h2>
|
||||
<p>이 약관은 서비스 화면에 게시해 효력이 생깁니다. 회사는 관련 법령을 어기지 않는 범위에서 약관을 바꿀 수 있으며, 바꿀 때는 시행 7일 전(이용자에게 불리한 변경은 30일 전)부터 서비스 안에서 알립니다.</p>
|
||||
<p>바뀐 약관에 동의하지 않으면 이용을 그만두고 탈퇴할 수 있습니다. 알린 시행일 뒤에도 계속 이용하면 바뀐 약관에 동의한 것으로 봅니다.</p>
|
||||
|
||||
<h2>3. 회원가입과 로그인</h2>
|
||||
<p>웹에서는 아이디, 비밀번호, 닉네임을 입력하고 가입합니다. 토스 미니앱에서는 토스 로그인에 동의하면 회원이 됩니다. 가입하거나 토스 로그인을 하면 이 약관과 <a href="/privacy">개인정보처리방침</a>에 동의한 것으로 봅니다.</p>
|
||||
<p>만 14세 미만은 회원이 될 수 없습니다. 다른 사람의 정보를 쓰거나 다른 사람을 사칭하는 닉네임을 쓸 수 없습니다.</p>
|
||||
|
||||
<h2>4. 서비스 이용</h2>
|
||||
<p>날씨와 각 점수, 노을, 주말·행사, 계절 정보는 로그인 없이 무료로 볼 수 있습니다. 좋아요, 댓글, 저장은 로그인한 뒤에 쓸 수 있습니다.</p>
|
||||
<p>회사는 운영상·기술상 필요에 따라 서비스의 내용을 바꾸거나 일부 또는 전부를 중단할 수 있으며, 중요한 변경이나 중단은 미리 알립니다. 다만 미리 알릴 수 없는 사정이 있으면 나중에 알릴 수 있습니다.</p>
|
||||
|
||||
<h2>5. 날씨 정보와 면책</h2>
|
||||
<p>서비스의 날씨, 미세먼지, 각 점수, 노을 판정, 주말 순위, 행사 정보는 공공 데이터와 외부 예보를 바탕으로 회사가 계산하거나 정리한 참고 정보입니다. 예보는 실제 날씨와 다를 수 있고, 외부 제공처의 사정으로 늦거나 빠질 수 있습니다.</p>
|
||||
<p>회사는 이 정보의 정확성이나 이 정보를 근거로 한 결정의 결과를 보증하지 않습니다. 야외 활동, 여행, 행사 참석 같은 결정은 이용자 스스로 판단하며, 기상특보나 행사 일정은 기상청과 각 주최 측의 공식 안내를 함께 확인해 주세요.</p>
|
||||
<p>회사의 고의나 중대한 과실로 생긴 손해는 이 면책에서 제외합니다.</p>
|
||||
|
||||
<h2>6. 게시물(댓글)</h2>
|
||||
<p>게시물에 대한 책임은 그 게시물을 쓴 회원에게 있습니다. 다음 게시물은 쓸 수 없습니다.</p>
|
||||
<ul>
|
||||
<li>욕설, 비방, 혐오, 음란한 내용</li>
|
||||
<li>다른 사람의 개인정보(이름, 연락처, 주소 등)를 드러내는 내용</li>
|
||||
<li>광고, 홍보, 같은 내용을 되풀이하는 도배</li>
|
||||
<li>다른 사람의 저작권 등 권리를 침해하거나 법령을 어기는 내용</li>
|
||||
</ul>
|
||||
<p>회사는 위에 해당하거나 권리자의 요청이 있는 게시물을 미리 알리지 않고 지우거나 보이지 않게 할 수 있습니다. 문제가 있는 게시물은 <a href="mailto:o2odev@o2o.kr">o2odev@o2o.kr</a>로 알려 주세요. 회원은 자신의 댓글을 언제든 직접 지울 수 있습니다.</p>
|
||||
<p>게시물의 저작권은 쓴 회원에게 있습니다. 회원은 회사가 서비스 안에 그 게시물을 보여 주는 데 필요한 범위에서 이용하도록 허락합니다.</p>
|
||||
|
||||
<h2>7. 회원의 의무와 이용 제한</h2>
|
||||
<p>회원은 자신의 계정을 스스로 관리해야 하며, 다른 사람에게 빌려주거나 넘길 수 없습니다.</p>
|
||||
<p>자동화된 수단으로 정보를 대량으로 가져가거나, 서비스 운영을 방해하거나, 이 약관을 어기면 회사는 해당 게시물을 지우고 서비스 이용을 제한할 수 있습니다.</p>
|
||||
|
||||
<h2>8. 회원 탈퇴</h2>
|
||||
<p>회원은 언제든 <a href="mailto:o2odev@o2o.kr">o2odev@o2o.kr</a>로 탈퇴를 요청할 수 있고, 회사는 지체 없이 처리합니다. 토스 미니앱 회원은 토스 앱에서 날씨각과의 연결을 끊을 수도 있습니다. 탈퇴하면 회원 정보, 댓글, 좋아요, 저장한 포스트를 <a href="/privacy">개인정보처리방침</a>에 따라 파기하며 되살릴 수 없습니다.</p>
|
||||
|
||||
<h2>9. 책임의 한계</h2>
|
||||
<p>회사는 천재지변, 정전, 외부 데이터 제공처의 장애처럼 회사가 통제할 수 없는 사유나 이용자의 잘못으로 생긴 서비스 장애에 대해서는 책임지지 않습니다. 회원끼리 또는 회원과 제3자 사이에 게시물로 생긴 분쟁에 대해서도 같습니다.</p>
|
||||
|
||||
<h2>10. 분쟁 해결</h2>
|
||||
<p>이 약관과 서비스 이용에는 대한민국 법을 적용합니다. 서비스 이용과 관련해 분쟁이 생기면 회사와 이용자는 먼저 성실히 협의하고, 소송이 필요하면 민사소송법에 따른 관할 법원에 제기합니다.</p>
|
||||
|
||||
<h2>11. 데이터 출처</h2>
|
||||
<p>서비스는 다음 기관과 제공처의 데이터를 사용합니다. 공공 데이터는 공공데이터포털(data.go.kr)을 통해 받으며 각 기관의 이용 조건을 따릅니다.</p>
|
||||
<ul>
|
||||
<li>기상청: 단기·초단기·중기 예보, 기상특보</li>
|
||||
<li>한국환경공단 에어코리아: 대기오염 실시간 측정 정보</li>
|
||||
<li>한국천문연구원: 공휴일·24절기, 해 뜨고 지는 시각</li>
|
||||
<li>한국관광공사: 축제·행사, 명소 정보와 사진 (ⓒ한국관광공사)</li>
|
||||
<li>한국문화정보원: 공연·전시 정보와 사진 (ⓒ한국문화정보원)</li>
|
||||
<li>Open-Meteo: 구름 등 기상 예보 (CC BY 4.0)</li>
|
||||
<li>팝가: 팝업스토어 정보</li>
|
||||
</ul>
|
||||
|
||||
<h2>12. 운영자 정보</h2>
|
||||
<p>상호: AIO2O<br />문의: <a href="mailto:o2odev@o2o.kr">o2odev@o2o.kr</a></p>
|
||||
|
||||
<h2>부칙</h2>
|
||||
<p>이 약관은 2026년 10월 14일부터 시행합니다.</p>
|
||||
</main>
|
||||
</body>
|
||||
</html>
|
||||
@@ -3,8 +3,8 @@
|
||||
import { type DefaultError, type InfiniteData, infiniteQueryOptions, queryOptions, type UseMutationOptions } from '@tanstack/react-query';
|
||||
|
||||
import { client } from '../client.gen';
|
||||
import { addComment, addMyGak, addTalk, authConfig, blockTalkAuthor, createCard, deleteComment, deleteMyGak, deleteTalk, getArticle, getCardImage, getFeed, getImage, getIndex, getPost, getSeasonWeek, getSky, getSkyRanking, getTalkImage, getTodayGuPage, getTodayPage, getTomorrowGuPage, getTomorrowPage, getWatchSummary, getWeatherNow, getWeatherToday, getWeek, getWeekRanking, googleLogin, healthzHealthzGet, likeComment, likePost, likeTalk, listArticles, listCards, listComments, listEvents, listIndices, listMyGak, listMyTalks, listPlaces, listPresets, listRegions, listSaved, listTalks, login, logout, me, nearestRegion, type Options, publishCard, refresh, rejectCard, reportTalk, savePost, scoreMyGak, signup, talkGroups, unlikeComment, unlikePost, unlikeTalk, unsavePost, updateMe, uploadTalkImage } from '../sdk.gen';
|
||||
import type { AddCommentData, AddCommentError, AddCommentResponse, AddMyGakData, AddMyGakError, AddMyGakResponse, AddTalkData, AddTalkError, AddTalkResponse, AuthConfigData, AuthConfigResponse, BlockTalkAuthorData, BlockTalkAuthorError, BlockTalkAuthorResponse, CreateCardData, CreateCardError, CreateCardResponse, DeleteCommentData, DeleteCommentError, DeleteCommentResponse, DeleteMyGakData, DeleteMyGakError, DeleteMyGakResponse, DeleteTalkData, DeleteTalkError, DeleteTalkResponse, GetArticleData, GetArticleError, GetArticleResponse, GetCardImageData, GetCardImageError, GetFeedData, GetFeedError, GetFeedResponse, GetImageData, GetImageError, GetIndexData, GetIndexError, GetIndexResponse, GetPostData, GetPostError, GetPostResponse, GetSeasonWeekData, GetSeasonWeekResponse, GetSkyData, GetSkyError, GetSkyRankingData, GetSkyRankingResponse, GetSkyResponse, GetTalkImageData, GetTalkImageError, GetTodayGuPageData, GetTodayGuPageError, GetTodayGuPageResponse, GetTodayPageData, GetTodayPageError, GetTodayPageResponse, GetTomorrowGuPageData, GetTomorrowGuPageError, GetTomorrowGuPageResponse, GetTomorrowPageData, GetTomorrowPageError, GetTomorrowPageResponse, GetWatchSummaryData, GetWatchSummaryError, GetWatchSummaryResponse, GetWeatherNowData, GetWeatherNowError, GetWeatherNowResponse, GetWeatherTodayData, GetWeatherTodayError, GetWeatherTodayResponse, GetWeekData, GetWeekError, GetWeekRankingData, GetWeekRankingResponse, GetWeekResponse, GoogleLoginData, GoogleLoginError, GoogleLoginResponse, HealthzHealthzGetData, HealthzHealthzGetResponse, LikeCommentData, LikeCommentError, LikeCommentResponse, LikePostData, LikePostError, LikePostResponse, LikeTalkData, LikeTalkError, LikeTalkResponse, ListArticlesData, ListArticlesError, ListArticlesResponse, ListCardsData, ListCardsError, ListCardsResponse, ListCommentsData, ListCommentsError, ListCommentsResponse, ListEventsData, ListEventsError, ListEventsResponse, ListIndicesData, ListIndicesError, ListIndicesResponse, ListMyGakData, ListMyGakError, ListMyGakResponse, ListMyTalksData, ListMyTalksError, ListMyTalksResponse, ListPlacesData, ListPlacesError, ListPlacesResponse, ListPresetsData, ListPresetsResponse, ListRegionsData, ListRegionsError, ListRegionsResponse, ListSavedData, ListSavedError, ListSavedResponse, ListTalksData, ListTalksError, ListTalksResponse, LoginData, LoginError, LoginResponse, LogoutData, LogoutError, LogoutResponse, MeData, MeError, MeResponse, NearestRegionData, NearestRegionError, NearestRegionResponse, PublishCardData, PublishCardError, PublishCardResponse, RefreshData, RefreshError, RefreshResponse, RejectCardData, RejectCardError, RejectCardResponse, ReportTalkData, ReportTalkError, ReportTalkResponse, SavePostData, SavePostError, SavePostResponse, ScoreMyGakData, ScoreMyGakError, ScoreMyGakResponse, SignupData, SignupError, SignupResponse, TalkGroupsData, TalkGroupsError, TalkGroupsResponse, UnlikeCommentData, UnlikeCommentError, UnlikeCommentResponse, UnlikePostData, UnlikePostError, UnlikePostResponse, UnlikeTalkData, UnlikeTalkError, UnlikeTalkResponse, UnsavePostData, UnsavePostError, UnsavePostResponse, UpdateMeData, UpdateMeError, UpdateMeResponse, UploadTalkImageData, UploadTalkImageError, UploadTalkImageResponse } from '../types.gen';
|
||||
import { addComment, addMyGak, addTalk, authConfig, blockTalkAuthor, createCard, deleteComment, deleteMyGak, deleteTalk, getArticle, getCardImage, getFeed, getImage, getIndex, getPost, getSeasonWeek, getSky, getSkyRanking, getTalkImage, getTodayGuPage, getTodayPage, getTomorrowGuPage, getTomorrowPage, getWatchSummary, getWeatherNow, getWeatherToday, getWeek, getWeekRanking, googleLogin, healthzHealthzGet, likeComment, likePost, likeTalk, listArticles, listCards, listComments, listEvents, listIndices, listMyGak, listMyTalks, listPlaces, listPresets, listRegions, listSaved, listTalks, login, logout, me, nearestRegion, type Options, publishCard, publishInstagram, refresh, rejectCard, reportTalk, savePost, scoreMyGak, signup, talkGroups, toss, tossUnlink, unlikeComment, unlikePost, unlikeTalk, unsavePost, updateMe, uploadTalkImage } from '../sdk.gen';
|
||||
import type { AddCommentData, AddCommentError, AddCommentResponse, AddMyGakData, AddMyGakError, AddMyGakResponse, AddTalkData, AddTalkError, AddTalkResponse, AuthConfigData, AuthConfigResponse, BlockTalkAuthorData, BlockTalkAuthorError, BlockTalkAuthorResponse, CreateCardData, CreateCardError, CreateCardResponse, DeleteCommentData, DeleteCommentError, DeleteCommentResponse, DeleteMyGakData, DeleteMyGakError, DeleteMyGakResponse, DeleteTalkData, DeleteTalkError, DeleteTalkResponse, GetArticleData, GetArticleError, GetArticleResponse, GetCardImageData, GetCardImageError, GetFeedData, GetFeedError, GetFeedResponse, GetImageData, GetImageError, GetIndexData, GetIndexError, GetIndexResponse, GetPostData, GetPostError, GetPostResponse, GetSeasonWeekData, GetSeasonWeekResponse, GetSkyData, GetSkyError, GetSkyRankingData, GetSkyRankingResponse, GetSkyResponse, GetTalkImageData, GetTalkImageError, GetTodayGuPageData, GetTodayGuPageError, GetTodayGuPageResponse, GetTodayPageData, GetTodayPageError, GetTodayPageResponse, GetTomorrowGuPageData, GetTomorrowGuPageError, GetTomorrowGuPageResponse, GetTomorrowPageData, GetTomorrowPageError, GetTomorrowPageResponse, GetWatchSummaryData, GetWatchSummaryError, GetWatchSummaryResponse, GetWeatherNowData, GetWeatherNowError, GetWeatherNowResponse, GetWeatherTodayData, GetWeatherTodayError, GetWeatherTodayResponse, GetWeekData, GetWeekError, GetWeekRankingData, GetWeekRankingResponse, GetWeekResponse, GoogleLoginData, GoogleLoginError, GoogleLoginResponse, HealthzHealthzGetData, HealthzHealthzGetResponse, LikeCommentData, LikeCommentError, LikeCommentResponse, LikePostData, LikePostError, LikePostResponse, LikeTalkData, LikeTalkError, LikeTalkResponse, ListArticlesData, ListArticlesError, ListArticlesResponse, ListCardsData, ListCardsError, ListCardsResponse, ListCommentsData, ListCommentsError, ListCommentsResponse, ListEventsData, ListEventsError, ListEventsResponse, ListIndicesData, ListIndicesError, ListIndicesResponse, ListMyGakData, ListMyGakError, ListMyGakResponse, ListMyTalksData, ListMyTalksError, ListMyTalksResponse, ListPlacesData, ListPlacesError, ListPlacesResponse, ListPresetsData, ListPresetsResponse, ListRegionsData, ListRegionsError, ListRegionsResponse, ListSavedData, ListSavedError, ListSavedResponse, ListTalksData, ListTalksError, ListTalksResponse, LoginData, LoginError, LoginResponse, LogoutData, LogoutError, LogoutResponse, MeData, MeError, MeResponse, NearestRegionData, NearestRegionError, NearestRegionResponse, PublishCardData, PublishCardError, PublishCardResponse, PublishInstagramData, PublishInstagramError, PublishInstagramResponse, RefreshData, RefreshError, RefreshResponse, RejectCardData, RejectCardError, RejectCardResponse, ReportTalkData, ReportTalkError, ReportTalkResponse, SavePostData, SavePostError, SavePostResponse, ScoreMyGakData, ScoreMyGakError, ScoreMyGakResponse, SignupData, SignupError, SignupResponse, TalkGroupsData, TalkGroupsError, TalkGroupsResponse, TossData, TossError, TossResponse, TossUnlinkData, TossUnlinkError, TossUnlinkResponse, UnlikeCommentData, UnlikeCommentError, UnlikeCommentResponse, UnlikePostData, UnlikePostError, UnlikePostResponse, UnlikeTalkData, UnlikeTalkError, UnlikeTalkResponse, UnsavePostData, UnsavePostError, UnsavePostResponse, UpdateMeData, UpdateMeError, UpdateMeResponse, UploadTalkImageData, UploadTalkImageError, UploadTalkImageResponse } from '../types.gen';
|
||||
|
||||
export type QueryKey<TOptions extends Options> = [
|
||||
Pick<TOptions, 'baseUrl' | 'body' | 'headers' | 'path' | 'query'> & {
|
||||
@@ -379,6 +379,40 @@ export const loginMutation = (options?: Partial<Options<LoginData>>): UseMutatio
|
||||
return mutationOptions;
|
||||
};
|
||||
|
||||
/**
|
||||
* 토스 로그인 (앱인토스 TossAuth.login 의 authorizationCode·referrer)
|
||||
*/
|
||||
export const tossMutation = (options?: Partial<Options<TossData>>): UseMutationOptions<TossResponse, TossError, Options<TossData>> => {
|
||||
const mutationOptions: UseMutationOptions<TossResponse, TossError, Options<TossData>> = {
|
||||
mutationFn: async (fnOptions) => {
|
||||
const { data } = await toss({
|
||||
...options,
|
||||
...fnOptions,
|
||||
throwOnError: true
|
||||
});
|
||||
return data;
|
||||
}
|
||||
};
|
||||
return mutationOptions;
|
||||
};
|
||||
|
||||
/**
|
||||
* 토스 연결 끊기 콜백 (토스 서버가 Basic Auth 로 부름)
|
||||
*/
|
||||
export const tossUnlinkMutation = (options?: Partial<Options<TossUnlinkData>>): UseMutationOptions<TossUnlinkResponse, TossUnlinkError, Options<TossUnlinkData>> => {
|
||||
const mutationOptions: UseMutationOptions<TossUnlinkResponse, TossUnlinkError, Options<TossUnlinkData>> = {
|
||||
mutationFn: async (fnOptions) => {
|
||||
const { data } = await tossUnlink({
|
||||
...options,
|
||||
...fnOptions,
|
||||
throwOnError: true
|
||||
});
|
||||
return data;
|
||||
}
|
||||
};
|
||||
return mutationOptions;
|
||||
};
|
||||
|
||||
/**
|
||||
* 구글 로그인 (처음이면 자동 닉네임으로 가입)
|
||||
*/
|
||||
@@ -1259,6 +1293,23 @@ export const rejectCardMutation = (options?: Partial<Options<RejectCardData>>):
|
||||
return mutationOptions;
|
||||
};
|
||||
|
||||
/**
|
||||
* 카드뉴스를 인스타그램에 캐러셀로 올리기 (관리자). 같은 카드는 한 번만
|
||||
*/
|
||||
export const publishInstagramMutation = (options?: Partial<Options<PublishInstagramData>>): UseMutationOptions<PublishInstagramResponse, PublishInstagramError, Options<PublishInstagramData>> => {
|
||||
const mutationOptions: UseMutationOptions<PublishInstagramResponse, PublishInstagramError, Options<PublishInstagramData>> = {
|
||||
mutationFn: async (fnOptions) => {
|
||||
const { data } = await publishInstagram({
|
||||
...options,
|
||||
...fnOptions,
|
||||
throwOnError: true
|
||||
});
|
||||
return data;
|
||||
}
|
||||
};
|
||||
return mutationOptions;
|
||||
};
|
||||
|
||||
export const getCardImageQueryKey = (options: Options<GetCardImageData>) => createQueryKey('getCardImage', options);
|
||||
|
||||
/**
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
// This file is auto-generated by @hey-api/openapi-ts
|
||||
|
||||
export { addComment, addMyGak, addTalk, authConfig, blockTalkAuthor, createCard, deleteComment, deleteMyGak, deleteTalk, getArticle, getCardImage, getFeed, getImage, getIndex, getPost, getSeasonWeek, getSky, getSkyRanking, getTalkImage, getTodayGuPage, getTodayPage, getTomorrowGuPage, getTomorrowPage, getWatchSummary, getWeatherNow, getWeatherToday, getWeek, getWeekRanking, googleLogin, healthzHealthzGet, likeComment, likePost, likeTalk, listArticles, listCards, listComments, listEvents, listIndices, listMyGak, listMyTalks, listPlaces, listPresets, listRegions, listSaved, listTalks, login, logout, me, nearestRegion, type Options, publishCard, refresh, rejectCard, reportTalk, savePost, scoreMyGak, signup, talkGroups, unlikeComment, unlikePost, unlikeTalk, unsavePost, updateMe, uploadTalkImage } from './sdk.gen';
|
||||
export { type AddCommentData, type AddCommentError, type AddCommentErrors, type AddCommentResponse, type AddCommentResponses, type AddMyGakData, type AddMyGakError, type AddMyGakErrors, type AddMyGakResponse, type AddMyGakResponses, type AddTalkData, type AddTalkError, type AddTalkErrors, type AddTalkResponse, type AddTalkResponses, type AirData, AirGrade, ArticleCategory, type ArticleSummary, type AuthConfigData, type AuthConfigResponse, type AuthConfigResponses, AuthProvider, type BandArticle, type BandEvent, type Bands, type BestTime, type BlockTalkAuthorData, type BlockTalkAuthorError, type BlockTalkAuthorErrors, type BlockTalkAuthorResponse, type BlockTalkAuthorResponses, type BodyUploadTalkImageV1TalkImagePost, type CardItem, CardStatus, type ClientOptions, type CommentData, type CommuteData, Confidence, type CreateCardData, type CreateCardError, type CreateCardErrors, type CreateCardResponse, type CreateCardResponses, type Cut, type DayData, type DeleteCommentData, type DeleteCommentError, type DeleteCommentErrors, type DeleteCommentResponse, type DeleteCommentResponses, type DeleteMyGakData, type DeleteMyGakError, type DeleteMyGakErrors, type DeleteMyGakResponse, type DeleteMyGakResponses, type DeleteTalkData, type DeleteTalkError, type DeleteTalkErrors, type DeleteTalkResponse, type DeleteTalkResponses, type ErrorInfo, type EventData, type Factor, type GakSlide, type GetArticleData, type GetArticleError, type GetArticleErrors, type GetArticleResponse, type GetArticleResponses, type GetCardImageData, type GetCardImageError, type GetCardImageErrors, type GetCardImageResponses, type GetFeedData, type GetFeedError, type GetFeedErrors, type GetFeedResponse, type GetFeedResponses, type GetImageData, type GetImageError, type GetImageErrors, type GetImageResponses, type GetIndexData, type GetIndexError, type GetIndexErrors, type GetIndexResponse, type GetIndexResponses, type GetPostData, type GetPostError, type GetPostErrors, type GetPostResponse, type GetPostResponses, type GetSeasonWeekData, type GetSeasonWeekResponse, type GetSeasonWeekResponses, type GetSkyData, type GetSkyError, type GetSkyErrors, type GetSkyRankingData, type GetSkyRankingResponse, type GetSkyRankingResponses, type GetSkyResponse, type GetSkyResponses, type GetTalkImageData, type GetTalkImageError, type GetTalkImageErrors, type GetTalkImageResponses, type GetTodayGuPageData, type GetTodayGuPageError, type GetTodayGuPageErrors, type GetTodayGuPageResponse, type GetTodayGuPageResponses, type GetTodayPageData, type GetTodayPageError, type GetTodayPageErrors, type GetTodayPageResponse, type GetTodayPageResponses, type GetTomorrowGuPageData, type GetTomorrowGuPageError, type GetTomorrowGuPageErrors, type GetTomorrowGuPageResponse, type GetTomorrowGuPageResponses, type GetTomorrowPageData, type GetTomorrowPageError, type GetTomorrowPageErrors, type GetTomorrowPageResponse, type GetTomorrowPageResponses, type GetWatchSummaryData, type GetWatchSummaryError, type GetWatchSummaryErrors, type GetWatchSummaryResponse, type GetWatchSummaryResponses, type GetWeatherNowData, type GetWeatherNowError, type GetWeatherNowErrors, type GetWeatherNowResponse, type GetWeatherNowResponses, type GetWeatherTodayData, type GetWeatherTodayError, type GetWeatherTodayErrors, type GetWeatherTodayResponse, type GetWeatherTodayResponses, type GetWeekData, type GetWeekError, type GetWeekErrors, type GetWeekRankingData, type GetWeekRankingResponse, type GetWeekRankingResponses, type GetWeekResponse, type GetWeekResponses, type GoogleLoginData, type GoogleLoginError, type GoogleLoginErrors, type GoogleLoginResponse, type GoogleLoginResponses, type HealthzHealthzGetData, type HealthzHealthzGetResponse, type HealthzHealthzGetResponses, type Hero, type HeroStat, type HeroTomorrow, type HourCell, type HoursSlide, type HttpValidationError, type ImageSlide, IndexCategory, type IndexSummary, type LikeCommentData, type LikeCommentError, type LikeCommentErrors, type LikeCommentResponse, type LikeCommentResponses, type LikePostData, type LikePostError, type LikePostErrors, type LikePostResponse, type LikePostResponses, type LikeTalkData, type LikeTalkError, type LikeTalkErrors, type LikeTalkResponse, type LikeTalkResponses, type ListArticlesData, type ListArticlesError, type ListArticlesErrors, type ListArticlesResponse, type ListArticlesResponses, type ListCardsData, type ListCardsError, type ListCardsErrors, type ListCardsResponse, type ListCardsResponses, type ListCommentsData, type ListCommentsError, type ListCommentsErrors, type ListCommentsResponse, type ListCommentsResponses, type ListEventsData, type ListEventsError, type ListEventsErrors, type ListEventsResponse, type ListEventsResponses, type ListIndicesData, type ListIndicesError, type ListIndicesErrors, type ListIndicesResponse, type ListIndicesResponses, type ListMyGakData, type ListMyGakError, type ListMyGakErrors, type ListMyGakResponse, type ListMyGakResponses, type ListMyTalksData, type ListMyTalksError, type LiLine truncated
|
||||
export { addComment, addMyGak, addTalk, authConfig, blockTalkAuthor, createCard, deleteComment, deleteMyGak, deleteTalk, getArticle, getCardImage, getFeed, getImage, getIndex, getPost, getSeasonWeek, getSky, getSkyRanking, getTalkImage, getTodayGuPage, getTodayPage, getTomorrowGuPage, getTomorrowPage, getWatchSummary, getWeatherNow, getWeatherToday, getWeek, getWeekRanking, googleLogin, healthzHealthzGet, likeComment, likePost, likeTalk, listArticles, listCards, listComments, listEvents, listIndices, listMyGak, listMyTalks, listPlaces, listPresets, listRegions, listSaved, listTalks, login, logout, me, nearestRegion, type Options, publishCard, publishInstagram, refresh, rejectCard, reportTalk, savePost, scoreMyGak, signup, talkGroups, toss, tossUnlink, unlikeComment, unlikePost, unlikeTalk, unsavePost, updateMe, uploadTalkImage } from './sdk.gen';
|
||||
export { type AddCommentData, type AddCommentError, type AddCommentErrors, type AddCommentResponse, type AddCommentResponses, type AddMyGakData, type AddMyGakError, type AddMyGakErrors, type AddMyGakResponse, type AddMyGakResponses, type AddTalkData, type AddTalkError, type AddTalkErrors, type AddTalkResponse, type AddTalkResponses, type AirData, AirGrade, ArticleCategory, type ArticleSummary, type AuthConfigData, type AuthConfigResponse, type AuthConfigResponses, AuthProvider, type BandArticle, type BandEvent, type Bands, type BestTime, type BlockTalkAuthorData, type BlockTalkAuthorError, type BlockTalkAuthorErrors, type BlockTalkAuthorResponse, type BlockTalkAuthorResponses, type BodyUploadTalkImageV1TalkImagePost, type CardItem, CardStatus, type ClientOptions, type CommentData, type CommuteData, Confidence, type CreateCardData, type CreateCardError, type CreateCardErrors, type CreateCardResponse, type CreateCardResponses, type Cut, type DayData, type DeleteCommentData, type DeleteCommentError, type DeleteCommentErrors, type DeleteCommentResponse, type DeleteCommentResponses, type DeleteMyGakData, type DeleteMyGakError, type DeleteMyGakErrors, type DeleteMyGakResponse, type DeleteMyGakResponses, type DeleteTalkData, type DeleteTalkError, type DeleteTalkErrors, type DeleteTalkResponse, type DeleteTalkResponses, type ErrorInfo, type EventData, type Factor, type GakSlide, type GetArticleData, type GetArticleError, type GetArticleErrors, type GetArticleResponse, type GetArticleResponses, type GetCardImageData, type GetCardImageError, type GetCardImageErrors, type GetCardImageResponses, type GetFeedData, type GetFeedError, type GetFeedErrors, type GetFeedResponse, type GetFeedResponses, type GetImageData, type GetImageError, type GetImageErrors, type GetImageResponses, type GetIndexData, type GetIndexError, type GetIndexErrors, type GetIndexResponse, type GetIndexResponses, type GetPostData, type GetPostError, type GetPostErrors, type GetPostResponse, type GetPostResponses, type GetSeasonWeekData, type GetSeasonWeekResponse, type GetSeasonWeekResponses, type GetSkyData, type GetSkyError, type GetSkyErrors, type GetSkyRankingData, type GetSkyRankingResponse, type GetSkyRankingResponses, type GetSkyResponse, type GetSkyResponses, type GetTalkImageData, type GetTalkImageError, type GetTalkImageErrors, type GetTalkImageResponses, type GetTodayGuPageData, type GetTodayGuPageError, type GetTodayGuPageErrors, type GetTodayGuPageResponse, type GetTodayGuPageResponses, type GetTodayPageData, type GetTodayPageError, type GetTodayPageErrors, type GetTodayPageResponse, type GetTodayPageResponses, type GetTomorrowGuPageData, type GetTomorrowGuPageError, type GetTomorrowGuPageErrors, type GetTomorrowGuPageResponse, type GetTomorrowGuPageResponses, type GetTomorrowPageData, type GetTomorrowPageError, type GetTomorrowPageErrors, type GetTomorrowPageResponse, type GetTomorrowPageResponses, type GetWatchSummaryData, type GetWatchSummaryError, type GetWatchSummaryErrors, type GetWatchSummaryResponse, type GetWatchSummaryResponses, type GetWeatherNowData, type GetWeatherNowError, type GetWeatherNowErrors, type GetWeatherNowResponse, type GetWeatherNowResponses, type GetWeatherTodayData, type GetWeatherTodayError, type GetWeatherTodayErrors, type GetWeatherTodayResponse, type GetWeatherTodayResponses, type GetWeekData, type GetWeekError, type GetWeekErrors, type GetWeekRankingData, type GetWeekRankingResponse, type GetWeekRankingResponses, type GetWeekResponse, type GetWeekResponses, type GoogleLoginData, type GoogleLoginError, type GoogleLoginErrors, type GoogleLoginResponse, type GoogleLoginResponses, type HealthzHealthzGetData, type HealthzHealthzGetResponse, type HealthzHealthzGetResponses, type Hero, type HeroStat, type HeroTomorrow, type HourCell, type HoursSlide, type HttpValidationError, type ImageSlide, IndexCategory, type IndexSummary, type LikeCommentData, type LikeCommentError, type LikeCommentErrors, type LikeCommentResponse, type LikeCommentResponses, type LikePostData, type LikePostError, type LikePostErrors, type LikePostResponse, type LikePostResponses, type LikeTalkData, type LikeTalkError, type LikeTalkErrors, type LikeTalkResponse, type LikeTalkResponses, type ListArticlesData, type ListArticlesError, type ListArticlesErrors, type ListArticlesResponse, type ListArticlesResponses, type ListCardsData, type ListCardsError, type ListCardsErrors, type ListCardsResponse, type ListCardsResponses, type ListCommentsData, type ListCommentsError, type ListCommentsErrors, type ListCommentsResponse, type ListCommentsResponses, type ListEventsData, type ListEventsError, type ListEventsErrors, type ListEventsResponse, type ListEventsResponses, type ListIndicesData, type ListIndicesError, type ListIndicesErrors, type ListIndicesResponse, type ListIndicesResponses, type ListMyGakData, type ListMyGakError, type ListMyGakErrors, type ListMyGakResponse, type ListMyGakResponses, type ListMyTalksData, type ListMyTalksError, type LiLine truncated
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
import { type Client, type ClientMeta, formDataBodySerializer, type Options as Options2, type RequestResult, type TDataShape } from './client';
|
||||
import { client } from './client.gen';
|
||||
import type { AddCommentData, AddCommentErrors, AddCommentResponses, AddMyGakData, AddMyGakErrors, AddMyGakResponses, AddTalkData, AddTalkErrors, AddTalkResponses, AuthConfigData, AuthConfigResponses, BlockTalkAuthorData, BlockTalkAuthorErrors, BlockTalkAuthorResponses, CreateCardData, CreateCardErrors, CreateCardResponses, DeleteCommentData, DeleteCommentErrors, DeleteCommentResponses, DeleteMyGakData, DeleteMyGakErrors, DeleteMyGakResponses, DeleteTalkData, DeleteTalkErrors, DeleteTalkResponses, GetArticleData, GetArticleErrors, GetArticleResponses, GetCardImageData, GetCardImageErrors, GetCardImageResponses, GetFeedData, GetFeedErrors, GetFeedResponses, GetImageData, GetImageErrors, GetImageResponses, GetIndexData, GetIndexErrors, GetIndexResponses, GetPostData, GetPostErrors, GetPostResponses, GetSeasonWeekData, GetSeasonWeekResponses, GetSkyData, GetSkyErrors, GetSkyRankingData, GetSkyRankingResponses, GetSkyResponses, GetTalkImageData, GetTalkImageErrors, GetTalkImageResponses, GetTodayGuPageData, GetTodayGuPageErrors, GetTodayGuPageResponses, GetTodayPageData, GetTodayPageErrors, GetTodayPageResponses, GetTomorrowGuPageData, GetTomorrowGuPageErrors, GetTomorrowGuPageResponses, GetTomorrowPageData, GetTomorrowPageErrors, GetTomorrowPageResponses, GetWatchSummaryData, GetWatchSummaryErrors, GetWatchSummaryResponses, GetWeatherNowData, GetWeatherNowErrors, GetWeatherNowResponses, GetWeatherTodayData, GetWeatherTodayErrors, GetWeatherTodayResponses, GetWeekData, GetWeekErrors, GetWeekRankingData, GetWeekRankingResponses, GetWeekResponses, GoogleLoginData, GoogleLoginErrors, GoogleLoginResponses, HealthzHealthzGetData, HealthzHealthzGetResponses, LikeCommentData, LikeCommentErrors, LikeCommentResponses, LikePostData, LikePostErrors, LikePostResponses, LikeTalkData, LikeTalkErrors, LikeTalkResponses, ListArticlesData, ListArticlesErrors, ListArticlesResponses, ListCardsData, ListCardsErrors, ListCardsResponses, ListCommentsData, ListCommentsErrors, ListCommentsResponses, ListEventsData, ListEventsErrors, ListEventsResponses, ListIndicesData, ListIndicesErrors, ListIndicesResponses, ListMyGakData, ListMyGakErrors, ListMyGakResponses, ListMyTalksData, ListMyTalksErrors, ListMyTalksResponses, ListPlacesData, ListPlacesErrors, ListPlacesResponses, ListPresetsData, ListPresetsResponses, ListRegionsData, ListRegionsErrors, ListRegionsResponses, ListSavedData, ListSavedErrors, ListSavedResponses, ListTalksData, ListTalksErrors, ListTalksResponses, LoginData, LoginErrors, LoginResponses, LogoutData, LogoutErrors, LogoutResponses, MeData, MeErrors, MeResponses, NearestRegionData, NearestRegionErrors, NearestRegionResponses, PublishCardData, PublishCardErrors, PublishCardResponses, RefreshData, RefreshErrors, RefreshResponses, RejectCardData, RejectCardErrors, RejectCardResponses, ReportTalkData, ReportTalkErrors, ReportTalkResponses, SavePostData, SavePostErrors, SavePostResponses, ScoreMyGakData, ScoreMyGakErrors, ScoreMyGakResponses, SignupData, SignupErrors, SignupResponses, TalkGroupsData, TalkGroupsErrors, TalkGroupsResponses, UnlikeCommentData, UnlikeCommentErrors, UnlikeCommentResponses, UnlikePostData, UnlikePostErrors, UnlikePostResponses, UnlikeTalkData, UnlikeTalkErrors, UnlikeTalkResponses, UnsavePostData, UnsavePostErrors, UnsavePostResponses, UpdateMeData, UpdateMeErrors, UpdateMeResponses, UploadTalkImageData, UploadTalkImageErrors, UploadTalkImageResponses } from './types.gen';
|
||||
import type { AddCommentData, AddCommentErrors, AddCommentResponses, AddMyGakData, AddMyGakErrors, AddMyGakResponses, AddTalkData, AddTalkErrors, AddTalkResponses, AuthConfigData, AuthConfigResponses, BlockTalkAuthorData, BlockTalkAuthorErrors, BlockTalkAuthorResponses, CreateCardData, CreateCardErrors, CreateCardResponses, DeleteCommentData, DeleteCommentErrors, DeleteCommentResponses, DeleteMyGakData, DeleteMyGakErrors, DeleteMyGakResponses, DeleteTalkData, DeleteTalkErrors, DeleteTalkResponses, GetArticleData, GetArticleErrors, GetArticleResponses, GetCardImageData, GetCardImageErrors, GetCardImageResponses, GetFeedData, GetFeedErrors, GetFeedResponses, GetImageData, GetImageErrors, GetImageResponses, GetIndexData, GetIndexErrors, GetIndexResponses, GetPostData, GetPostErrors, GetPostResponses, GetSeasonWeekData, GetSeasonWeekResponses, GetSkyData, GetSkyErrors, GetSkyRankingData, GetSkyRankingResponses, GetSkyResponses, GetTalkImageData, GetTalkImageErrors, GetTalkImageResponses, GetTodayGuPageData, GetTodayGuPageErrors, GetTodayGuPageResponses, GetTodayPageData, GetTodayPageErrors, GetTodayPageResponses, GetTomorrowGuPageData, GetTomorrowGuPageErrors, GetTomorrowGuPageResponses, GetTomorrowPageData, GetTomorrowPageErrors, GetTomorrowPageResponses, GetWatchSummaryData, GetWatchSummaryErrors, GetWatchSummaryResponses, GetWeatherNowData, GetWeatherNowErrors, GetWeatherNowResponses, GetWeatherTodayData, GetWeatherTodayErrors, GetWeatherTodayResponses, GetWeekData, GetWeekErrors, GetWeekRankingData, GetWeekRankingResponses, GetWeekResponses, GoogleLoginData, GoogleLoginErrors, GoogleLoginResponses, HealthzHealthzGetData, HealthzHealthzGetResponses, LikeCommentData, LikeCommentErrors, LikeCommentResponses, LikePostData, LikePostErrors, LikePostResponses, LikeTalkData, LikeTalkErrors, LikeTalkResponses, ListArticlesData, ListArticlesErrors, ListArticlesResponses, ListCardsData, ListCardsErrors, ListCardsResponses, ListCommentsData, ListCommentsErrors, ListCommentsResponses, ListEventsData, ListEventsErrors, ListEventsResponses, ListIndicesData, ListIndicesErrors, ListIndicesResponses, ListMyGakData, ListMyGakErrors, ListMyGakResponses, ListMyTalksData, ListMyTalksErrors, ListMyTalksResponses, ListPlacesData, ListPlacesErrors, ListPlacesResponses, ListPresetsData, ListPresetsResponses, ListRegionsData, ListRegionsErrors, ListRegionsResponses, ListSavedData, ListSavedErrors, ListSavedResponses, ListTalksData, ListTalksErrors, ListTalksResponses, LoginData, LoginErrors, LoginResponses, LogoutData, LogoutErrors, LogoutResponses, MeData, MeErrors, MeResponses, NearestRegionData, NearestRegionErrors, NearestRegionResponses, PublishCardData, PublishCardErrors, PublishCardResponses, PublishInstagramData, PublishInstagramErrors, PublishInstagramResponses, RefreshData, RefreshErrors, RefreshResponses, RejectCardData, RejectCardErrors, RejectCardResponses, ReportTalkData, ReportTalkErrors, ReportTalkResponses, SavePostData, SavePostErrors, SavePostResponses, ScoreMyGakData, ScoreMyGakErrors, ScoreMyGakResponses, SignupData, SignupErrors, SignupResponses, TalkGroupsData, TalkGroupsErrors, TalkGroupsResponses, TossData, TossErrors, TossResponses, TossUnlinkData, TossUnlinkErrors, TossUnlinkResponses, UnlikeCommentData, UnlikeCommentErrors, UnlikeCommentResponses, UnlikePostData, UnlikePostErrors, UnlikePostResponses, UnlikeTalkData, UnlikeTalkErrors, UnlikeTalkResponses, UnsavePostData, UnsavePostErrors, UnsavePostResponses, UpdateMeData, UpdateMeErrors, UpdateMeResponses, UploadTalkImageData, UploadTalkImageErrors, UploadTalkImageResponses } from './types.gen';
|
||||
|
||||
export type Options<TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown> = Options2<TData, ThrowOnError, TResponse> & {
|
||||
/**
|
||||
@@ -127,6 +127,30 @@ export const login = <ThrowOnError extends boolean = true>(options: Options<Logi
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* 토스 로그인 (앱인토스 TossAuth.login 의 authorizationCode·referrer)
|
||||
*/
|
||||
export const toss = <ThrowOnError extends boolean = true>(options: Options<TossData, ThrowOnError>): RequestResult<TossResponses, TossErrors, ThrowOnError> => (options.client ?? client).post<TossResponses, TossErrors, ThrowOnError>({
|
||||
url: '/v1/auth/toss',
|
||||
...options,
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
...options.headers
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* 토스 연결 끊기 콜백 (토스 서버가 Basic Auth 로 부름)
|
||||
*/
|
||||
export const tossUnlink = <ThrowOnError extends boolean = true>(options: Options<TossUnlinkData, ThrowOnError>): RequestResult<TossUnlinkResponses, TossUnlinkErrors, ThrowOnError> => (options.client ?? client).post<TossUnlinkResponses, TossUnlinkErrors, ThrowOnError>({
|
||||
url: '/v1/auth/toss/unlink',
|
||||
...options,
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
...options.headers
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* 구글 로그인 (처음이면 자동 닉네임으로 가입)
|
||||
*/
|
||||
@@ -408,6 +432,11 @@ export const publishCard = <ThrowOnError extends boolean = true>(options: Option
|
||||
*/
|
||||
export const rejectCard = <ThrowOnError extends boolean = true>(options: Options<RejectCardData, ThrowOnError>): RequestResult<RejectCardResponses, RejectCardErrors, ThrowOnError> => (options.client ?? client).post<RejectCardResponses, RejectCardErrors, ThrowOnError>({ url: '/v1/card/{card_id}/reject', ...options });
|
||||
|
||||
/**
|
||||
* 카드뉴스를 인스타그램에 캐러셀로 올리기 (관리자). 같은 카드는 한 번만
|
||||
*/
|
||||
export const publishInstagram = <ThrowOnError extends boolean = true>(options: Options<PublishInstagramData, ThrowOnError>): RequestResult<PublishInstagramResponses, PublishInstagramErrors, ThrowOnError> => (options.client ?? client).post<PublishInstagramResponses, PublishInstagramErrors, ThrowOnError>({ url: '/v1/card/{card_id}/instagram', ...options });
|
||||
|
||||
/**
|
||||
* 카드뉴스 이미지
|
||||
*/
|
||||
|
||||
@@ -123,13 +123,20 @@ export type ArticleSummary = {
|
||||
/**
|
||||
* AuthProvider
|
||||
*/
|
||||
export const AuthProvider = { /**
|
||||
export const AuthProvider = {
|
||||
/**
|
||||
* LOCAL
|
||||
*/
|
||||
LOCAL: 1, /**
|
||||
LOCAL: 1,
|
||||
/**
|
||||
* GOOGLE
|
||||
*/
|
||||
GOOGLE: 2 } as const;
|
||||
GOOGLE: 2,
|
||||
/**
|
||||
* TOSS
|
||||
*/
|
||||
TOSS: 3
|
||||
} as const;
|
||||
|
||||
/**
|
||||
* AuthProvider
|
||||
@@ -285,6 +292,10 @@ export type CardItem = {
|
||||
* Image Urls
|
||||
*/
|
||||
image_urls?: Array<string>;
|
||||
/**
|
||||
* Ig Media Id
|
||||
*/
|
||||
ig_media_id?: string | null;
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -1685,6 +1696,36 @@ export type ReqTalkReport = {
|
||||
reason: TalkReport;
|
||||
};
|
||||
|
||||
/**
|
||||
* Req_TossLogin
|
||||
*/
|
||||
export type ReqTossLogin = {
|
||||
/**
|
||||
* Authorization Code
|
||||
*/
|
||||
authorization_code: string;
|
||||
/**
|
||||
* Referrer
|
||||
*/
|
||||
referrer: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* Req_TossUnlink
|
||||
*
|
||||
* 토스가 보내는 모양 그대로 (camelCase)
|
||||
*/
|
||||
export type ReqTossUnlink = {
|
||||
/**
|
||||
* Userkey
|
||||
*/
|
||||
userKey: number;
|
||||
/**
|
||||
* Referrer
|
||||
*/
|
||||
referrer: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* Req_UpdateMe
|
||||
*/
|
||||
@@ -1797,6 +1838,10 @@ export type ResCard = {
|
||||
* Image Urls
|
||||
*/
|
||||
image_urls?: Array<string>;
|
||||
/**
|
||||
* Ig Media Id
|
||||
*/
|
||||
ig_media_id?: string | null;
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -2408,6 +2453,17 @@ export type ResTalkList = {
|
||||
next_cursor?: string | null;
|
||||
};
|
||||
|
||||
/**
|
||||
* Res_TossUnlink
|
||||
*/
|
||||
export type ResTossUnlink = {
|
||||
result?: ErrorInfo;
|
||||
/**
|
||||
* Msg
|
||||
*/
|
||||
msg?: string | null;
|
||||
};
|
||||
|
||||
/**
|
||||
* Res_WatchSummary
|
||||
*/
|
||||
@@ -4305,6 +4361,62 @@ export type LoginResponses = {
|
||||
|
||||
export type LoginResponse = LoginResponses[keyof LoginResponses];
|
||||
|
||||
export type TossData = {
|
||||
body: ReqTossLogin;
|
||||
path?: never;
|
||||
query?: never;
|
||||
url: '/v1/auth/toss';
|
||||
};
|
||||
|
||||
export type TossErrors = {
|
||||
/**
|
||||
* Validation Error
|
||||
*/
|
||||
422: HttpValidationError;
|
||||
};
|
||||
|
||||
export type TossError = TossErrors[keyof TossErrors];
|
||||
|
||||
export type TossResponses = {
|
||||
/**
|
||||
* Successful Response
|
||||
*/
|
||||
200: ResAuth;
|
||||
};
|
||||
|
||||
export type TossResponse = TossResponses[keyof TossResponses];
|
||||
|
||||
export type TossUnlinkData = {
|
||||
body: ReqTossUnlink;
|
||||
headers?: {
|
||||
/**
|
||||
* Authorization
|
||||
*/
|
||||
authorization?: string | null;
|
||||
};
|
||||
path?: never;
|
||||
query?: never;
|
||||
url: '/v1/auth/toss/unlink';
|
||||
};
|
||||
|
||||
export type TossUnlinkErrors = {
|
||||
/**
|
||||
* Validation Error
|
||||
*/
|
||||
422: HttpValidationError;
|
||||
};
|
||||
|
||||
export type TossUnlinkError = TossUnlinkErrors[keyof TossUnlinkErrors];
|
||||
|
||||
export type TossUnlinkResponses = {
|
||||
/**
|
||||
* Successful Response
|
||||
*/
|
||||
200: ResTossUnlink;
|
||||
};
|
||||
|
||||
export type TossUnlinkResponse = TossUnlinkResponses[keyof TossUnlinkResponses];
|
||||
|
||||
export type GoogleLoginData = {
|
||||
body: ReqGoogle;
|
||||
path?: never;
|
||||
@@ -5719,6 +5831,42 @@ export type RejectCardResponses = {
|
||||
|
||||
export type RejectCardResponse = RejectCardResponses[keyof RejectCardResponses];
|
||||
|
||||
export type PublishInstagramData = {
|
||||
body?: never;
|
||||
headers?: {
|
||||
/**
|
||||
* X-Admin-Key
|
||||
*/
|
||||
'x-admin-key'?: string | null;
|
||||
};
|
||||
path: {
|
||||
/**
|
||||
* Card Id
|
||||
*/
|
||||
card_id: number;
|
||||
};
|
||||
query?: never;
|
||||
url: '/v1/card/{card_id}/instagram';
|
||||
};
|
||||
|
||||
export type PublishInstagramErrors = {
|
||||
/**
|
||||
* Validation Error
|
||||
*/
|
||||
422: HttpValidationError;
|
||||
};
|
||||
|
||||
export type PublishInstagramError = PublishInstagramErrors[keyof PublishInstagramErrors];
|
||||
|
||||
export type PublishInstagramResponses = {
|
||||
/**
|
||||
* Successful Response
|
||||
*/
|
||||
200: ResCard;
|
||||
};
|
||||
|
||||
export type PublishInstagramResponse = PublishInstagramResponses[keyof PublishInstagramResponses];
|
||||
|
||||
export type GetCardImageData = {
|
||||
body?: never;
|
||||
path: {
|
||||
|
||||
@@ -2,6 +2,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 '../api/client/@tanstack/react-query.gen'
|
||||
import { IS_TOSS } from '../lib/platform'
|
||||
import { cx } from '../lib/utils'
|
||||
import { kindOfHour, kst, seasonOf, type TimeKind } from './lib'
|
||||
import './b.css'
|
||||
@@ -12,6 +13,7 @@ import { useRegion } from './regionContext'
|
||||
import { useSheet } from './sheetContext'
|
||||
import { SheetProvider } from './Sheets'
|
||||
import { SkyContext, useSky } from './skyContext'
|
||||
import { TossIntro } from './tossIntro'
|
||||
import { PinIcon, TabIcon } from './svg'
|
||||
import { Avatar, Ic, Skel } from './ui'
|
||||
|
||||
@@ -60,7 +62,7 @@ function TopBar() {
|
||||
<PinIcon className="size-3.5 shrink-0" />
|
||||
{locateStatus === 'locating' ? <Skel className="w-[72px]" /> : <span className="truncate whitespace-nowrap"><span className="max-[399px]:hidden">{region.name}</span><span className="min-[400px]:hidden">{region.name.split(' ').at(-1)}</span></span>}
|
||||
</button>
|
||||
{mePending ? (
|
||||
{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)]">
|
||||
@@ -305,6 +307,7 @@ export function BLayout() {
|
||||
<RegionProvider>
|
||||
<SheetProvider>
|
||||
<Shell />
|
||||
<TossIntro />
|
||||
</SheetProvider>
|
||||
</RegionProvider>
|
||||
</AuthProvider>
|
||||
|
||||
@@ -302,8 +302,9 @@ function LineCard({ post }: PostProps) {
|
||||
)
|
||||
}
|
||||
|
||||
/** 인스타식 게시물: 옆으로 넘기는 슬라이드, 두 번 눌러 좋아요 */
|
||||
/** 인스타식 게시물: 옆으로 넘기는 슬라이드, 두 번 눌러 좋아요. 모르는 종류(서버에 새로 생긴 것)는 건너뛴다 */
|
||||
export function PostCard({ post }: PostProps) {
|
||||
if (!(post.post_type in ACCOUNTS)) return null
|
||||
return post.size === 'line' ? <LineCard post={post} /> : <FullCard post={post} />
|
||||
}
|
||||
|
||||
|
||||
@@ -20,6 +20,7 @@ import {
|
||||
} from '../api/client/@tanstack/react-query.gen'
|
||||
import { AuthProvider, type CommentData, type Factor, type ResAuth, type ResCommentList, type ResIndexDetail } from '../api/client/types.gen'
|
||||
import { track } from '../lib/analytics'
|
||||
import { IS_TOSS, tossShare } from '../lib/platform'
|
||||
import { cx } from '../lib/utils'
|
||||
import { useAuth } from './authContext'
|
||||
import { ago, ARTICLE_CAT, articleMeta, AVATAR_COLORS, cardBg, CHARACTERS, dateRange, loadOf, MOODS, shortDay } from './lib'
|
||||
@@ -562,6 +563,19 @@ function ShareSheet({ share }: { share: SharePayload }) {
|
||||
const send = () => {
|
||||
if (!image) return
|
||||
const file = new File([image.blob], `nalssigak-${SHARE_SIZES[size].ratio.replace(':', 'x')}.png`, { type: 'image/png' })
|
||||
if (IS_TOSS) {
|
||||
tossShare(image.blob, file.name, share.title).then(
|
||||
(r) => {
|
||||
setToast(r === 'saved' ? '이미지를 저장하고 링크를 보냈어요' : '링크를 보냈어요')
|
||||
track('share', { content_type: 'image', item_id: share.title, method: 'share_sheet', ratio: SHARE_SIZES[size].ratio })
|
||||
},
|
||||
(e: unknown) => {
|
||||
console.error('[share] toss', e)
|
||||
setToast('보내지 못했어요. 한 번 더 눌러 주세요')
|
||||
},
|
||||
)
|
||||
return
|
||||
}
|
||||
if (navigator.canShare?.({ files: [file], text, url: SITE_URL })) {
|
||||
const copied = navigator.clipboard?.writeText(SITE_URL).then(
|
||||
() => true,
|
||||
@@ -820,6 +834,7 @@ function LoginSheet({ onDone, onLoggedIn }: { onDone: () => void; onLoggedIn: ()
|
||||
const fail = () => setError('서버에 닿지 못했어요. 잠시 뒤에 다시 해 주세요.')
|
||||
|
||||
if (me) return <MeSheet onDone={onDone} />
|
||||
if (IS_TOSS) return <TossNoLoginSheet onDone={onDone} />
|
||||
|
||||
return (
|
||||
<Body>
|
||||
@@ -843,6 +858,18 @@ function LoginSheet({ onDone, onLoggedIn }: { onDone: () => void; onLoggedIn: ()
|
||||
)
|
||||
}
|
||||
|
||||
/** 토스판은 로그인이 없다. 로그인이 필요한 곳(두 번째 내 각)에서 안내만 한다 */
|
||||
function TossNoLoginSheet({ onDone }: { onDone: () => void }) {
|
||||
return (
|
||||
<Body className="flex flex-col gap-2.5">
|
||||
<p className="m-0 text-center text-sm font-semibold text-(--ink2)">토스에서는 내 각을 하나만 만들 수 있어요. 지금 각을 지우고 새로 만들어 주세요.</p>
|
||||
<button type="button" onClick={onDone} className="cursor-pointer rounded-[14px] bg-(--orange) p-[13px] font-jua text-[17px] text-white shadow-[inset_0_-5px_0_var(--orange-deep)]">
|
||||
알겠어요
|
||||
</button>
|
||||
</Body>
|
||||
)
|
||||
}
|
||||
|
||||
/* ---------- 내 정보: 캐릭터·닉네임·로그아웃 ---------- */
|
||||
function MeSheet({ onDone }: { onDone: () => void }) {
|
||||
const install = useInstall()
|
||||
@@ -880,7 +907,7 @@ function MeSheet({ onDone }: { onDone: () => void }) {
|
||||
<Body className="flex flex-col gap-3">
|
||||
<div className="flex flex-col items-center gap-1.5">
|
||||
<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.GOOGLE ? '구글 계정으로 로그인했어요' : `${me.login_id}(으)로 로그인했어요`}</p>
|
||||
<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>
|
||||
{installable && (
|
||||
<button type="button" onClick={() => install('menu')} className="cursor-pointer rounded-2xl bg-[#fff4ec] py-2.5 font-jua text-[15.5px] text-(--orange)">
|
||||
@@ -1046,12 +1073,12 @@ function RegionSheet({ onDone }: { onDone: () => void }) {
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
<p className="mt-4 flex items-center justify-center gap-2 text-[13px] font-bold text-(--ink2)">
|
||||
{!IS_TOSS && <p className="mt-4 flex items-center justify-center gap-2 text-[13px] font-bold text-(--ink2)">
|
||||
{me ? `${me.nickname}(으)로 로그인했어요` : '로그인하면 좋아요·댓글을 쓸 수 있어요'}
|
||||
<button type="button" onClick={me ? logout : () => open({ type: 'login' })} className="cursor-pointer font-extrabold text-(--rain)">
|
||||
{me ? '로그아웃' : '로그인'}
|
||||
</button>
|
||||
</p>
|
||||
</p>}
|
||||
</Body>
|
||||
)
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import regionPages from '../../seo/region.json'
|
||||
import { nearestRegion } from '../api/client/sdk.gen'
|
||||
import type { RegionData } from '../api/client/types.gen'
|
||||
import { track } from '../lib/analytics'
|
||||
import { IS_TOSS, tossLocation } from '../lib/platform'
|
||||
import { DEFAULT_REGION, ownPage, RegionContext, type LocateStatus } from './regionContext'
|
||||
|
||||
const KEY = 'nalssigak.b.region'
|
||||
@@ -55,8 +56,8 @@ export function RegionProvider({ children }: { children: ReactNode }) {
|
||||
const [chosen, setRegionState] = useState<RegionData>(() => (page ? regionIn(page, stored) : (stored ?? DEFAULT_REGION)))
|
||||
// 앱 안에서 다른 지역 페이지로 옮겨 가면 그 지역으로
|
||||
const region = page && !page.regions.some((g) => g.code === chosen.code) ? regionIn(page, stored) : chosen
|
||||
const canLocate = typeof navigator !== 'undefined' && 'geolocation' in navigator
|
||||
const [locateStatus, setLocateStatus] = useState<LocateStatus>(!landing && !stored && canLocate ? 'locating' : 'idle')
|
||||
const canLocate = IS_TOSS || (typeof navigator !== 'undefined' && 'geolocation' in navigator)
|
||||
const [locateStatus, setLocateStatus] = useState<LocateStatus>(!landing && (!stored || IS_TOSS) && canLocate ? 'locating' : 'idle')
|
||||
|
||||
// 지역 페이지에서 고르면 주소도 그 지역 페이지로 바꿔, 공유한 링크가 보던 화면과 같게 한다
|
||||
const setRegion = useCallback((r: RegionData) => {
|
||||
@@ -66,18 +67,33 @@ export function RegionProvider({ children }: { children: ReactNode }) {
|
||||
if (pageRef.current && next && next !== pageRef.current) navigate(`/${dayRef.current}/${next.path}`)
|
||||
}, [navigate])
|
||||
|
||||
// quiet 면 못 찾아도 상태를 바꾸지 않는다 (사람이 누른 게 아니라 안내 문구를 띄우지 않음)
|
||||
const findNearest = useCallback((apply: (r: RegionData) => void, quiet = false) => {
|
||||
// quiet 면 못 찾아도 상태를 바꾸지 않는다 (사람이 누른 게 아니라 안내 문구를 띄우지 않음). ask=false 면 토스에서 권한 창 없이, 이미 허용한 사람만
|
||||
const findNearest = useCallback((apply: (r: RegionData) => void, quiet = false, ask = true) => {
|
||||
const fromCoords = (lat: number, lon: number) => {
|
||||
nearestRegion({ query: { lat, lon } })
|
||||
.then(({ data: res }) => {
|
||||
if (!res.region) throw new Error('가까운 구를 찾지 못함')
|
||||
setLocateStatus('idle')
|
||||
apply(res.region)
|
||||
})
|
||||
.catch(() => !quiet && setLocateStatus('error'))
|
||||
}
|
||||
if (IS_TOSS) {
|
||||
tossLocation(ask).then(
|
||||
(loc) => {
|
||||
if (loc === null) setLocateStatus('idle')
|
||||
else if (loc === 'denied') setLocateStatus(quiet ? 'idle' : 'denied')
|
||||
else fromCoords(loc.lat, loc.lon)
|
||||
},
|
||||
(e: unknown) => {
|
||||
console.error('[region] toss location', e)
|
||||
setLocateStatus(quiet ? 'idle' : 'error')
|
||||
},
|
||||
)
|
||||
return
|
||||
}
|
||||
navigator.geolocation.getCurrentPosition(
|
||||
(pos) => {
|
||||
nearestRegion({ query: { lat: pos.coords.latitude, lon: pos.coords.longitude } })
|
||||
.then(({ data: res }) => {
|
||||
if (!res.region) throw new Error('가까운 구를 찾지 못함')
|
||||
setLocateStatus('idle')
|
||||
apply(res.region)
|
||||
})
|
||||
.catch(() => !quiet && setLocateStatus('error'))
|
||||
},
|
||||
(pos) => fromCoords(pos.coords.latitude, pos.coords.longitude),
|
||||
(err) => !quiet && setLocateStatus(err.code === err.PERMISSION_DENIED ? 'denied' : 'error'),
|
||||
{ timeout: 10000, maximumAge: 600000 },
|
||||
)
|
||||
@@ -98,14 +114,14 @@ export function RegionProvider({ children }: { children: ReactNode }) {
|
||||
|
||||
useEffect(() => {
|
||||
if (!canLocate) return
|
||||
// 처음 온 사람만 위치 권한을 물어 가장 가까운 구로 맞춘다
|
||||
// 처음 온 사람은 위치 권한을 물어 가장 가까운 구로 맞춘다. 토스판은 지역을 고른 적 있어도 권한이 있으면 들어올 때마다 지금 위치로
|
||||
if (!landing) {
|
||||
if (!stored) {
|
||||
findNearest((r) => {
|
||||
setRegion(r)
|
||||
track('region_change', { region_name: r.name, method: 'location' })
|
||||
})
|
||||
const apply = (r: RegionData) => {
|
||||
setRegion(r)
|
||||
track('region_change', { region_name: r.name, method: 'location' })
|
||||
}
|
||||
if (!stored) findNearest(apply)
|
||||
else if (IS_TOSS) findNearest(apply, false, false)
|
||||
return
|
||||
}
|
||||
// 지역 페이지로 들어오면 그 지역을 보여 준다. 구로 나뉜 시는 위치를 이미 허용했고 그 시 안에 있으면 지금 있는 구로
|
||||
|
||||
@@ -12,6 +12,7 @@ import {
|
||||
import { uploadTalkImage } from '../api/client/sdk.gen'
|
||||
import { TalkReport, TalkTopic, type TalkData } from '../api/client/types.gen'
|
||||
import { API_BASE_URL } from '../api/setup'
|
||||
import { IS_TOSS } from '../lib/platform'
|
||||
import { cx } from '../lib/utils'
|
||||
import { useAuth } from './authContext'
|
||||
import { ago, kst } from './lib'
|
||||
@@ -251,10 +252,15 @@ function TalkRow({ t, onGone, compact }: { t: TalkData; onGone?: () => void; com
|
||||
)}
|
||||
{t.image && !compact && <img src={src} alt="" loading="lazy" className="mt-2 aspect-[4/5] w-full rounded-2xl bg-[#eef4fc] object-cover" />}
|
||||
<small className={cx('block text-xs font-bold text-(--ink3)', compact ? 'mt-auto pt-1.5' : 'mt-0.5')}>
|
||||
{ago(t.created_at)} · 좋아요 {count}개 ·{' '}
|
||||
<button type="button" onClick={() => setMenu(menu === 'closed' ? 'open' : 'closed')} aria-expanded={menu !== 'closed'} className="cursor-pointer font-bold text-(--ink3)">
|
||||
{t.mine ? '내 글' : '더보기'}
|
||||
</button>
|
||||
{ago(t.created_at)} · 좋아요 {count}개
|
||||
{!IS_TOSS && (
|
||||
<>
|
||||
{' · '}
|
||||
<button type="button" onClick={() => setMenu(menu === 'closed' ? 'open' : 'closed')} aria-expanded={menu !== 'closed'} className="cursor-pointer font-bold text-(--ink3)">
|
||||
{t.mine ? '내 글' : '더보기'}
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
</small>
|
||||
{menu !== 'closed' && (
|
||||
<div className="mt-1.5 flex flex-wrap gap-1.5 text-[12.5px] font-extrabold" role="group" aria-label="글 메뉴">
|
||||
@@ -298,6 +304,7 @@ function TalkRow({ t, onGone, compact }: { t: TalkData; onGone?: () => void; com
|
||||
/** 이야기 탭: 쓰기 칸과 전국 최신 글 (아래로 더 받기) */
|
||||
/** 피드 위 쓰는 칸. 늘 펼쳐 두고, 방금 올린 글은 바로 아래에 보인다 (피드 사이 글은 새로 받을 때 섞인다) */
|
||||
export function FeedComposer({ onPosted }: { onPosted: (t: TalkData) => void }) {
|
||||
if (IS_TOSS) return null
|
||||
return (
|
||||
<div className="mt-3.5">
|
||||
<Composer onDone={onPosted} />
|
||||
@@ -367,7 +374,8 @@ export function FirstTalkCard() {
|
||||
/** '동네 사람들' 자리: 글이 GROUP_MIN 개 이상이면 묶음, 아니면 첫 글 쓰기 */
|
||||
export function NearTalks({ talks, loaded }: { talks: TalkData[]; loaded: boolean }) {
|
||||
if (!loaded) return null
|
||||
return talks.length >= GROUP_MIN ? <TalkGroup title="동네 사람들" talks={talks} /> : <FirstTalkCard />
|
||||
if (talks.length >= GROUP_MIN) return <TalkGroup title="동네 사람들" talks={talks} />
|
||||
return IS_TOSS ? null : <FirstTalkCard />
|
||||
}
|
||||
|
||||
/** 내 정보 창의 내가 쓴 글 */
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
import { useState } from 'react'
|
||||
import { IS_TOSS } from '../lib/platform'
|
||||
import { Ic } from './ui'
|
||||
|
||||
const KEY = 'nalssigak.b.tossIntroSeen'
|
||||
|
||||
const POINTS = [
|
||||
['sun', '세차·빨래·러닝 각 점수'],
|
||||
['sunset', '오늘 노을이 예쁜 시간'],
|
||||
['fireworks', '이번 주말 가까운 행사'],
|
||||
] as const
|
||||
|
||||
function seen() {
|
||||
try {
|
||||
return localStorage.getItem(KEY) === '1'
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
/** 토스판을 처음 열면 서비스 소개를 먼저 보여 준다 (앱인토스 검수: 로그인 전에 서비스 설명) */
|
||||
export function TossIntro() {
|
||||
const [open, setOpen] = useState(() => IS_TOSS && !seen())
|
||||
if (!open) return null
|
||||
|
||||
const start = () => {
|
||||
try {
|
||||
localStorage.setItem(KEY, '1')
|
||||
} catch (e) {
|
||||
console.warn('[intro] 본 기록을 저장하지 못함', e)
|
||||
}
|
||||
setOpen(false)
|
||||
}
|
||||
|
||||
return (
|
||||
<div role="dialog" aria-modal="true" aria-labelledby="toss-intro-title" className="fixed inset-0 z-70 flex flex-col items-center justify-center gap-6 bg-[#d6ebff] px-8 text-(--ink)">
|
||||
<Ic name="rabbit" className="w-24" />
|
||||
<div className="text-center">
|
||||
<h1 id="toss-intro-title" className="m-0 font-jua text-[28px] font-normal">
|
||||
날씨각
|
||||
</h1>
|
||||
<p className="m-0 mt-1.5 text-[15px] font-semibold text-(--ink2)">오늘 날씨에 맞는 일을 점수로 알려 줘요</p>
|
||||
</div>
|
||||
<ul className="m-0 flex w-full max-w-xs list-none flex-col gap-2.5 p-0">
|
||||
{POINTS.map(([icon, label]) => (
|
||||
<li key={label} className="flex items-center gap-3 rounded-[18px] bg-white/80 px-4 py-3 text-[15px] font-extrabold">
|
||||
<Ic name={icon} className="w-8 shrink-0" />
|
||||
{label}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
<button type="button" onClick={start} className="w-full max-w-xs cursor-pointer rounded-[14px] bg-(--orange) p-[13px] font-jua text-[17px] text-white shadow-[inset_0_-5px_0_var(--orange-deep)]">
|
||||
시작하기
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
import { useState, type CSSProperties, type ReactNode } from 'react'
|
||||
import { Link } from 'react-router'
|
||||
import { IS_TOSS } from '../lib/platform'
|
||||
import { cx } from '../lib/utils'
|
||||
import { useCarousel, type Carousel } from './carousel'
|
||||
import { AVATAR_COLORS, iconSrc, moodEmoji, naverMap, type Load } from './lib'
|
||||
@@ -202,6 +203,8 @@ export function StateBox({ load, onRetry, empty, className, hold }: StateProps)
|
||||
/** 줄 목록 (라벨 · 값) */
|
||||
/** 위치가 정해진 장소 이름. 누르면 네이버 지도가 새 탭으로 열린다 */
|
||||
export function MapLink({ place, children, className }: { place: string; children: ReactNode; className?: string }) {
|
||||
// 앱인토스는 외부 이동을 막는다
|
||||
if (IS_TOSS) return <span className={className}>{children}</span>
|
||||
return (
|
||||
<a href={naverMap(place)} target="_blank" rel="noopener noreferrer" aria-label={`${place}, 네이버 지도에서 보기`} className={cx('underline decoration-dotted decoration-1 underline-offset-[3px]', className)}>
|
||||
{children}
|
||||
|
||||
@@ -3,7 +3,7 @@ type Events = {
|
||||
view_gak: { index_id: number; gak_name: string; score: number; rank: number }
|
||||
select_content: { content_type: 'article'; item_id: number; category: string }
|
||||
share: { content_type: 'image'; item_id: string; method: 'share_sheet' | 'download'; ratio: string }
|
||||
login: { method: 'id' | 'google' }
|
||||
login: { method: 'id' | 'google' | 'toss' }
|
||||
sign_up: { method: 'id' }
|
||||
region_change: { region_name: string; method: 'list' | 'location' }
|
||||
install_banner_view: Record<string, never>
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
/** 웹/앱인토스 차이를 모으는 곳. 토스 SDK 는 토스 빌드(`vite build --mode toss`)에서만 불러온다 */
|
||||
export const IS_TOSS = import.meta.env.MODE === 'toss'
|
||||
|
||||
const TOSS_APP = 'intoss://nalssigak'
|
||||
|
||||
// 웹 빌드에서는 이 분기가 지워져 SDK 가 번들에 들어가지 않는다
|
||||
const sdk = () => (import.meta.env.MODE === 'toss' ? import('@apps-in-toss/web-framework') : Promise.reject(new Error('토스 앱 밖에서는 쓸 수 없어요')))
|
||||
|
||||
function toBase64(blob: Blob): Promise<string> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const reader = new FileReader()
|
||||
reader.onload = () => resolve(String(reader.result).split(',')[1] ?? '')
|
||||
reader.onerror = () => reject(reader.error)
|
||||
reader.readAsDataURL(blob)
|
||||
})
|
||||
}
|
||||
|
||||
/** 토스: 이미지를 기기에 저장하고 토스 앱 링크를 공유창으로 보낸다 */
|
||||
export async function tossShare(image: Blob, fileName: string, title: string): Promise<'saved' | 'link-only'> {
|
||||
const { File, Share } = await sdk()
|
||||
let saved = false
|
||||
if (File.saveBase64.isSupported()) {
|
||||
await File.saveBase64({ data: await toBase64(image), fileName, mimeType: image.type })
|
||||
saved = true
|
||||
}
|
||||
const link = await Share.createLink({ path: TOSS_APP })
|
||||
await Share.sendMessage({ message: `${title} · 날씨각 ${link}` })
|
||||
return saved ? 'saved' : 'link-only'
|
||||
}
|
||||
|
||||
/** 토스: 토스 로그인 창을 띄우고 서버로 보낼 인가 코드를 받는다 */
|
||||
export async function tossLogin() {
|
||||
const { TossAuth } = await sdk()
|
||||
return TossAuth.login()
|
||||
}
|
||||
|
||||
export type TossLocation = { lat: number; lon: number } | 'denied'
|
||||
|
||||
/** 토스: 위치를 읽는다. 권한이 없으면 ask 일 때만 권한 창을 띄운다 */
|
||||
export async function tossLocation(ask: boolean): Promise<TossLocation | null> {
|
||||
const { Accuracy, Device } = await sdk()
|
||||
let status = await Device.getLocation.getPermission()
|
||||
if (status !== 'allowed' && ask) status = await Device.getLocation.openPermissionDialog()
|
||||
if (status !== 'allowed') return ask ? 'denied' : null
|
||||
const { coords } = await Device.getLocation({ accuracy: Accuracy.Balanced })
|
||||
return { lat: coords.latitude, lon: coords.longitude }
|
||||
}
|
||||
@@ -19,5 +19,5 @@
|
||||
"erasableSyntaxOnly": true,
|
||||
"noFallthroughCasesInSwitch": true
|
||||
},
|
||||
"include": ["vite.config.ts"]
|
||||
"include": ["vite.config.ts", "apps-in-toss.config.ts"]
|
||||
}
|
||||
@@ -2,7 +2,7 @@ import { mkdirSync, readdirSync, readFileSync, writeFileSync } from 'node:fs'
|
||||
import { dirname, resolve } from 'node:path'
|
||||
import tailwindcss from '@tailwindcss/vite'
|
||||
import react from '@vitejs/plugin-react'
|
||||
import { defineConfig, type Plugin } from 'vite'
|
||||
import { defineConfig, loadEnv, type Plugin } from 'vite'
|
||||
|
||||
type Gak = { name: string; description: string }
|
||||
type RegionPage = { path: string; name: string; main: string; regions: { code: string; name: string }[] }
|
||||
@@ -253,7 +253,19 @@ function seoPages(): Plugin {
|
||||
}
|
||||
}
|
||||
|
||||
// 토스 빌드는 토스 도메인에서 열리므로 API·사이트 주소를 HTTPS 절대 주소로 받아야 한다
|
||||
function checkTossEnv(mode: string) {
|
||||
if (mode !== 'toss') return
|
||||
const env = loadEnv(mode, process.cwd())
|
||||
for (const key of ['VITE_API_BASE_URL', 'VITE_SITE_URL']) {
|
||||
if (!env[key]?.startsWith('https://')) throw new Error(`토스 빌드: ${key} 에 https:// 주소가 필요해요 (frontend/.env.toss)`)
|
||||
}
|
||||
}
|
||||
|
||||
// https://vite.dev/config/
|
||||
export default defineConfig({
|
||||
plugins: [react(), tailwindcss(), seoPages()],
|
||||
export default defineConfig(({ mode }) => {
|
||||
checkTossEnv(mode)
|
||||
return {
|
||||
plugins: [react(), tailwindcss(), ...(mode === 'toss' ? [] : [seoPages()])],
|
||||
}
|
||||
})
|
||||