Compare commits
64
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
aa05d870a2 | ||
|
|
cac6ea236f | ||
|
|
d6525f592c | ||
|
|
ffc330d478 | ||
|
|
7b5d905298 | ||
|
|
91deb28ec3 | ||
|
|
76a640feab | ||
|
|
1fa0695c84 | ||
|
|
5734b57758 | ||
|
|
2fe00c916e | ||
|
|
b889f69135 | ||
|
|
0436971cf1 | ||
|
|
78aad46946 | ||
|
|
c468f91212 | ||
|
|
f1a46ea4a2 | ||
|
|
a5fc6c92b5 | ||
|
|
3857ef8d14 | ||
|
|
b4fcb313c7 | ||
|
|
c7152563b9 | ||
|
|
0a1544c7f3 | ||
|
|
d2438ec74c | ||
|
|
91a86a2c10 | ||
|
|
cd6769ccef | ||
|
|
3e376ae4b8 | ||
|
|
e059e294d0 | ||
|
|
ce6efe979a | ||
|
|
3cc0da6195 | ||
|
|
90c4a36c25 | ||
|
|
dddd52475e | ||
|
|
17e29d7e31 | ||
|
|
58c9d38474 | ||
|
|
343e3ee2fb | ||
|
|
f6ddc67f77 | ||
|
|
f9e927aece | ||
|
|
d6cedcdec7 | ||
|
|
116f644bb7 | ||
|
|
59fb09a83c | ||
|
|
23629eeb68 | ||
|
|
177e14b990 | ||
|
|
dce9238cef | ||
|
|
f1846ddf66 | ||
|
|
9e80db8310 | ||
|
|
d5dc8e0727 | ||
|
|
471353212a | ||
|
|
64bdbcae39 | ||
|
|
d54606613e | ||
|
|
93232575d2 | ||
|
|
242d6cb2cb | ||
|
|
a297c7d8f5 | ||
|
|
ba62e82f1b | ||
|
|
b130b32f0b | ||
|
|
87055a73dc | ||
|
|
dd1e28ad3e | ||
|
|
46087e64da | ||
|
|
e8382f450b | ||
|
|
498e4d677a | ||
|
|
c00623e690 | ||
|
|
e923a0760b | ||
|
|
4d420153ec | ||
|
|
f4d5472776 | ||
|
|
73294622ad | ||
|
|
4ebf1cd894 | ||
|
|
2ce1fa2aed | ||
|
|
e9cb07be60 |
No files matched your search
+1
-1
@@ -5,7 +5,7 @@
|
||||
DATA_GO_KR_SERVICE_KEY=
|
||||
# 행사 수집(7일마다) 완료 알림 — Microsoft Teams Workflows 수신 webhook. 비우면 보내지 않는다.
|
||||
TEAMS_WEBHOOK_URL=
|
||||
IMAGE_PROXY_HOSTS=tong.visitkorea.or.kr,www.culture.go.kr
|
||||
IMAGE_PROXY_HOSTS=tong.visitkorea.or.kr,www.culture.go.kr,culture.seoul.go.kr
|
||||
|
||||
# ── 백엔드: DB·Redis (네이티브 실행 기준. compose 안에서는 compose.yaml 이 host·port 를 덮어쓴다)
|
||||
DB_HOST=localhost
|
||||
|
||||
@@ -1,5 +1,20 @@
|
||||
# TODO
|
||||
|
||||
## 출시 전 (10/8 확정)
|
||||
|
||||
| 상태 | 할 일 | 이유 | 관련 파일 |
|
||||
|---|---|---|---|
|
||||
| [x] | 계절 소식 사진 연결 (11장) | 출시 전 | `frontend/public/season/`, `backend/seed/article.json` |
|
||||
| [x] | 노을 명소 보강 — 30km 안 명소 없는 구 89 → 23 | 출시 전 | `backend/seed/sunset_spot.csv` |
|
||||
| [x] | 기능 QA 작성 (`docs/QA_체크리스트.md` 100항목) + 찾은 버그 수정 | 출시 전 | `docs/QA_체크리스트.md` |
|
||||
| [ ] | 모바일 실기기 테스트 (QA 체크리스트로) | 출시 전 | `docs/QA_체크리스트.md` |
|
||||
| [x] | 각 늘리기 27 → 34 + 순위에 중요도 반영 | 출시 전 | `backend/seed/index_definition.json` |
|
||||
| [x] | 노치 대응 — 상단 띠 불투명, 시간대별 `theme-color` | 출시 전 | `frontend/index.html`, `frontend/src/b/BLayout.tsx` |
|
||||
| [x] | 데이트 명소 전국 (2,445곳, 30km) | 출시 전 | `backend/seed/place_tourapi.csv` |
|
||||
| [x] | 좋아요·댓글 시도 단위로 나누기 | 출시 전 | `backend/services/feed_service.py` |
|
||||
| [x] | 노을 판정 확인 방법·SEO 방식 — 추천안을 아래 [결정 필요] 행에 정리 | 출시 전 | |
|
||||
| [ ] | `release/launch-1008` → main 병합, 킹서버 배포, 시드 재적재·`feed:*` 캐시 삭제, 운영 JWT 비밀키 교체 (운영 영향, 확인 받고) | 출시 | `deploy.sh`, `backend/scripts/load_seed.py` |
|
||||
|
||||
## 진행 순서
|
||||
|
||||
결정이 필요 없는 것부터, 사용자 눈에 틀린 정보가 보이는 것 → 기능 → 다듬기 순.
|
||||
@@ -22,9 +37,11 @@
|
||||
| [x] | 행사 독립 카드 최대 3장, 피드 무작위 노출 (하루 같은 자리) | 10/2 회의 | `backend/services/feed_service.py` |
|
||||
| [x] | 계절 소식 제철 7개 추가 (햇밤·햇땅콩·은행·고구마·귤·부사·김장) — 피드백 대기 | 10/2 회의 | `backend/seed/article.json` |
|
||||
| [x] | 새 각 추가 (야구·공부·넷플릭스·군밤) | 10/2 회의 | `backend/seed/index_definition.json` |
|
||||
| [x] | 각 늘리기 27→34 (골프·집콕·낚시·드라이브·연날리기·물놀이·김장), 집콕각은 미세먼지 탁할수록 좋게 | 사용자 요청 | `backend/seed/index_definition.json`, `backend/services/calc/index_calc.py` |
|
||||
| [x] | 주말 전국 지역 랭킹 — 노을 순위 대표 30곳의 토·일 '나들이 날씨 점수'(낮 10~17시 비 40·기온 35·하늘 15·바람 10, 비 60%↑면 최대 30점) 순위. `GET /v1/week/ranking`, 주말 화면 '이번 주말 전국 날씨 순위'(토/일 탭, 10위까지). 워커가 06:40·18:40에 계산해 Redis에 13시간 저장, 없으면 API가 그 자리에서 계산 | 10/2 회의 최종 그림 | `backend/services/weekend_rank.py`, `backend/services/calc/index_calc.py` (`outing`), `frontend/src/b/WeekPage.tsx` |
|
||||
| [x] | 노을 명소 지역별 목록 연결 — 지금 명소 데이터가 서울 마포구 3곳뿐이고 구 코드로만 찾아서 분당구 등은 하나도 안 나옴 | 10/2 회의 (추후), 사용자 지적 | `backend/seed/sunset_spot.csv`, `backend/services/sky_service.py` |
|
||||
| [ ] | 노을 명소 30km 안에 하나도 없는 구 89/256 — 광주·대전·세종·충북·강원·경북 내륙·전북 내륙 등. TourAPI 키워드로는 안 잡혀 직접 추가하거나 반경을 넓힐지 결정 필요 | 명소 확충 결과 | `backend/seed/sunset_spot.csv`, `backend/services/sky_service.py` |
|
||||
| [x] | 노을 명소 30km 안에 하나도 없는 구 89/256 — 광주·대전·세종·충북·강원·경북 내륙·전북 내륙 등. TourAPI 키워드로는 안 잡혀 직접 추가하거나 반경을 넓힐지 결정 필요 → 노을 근거를 확인한 21곳을 추가해 89 → 23 | 명소 확충 결과 | `backend/seed/sunset_spot.csv`, `backend/services/sky_service.py` |
|
||||
| [ ] | 노을 명소 30km 안에 없는 구 23/256(최대 51.8km, 지금은 가장 가까운 1곳을 거리와 함께 보여 줌) — 강원 동해·삼척·양구·인제·태백·횡성, 경남 거창·산청·함양, 경북 구미·김천·봉화·안동·울진·의성, 대구 군위, 전남 곡성·구례, 전북 남원·임실·장수·진안, 충북 보은. 노을 근거를 찾지 못함. 반경 밖이면 화면엔 '근처에 등록된 노을 명소가 없어요'만 나오고 가장 가까운 곳·거리는 안 나옴 | 명소 보강 결과 | `backend/seed/sunset_spot.csv`, `backend/services/sky_service.py` (`nearest_spots`), `frontend/src/b/SkyPage.tsx` |
|
||||
| [x] | 명소 '서쪽이 트임'(west_open)·설명 꼬리말은 TourAPI 개요를 보고 사람이 붙인 값 — 현장 확인 안 됨. 분당구는 가장 가까운 곳이 17~18km(일자산·반포·광나루)라 수도권 동남부 명소 보강 필요 → 화면에서 설명을 빼고 방향·거리만 보여줌. 현장 확인은 여전히 안 됨 | 명소 확충 결과 | `backend/seed/sunset_spot.csv` |
|
||||
| [ ] | TourAPI 좌표 오류로 뺀 곳: 기흥레스피아호수공원(용인)·급치산전망대(진도) — 좌표가 (19.69, 117.99). 좌표를 직접 넣어 추가할지 결정 | 명소 확충 결과 | `backend/seed/sunset_spot_tourapi.csv` |
|
||||
| [x] | 서울·경기 반영 범위 확인 — 서울 25구·경기 31시군(구 있는 시는 구 단위, 부천 3구·화성 4구 포함) 모두 있고 코드도 기상청 격자표(2607) 현행 코드와 일치 | 10/2 회의 확인 필요 | `backend/seed/region.csv` |
|
||||
@@ -47,11 +64,11 @@
|
||||
| [ ] | 월요일 0시~06:40엔 새 주말 점수가 아직 없어 당일치기 카드가 꺼짐 (주말 화면 순위는 그 자리에서 계산해 채움). 필요하면 03:00 작업에도 계산 추가 | 당일치기 작업 중 발견 | `backend/worker_main.py`, `backend/scheduler/jobs.py` |
|
||||
| [ ] | 주말 점수 계산이 대표 지역·후보 도시 34곳 예보를 받음 — 1회 기상청 단기 최대 34(처음엔 68)·중기 68건, 하루 2회 ≈ 200건. 당일치기 도시 행사는 그 도시 주변 시도 TourAPI·문화정보(시도별 하루 1회 캐시). 운영 배포 때 일일 한도와 함께 확인 | 주말 랭킹 작업 | `backend/services/weekend_rank.py`, `backend/docs/load-estimate.md` |
|
||||
| [ ] | 기상청 vs Open-Meteo 정확도 비교 — 두 예보를 3일 모아 기상청 실황과 맞춰 봄 (비 오는 날 포함). 10/6 비교는 전국 맑음이라 비 판단 근거가 약함 | 운영적합성 점검 | `backend/scripts/compare_open_meteo.py` |
|
||||
| [ ] | **[결정 필요]** 각 순위에 중요도 반영 — 점수만으로 정해 환기·세차각이 상위권. 안: `index_definition.priority`(상/중/하) 추가, 정렬은 점수×가중치(상 1.0·중 0.85·하 0.7), 표시 점수는 그대로. 정할 것: 등급 배정(초안 — 상: 빨래·산책·피크닉·등산·캠핑·러닝·자전거 / 중: 야장·치맥·별보기·멍뭉산책·사진산책·김서림·화장붕괴·택시대란·배달폭주 / 하: 환기·세차·가드닝·야구·짬뽕·막걸리·뜨아·냉면·공부·넷플릭스·군밤), 가중치 값, 로컬·운영 DB `ALTER TABLE index_definition ADD COLUMN priority SMALLINT NOT NULL DEFAULT 2` 실행 | 사용자 지적 | `backend/services/index_service.py:119`, `backend/common/database/model/models.py`, `backend/postgres-init/init.sql`, `backend/seed/index_definition.json` |
|
||||
| [x] | 각 순위에 중요도 반영 — 점수만으로 정해 환기·세차각이 상위권. 안: `index_definition.priority`(상/중/하) 추가, 정렬은 점수×가중치(상 1.0·중 0.85·하 0.7), 표시 점수는 그대로. 정할 것: 등급 배정(초안 — 상: 빨래·산책·피크닉·등산·캠핑·러닝·자전거 / 중: 야장·치맥·별보기·멍뭉산책·사진산책·김서림·화장붕괴·택시대란·배달폭주 / 하: 환기·세차·가드닝·야구·짬뽕·막걸리·뜨아·냉면·공부·넷플릭스·군밤), 가중치 값, 로컬·운영 DB `ALTER TABLE index_definition ADD COLUMN priority SMALLINT NOT NULL DEFAULT 2` 실행 | 사용자 지적 | `backend/services/index_service.py:119`, `backend/common/database/model/models.py`, `backend/postgres-init/init.sql`, `backend/seed/index_definition.json` |
|
||||
| [x] | 각 상세 창 점수 칸을 오늘/내일/토/일로 — 단기예보(시간별)는 약 4일 뒤까지라 월~수엔 주말 점수를 같은 방식으로 못 냄. 안: 범위 밖 주말은 중기예보(기온·비 확률)로 대략 점수 + "예상" 표시, 오늘·내일이 주말이면 다음 주말 표시 | 사용자 요청 | `backend/services/index_service.py` (`DAYS = 3`), `frontend/src/b/Sheets.tsx` |
|
||||
| [x] | 그날 밤 달 모양 — 밤 히어로에 달 모양·밝기, 보름·삭인 밤엔 '오늘 밤 달' 포스트 (사용자 결정 1·4안). 보름·삭 시각은 Meeus 계산(오차 2분 안) — 계산은 `moon.py`로 외부 API 없이 가능 | 사용자 질문 | `backend/services/calc/moon.py` |
|
||||
| [ ] | **[결정 필요]** 각과 상관없는 요소 비중 — 김서림각 바람, 택시대란·배달폭주·넷플릭스각 습도가 '상관없음'인데 비중 5%라 항상 50점으로 섞임. 0으로 할지 / 짬뽕·배달폭주각에 '공기 맑음' 5%가 좋은 쪽으로 들어가는 게 맞는지 | 6각 차트 수정 중 발견 | `backend/seed/index_definition.json` |
|
||||
| [ ] | **[결정 필요]** 계절 이야기 사진 — CC BY-SA 등 8장은 저작자·라이선스 표시 필요(표시 위치 정하기), `howgak` 글은 맞는 사진 없음(일러스트/아이콘), `tangerine`(퍼블릭 도메인) 사용 여부, `di`(매미)·`peanut_new`(일본 삶은 땅콩) 주제 적합성 | 사진 수집 중 발견 | `frontend/public/season/sources.json` |
|
||||
| [x] | **[결정 필요]** 계절 이야기 사진 — CC BY-SA 등 8장은 저작자·라이선스 표시 필요(표시 위치 정하기), `howgak` 글은 맞는 사진 없음(일러스트/아이콘), `tangerine`(퍼블릭 도메인) 사용 여부, `di`(매미)·`peanut_new`(일본 삶은 땅콩) 주제 적합성 | 사진 수집 중 발견 | `frontend/public/season/sources.json` |
|
||||
| [x] | 포스트 본문이 슬라이드 내용 반복 — 축제("N월 N일부터…까지예요" = 기간 줄), 오늘 날씨, 생활 알림, 내일 미리보기, 한 문장, 각, 노을. 본문엔 슬라이드에 없는 한 줄만 | 전체 검수 | `backend/services/feed_service.py` |
|
||||
| [x] | 아이콘 오용 — 밤 '한 문장' 카드에 망원경(`stars`), 폭염·한파 특보에도 우산 아이콘·"☔ 우산 챙겨!", 흐린 날 노을 시간대 칸에 노을 그림, 데이터 없는 칸에 해·구름 그림, 흐려도 "맑음"·해 그림(주말 플랜·주말 화면), 행사 아이콘 `calendar`/`fireworks` 혼용 | 전체 검수 | `backend/seed/article.json:103,117`, `backend/services/feed_service.py:420`, `backend/services/weather_service.py:85,94`, `backend/services/weekend_plan.py:52,95,116`, `frontend/src/b/WeekPage.tsx:85` |
|
||||
| [x] | 뜻 모를 표시 — "출처: 날씨각 (검수 전 예시)" 노출, "41번째 주", "해 지는 쪽 263°", 점수 뒤 "점" 없음, "추천: 피크닉각 추천", 노을 시각 18:12/6:12 이중 표기, 날짜 "10.04"/"10.4" 혼용, "구름많음"/"구름 많음" 혼용 | 전체 검수 | `backend/seed/article.json`, `frontend/src/b/SeasonPage.tsx:32`, `frontend/src/b/SkyPage.tsx`, `frontend/src/b/WeekPage.tsx:69` |
|
||||
@@ -64,7 +81,8 @@
|
||||
| [ ] | 문화정보 API 승인 후 실제 응답 확인 — 지금 `SERVICE_KEY_IS_NOT_REGISTERED_ERROR`(403). 날짜 형식, `gpsX`/`gpsY` 순서, 썸네일 https 여부 확인. 승인 직후 바로 보려면 Redis `event:{sido}:{날짜}` 키 삭제 | 전시 연결 중 발견 | `backend/services/external/culture_api.py` |
|
||||
| [ ] | **[결정 필요]** 두 달 넘는 전시가 `MAX_EVENT_DAYS = 60` 필터에 걸려 빠짐 — 전시는 기준을 따로 둘지 | 전시 연결 중 발견 | `backend/services/week_service.py` |
|
||||
| [ ] | 전시 썸네일 저작권 확인 — 데이터셋은 '이용허락범위 제한 없음'이나 원저작권이 주최 기관에 있을 수 있음 | 전시 연결 중 발견 | `backend/services/week_service.py` (`image_credit`) |
|
||||
| [ ] | 계절 이야기 사진 연결 — 받은 13장(`frontend/public/season/`)을 `article`에 사진 칸 추가해 띠·목록·상세·피드에 표시, CC BY 계열은 저작자·라이선스 표시. 스켈레톤 작업 끝난 뒤 진행 | 사용자 요청 | `backend/common/database/model/models.py`, `backend/seed/article.json`, `frontend/src/b/SeasonPage.tsx`, `frontend/src/b/Sheets.tsx`, `frontend/src/b/TodayPage.tsx` |
|
||||
| [x] | 계절 이야기 사진 연결 — 받은 13장(`frontend/public/season/`)을 `article`에 사진 칸 추가해 띠·목록·상세·피드에 표시, CC BY 계열은 저작자·라이선스 표시. 스켈레톤 작업 끝난 뒤 진행 | 사용자 요청 | `backend/common/database/model/models.py`, `backend/seed/article.json`, `frontend/src/b/SeasonPage.tsx`, `frontend/src/b/Sheets.tsx`, `frontend/src/b/TodayPage.tsx` |
|
||||
| [ ] | **[결정 필요]** 계절 이야기 사진 2장 안 씀 — `di.jpg`(매미)는 불쾌지수 글과 주제가 다르고, `peanut_new.jpg`(일본 가토리시 삶은 땅콩, 왼쪽은 일본 대립종)는 '국산 햇땅콩' 글과 맞지 않아 아이콘 유지. 맞는 사진을 새로 구할지 | 계절 이야기 사진 연결 중 판단 | `frontend/public/season/sources.json`, `backend/seed/article.json` |
|
||||
| [x] | (로컬 반영함, 운영 DB는 배포 때 같은 ALTER 필요) 로컬 DB 칼럼 추가 후 백엔드·워커 컨테이너 다시 빌드 — 지금 9810 백엔드는 이미지로 떠 있어 이번 백엔드 수정이 화면에 안 보임. 필요한 ALTER: `weather_daily.rain_prob_am`/`rain_prob_pm SMALLINT NULL`, `index_score.estimated BOOLEAN NOT NULL DEFAULT false`. 진행 중인 백엔드 작업이 끝난 뒤 실행 | 오늘/내일/토/일 작업 중 발견 | `backend/postgres-init/init.sql`, `compose.yaml` |
|
||||
| [ ] | **[결정 필요]** 확정 시안(`docs/시안_B_확정.html` 489·585행, `.trend3`)에 각 점수 칸이 아직 "오늘·내일·모레" 3칸 — 실제는 오늘/내일/토/일 4칸. 시안도 고칠지 | 오늘/내일/토/일 작업 중 발견 | `docs/시안_B_확정.html` |
|
||||
| [x] | (로컬 반영함, 운영은 배포 때) 행사 아이콘 `calendar`→`fireworks` 기존 DB 반영 — 코드·`init.sql` 기본값만 바뀌어 이미 들어간 행사는 그대로. 필요한 명령: `UPDATE event SET icon='fireworks' WHERE icon='calendar'; ALTER TABLE event ALTER COLUMN icon SET DEFAULT 'fireworks';` (운영은 확인 받고) | 아이콘 오용 수정 중 발견 | `backend/postgres-init/init.sql`, `backend/common/database/model/models.py` |
|
||||
@@ -72,7 +90,7 @@
|
||||
| [ ] | 한 문장 8개(`quote-clear-2·3`, `quote-cloud-1·2`, `quote-rain-1·2`, `quote-any-1`, `quote-night-3`) 문구 검수 — 직접 쓴 예시 문장이라 출처 없이 나감 | 출처 줄 '날씨각 (검수 전 예시)' 삭제하며 메모 옮김 | `backend/seed/article.json` |
|
||||
| [ ] | 미세먼지 포스트에 오늘 시간대별 예보 추가 — 지금은 실시간 측정값만. 에어코리아 예보 API(`getMinuDustFrcstDspth`, 권역별 오늘·내일 등급) 연결 필요 | 미세먼지 포스트 작업 중 발견 | `backend/services/external/airkorea.py`, `backend/services/feed_service.py` (`_air`) |
|
||||
| [ ] | 마스크 아이콘 없음 — 미세먼지 포스트가 좋음·보통은 `vent`, 나쁨 이상은 `cloud`를 씀 | 미세먼지 포스트 작업 중 발견 | `frontend/public/icons/`, `backend/services/feed_service.py` (`_air`) |
|
||||
| [ ] | **[결정 필요]** 주말 화면 '데이트 명소'는 아직 시도 기준(`places`) — 행사처럼 거리 기준으로 바꿀지. 지금 명소 데이터는 10곳뿐 | 행사 거리 기준 작업 중 발견 | `backend/services/week_service.py` (`places`), `frontend/src/b/WeekPage.tsx` |
|
||||
| [x] | 주말 화면 '데이트 명소'는 아직 시도 기준(`places`) — 행사처럼 거리 기준으로 바꿀지. 지금 명소 데이터는 10곳뿐 | 행사 거리 기준 작업 중 발견 | `backend/services/week_service.py` (`places`), `frontend/src/b/WeekPage.tsx` |
|
||||
| [ ] | 행사 수집이 사용자 한 명당 주변 시도 2~4곳으로 늘어 TourAPI·문화정보 API 호출이 시도 수만큼 늘어남(시도별 하루 1회 캐시) — 운영 배포 때 일일 호출 한도 확인 | 행사 거리 기준 작업 중 발견 | `backend/services/week_service.py` (`_ensure_events`), `backend/docs/load-estimate.md` |
|
||||
| [ ] | 다른 문서의 포스트 종류 목록·행사 시도 기준 설명 갱신 (`PostType` 12 미세먼지, 30km 행사) — `docs/포스트_종류별_내용.html`만 고침 | 문서 점검 | `backend/docs/`, `docs/화면별_데이터_출처.html`, `docs/데이터_흐름.html`, `docs/콘텐츠_설계서.md` |
|
||||
| [ ] | **[결정 필요]** 스켈레톤 작업에서 바뀐 디자인 — 댓글 없음 안내가 글자 두 줄 → 상자(스켈레톤 3줄 크기) | 스켈레톤 작업 중 발견 | `frontend/src/b/Sheets.tsx` (`CommentsSheet`) |
|
||||
@@ -94,13 +112,40 @@
|
||||
| [x] | 문화정보원 API 가 `23 LIMITED_NUMBER_OF_SERVICE_REQUESTS_PER_SECOND_EXCEEDS_ERROR` 를 냄 — 쪽 사이 1초, 시도 사이 1초 간격을 둬 17개 시도 수집에서 오류 없음 | 콘서트 수집 점검 중 발견 | `backend/services/external/culture_api.py` |
|
||||
| [x] | `event.kind` 칸 추가(1=축제 2=전시 3=콘서트 4=팝업). 행사 종류(축제·전시·콘서트·팝업)를 구분하는 칸이 없음 — 지금은 `source_id` 접두어로만 구분하고 전시·콘서트는 둘 다 `kcis:` 라 섞임 | 콘서트 수집 | `backend/postgres-init/init.sql` (`event`) |
|
||||
| [x] | 히어로 두 칸을 상황별로 고름(비→미세먼지→자외선→일교차→체감→불쾌지수, 모자라면 기본값), 아이콘·색도 상태별 (시안 A, 사용자 결정). 히어로 내용 전체 다시 보기 — 아이콘이 뜻과 안 맞음: 불쾌지수에 온도계(불쾌지수는 기온+습도), '지금 비'는 비가 안 와도 우산. 칸마다 무엇을 보여줄지(불쾌지수가 필요한지 포함)부터 다시 정하기 | 사용자 지적 | `frontend/src/b/TodayPage.tsx` (`HeroStat`) |
|
||||
| [ ] | 검색 노출(SEO·AEO) 대응 빌드 방식 정하기 — 지금은 브라우저에서만 그리는 React(Vite)라 검색엔진·AI가 내용을 못 읽음. SSR 말고도 미리 그려 두는 방식(정적 사전 렌더링), 일부 페이지만 서버에서 그리기 등을 비교해 추천안 내기 | 지시 사항 (SEO·AEO 필요) | `frontend/vite.config.ts`, `frontend/nginx.conf` |
|
||||
| [x] | 검색 노출 1단계: 메타는 `index.html` 하나로 유지 + canonical, `robots.txt`·`sitemap.xml`(메인 한 줄) 추가 — 탭별 HTML로 나누는 안은 효과(탭별 공유 미리보기·탭별 색인)가 작아 보류. 도메인 `weather.o2o.kr` 고정이라 바뀌면 두 파일도 수정 | 10/8 논의 | `frontend/index.html`, `frontend/public/robots.txt`, `frontend/public/sitemap.xml` |
|
||||
| [ ] | **[보류]** AEO·일반 검색어 유입 — 본문이 HTML에 없어 네이버 Yeti·AI 크롤러(GPTBot 등)는 메타만 읽고, 일반 검색어("세차하기 좋은 날씨" 등)는 메타만으로 순위에 못 듦. 지금 탭 내용은 지역별·매일 바뀌는 값이라 색인돼도 금방 틀림. 하려면 검색어용 페이지(각 기준·월별 노을 시간·노을 명소·계절 글·월별 행사)를 새로 만들어야 함 → 기획 결정 필요. 계절 이야기 글은 지역 무관이라 글마다 주소만 붙이면 바로 후보 | 10/8 논의 | [검색 유입 기획](https://claude.ai/artifact/SKz9SipYyguERGF8weUpZs), [검색어 리서치](https://claude.ai/artifact/Eu5ax3DbR9SdnhKdMRzE3p) |
|
||||
| [ ] | 구글 서치 콘솔·네이버 서치어드바이저에 사이트 등록, `sitemap.xml` 제출 — 배포 뒤 | 등록·제출 없으면 새 도메인은 색인이 늦음 | https://search.google.com/search-console , https://searchadvisor.naver.com |
|
||||
| [x] | 세션 여러 개가 같은 테스트 DB·Redis를 쓰면 서로 지움 — `TEST_DB_NAME`·`TEST_REDIS_DB`로 폴더마다 다르게 줄 수 있게 함 | 테스트 충돌 (10/7 두 번) | `backend/tests/conftest.py` |
|
||||
| [x] | 피드 행사 카드·띠를 축제→팝업→전시→콘서트 차례로 돌아가며 고름 (사용자 결정). 피드 행사 카드(최대 3장)가 연주회로 채워짐 — 시작일이 오늘에 가까운 순이라 하루짜리 콘서트(서울 170건)가 위를 차지. 기획엔 "축제·행사"만 있고 콘서트·팝업을 어떻게 섞을지 없음. 안: 종류별 1장씩(축제·전시·팝업 우선) 또는 피드에서 콘서트 제외 | 사용자 지적 | `backend/services/week_service.py` (`events` 정렬), `backend/services/feed_service.py` (`PostType.EVENT`), `docs/피드_기획.html` |
|
||||
| [ ] | 노을 하늘 상황 판정이 실제와 맞는지 확인할 방법 정하기 — 기준값(중·높은 구름 25~75% 등)은 추정값. 사진 기록·사용자 반응 등 후보 | 노을 탭 다시 기획 (10/7) | `backend/services/calc/sky_score.py` (`situation`) |
|
||||
| [ ] | **[결정 필요]** 노을 하늘 상황 판정이 실제와 맞는지 확인할 방법 정하기 — 기준값(중·높은 구름 25~75% 등)은 추정값. 추천안: 서쪽이 트인 공개 웹캠·CCTV 6~8곳을 워커가 매일 '가장 붉을 때' 시각에 캡처하고, 같은 날 13시 기준 예보(상황·판정)를 따로 남김. 사람이 주 1회 사진에 잿빛/은은/고움/붉음 라벨(30분 내외) → 판정(나가 볼 만해요/애매/쉬어요) 3×3 적중표, 특히 '나가 볼 만해요' 적중률(목표 70%↑). 6~8주(약 300장)면 기준값 조정 가능. 비용 0원, 테이블 1개+워커 잡 1개+라벨 CSV로 2~3일. 결정할 것: 웹캠 출처·이용 조건, 라벨 담당 | 노을 탭 다시 기획 (10/7). 사용자 '예뻤어요/별로'는 출시 전엔 표본이 없고 출시 후 보조 지표로, 기상청 ASOS 운량은 전운량·중하층운량만이라 구름 입력 검증용이지 노을이 예뻤는지는 못 알려줌, 인스타 해시태그는 예쁜 날만 올라와 '쉬어요' 검증 불가·수집 약관 문제. `sky_score`는 갱신 때 덮어쓰고 7일 뒤 지워져 지금은 과거 예보가 안 남음 | `backend/services/calc/sky_score.py` (`situation`), `backend/services/sky_service.py`, `backend/scheduler/jobs.py` |
|
||||
| [x] | 공유 이미지: 행사 카드의 장소(지도 링크)가 빠짐 — 버튼과 함께 `<a>`도 빼서 생김. 링크는 남기고 버튼만 빼야 함 | 공유 이미지 점검 (10/7) | `frontend/src/b/storyImage.ts` (`keep`), `frontend/src/b/ui.tsx` (지도 링크) |
|
||||
| [x] | 공유 이미지: 행사 사진은 백엔드 `/v1/image`(허용 호스트만)로 대신 받음 (사용자 결정). 행사 사진(한국관광공사·문화정보원)이 CORS 차단으로 하얗게 빠짐. 안: 백엔드가 사진을 대신 받아 주기 / 공유 때만 사진 대신 아이콘 | 공유 이미지 점검 (10/7) | `frontend/src/b/storyImage.ts`, `backend` 이미지 응답 |
|
||||
| [x] | 공유 이미지: 2장 카드는 한 이미지에 엇갈려 묶음 (사용자 결정). 여러 장 카드는 보고 있는 1장만 나감(주말 예보는 2번째 장 내용이 빠짐). 1장만 / 장마다 이미지 여러 장 / 2장을 한 이미지에 중 정하기 | 공유 이미지 점검 (10/7) | `frontend/src/b/storyImage.ts`, `frontend/src/b/Post.tsx` (`share`) |
|
||||
| [x] | 공유 이미지: 카드 아래 긴 제목이 한 줄 폭에 눌려 찌그러짐 — 두 줄 나눔 또는 말줄임 | 공유 이미지 점검 (10/7) | `frontend/src/b/storyImage.ts` (`fillText`) |
|
||||
| [x] | 공유 이미지: 카드 아래 제목을 빼고 주소 알약으로 바꿈 (시안 A, 사용자 결정). 카드 안 제목과 카드 아래 제목이 같아 두 번 보임. 아래 줄을 뺄지, 다른 말(지역·날짜)로 바꿀지 정하기 | 공유 이미지 점검 (10/7) | `frontend/src/b/storyImage.ts` |
|
||||
| [ ] | 노치(아이폰 상단 카메라 영역) 대응 — 화면 위·아래가 노치·홈 막대에 가리지 않게 safe-area 여백 점검 | 사용자 요청 | `frontend/index.html`, `frontend/src/b/BLayout.tsx` |
|
||||
| [x] | 노치(아이폰 상단 카메라 영역) 대응 — 화면 위·아래가 노치·홈 막대에 가리지 않게 safe-area 여백 점검 | 사용자 요청 | `frontend/index.html`, `frontend/src/b/BLayout.tsx` |
|
||||
| [x] | 홈 화면 상태바 색(`theme-color`)이 낮 하늘색 고정 — 밤 테마 등 시간대 따라 바꿀지 → 시간대 따라 바꿈 | 노치 대응 중 발견 (10/8) | `frontend/index.html` |
|
||||
| [x] | 안드로이드 뒤로 가기: 시트가 열려 있을 때 시트만 닫히지 않고 페이지가 뒤로 감 (방문 기록 미사용) | QA 작성 중 발견 (10/8) | `frontend/src/b/Sheets.tsx:53` |
|
||||
| [x] | 로그아웃 상태에서 댓글 "게시" → 로그인 시트 → 로그인 후 시트가 닫혀 쓰던 댓글이 사라지고 댓글 화면으로 안 돌아옴 | QA 작성 중 발견 (10/8) | `frontend/src/b/Sheets.tsx:662`, `:753` |
|
||||
| [x] | 터치 영역 44px 미만 — 포스트 하트·댓글·보내기 28px, 댓글 하트 약 16px, 시트 × 30px | QA 작성 중 발견 (10/8) | `frontend/src/b/Post.tsx:426`, `frontend/src/b/Sheets.tsx:637`, `:96` |
|
||||
| [x] | 주말 순위 로드 실패 시 토/일 칩이 눌리는 것처럼 보이지만 동작 없음 | QA 작성 중 발견 (10/8) | `frontend/src/b/WeekPage.tsx:278` |
|
||||
| [x] | "지금 위치로 찾기" 성공 후 지역 시트가 안 닫힘 (목록에서 고르면 닫힘) — 닫을지 정하기 | QA 작성 중 발견 (10/8) | `frontend/src/b/region.tsx:44`, `frontend/src/b/Sheets.tsx:938` |
|
||||
| [ ] | **[결정 필요]** 데이트 명소: 서울 기존 10곳(직접 고른 곳)을 거리순과 상관없이 앞에 고정할지 | 데이트 명소 전국 확대 (10/8) | `backend/services/week_service.py` (`pick_places`) |
|
||||
| [ ] | 데이트 명소: 14개 구는 30km 안 실내 명소가 없어 비 오는 날에도 야외만 나옴 | 데이트 명소 전국 확대 (10/8) | `backend/seed/place_tourapi.csv` |
|
||||
| [ ] | 데이트 명소: 동네 고르기 목록에 기존 동네 이름(성수 등)과 새 구 이름이 섞이고 서울은 목록이 길어짐 | 데이트 명소 전국 확대 (10/8) | `frontend/src/b/WeekPage.tsx` |
|
||||
| [ ] | 각 문서: 강풍 특보 조건이 "wind 특보가 있으면"으로 찍힘 (등산·골프·낚시각) | 각 늘리기 중 발견 (10/8) | `backend/scripts/gen_gak_doc.py` |
|
||||
| [ ] | 각 문서: "한눈에 보기" 표에 자외선·햇빛·가시거리 비중이 빠져 합이 100%가 안 됨 (등산·드라이브·물놀이각) | 각 늘리기 중 발견 (10/8) | `backend/scripts/gen_gak_doc.py` |
|
||||
| [x] | 각 중요도: 새 각 7개 제안 — 드라이브 상 / 골프·낚시·물놀이 중 / 집콕·연날리기·김장 하 | 각 늘리기 (10/8) | `backend/seed/index_definition.json` |
|
||||
| [ ] | `tests/test_sky_api.py` 2개가 09시 직전(08:58 KST)에 실패 — 시간대 경계 의존, 재실행 시 통과 | 계절 사진 작업 중 발견 (10/8) | `backend/tests/test_sky_api.py` |
|
||||
| [ ] | 개인정보처리방침·이용약관 모달 (출시 후로 미룸) — `feat/legal` 브랜치(f6ddc67)에 구현 완료, 병합 전. 남은 것: `OPERATOR` 자리표시(회사명·대표자·사업자번호·주소·문의 이메일·보호책임자·호스팅 업체·로그 보유 기간), 탈퇴 기능 없음, 위치 좌표가 nginx 접속 로그에 남음, 만 14세 미만 확인 없음, 약관 열면 가입 입력값 사라짐, 위치정보법 신고 대상 법무 확인 | 사용자 결정 (10/8) | `frontend/src/b/legal/`, `frontend/src/b/Sheets.tsx` |
|
||||
| [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` |
|
||||
| [x] | 전체 날씨 점수 기준 강화 — 100점은 '1년에 하루' 수준으로만 → 각과 같은 계산에 기준만 좁힘(체감 21±0.5°·습도 45~55%·해 90%↑·바람 1m/s↓·초미세먼지 10↓, 사용자 결정 '기준만 좁히기'). 실제 연 몇 번 나오는지는 미확인 (`docs/점수_계산식.md` 2) | 10/8 회의 결정 | `backend/services/index_service.py:203` |
|
||||
| [ ] | 각 점수를 아침·낮·저녁·밤 시간대별로 — 지금은 하루 중 가장 좋은 시간대 점수로 하루 고정이라 비가 와도 안 바뀜 | 10/8 회의 결정 | `backend/services/calc/index_calc.py:297` |
|
||||
| [ ] | 히어로에 습도·불쾌지수 항상 표시 — 지금은 상황별 두 칸이라 불쾌지수는 일정 수치 이상일 때만 | 10/8 회의 결정 | `frontend/src/b/TodayPage.tsx` (`HeroStat`) |
|
||||
| [ ] | 달 '밝기 %' 정의(밝기인지 보이는 면적인지) + 구름·달 모양 반영 산정 로직 | 10/8 회의 | `backend/services/calc/moon.py` |
|
||||
| [ ] | 노을: 하늘 상황 문구 대신 점수 강조(10/7 다시 기획에서 되돌림). 골든아워·블루아워 설명은 시간표 아래에 넣음 | 10/8 회의, 사용자 결정 | `frontend/src/b/SkyPage.tsx`, `backend/services/sky_service.py` |
|
||||
| [ ] | 주말 예보 UI 개선 — 회의에서 구체 내용 없음 | 10/8 회의 | `frontend/src/b/WeekPage.tsx` |
|
||||
| [ ] | AEO·SEO 메타데이터 + 구글·네이버 검색 등록 (금일 핵심 업무), 넣은 태그·키워드 정의서 작성, 매시간 갱신 콘텐츠 노출 방식 정리 → 대표 보고. 도메인은 별도 유지 | 10/8 회의 결정 | `frontend/index.html`, `docs/` |
|
||||
| [ ] | `docs/콘텐츠_구현기획.md` 2-1의 오늘 날씨 점수 식이 예전 기준(기온 40·비 30·바람 15·미세먼지 15) — 새 기준은 `docs/점수_계산식.md` | 점수 계산식 정리 중 발견 (10/8) | `docs/콘텐츠_구현기획.md` |
|
||||
@@ -183,6 +183,7 @@ class IndexDefinition(Base):
|
||||
limit_description: Mapped[Optional[str]] = mapped_column(String(200), nullable=True)
|
||||
sentences: Mapped[dict] = mapped_column(JSONB)
|
||||
sort_order: Mapped[int] = mapped_column(SmallInteger)
|
||||
priority: Mapped[int] = mapped_column(SmallInteger, default=2, server_default="2")
|
||||
|
||||
|
||||
class IndexScore(Base):
|
||||
@@ -205,6 +206,7 @@ class IndexScore(Base):
|
||||
zero_reason: Mapped[Optional[str]] = mapped_column(String(100), nullable=True)
|
||||
notes: Mapped[dict] = mapped_column(JSONB)
|
||||
estimated: Mapped[bool] = mapped_column(Boolean, default=False)
|
||||
slots: Mapped[dict] = mapped_column(JSONB, default=dict, server_default="{}")
|
||||
computed_at: Mapped[datetime] = mapped_column(DateTime(timezone=True))
|
||||
|
||||
|
||||
@@ -227,6 +229,9 @@ class Place(Base):
|
||||
reason: Mapped[str] = mapped_column(String(60))
|
||||
best_time: Mapped[str] = mapped_column(String(30))
|
||||
sort_order: Mapped[int] = mapped_column(SmallInteger, default=0)
|
||||
lat: Mapped[Optional[Decimal]] = mapped_column(Numeric(8, 5), nullable=True)
|
||||
lon: Mapped[Optional[Decimal]] = mapped_column(Numeric(8, 5), nullable=True)
|
||||
image_url: Mapped[Optional[str]] = mapped_column(String(500), nullable=True)
|
||||
|
||||
|
||||
class Event(Base):
|
||||
@@ -280,6 +285,8 @@ class Article(Base):
|
||||
show_from: Mapped[Optional[date]] = mapped_column(Date, nullable=True)
|
||||
show_until: Mapped[Optional[date]] = mapped_column(Date, nullable=True)
|
||||
sort_order: Mapped[int] = mapped_column(SmallInteger, default=0)
|
||||
image_url: Mapped[Optional[str]] = mapped_column(String(200), nullable=True)
|
||||
image_credit: Mapped[Optional[str]] = mapped_column(String(60), nullable=True)
|
||||
|
||||
|
||||
class Post(Base):
|
||||
@@ -288,6 +295,7 @@ class Post(Base):
|
||||
post_id: Mapped[int] = mapped_column(BigInteger, primary_key=True)
|
||||
feed_date: Mapped[date] = mapped_column(Date)
|
||||
position: Mapped[int] = mapped_column(SmallInteger)
|
||||
scope: Mapped[str] = mapped_column(String(2), default="00")
|
||||
post_type: Mapped[int] = mapped_column(SmallInteger)
|
||||
ref_type: Mapped[int] = mapped_column(SmallInteger, default=1)
|
||||
ref_id: Mapped[Optional[int]] = mapped_column(BigInteger, nullable=True)
|
||||
|
||||
@@ -29,7 +29,7 @@ class Settings(BaseSettings):
|
||||
data_go_kr_service_key: str = ""
|
||||
teams_webhook_url: str = ""
|
||||
# 공유 이미지용 사진 대신 받기를 허용할 호스트 (쉼표로 구분)
|
||||
image_proxy_hosts: str = "tong.visitkorea.or.kr,www.culture.go.kr"
|
||||
image_proxy_hosts: str = "tong.visitkorea.or.kr,www.culture.go.kr,culture.seoul.go.kr"
|
||||
|
||||
jwt_access_secret: str = ""
|
||||
jwt_refresh_secret: str = ""
|
||||
|
||||
@@ -9,13 +9,13 @@ from common.database.model.models import Post
|
||||
|
||||
|
||||
class FeedCRUD:
|
||||
async def day(self, s: AsyncSession, day: date) -> list[Post]:
|
||||
stmt = select(Post).where(Post.feed_date == day, Post.deleted.is_(False)).order_by(Post.position)
|
||||
async def day(self, s: AsyncSession, day: date, scopes: list[str]) -> list[Post]:
|
||||
stmt = select(Post).where(Post.feed_date == day, Post.scope.in_(scopes), Post.deleted.is_(False)).order_by(Post.position, Post.scope)
|
||||
return list((await s.scalars(stmt)).all())
|
||||
|
||||
async def positions(self, s: AsyncSession, day: date) -> set[int]:
|
||||
"""그날 이미 만든 카드 번호. 지운 카드도 넣어 다시 만들지 않게 한다."""
|
||||
return set((await s.scalars(select(Post.position).where(Post.feed_date == day))).all())
|
||||
async def positions(self, s: AsyncSession, day: date) -> set[tuple[str, int]]:
|
||||
"""그날 이미 만든 (scope, 카드 번호). 지운 카드도 넣어 다시 만들지 않게 한다."""
|
||||
return {(scope, pos) for scope, pos in (await s.execute(select(Post.scope, Post.position).where(Post.feed_date == day))).all()}
|
||||
|
||||
async def insert_day(self, s: AsyncSession, rows: list[dict]) -> None:
|
||||
if rows:
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
from datetime import date
|
||||
|
||||
from sqlalchemy import func, select
|
||||
from sqlalchemy import func, select, text
|
||||
from sqlalchemy.dialects.postgresql import insert
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
@@ -34,6 +34,13 @@ class IndexCRUD:
|
||||
stmt = select(func.min(IndexScore.computed_at)).where(IndexScore.region_code == region_code, IndexScore.score_date == day)
|
||||
return await s.scalar(stmt)
|
||||
|
||||
async def has_unslotted(self, s: AsyncSession, region_code: str, day: date) -> bool:
|
||||
"""그날 행 중 구간 점수가 비어 있는 행(구간 계산 전 행)이 있는지."""
|
||||
stmt = select(IndexScore.index_id).where(
|
||||
IndexScore.region_code == region_code, IndexScore.score_date == day, text("index_score.slots = '{}'::jsonb")
|
||||
).limit(1)
|
||||
return (await s.scalar(stmt)) is not None
|
||||
|
||||
async def upsert_scores(self, s: AsyncSession, rows: list[dict]) -> None:
|
||||
if not rows:
|
||||
return
|
||||
|
||||
@@ -58,5 +58,9 @@ class SkyCRUD:
|
||||
)
|
||||
return list((await s.scalars(stmt)).all())
|
||||
|
||||
async def west_open_spots(self, s: AsyncSession) -> list[SunsetSpot]:
|
||||
"""서쪽이 트인 노을 명소 (sort_order 0)."""
|
||||
return list((await s.scalars(select(SunsetSpot).where(SunsetSpot.sort_order == 0))).all())
|
||||
|
||||
async def ranking_regions(self, s: AsyncSession) -> list[Region]:
|
||||
return list((await s.scalars(select(Region).where(Region.is_ranking_spot.is_(True)))).all())
|
||||
@@ -52,6 +52,9 @@ class WeatherCRUD:
|
||||
async def latest_issued(self, s: AsyncSession, region_code: str) -> Optional[datetime]:
|
||||
return await s.scalar(select(func.max(WeatherHourly.issued_at)).where(WeatherHourly.region_code == region_code))
|
||||
|
||||
async def has_hourly_at(self, s: AsyncSession, region_code: str, at: datetime) -> bool:
|
||||
return await s.get(WeatherHourly, (region_code, at)) is not None
|
||||
|
||||
async def hourly_between(self, s: AsyncSession, region_code: str, start: datetime, end: datetime) -> list[WeatherHourly]:
|
||||
stmt = (
|
||||
select(WeatherHourly)
|
||||
|
||||
@@ -26,14 +26,18 @@ class WeekCRUD:
|
||||
if rows:
|
||||
await s.execute(insert(Holiday).values(rows).on_conflict_do_nothing(index_elements=["holiday_date", "name"]))
|
||||
|
||||
async def places(self, s: AsyncSession, sido_code: str) -> list[Place]:
|
||||
stmt = select(Place).where(Place.region_code.startswith(sido_code)).order_by(Place.sort_order)
|
||||
async def places_in_box(self, s: AsyncSession, lat: float, lon: float, dlat: float, dlon: float) -> list[Place]:
|
||||
stmt = select(Place).where(Place.lat.between(lat - dlat, lat + dlat), Place.lon.between(lon - dlon, lon + dlon))
|
||||
return list((await s.scalars(stmt)).all())
|
||||
|
||||
async def all_places(self, s: AsyncSession) -> list[Place]:
|
||||
return list((await s.scalars(select(Place).where(Place.lat.is_not(None)))).all())
|
||||
|
||||
async def replace_places(self, s: AsyncSession, rows: list[dict]) -> None:
|
||||
await s.execute(delete(Place))
|
||||
if rows:
|
||||
await s.execute(insert(Place).values(rows))
|
||||
# asyncpg 는 한 문장에 인자 32767개까지라 나눠 넣는다.
|
||||
for i in range(0, len(rows), 1000):
|
||||
await s.execute(insert(Place).values(rows[i:i + 1000]))
|
||||
|
||||
async def events(self, s: AsyncSession, sido_codes: list[str], since: date, until: date) -> list[Event]:
|
||||
stmt = select(Event).where(Event.sido_code.in_(sido_codes), Event.end_date >= since, Event.start_date <= until)
|
||||
|
||||
@@ -40,18 +40,19 @@ Open-Meteo(`api.open-meteo.com/v1/forecast`)에서 받는 데이터와 저장
|
||||
|
||||
```
|
||||
canvas = max(mid20, high20)
|
||||
f_canvas = 0.2 + 0.8 × canvas/50 (canvas ≤ 50) / max(0, 1 - (canvas-50)/50) (canvas > 50)
|
||||
f_canvas = 0.4 + 0.6 × canvas/50 (canvas ≤ 50) / max(0, 1 - (canvas-50)/50) (canvas > 50)
|
||||
f_near = 1 - 0.8 × low20 / 100
|
||||
light = 1 - min(low100 + 0.5×mid100, 100) / 100
|
||||
구름 점수 = 100 × (0.75×f_canvas + 0.25×f_near) × (0.25 + 0.75×light)
|
||||
점수 = min(100, round(모델 평균 구름 점수 × 공기 보정))
|
||||
```
|
||||
|
||||
- 맑은 하늘(구름 0%)은 40점(은은함)이고, 구름이 몇 %만 있어도 점수가 갈린다. 예전에는 10% 미만을 0.3으로 고정해 맑은 날 전국이 48점에 몰리고, 10%에서 점수가 오히려 떨어졌다.
|
||||
- 공기 보정 (`air_factor`, 구 중심 해 질·뜰 무렵 값. 값이 없으면 ×1.0):
|
||||
- 가시거리(`openmeteo_hourly.visibility_m`, 가장 가까운 3시간 구간): 40km 이상 ×1.0 ~ 5km 이하 ×0.6. 뿌연 공기는 색을 흐린다.
|
||||
- 습도(`weather_hourly.humidity`, 가장 가까운 정시): 50% 이하 ×1.0 ~ 90% 이상 ×0.75.
|
||||
- 맑은 하늘(구름 0%)은 55점(은은함)이고, 구름이 몇 %만 있어도 점수가 갈린다. 예전에는 10% 미만을 0.3으로 고정해 맑은 날 전국이 48점에 몰리고, 10%에서 점수가 오히려 떨어졌다.
|
||||
- 공기 보정 (`air_factor`, 구 중심 해 질·뜰 무렵 값. 값이 없으면 ×1.0). 평소 공기(가시거리 20km·습도 60%)를 ×1.0 으로 두고 좋으면 올리고 나쁘면 내린다. 맑은 날 전국이 한 점수(구름 0% = 55점)에 몰리지 않게 하려는 것:
|
||||
- 가시거리(`openmeteo_hourly.visibility_m`, 가장 가까운 3시간 구간): 5km 이하 ×0.8 · 20km ×1.0 · 40km 이상 ×1.12, 사이는 직선. 뿌연 공기는 색을 흐리고 맑은 공기는 더 선명하다.
|
||||
- 습도(`weather_hourly.humidity`, 가장 가까운 정시): 40% 이하 ×1.06 · 60% ×1.0 · 90% 이상 ×0.85, 사이는 직선.
|
||||
- 비 갠 뒤: 2~6시간 전 비 확률 60% 이상이고 그 시각 비 확률 40% 미만이면 ×1.15.
|
||||
- 서쪽이 트인 곳 (노을만): 구 중심 20km 안에 서쪽이 트인 노을 명소(`sunset_spot.sort_order` 0 = `sunset_spot.csv`의 `west_open` 1)가 있으면 ×1.1. 산·건물에 가리지 않고 해가 지평선까지 보이는 곳이라서. 명소에는 바다뿐 아니라 강변·높은 전망대도 있어 서울 마포·강남, 대구 수성 같은 내륙 구도 받는다. 일출은 동쪽이 트였는지 데이터가 없어 넣지 않는다.
|
||||
- 모델마다 따로 계산해 **평균**을 최종 점수로 쓰고, 모델 점수의 표준편차로 신뢰도를 정한다 (8 미만 높음, 15 미만 보통, 그 이상 낮음). 모델이 2개 미만이면 낮음. 신뢰도는 공기 보정 전 구름 점수로 본다.
|
||||
- 등급: 80 이상 붉음, 60 이상 고움, 40 이상 은은함, 그 미만 흐림.
|
||||
|
||||
@@ -140,17 +141,19 @@ light = 1 - min(low100 + 0.5×mid100, 100) / 100
|
||||
| 지수 | 새 비중 | 바뀐 기존 비중 (기온·비·바람·습도·공기) | 추가 0점 조건 |
|
||||
|---|---|---|---|
|
||||
| 빨래각 | 햇빛 25 | 15·30·15·10·0 | |
|
||||
| 멍뭉산책각 | 자외선 5 | 35·25·10·5·15 | 지표면 온도 45° 이상 |
|
||||
| 피크닉각 | 자외선 10 | 25·25·15·5·10 | |
|
||||
| 등산각 | 자외선 5, 가시거리 5 | 25·25·20·5·10 | |
|
||||
| 러닝각 | 자외선 5 | 35·20·10·15·10 | |
|
||||
| 가드닝각 | 자외선 5 | 25·30·10·15·10 | |
|
||||
| 피크닉각 | 자외선 10, 햇빛 10 | 20·20·15·5·10 | |
|
||||
| 등산각 | 자외선 10, 햇빛 10, 가시거리 5 | 20·20·15·5·10 | |
|
||||
| 자전거각 | 자외선 10, 햇빛 10 | 20·20·20·5·10 | 돌풍 15m/s 이상 |
|
||||
| 가드닝각 | 자외선 10, 햇빛 10 | 20·25·10·10·10 | |
|
||||
| 세차각 | 자외선 10, 햇빛 10 | 5·40·10·10·10 | |
|
||||
| 별보기각 | 가시거리 15 | 5·10·5·5·15 (시간대 45 그대로) | |
|
||||
| 사진산책각 | 가시거리 10 | 10·25·10·5·10 (시간대 30 그대로) | |
|
||||
| 자전거각 | | 변경 없음 | 돌풍 15m/s 이상 |
|
||||
| 멍뭉산책각 | | 40·25·10·5·15 | 지표면 온도 45° 이상 |
|
||||
| 러닝각 | | 35·20·10·15·15 | |
|
||||
| 캠핑각 | | 변경 없음 | 돌풍 15m/s 이상 |
|
||||
|
||||
- 나머지 17개 지수는 점수가 바뀌지 않는다 (적용 전후 비교로 확인).
|
||||
- 해가 떠 있는 시간대의 야외 활동(피크닉·등산·자전거·가드닝·세차)은 햇빛과 자외선을 **같은 비중(10씩)으로 함께** 둔다. 햇빛은 많을수록, 자외선은 낮을수록 점수가 높다. 자외선만 있으면 흐린 날이 "자외선 낮음 = 좋음"으로 맑은 날보다 높게 나오고, 햇빛만 있으면 한여름 강한 자외선을 놓친다.
|
||||
- 러닝각(6~8·19~22시)·멍뭉산책각(7~9·17~20시)은 자외선을 뺐다. 이른 아침·저녁이라 자외선이 늘 0이라 점수를 가르지 못했다. 그 비중은 러닝은 공기, 멍뭉산책은 기온으로 옮겼다. 사진산책각(일몰 무렵)도 같은 이유로 햇빛·자외선을 두지 않는다.
|
||||
- 비중·기준값은 초안이다. 수치는 `seed/index_definition.json`에서 바꾸고 `load_seed.py`로 다시 넣는다.
|
||||
|
||||
### 3시간 구간을 계산 창에 연결하는 규칙
|
||||
|
||||
@@ -153,12 +153,14 @@ CREATE TABLE IF NOT EXISTS public.index_score (
|
||||
zero_reason VARCHAR(100) NULL, -- 0점이 된 이유 (걸리지 않았으면 NULL)
|
||||
notes JSONB NOT NULL, -- 요소별 근거 문장 {"temp": "체감 21°, 편한 범위 18~24° 안", ...}
|
||||
estimated BOOLEAN NOT NULL DEFAULT false, -- 시간별 예보가 없어 중기예보로 낸 예상 점수
|
||||
slots JSONB NOT NULL DEFAULT '{}', -- 오늘만: 구간별 점수 {"morning"|"day"|"evening"|"night"|"early": {score, summary, factors, zero_reason, notes}}. 각 시간대와 안 겹치는 구간은 없음
|
||||
computed_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
PRIMARY KEY (region_code, score_date, index_id)
|
||||
);
|
||||
ALTER TABLE public.index_score ADD COLUMN IF NOT EXISTS uv_score SMALLINT NOT NULL DEFAULT 0;
|
||||
ALTER TABLE public.index_score ADD COLUMN IF NOT EXISTS sun_score SMALLINT NOT NULL DEFAULT 0;
|
||||
ALTER TABLE public.index_score ADD COLUMN IF NOT EXISTS view_score SMALLINT NOT NULL DEFAULT 0;
|
||||
ALTER TABLE public.index_score ADD COLUMN IF NOT EXISTS slots JSONB NOT NULL DEFAULT '{}';
|
||||
|
||||
-- 피드 카드. 매일 03:00 스케줄러가 그날 카드를 전부 만들고, 볼 때 시간대에 따라 켜고 끄고 순서를 정해 그 구 데이터로 채운다.
|
||||
CREATE TABLE IF NOT EXISTS public.post (
|
||||
@@ -175,7 +177,9 @@ CREATE TABLE IF NOT EXISTS public.post (
|
||||
end_at TIMESTAMPTZ NULL, -- NULL = 그날 끝까지
|
||||
deleted BOOLEAN NOT NULL DEFAULT FALSE
|
||||
);
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS uq_post_feed ON public.post (feed_date, position) WHERE deleted = FALSE;
|
||||
ALTER TABLE public.post ADD COLUMN IF NOT EXISTS scope VARCHAR(2) NOT NULL DEFAULT '00'; -- '00'=전국, 그 외 시도 코드(region.code 앞 2자리). 좋아요·댓글이 이 단위로 나뉜다
|
||||
DROP INDEX IF EXISTS public.uq_post_feed;
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS uq_post_feed_scope ON public.post (feed_date, position, scope) WHERE deleted = FALSE;
|
||||
|
||||
-- 사람·반응 (좋아요·저장·댓글은 로그인 필요, 보내기는 누구나)
|
||||
|
||||
@@ -286,11 +290,13 @@ CREATE TABLE IF NOT EXISTS public.index_definition (
|
||||
zero_rules JSONB NOT NULL DEFAULT '[]', -- 바로 0점 조건 [{"field": "rain_prob", "op": ">=", "value": 80}]. 화면 문장은 여기서 만든다
|
||||
limit_description VARCHAR(200) NULL, -- 반영 못 한 것
|
||||
sentences JSONB NOT NULL DEFAULT '{}', -- 문장 틀 {summary, headline, rabbit, bear, notes}
|
||||
sort_order SMALLINT NOT NULL DEFAULT 0
|
||||
sort_order SMALLINT NOT NULL DEFAULT 0,
|
||||
priority SMALLINT NOT NULL DEFAULT 2 -- 중요도: 1=상 2=중 3=하. 순위는 점수 × 가중치로 정한다
|
||||
);
|
||||
ALTER TABLE public.index_definition ADD COLUMN IF NOT EXISTS weight_uv SMALLINT NOT NULL DEFAULT 0;
|
||||
ALTER TABLE public.index_definition ADD COLUMN IF NOT EXISTS weight_sun SMALLINT NOT NULL DEFAULT 0;
|
||||
ALTER TABLE public.index_definition ADD COLUMN IF NOT EXISTS weight_view SMALLINT NOT NULL DEFAULT 0;
|
||||
ALTER TABLE public.index_definition ADD COLUMN IF NOT EXISTS priority SMALLINT NOT NULL DEFAULT 2;
|
||||
|
||||
-- 노을 명소.
|
||||
CREATE TABLE IF NOT EXISTS public.sunset_spot (
|
||||
@@ -303,18 +309,24 @@ CREATE TABLE IF NOT EXISTS public.sunset_spot (
|
||||
sort_order SMALLINT NOT NULL DEFAULT 0 -- 0 해 지는 쪽이 트인 곳(먼저), 1 그 밖
|
||||
);
|
||||
|
||||
-- 날씨 맞춤 데이트 명소 (주말·행사 탭).
|
||||
-- 날씨 맞춤 데이트 명소 (주말·행사 탭). 구 중심에서 가까운 곳을 고른다.
|
||||
CREATE TABLE IF NOT EXISTS public.place (
|
||||
place_id SERIAL PRIMARY KEY,
|
||||
region_code VARCHAR(10) NOT NULL,
|
||||
area VARCHAR(20) NOT NULL, -- 동네 묶음 ("성수", "연남·망원")
|
||||
area VARCHAR(20) NOT NULL, -- 동네 묶음 ("성수", "연남·망원") 또는 구 이름
|
||||
name VARCHAR(40) NOT NULL,
|
||||
is_outdoor BOOLEAN NOT NULL, -- 맑으면 야외, 비 오면 실내를 먼저
|
||||
icon VARCHAR(30) NOT NULL,
|
||||
reason VARCHAR(60) NOT NULL, -- "돗자리 펴고 낮 피크닉"
|
||||
best_time VARCHAR(30) NOT NULL, -- "낮 12시~4시"
|
||||
sort_order SMALLINT NOT NULL DEFAULT 0
|
||||
sort_order SMALLINT NOT NULL DEFAULT 0,
|
||||
lat NUMERIC(8,5) NULL, -- 시드가 늘 채운다
|
||||
lon NUMERIC(8,5) NULL,
|
||||
image_url VARCHAR(500) NULL -- TourAPI firstimage
|
||||
);
|
||||
ALTER TABLE public.place ADD COLUMN IF NOT EXISTS lat NUMERIC(8,5) NULL;
|
||||
ALTER TABLE public.place ADD COLUMN IF NOT EXISTS lon NUMERIC(8,5) NULL;
|
||||
ALTER TABLE public.place ADD COLUMN IF NOT EXISTS image_url VARCHAR(500) NULL;
|
||||
|
||||
-- 축제·행사.
|
||||
CREATE TABLE IF NOT EXISTS public.event (
|
||||
@@ -374,5 +386,9 @@ CREATE TABLE IF NOT EXISTS public.article (
|
||||
body JSONB NOT NULL, -- 문단 목록
|
||||
show_from DATE NULL, -- 계절 소식이 보이는 기간 (NULL = 늘)
|
||||
show_until DATE NULL,
|
||||
sort_order SMALLINT NOT NULL DEFAULT 0
|
||||
sort_order SMALLINT NOT NULL DEFAULT 0,
|
||||
image_url VARCHAR(200) NULL, -- 사진 (frontend/public/season/, NULL = 아이콘)
|
||||
image_credit VARCHAR(60) NULL -- 사진 출처 표기 ("ⓒ저작자 · CC BY-SA 4.0"), 표기가 필요 없으면 NULL
|
||||
);
|
||||
ALTER TABLE public.article ADD COLUMN IF NOT EXISTS image_url VARCHAR(200) NULL;
|
||||
ALTER TABLE public.article ADD COLUMN IF NOT EXISTS image_credit VARCHAR(60) NULL;
|
||||
@@ -131,6 +131,7 @@ class TopIndex(WebPacketProtocol):
|
||||
score: int
|
||||
rank: int
|
||||
summary: Optional[str] = None
|
||||
active: bool = Field(default=True, description="지금 구간이 이 각의 시간대와 겹침. false 면 순위 밖, score 는 하루 점수")
|
||||
|
||||
|
||||
class HeroStat(WebPacketProtocol):
|
||||
@@ -171,6 +172,8 @@ class BandArticle(WebPacketProtocol):
|
||||
title: str
|
||||
meta: str
|
||||
icon: str
|
||||
image: Optional[str] = None
|
||||
image_credit: Optional[str] = None
|
||||
|
||||
|
||||
class Bands(WebPacketProtocol):
|
||||
|
||||
@@ -5,7 +5,8 @@ from fastapi import APIRouter, Depends, Path, Query
|
||||
|
||||
from common.enums import ErrorType, IndexCategory
|
||||
from common.models.errors import error_info
|
||||
from router.v1.index.protocol import Factor, IndexSummary, Res_IndexDetail, Res_IndexList, ScoreBand, TrendPoint
|
||||
from router.v1.index.protocol import Factor, IndexSummary, Res_IndexDetail, Res_IndexList, ScoreBand, SlotPoint, TrendPoint
|
||||
from services.calc.day_slot import SLOT_LABEL
|
||||
from services.calc.index_calc import AXES, axis_label, zero_rules_text
|
||||
from services.index_service import IndexItem, IndexService, slot_label
|
||||
|
||||
@@ -18,10 +19,11 @@ def _summary(i: IndexItem, today: date) -> IndexSummary:
|
||||
index_id=d.index_id, code=d.code, name=d.name, icon=d.icon, category=IndexCategory(d.category), is_fun=d.is_fun,
|
||||
is_core=d.is_core, score=i.score.score, rank=i.rank, summary=i.score.summary,
|
||||
trend=[TrendPoint(day=t.score_date, label=slot_label(t.score_date, today), score=t.score, estimated=t.estimated) for t in i.trend],
|
||||
active=i.active, slot=i.slot, slots=[SlotPoint(slot=k, label=SLOT_LABEL[k], score=v) for k, v in i.slots.items()],
|
||||
)
|
||||
|
||||
|
||||
@router.get("/list", response_model=Res_IndexList, response_model_exclude_none=True, summary="지수 목록 (점수순, 1~3위, 오늘 날씨 점수)")
|
||||
@router.get("/list", response_model=Res_IndexList, response_model_exclude_none=True, summary="지수 목록 (지금 구간 점수순, 1~3위, 지금 날씨 점수)")
|
||||
async def list_indices(
|
||||
region: str = Query(..., description="구 행정코드"),
|
||||
category: Optional[IndexCategory] = Query(None),
|
||||
@@ -32,8 +34,9 @@ async def list_indices(
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return Res_IndexList(result=error_info(err))
|
||||
items = [_summary(i, board.day) for i in board.items]
|
||||
top3 = [_summary(i, board.day) for i in board.ranked[:3]]
|
||||
filtered = [x for x in items if (category is None or x.category is category) and (not core or x.is_core)]
|
||||
return Res_IndexList(region_code=board.region.code, day=board.day, weather_score=board.weather_score, top3=items[:3], items=filtered)
|
||||
return Res_IndexList(region_code=board.region.code, day=board.day, weather_score=board.weather_score, top3=top3, items=filtered)
|
||||
|
||||
|
||||
@router.get("/{index_id}", response_model=Res_IndexDetail, response_model_exclude_none=True, summary="지수 계산 근거")
|
||||
|
||||
@@ -14,6 +14,12 @@ class TrendPoint(WebPacketProtocol):
|
||||
estimated: bool = Field(description="시간별 예보가 없어 중기예보로 낸 예상 점수")
|
||||
|
||||
|
||||
class SlotPoint(WebPacketProtocol):
|
||||
slot: str = Field(description="morning / day / evening / night")
|
||||
label: str = Field(description="아침 / 낮 / 저녁 / 밤")
|
||||
score: int
|
||||
|
||||
|
||||
class IndexSummary(WebPacketProtocol):
|
||||
index_id: int
|
||||
code: str
|
||||
@@ -26,12 +32,15 @@ class IndexSummary(WebPacketProtocol):
|
||||
rank: int
|
||||
summary: str
|
||||
trend: list[TrendPoint] = []
|
||||
active: bool = Field(default=True, description="지금 구간이 이 각의 시간대와 겹침. false 면 순위 밖, score 는 하루 점수")
|
||||
slot: Optional[str] = Field(default=None, description="score 가 어느 구간 점수인지 (지금 구간)")
|
||||
slots: list[SlotPoint] = Field(default=[], description="오늘 구간별 점수. 각 시간대와 안 겹치는 구간은 없음")
|
||||
|
||||
|
||||
class Res_IndexList(Res_WebPacketProtocol):
|
||||
region_code: Optional[str] = None
|
||||
day: Optional[date] = None
|
||||
weather_score: Optional[int] = None
|
||||
weather_score: Optional[int] = Field(default=None, description="지금 날씨 점수 (지금 구간 기준)")
|
||||
top3: list[IndexSummary] = []
|
||||
items: list[IndexSummary] = []
|
||||
|
||||
|
||||
@@ -17,6 +17,8 @@ class ArticleSummary(WebPacketProtocol):
|
||||
title: str
|
||||
read_minutes: int
|
||||
icon: str
|
||||
image: Optional[str] = None # 있으면 아이콘 대신 사진
|
||||
image_credit: Optional[str] = None # 사진 출처 표기 ("ⓒ저작자 · CC BY-SA 4.0")
|
||||
|
||||
|
||||
class Res_SeasonWeek(Res_WebPacketProtocol):
|
||||
|
||||
@@ -12,7 +12,8 @@ router = APIRouter(prefix="/v1/season", tags=["season"])
|
||||
|
||||
|
||||
def _summary(a: Article) -> ArticleSummary:
|
||||
return ArticleSummary(article_id=a.article_id, code=a.code, category=ArticleCategory(a.category), title=a.title, read_minutes=a.read_minutes, icon=a.icon)
|
||||
return ArticleSummary(article_id=a.article_id, code=a.code, category=ArticleCategory(a.category), title=a.title, read_minutes=a.read_minutes, icon=a.icon,
|
||||
image=a.image_url, image_credit=a.image_credit)
|
||||
|
||||
|
||||
@router.get("/week", response_model=Res_SeasonWeek, response_model_exclude_none=True, summary="이번 주 계절 책: 시, 절기, 계절 소식")
|
||||
|
||||
@@ -97,7 +97,7 @@ async def get_watch_summary(
|
||||
res.warning = now_w.warnings[0].text if now_w.warnings else None
|
||||
|
||||
if board is not None:
|
||||
res.top = [_top(i) for i in board.items[:TOP_N]]
|
||||
res.top = [_top(i) for i in board.ranked[:TOP_N]]
|
||||
codes = [c.strip() for c in (pick or "").split(",") if c.strip()][:MAX_PICKS]
|
||||
by_code = {i.definition.code: i for i in board.items}
|
||||
res.picks = [_top(by_code[c]) for c in codes if c in by_code]
|
||||
|
||||
@@ -32,6 +32,9 @@ class PlaceData(WebPacketProtocol):
|
||||
reason: str
|
||||
best_time: str
|
||||
is_good: bool
|
||||
distance_km: float # 구 중심에서 떨어진 거리
|
||||
image: Optional[str] = None
|
||||
image_credit: Optional[str] = None # 사진 출처 표기 ("ⓒ한국관광공사")
|
||||
|
||||
|
||||
class Res_PlaceList(Res_WebPacketProtocol):
|
||||
|
||||
@@ -9,7 +9,7 @@ from common.utils.kma_time import now_kst
|
||||
from router.v1.week.protocol import (
|
||||
DayData, EventData, PlaceData, Res_EventList, Res_PlaceList, Res_Week, Res_WeekRanking, WeekRankDay, WeekRankItem,
|
||||
)
|
||||
from services.week_service import WeekService, image_credit
|
||||
from services.week_service import WeekService, image_credit, place_credit
|
||||
from services.weekend_rank import WeekendRank, rank_days, weekend_days
|
||||
|
||||
router = APIRouter(prefix="/v1/week", tags=["week"])
|
||||
@@ -45,20 +45,20 @@ async def get_week_ranking() -> Res_WeekRanking:
|
||||
])
|
||||
|
||||
|
||||
@router.get("/place/list", response_model=Res_PlaceList, response_model_exclude_none=True, summary="날씨 맞춤 데이트 명소")
|
||||
@router.get("/place/list", response_model=Res_PlaceList, response_model_exclude_none=True, summary="날씨 맞춤 데이트 명소 (구 중심 30km 안, 없으면 가장 가까운 곳)")
|
||||
async def list_places(
|
||||
region: str = Query(...), day: Optional[date] = Query(None, description="기본은 오늘"), area: Optional[str] = Query(None),
|
||||
service: WeekService = Depends(),
|
||||
) -> Res_PlaceList:
|
||||
target = day or now_kst().date()
|
||||
err, items, areas = await service.places(region, target, area)
|
||||
err, items, areas, rainy = await service.places(region, target, area)
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return Res_PlaceList(result=error_info(err))
|
||||
rainy = any(not i.place.is_outdoor and i.is_good for i in items)
|
||||
return Res_PlaceList(areas=areas, rainy=rainy, places=[
|
||||
PlaceData(
|
||||
place_id=i.place.place_id, area=i.place.area, name=i.place.name, is_outdoor=i.place.is_outdoor, icon=i.place.icon,
|
||||
reason=i.place.reason, best_time=i.place.best_time, is_good=i.is_good,
|
||||
reason=i.place.reason, best_time=i.place.best_time, is_good=i.is_good, distance_km=i.distance_km,
|
||||
image=i.place.image_url, image_credit=place_credit(i.place),
|
||||
)
|
||||
for i in items
|
||||
])
|
||||
|
||||
@@ -21,10 +21,10 @@ from services.external.culture_api import SIDO_NAME
|
||||
from services.external.data_go_kr import DataGoKrNotConfigured, DataGoKrRequestFailed
|
||||
from services.external.open_meteo import OpenMeteoRequestFailed, fetch_weather, parse_weather
|
||||
from services.feed_service import build_feed_day, clear_feed_cache
|
||||
from services.week_service import collect_events
|
||||
from services.week_service import collect_events, drop_known
|
||||
from services.weekend_rank import WeekendRank
|
||||
|
||||
_POPGA_SEEN = "popga:lastmod" # {팝업 id: 마지막으로 읽은 lastmod}, 바뀐 페이지만 다시 읽는다
|
||||
_POPGA_SEEN = "popga:lastmod:v2" # {팝업 id: 마지막으로 읽은 lastmod}, 바뀐 페이지만 다시 읽는다. 받는 분류가 바뀌면 이름을 바꿔 처음부터 읽는다
|
||||
_POPGA_BATCH = 100
|
||||
EVENTS_DONE = "events:collected" # 행사 수집을 마친 표시. 7일 유지, 없으면 worker 가 켜질 때 한 번 돈다
|
||||
_EVENTS_TTL_SEC = 7 * 86400
|
||||
@@ -98,13 +98,14 @@ async def refresh_openmeteo_weather() -> ErrorType:
|
||||
|
||||
|
||||
async def build_today_feed() -> ErrorType:
|
||||
"""그날 전국 공통 피드 칸을 넣고, 구별 피드 캐시를 비운다."""
|
||||
err = await build_feed_day(now_kst().date(), FeedCRUD(), SeasonCRUD())
|
||||
"""그날 피드 칸(전국·시도별)을 넣고, 구별 피드 캐시를 비운다."""
|
||||
err = await build_feed_day(now_kst().date(), FeedCRUD(), SeasonCRUD(), RegionCRUD())
|
||||
await clear_feed_cache()
|
||||
return err
|
||||
|
||||
|
||||
async def _save_popups(rows: list[dict], seen: dict[str, str]) -> ErrorType:
|
||||
rows = await drop_known(rows)
|
||||
err = await DB_SESSION_MNG.execute_lambda_run([lambda s: WeekCRUD().upsert_events(s, rows)])
|
||||
if err is ErrorType.SUCCESS and seen:
|
||||
await REDIS.conn.hset(_POPGA_SEEN, mapping=seen)
|
||||
@@ -147,7 +148,7 @@ async def refresh_popups() -> ErrorType:
|
||||
|
||||
|
||||
async def _popup_count() -> int:
|
||||
q = text("SELECT count(*) FROM public.event WHERE source_id LIKE 'popga:%' AND end_date >= (now() AT TIME ZONE 'Asia/Seoul')::date")
|
||||
q = text("SELECT count(*) FROM public.event WHERE source_id LIKE 'popga:%' AND kind = 4 AND end_date >= (now() AT TIME ZONE 'Asia/Seoul')::date")
|
||||
err, n = await DB_SESSION_MNG.execute_lambda(lambda s: s.scalar(q))
|
||||
return n if err is ErrorType.SUCCESS and n is not None else 0
|
||||
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
"""TourAPI 분류(lclsSystm3)에서 데이트에 맞는 관광지를 전국으로 모아 seed/place_tourapi.csv 로 쓴다 (일회성, 다시 돌리면 덮어씀).
|
||||
|
||||
손으로 고른 seed/place.csv 와 같은 곳(contentid)은 뺀다.
|
||||
실행: docker exec o2o-weather-backend-1 python scripts/fetch_date_places.py
|
||||
"""
|
||||
import asyncio
|
||||
import csv
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
|
||||
import httpx # noqa: E402
|
||||
|
||||
from common.utils.geo import haversine_km # noqa: E402
|
||||
from scripts.load_seed import SEED_DIR, read_regions # noqa: E402
|
||||
from services.external.data_go_kr import get_all_items # noqa: E402
|
||||
|
||||
LIST_URL = "https://apis.data.go.kr/B551011/KorService2/areaBasedList2"
|
||||
OUT = os.path.join(SEED_DIR, "place_tourapi.csv")
|
||||
_BASE = {"_type": "json", "MobileOS": "ETC", "MobileApp": "nalssigak", "arrange": "A"}
|
||||
# lclsSystm3 → (야외, 아이콘, 한 줄 이유, 추천 시간). 이유는 분류에서 나오는 말만 쓴다.
|
||||
CATEGORIES = {
|
||||
"VE030100": (True, "picnic", "공원 산책·피크닉", "낮 12시~4시"),
|
||||
"VE010200": (True, "stars", "전망대에서 보는 경치·야경", "해 진 뒤"),
|
||||
"VE010300": (True, "stars", "다리 위 야경 산책", "해 진 뒤"),
|
||||
"VE040300": (True, "walk", "둘레길 함께 걷기", "선선한 오후"),
|
||||
"NA010200": (True, "walk", "숲길 산책", "오전 10시~"),
|
||||
"NA020200": (True, "walk", "호숫가 산책", "선선한 저녁"),
|
||||
"NA040700": (True, "garden", "수목원·정원 꽃길 산책", "오전 10시~"),
|
||||
"VE040100": (True, "photo", "골목·카페거리 구경", "오후 2시~"),
|
||||
"NA020900": (True, "sunset", "바닷가 산책", "노을 무렵"),
|
||||
"VE020400": (False, "rain", "비 와도 실내 아쿠아리움", "비 오는 오후"),
|
||||
"VE070600": (False, "bulb", "비 오면 미술관으로", "비 오는 날"),
|
||||
}
|
||||
FIELDS = ["source", "region_name", "area", "name", "is_outdoor", "icon", "reason", "best_time", "lat", "lon", "image_url"]
|
||||
|
||||
|
||||
def _clean(text: str) -> str:
|
||||
return re.sub(r"\s+", " ", text or "").strip()
|
||||
|
||||
|
||||
def _manual_ids() -> set[str]:
|
||||
with open(os.path.join(SEED_DIR, "place.csv"), encoding="utf-8") as f:
|
||||
return {r["source"].removeprefix("tourapi:") for r in csv.DictReader(f) if r["source"].startswith("tourapi:")}
|
||||
|
||||
|
||||
async def main() -> int:
|
||||
regions = read_regions()
|
||||
skip = _manual_ids()
|
||||
rows: dict[str, dict] = {}
|
||||
async with httpx.AsyncClient(timeout=30) as client:
|
||||
for code, (outdoor, icon, reason, best_time) in CATEGORIES.items():
|
||||
params = {**_BASE, "lclsSystm1": code[:2], "lclsSystm2": code[:4], "lclsSystm3": code}
|
||||
items = await get_all_items(client, LIST_URL, params, page_size=500)
|
||||
kept = 0
|
||||
for it in items:
|
||||
cid, title = str(it["contentid"]), _clean(it.get("title", ""))
|
||||
if cid in skip or cid in rows or not title or not it.get("mapx") or not it.get("mapy"):
|
||||
continue
|
||||
lat, lon = round(float(it["mapy"]), 5), round(float(it["mapx"]), 5)
|
||||
if not (33 <= lat <= 39 and 124 <= lon <= 132):
|
||||
print(f"skip {cid} {title}: 좌표가 국내 밖 ({lat}, {lon})")
|
||||
continue
|
||||
near = min(regions, key=lambda r: haversine_km(lat, lon, r["lat"], r["lon"]))
|
||||
rows[cid] = {
|
||||
"source": f"tourapi:{cid}", "region_name": near["name"], "area": near["short_name"], "name": title[:60],
|
||||
"is_outdoor": int(outdoor), "icon": icon, "reason": reason, "best_time": best_time, "lat": lat, "lon": lon,
|
||||
"image_url": (it.get("firstimage") or "").replace("http://", "https://", 1),
|
||||
}
|
||||
kept += 1
|
||||
print(f"{code}: {len(items)} -> {kept}")
|
||||
out = sorted(rows.values(), key=lambda r: (r["region_name"], r["name"]))
|
||||
with open(OUT, "w", encoding="utf-8", newline="") as f:
|
||||
w = csv.DictWriter(f, fieldnames=FIELDS)
|
||||
w.writeheader()
|
||||
w.writerows(out)
|
||||
print(f"place {len(out)} -> {OUT}")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(asyncio.run(main()))
|
||||
@@ -1,11 +1,17 @@
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
|
||||
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
sys.path.insert(0, ROOT)
|
||||
|
||||
from services.calc.index_calc import PRIORITY_WEIGHT # noqa: E402
|
||||
|
||||
SEED = os.path.join(ROOT, "seed", "index_definition.json")
|
||||
OUT = os.path.join(os.path.dirname(ROOT), "docs", "각_계산기준.md")
|
||||
|
||||
CAT = {1: "밖에서 놀기", 2: "먹고 마시기", 3: "집안일", 4: "생활 고민"}
|
||||
PRIO = {1: "상", 2: "중", 3: "하"}
|
||||
WD = {"mon": "월", "tue": "화", "wed": "수", "thu": "목", "fri": "금", "sat": "토", "sun": "일", "holiday": "공휴일", "default": "그 외"}
|
||||
FIELD = {"rain_prob": ("비 확률", "%"), "wind_ms": ("바람", "m/s"), "feels_c": ("체감", "°"), "pm25": ("초미세먼지", "㎍/㎥"), "cloudy_ratio": ("흐린 시간 비율", "%"), "gust_ms": ("돌풍", "m/s"), "ground_c": ("지면 온도", "°")}
|
||||
|
||||
@@ -70,7 +76,13 @@ def zero(z):
|
||||
return s + (f" 최대 {z['cap']}점" if "cap" in z else " 0점")
|
||||
|
||||
|
||||
AX = [("temp", "기온", temp), ("rain", "비", rain), ("wind", "바람", wind), ("humidity", "습도", hum), ("air", "미세먼지", None),
|
||||
def air(r):
|
||||
if r["full"] > r["zero"]:
|
||||
return f"초미세먼지 높을수록 좋음 ({r['zero']}㎍/㎥=0점 → {r['full']}㎍/㎥=100점)"
|
||||
return "초미세먼지 낮을수록 좋음"
|
||||
|
||||
|
||||
AX = [("temp", "기온", temp), ("rain", "비", rain), ("wind", "바람", wind), ("humidity", "습도", hum), ("air", "미세먼지", air),
|
||||
("uv", "자외선", lambda r: f"자외선 {r['full']} 이하면 만점, {r['zero']} 이상이면 0점 (Open-Meteo)"),
|
||||
("sun", "햇빛", lambda r: f"해 난 비율 {round(r['full'] * 100)}% 이상이면 만점, {round(r['zero'] * 100)}% 이하면 0점 (Open-Meteo)"),
|
||||
("view", "가시거리", lambda r: f"{r['full']}km 이상이면 만점, {r['zero']}km 이하면 0점 (Open-Meteo)"),
|
||||
@@ -91,27 +103,28 @@ def main() -> None:
|
||||
P("- 최종 점수 = 비중대로 섞은 점수 × (0.75 + 0.25 × 가장 낮은 요소 점수 ÷ 100). 비중 0%인 요소는 '가장 낮은 요소'에서 뺍니다. 가장 낮은 요소가 0점이면 25%가 깎입니다.")
|
||||
P("- '0점 조건'에 걸리면 0점, '최대 N점' 조건에 걸리면 N점을 넘지 못합니다.")
|
||||
P("- 시간대가 여러 개면 그중 가장 좋은 시간대 점수를 씁니다.")
|
||||
P("- 미세먼지는 모든 각이 같은 규칙입니다: 초미세먼지 15㎍/㎥ 이하 100점 → 75㎍/㎥ 이상 0점.")
|
||||
P("- 바람·미세먼지·노을 정보가 없으면 70점으로 둡니다.\n")
|
||||
P("- 미세먼지는 초미세먼지 15㎍/㎥ 이하 100점 → 75㎍/㎥ 이상 0점입니다. 집콕각처럼 규칙을 따로 적은 각만 거꾸로(탁할수록 좋음) 셉니다.")
|
||||
P("- 바람·미세먼지·노을 정보가 없으면 70점으로 둡니다.")
|
||||
P("- 순위는 점수 × 중요도 가중치(" + " · ".join(f"{PRIO[k]} {v}" for k, v in PRIORITY_WEIGHT.items()) + ")로 정합니다. 화면에 보이는 점수는 그대로입니다.\n")
|
||||
P("## 한눈에 보기\n")
|
||||
P("| 순서 | 각 | 코드 | 분류 | 시간대 | 기온 | 비 | 바람 | 습도 | 미세먼지 | 시간 | 재미 각 | 계절 핵심 |")
|
||||
P("|---:|---|---|---|---|---:|---:|---:|---:|---:|---:|:---:|:---:|")
|
||||
P("| 순서 | 각 | 코드 | 분류 | 중요도 | 시간대 | 기온 | 비 | 바람 | 습도 | 미세먼지 | 시간 | 재미 각 | 계절 핵심 |")
|
||||
P("|---:|---|---|---|:---:|---|---:|---:|---:|---:|---:|---:|:---:|:---:|")
|
||||
for x in sorted(d, key=lambda x: x["sort_order"]):
|
||||
P(f"| {x['sort_order']} | {x['name']} | `{x['code']}` | {CAT[x['category']]} | {' / '.join(win(w) for w in x['windows'])} | "
|
||||
P(f"| {x['sort_order']} | {x['name']} | `{x['code']}` | {CAT[x['category']]} | {PRIO[x['priority']]} | {' / '.join(win(w) for w in x['windows'])} | "
|
||||
+ " | ".join(f"{x['weight_' + a]}%" for a in ("temp", "rain", "wind", "humidity", "air", "time"))
|
||||
+ f" | {'○' if x['is_fun'] else ''} | {'○' if x['is_core'] else ''} |")
|
||||
P("\n## 각별 자세히\n")
|
||||
for x in sorted(d, key=lambda x: x["sort_order"]):
|
||||
P(f"### {x['name']} (`{x['code']}`)\n")
|
||||
P(f"- 설명: {x['description']}")
|
||||
P(f"- 분류: {CAT[x['category']]} · 아이콘 `{x['icon']}` · 재미 각 {'예' if x['is_fun'] else '아니오'} · 계절 핵심 {'예' if x['is_core'] else '아니오'} · 계산 근거 화면 {'있음' if x['has_detail'] else '없음'}")
|
||||
P(f"- 분류: {CAT[x['category']]} · 중요도 {PRIO[x['priority']]} · 아이콘 `{x['icon']}` · 재미 각 {'예' if x['is_fun'] else '아니오'} · 계절 핵심 {'예' if x['is_core'] else '아니오'} · 계산 근거 화면 {'있음' if x['has_detail'] else '없음'}")
|
||||
P(f"- 시간대: {' / '.join(win(w) for w in x['windows'])}")
|
||||
P("- 요소별 규칙 (비중):")
|
||||
for key, label, fn in AX:
|
||||
w = x.get("weight_" + key, 0)
|
||||
if key in _OPTIONAL and not w:
|
||||
continue
|
||||
rule = "초미세먼지 낮을수록 좋음" if fn is None else fn(x["factor_rules"][key])
|
||||
rule = fn(x["factor_rules"].get(key, {"zero": 75, "full": 15}))
|
||||
P(f" - {label} {w}%: {rule}")
|
||||
zs = [zero(z) for z in x["zero_rules"]]
|
||||
P(f"- 점수 깎이는 조건: {', '.join(zs) if zs else '없음'}")
|
||||
|
||||
@@ -56,10 +56,12 @@ async def main() -> int:
|
||||
"lat": float(r["lat"]), "lon": float(r["lon"]), "sort_order": 0 if r["west_open"] == "1" else 1}
|
||||
for r in _read("sunset_spot.csv")
|
||||
]
|
||||
# 손으로 고른 place.csv 와 TourAPI 에서 모은 place_tourapi.csv (scripts/fetch_date_places.py). source 는 출처 기록용.
|
||||
places = [
|
||||
{"region_code": code_by_name[r["region_name"]], "area": r["area"], "name": r["name"], "is_outdoor": r["is_outdoor"] == "1",
|
||||
"icon": r["icon"], "reason": r["reason"], "best_time": r["best_time"], "sort_order": int(r["sort_order"])}
|
||||
for r in _read("place.csv")
|
||||
"icon": r["icon"], "reason": r["reason"], "best_time": r["best_time"], "sort_order": int(r.get("sort_order") or 0),
|
||||
"lat": float(r["lat"]), "lon": float(r["lon"]), "image_url": r.get("image_url") or None}
|
||||
for r in _read("place.csv") + _read("place_tourapi.csv")
|
||||
]
|
||||
# 직접 넣는 행사 (TourAPI 에 없는 것). source_id 가 없는 줄만 이 파일로 바꿔 넣는다.
|
||||
events = [
|
||||
@@ -70,7 +72,8 @@ async def main() -> int:
|
||||
]
|
||||
articles = [
|
||||
{**a, "show_from": date.fromisoformat(a["show_from"]) if a["show_from"] else None,
|
||||
"show_until": date.fromisoformat(a["show_until"]) if a["show_until"] else None}
|
||||
"show_until": date.fromisoformat(a["show_until"]) if a["show_until"] else None,
|
||||
"image_url": a.get("image_url"), "image_credit": a.get("image_credit")}
|
||||
for a in _json("article.json")
|
||||
]
|
||||
weeks = _json("season_week.json")
|
||||
|
||||
@@ -5,6 +5,8 @@
|
||||
"title": "설악산 첫 단풍, 절정은 언제?",
|
||||
"read_minutes": 3,
|
||||
"icon": "maple",
|
||||
"image_url": "/season/maple.jpg",
|
||||
"image_credit": "ⓒJoycekim77 · CC BY-SA 3.0",
|
||||
"show_from": "2026-09-20",
|
||||
"show_until": "2026-10-25",
|
||||
"body": [
|
||||
@@ -20,6 +22,8 @@
|
||||
"title": "하늘공원 억새가 반짝이는 시간",
|
||||
"read_minutes": 2,
|
||||
"icon": "sheaf",
|
||||
"image_url": "/season/reed.jpg",
|
||||
"image_credit": "ⓒJocelyndurrey · CC BY-SA 4.0",
|
||||
"show_from": "2026-09-25",
|
||||
"show_until": "2026-10-31",
|
||||
"body": [
|
||||
@@ -34,6 +38,8 @@
|
||||
"title": "대관령 첫서리, 서울은 한 달 뒤",
|
||||
"read_minutes": 2,
|
||||
"icon": "snow",
|
||||
"image_url": "/season/frost.jpg",
|
||||
"image_credit": "ⓒSally V · CC BY-SA 4.0",
|
||||
"show_from": "2026-10-01",
|
||||
"show_until": "2026-11-15",
|
||||
"body": [
|
||||
@@ -77,6 +83,7 @@
|
||||
"title": "노을은 왜 해 지고 15분 뒤가 더 붉을까?",
|
||||
"read_minutes": 3,
|
||||
"icon": "sunset",
|
||||
"image_url": "/season/sunset.jpg",
|
||||
"show_from": null,
|
||||
"show_until": null,
|
||||
"body": [
|
||||
@@ -91,6 +98,7 @@
|
||||
"title": "비 확률 30%면 우산을 챙겨야 할까?",
|
||||
"read_minutes": 2,
|
||||
"icon": "umbrella",
|
||||
"image_url": "/season/umbrella.jpg",
|
||||
"show_from": null,
|
||||
"show_until": null,
|
||||
"body": [
|
||||
@@ -251,6 +259,7 @@
|
||||
"title": "햇밤, 바로 먹을까 두었다 먹을까?",
|
||||
"read_minutes": 2,
|
||||
"icon": "chestnut",
|
||||
"image_url": "/season/chestnut_new.jpg",
|
||||
"show_from": "2026-09-15",
|
||||
"show_until": "2026-10-31",
|
||||
"body": [
|
||||
@@ -281,6 +290,8 @@
|
||||
"title": "은행 냄새 나는 길, 언제까지일까",
|
||||
"read_minutes": 2,
|
||||
"icon": "fallen_leaf",
|
||||
"image_url": "/season/ginkgo.jpg",
|
||||
"image_credit": "ⓒKorea.net · CC BY-SA 2.0",
|
||||
"show_from": "2026-10-10",
|
||||
"show_until": "2026-11-15",
|
||||
"body": [
|
||||
@@ -296,6 +307,8 @@
|
||||
"title": "군고구마가 생각나는 첫 추위",
|
||||
"read_minutes": 2,
|
||||
"icon": "sweet_potato",
|
||||
"image_url": "/season/sweet_potato.jpg",
|
||||
"image_credit": "ⓒ국립국어원 · CC BY-SA 2.0 KR",
|
||||
"show_from": "2026-10-15",
|
||||
"show_until": "2026-12-31",
|
||||
"body": [
|
||||
@@ -311,6 +324,7 @@
|
||||
"title": "노지 귤이 나오기 시작해요",
|
||||
"read_minutes": 2,
|
||||
"icon": "tangerine",
|
||||
"image_url": "/season/tangerine.jpg",
|
||||
"show_from": "2026-10-20",
|
||||
"show_until": "2026-12-31",
|
||||
"body": [
|
||||
@@ -326,6 +340,8 @@
|
||||
"title": "부사 사과가 나오는 때",
|
||||
"read_minutes": 2,
|
||||
"icon": "apple",
|
||||
"image_url": "/season/apple_fuji.jpg",
|
||||
"image_credit": "ⓒAomorikuma · CC BY-SA 4.0",
|
||||
"show_from": "2026-10-20",
|
||||
"show_until": "2026-11-30",
|
||||
"body": [
|
||||
@@ -341,6 +357,7 @@
|
||||
"title": "김장, 언제 하면 좋을까?",
|
||||
"read_minutes": 2,
|
||||
"icon": "kimchi",
|
||||
"image_url": "/season/kimjang.jpg",
|
||||
"show_from": "2026-11-01",
|
||||
"show_until": "2026-12-15",
|
||||
"body": [
|
||||
|
||||
@@ -70,7 +70,8 @@
|
||||
"60": "꽤 괜찮은 저녁! 바람만 살랑 불어 주면 딱이에요.",
|
||||
"80": "18~24°에 바람 살랑, 비 걱정 없음! 오늘은 무조건 바깥 자리 🍻"
|
||||
},
|
||||
"sort_order": 1
|
||||
"sort_order": 1,
|
||||
"priority": 2
|
||||
},
|
||||
{
|
||||
"code": "picnic",
|
||||
@@ -87,13 +88,13 @@
|
||||
"to": 16
|
||||
}
|
||||
],
|
||||
"weight_temp": 25,
|
||||
"weight_rain": 25,
|
||||
"weight_temp": 20,
|
||||
"weight_rain": 20,
|
||||
"weight_wind": 15,
|
||||
"weight_humidity": 5,
|
||||
"weight_air": 10,
|
||||
"weight_uv": 10,
|
||||
"weight_sun": 0,
|
||||
"weight_sun": 10,
|
||||
"weight_view": 0,
|
||||
"weight_time": 10,
|
||||
"factor_rules": {
|
||||
@@ -126,6 +127,10 @@
|
||||
"uv": {
|
||||
"zero": 8,
|
||||
"full": 2
|
||||
},
|
||||
"sun": {
|
||||
"zero": 0.2,
|
||||
"full": 0.8
|
||||
}
|
||||
},
|
||||
"zero_rules": [
|
||||
@@ -142,7 +147,8 @@
|
||||
"60": "돗자리 펴기 괜찮은 날! 바람막이 하나면 완벽해요.",
|
||||
"80": "20~26°에 바람 잔잔, 김밥 싸서 당장 출발! 🧺"
|
||||
},
|
||||
"sort_order": 2
|
||||
"sort_order": 2,
|
||||
"priority": 1
|
||||
},
|
||||
{
|
||||
"code": "chimaek",
|
||||
@@ -214,7 +220,8 @@
|
||||
"60": "바깥 테이블 괜찮아요! 얇은 겉옷 하나만 챙겨요.",
|
||||
"80": "20~27°의 선선한 저녁, 치킨에 맥주 부르는 날 🍗"
|
||||
},
|
||||
"sort_order": 3
|
||||
"sort_order": 3,
|
||||
"priority": 2
|
||||
},
|
||||
{
|
||||
"code": "walk",
|
||||
@@ -284,7 +291,8 @@
|
||||
"60": "한 바퀴 돌기 좋은 저녁! 이어폰 챙겨서 가볍게 나가요.",
|
||||
"80": "15~23°에 공기 맑고 바람 살랑, 동네 한 바퀴 무조건 🚶"
|
||||
},
|
||||
"sort_order": 4
|
||||
"sort_order": 4,
|
||||
"priority": 1
|
||||
},
|
||||
{
|
||||
"code": "vent",
|
||||
@@ -359,7 +367,8 @@
|
||||
"60": "열어도 괜찮아요. 맞바람 나게 10분이면 충분!",
|
||||
"80": "공기 맑고 바람도 적당, 창문 활짝 열 시간 🌬️"
|
||||
},
|
||||
"sort_order": 5
|
||||
"sort_order": 5,
|
||||
"priority": 3
|
||||
},
|
||||
{
|
||||
"code": "hiking",
|
||||
@@ -376,13 +385,13 @@
|
||||
"to": 12
|
||||
}
|
||||
],
|
||||
"weight_temp": 25,
|
||||
"weight_rain": 25,
|
||||
"weight_wind": 20,
|
||||
"weight_temp": 20,
|
||||
"weight_rain": 20,
|
||||
"weight_wind": 15,
|
||||
"weight_humidity": 5,
|
||||
"weight_air": 10,
|
||||
"weight_uv": 5,
|
||||
"weight_sun": 0,
|
||||
"weight_uv": 10,
|
||||
"weight_sun": 10,
|
||||
"weight_view": 5,
|
||||
"weight_time": 5,
|
||||
"factor_rules": {
|
||||
@@ -420,6 +429,10 @@
|
||||
"view": {
|
||||
"zero": 5,
|
||||
"full": 20
|
||||
},
|
||||
"sun": {
|
||||
"zero": 0.2,
|
||||
"full": 0.8
|
||||
}
|
||||
},
|
||||
"zero_rules": [
|
||||
@@ -441,7 +454,8 @@
|
||||
"60": "오를 만해요! 바람막이 챙기고 일찍 출발해요.",
|
||||
"80": "산 위도 선선하고 바람 잔잔, 정상 인증각 ⛰️"
|
||||
},
|
||||
"sort_order": 6
|
||||
"sort_order": 6,
|
||||
"priority": 1
|
||||
},
|
||||
{
|
||||
"code": "carwash",
|
||||
@@ -460,12 +474,12 @@
|
||||
}
|
||||
],
|
||||
"weight_temp": 5,
|
||||
"weight_rain": 60,
|
||||
"weight_rain": 40,
|
||||
"weight_wind": 10,
|
||||
"weight_humidity": 10,
|
||||
"weight_air": 10,
|
||||
"weight_uv": 0,
|
||||
"weight_sun": 0,
|
||||
"weight_uv": 10,
|
||||
"weight_sun": 10,
|
||||
"weight_view": 0,
|
||||
"weight_time": 5,
|
||||
"factor_rules": {
|
||||
@@ -488,6 +502,14 @@
|
||||
"time": {
|
||||
"type": "fixed",
|
||||
"value": 100
|
||||
},
|
||||
"uv": {
|
||||
"zero": 8,
|
||||
"full": 2
|
||||
},
|
||||
"sun": {
|
||||
"zero": 0.2,
|
||||
"full": 0.8
|
||||
}
|
||||
},
|
||||
"zero_rules": [
|
||||
@@ -505,7 +527,8 @@
|
||||
"60": "세차해도 괜찮아요. 먼지는 좀 붙을 수 있어요.",
|
||||
"80": "비 걱정 없고 공기도 맑아요. 반짝반짝 오래가는 날 ✨"
|
||||
},
|
||||
"sort_order": 7
|
||||
"sort_order": 7,
|
||||
"priority": 3
|
||||
},
|
||||
{
|
||||
"code": "camping",
|
||||
@@ -579,7 +602,8 @@
|
||||
"60": "하룻밤 괜찮아요. 새벽엔 쌀쌀하니 담요 챙기기!",
|
||||
"80": "밤새 12~22°에 바람 잔잔, 불멍하기 딱 좋은 밤 🔥"
|
||||
},
|
||||
"sort_order": 8
|
||||
"sort_order": 8,
|
||||
"priority": 1
|
||||
},
|
||||
{
|
||||
"code": "running",
|
||||
@@ -604,8 +628,8 @@
|
||||
"weight_rain": 20,
|
||||
"weight_wind": 10,
|
||||
"weight_humidity": 15,
|
||||
"weight_air": 10,
|
||||
"weight_uv": 5,
|
||||
"weight_air": 15,
|
||||
"weight_uv": 0,
|
||||
"weight_sun": 0,
|
||||
"weight_view": 0,
|
||||
"weight_time": 5,
|
||||
@@ -629,10 +653,6 @@
|
||||
"time": {
|
||||
"type": "fixed",
|
||||
"value": 100
|
||||
},
|
||||
"uv": {
|
||||
"zero": 8,
|
||||
"full": 2
|
||||
}
|
||||
},
|
||||
"zero_rules": [
|
||||
@@ -654,7 +674,8 @@
|
||||
"60": "뛸 만해요! 아침·저녁 중 시원한 쪽 고르기.",
|
||||
"80": "8~18°에 공기 보송, 기록 갱신각 🏃"
|
||||
},
|
||||
"sort_order": 9
|
||||
"sort_order": 9,
|
||||
"priority": 1
|
||||
},
|
||||
{
|
||||
"code": "stars",
|
||||
@@ -719,7 +740,8 @@
|
||||
"60": "꽤 보여요! 불빛 적은 곳으로 조금만 나가요.",
|
||||
"80": "달은 어둡고 공기는 맑아요. 은하수 노려볼 만한 밤 ✨"
|
||||
},
|
||||
"sort_order": 10
|
||||
"sort_order": 10,
|
||||
"priority": 2
|
||||
},
|
||||
{
|
||||
"code": "jjamppong",
|
||||
@@ -777,7 +799,8 @@
|
||||
"60": "쌀쌀하거나 비 와서 국물 각 잡혀요!",
|
||||
"80": "춥고 비까지! 얼큰한 짬뽕 한 그릇 무조건 🍜"
|
||||
},
|
||||
"sort_order": 11
|
||||
"sort_order": 11,
|
||||
"priority": 3
|
||||
},
|
||||
{
|
||||
"code": "makgeolli",
|
||||
@@ -833,7 +856,8 @@
|
||||
"60": "비 기운이 있어요. 파전 반죽 준비각!",
|
||||
"80": "비 오고 선선한 저녁, 파전에 막걸리 확정 🍶"
|
||||
},
|
||||
"sort_order": 12
|
||||
"sort_order": 12,
|
||||
"priority": 3
|
||||
},
|
||||
{
|
||||
"code": "iced_hot",
|
||||
@@ -887,7 +911,8 @@
|
||||
"60": "아침 공기가 차요. 오늘은 뜨아로 갈아탈 때!",
|
||||
"80": "아침이 한 자릿수, 따뜻한 커피 없인 못 버텨요 ☕"
|
||||
},
|
||||
"sort_order": 13
|
||||
"sort_order": 13,
|
||||
"priority": 3
|
||||
},
|
||||
{
|
||||
"code": "laundry",
|
||||
@@ -951,7 +976,8 @@
|
||||
"60": "잘 마르는 편이에요. 두꺼운 건 오후까지 두기!",
|
||||
"80": "따뜻하고 보송한데 바람까지 솔솔, 이불 빨래 가능한 날 ☀️"
|
||||
},
|
||||
"sort_order": 14
|
||||
"sort_order": 14,
|
||||
"priority": 1
|
||||
},
|
||||
{
|
||||
"code": "bike",
|
||||
@@ -968,13 +994,13 @@
|
||||
"to": 19
|
||||
}
|
||||
],
|
||||
"weight_temp": 25,
|
||||
"weight_rain": 25,
|
||||
"weight_wind": 25,
|
||||
"weight_temp": 20,
|
||||
"weight_rain": 20,
|
||||
"weight_wind": 20,
|
||||
"weight_humidity": 5,
|
||||
"weight_air": 10,
|
||||
"weight_uv": 5,
|
||||
"weight_sun": 0,
|
||||
"weight_uv": 10,
|
||||
"weight_sun": 10,
|
||||
"weight_view": 0,
|
||||
"weight_time": 5,
|
||||
"factor_rules": {
|
||||
@@ -1007,6 +1033,10 @@
|
||||
"uv": {
|
||||
"zero": 8,
|
||||
"full": 2
|
||||
},
|
||||
"sun": {
|
||||
"zero": 0.2,
|
||||
"full": 0.8
|
||||
}
|
||||
},
|
||||
"zero_rules": [
|
||||
@@ -1033,7 +1063,8 @@
|
||||
"60": "탈 만해요! 강변은 바람 좀 부니 바람막이 챙기기.",
|
||||
"80": "15~24°에 바람 잔잔, 멀리 달려도 좋은 날 🚲"
|
||||
},
|
||||
"sort_order": 15
|
||||
"sort_order": 15,
|
||||
"priority": 1
|
||||
},
|
||||
{
|
||||
"code": "dog",
|
||||
@@ -1054,12 +1085,12 @@
|
||||
"to": 20
|
||||
}
|
||||
],
|
||||
"weight_temp": 35,
|
||||
"weight_temp": 40,
|
||||
"weight_rain": 25,
|
||||
"weight_wind": 10,
|
||||
"weight_humidity": 5,
|
||||
"weight_air": 15,
|
||||
"weight_uv": 5,
|
||||
"weight_uv": 0,
|
||||
"weight_sun": 0,
|
||||
"weight_view": 0,
|
||||
"weight_time": 5,
|
||||
@@ -1086,10 +1117,6 @@
|
||||
"time": {
|
||||
"type": "fixed",
|
||||
"value": 100
|
||||
},
|
||||
"uv": {
|
||||
"zero": 8,
|
||||
"full": 2
|
||||
}
|
||||
},
|
||||
"zero_rules": [
|
||||
@@ -1116,7 +1143,8 @@
|
||||
"60": "산책 괜찮아요! 그늘 많은 길로 가요.",
|
||||
"80": "5~22°에 공기 맑음, 멍멍이 신나는 날 🐶"
|
||||
},
|
||||
"sort_order": 16
|
||||
"sort_order": 16,
|
||||
"priority": 2
|
||||
},
|
||||
{
|
||||
"code": "glasses",
|
||||
@@ -1170,7 +1198,8 @@
|
||||
"60": "출근길 안경에 김 서려요. 닦을 천 챙기기!",
|
||||
"80": "영하권 아침에 습하기까지, 문 열자마자 앞이 하얘져요 👓"
|
||||
},
|
||||
"sort_order": 17
|
||||
"sort_order": 17,
|
||||
"priority": 2
|
||||
},
|
||||
{
|
||||
"code": "makeup",
|
||||
@@ -1224,7 +1253,8 @@
|
||||
"60": "덥고 습해서 무너지기 쉬워요. 픽서 챙기기!",
|
||||
"80": "30° 넘는 찜통에 습도까지, 기름종이 필수 🫠"
|
||||
},
|
||||
"sort_order": 18
|
||||
"sort_order": 18,
|
||||
"priority": 2
|
||||
},
|
||||
{
|
||||
"code": "naengmyeon",
|
||||
@@ -1280,7 +1310,8 @@
|
||||
"60": "점심에 덥네요. 냉면 한 그릇 생각나요!",
|
||||
"80": "30° 넘는 한낮, 살얼음 동동 냉면 확정 🥶"
|
||||
},
|
||||
"sort_order": 19
|
||||
"sort_order": 19,
|
||||
"priority": 3
|
||||
},
|
||||
{
|
||||
"code": "taxi",
|
||||
@@ -1336,7 +1367,8 @@
|
||||
"60": "비나 추위로 택시 잡기 힘들어요. 막차 시간 확인!",
|
||||
"80": "비 오는 추운 밤, 택시 전쟁이에요. 막차 타세요 🚕"
|
||||
},
|
||||
"sort_order": 20
|
||||
"sort_order": 20,
|
||||
"priority": 2
|
||||
},
|
||||
{
|
||||
"code": "delivery",
|
||||
@@ -1393,7 +1425,8 @@
|
||||
"60": "비나 추위로 주문이 몰려요. 일찍 시키기!",
|
||||
"80": "비 오는 추운 저녁, 배달 한참 걸려요. 지금 바로 주문! 🛵"
|
||||
},
|
||||
"sort_order": 21
|
||||
"sort_order": 21,
|
||||
"priority": 2
|
||||
},
|
||||
{
|
||||
"code": "garden",
|
||||
@@ -1410,13 +1443,13 @@
|
||||
"to": 10
|
||||
}
|
||||
],
|
||||
"weight_temp": 25,
|
||||
"weight_rain": 30,
|
||||
"weight_temp": 20,
|
||||
"weight_rain": 25,
|
||||
"weight_wind": 10,
|
||||
"weight_humidity": 15,
|
||||
"weight_humidity": 10,
|
||||
"weight_air": 10,
|
||||
"weight_uv": 5,
|
||||
"weight_sun": 0,
|
||||
"weight_uv": 10,
|
||||
"weight_sun": 10,
|
||||
"weight_view": 0,
|
||||
"weight_time": 5,
|
||||
"factor_rules": {
|
||||
@@ -1446,6 +1479,10 @@
|
||||
"uv": {
|
||||
"zero": 8,
|
||||
"full": 2
|
||||
},
|
||||
"sun": {
|
||||
"zero": 0.2,
|
||||
"full": 0.8
|
||||
}
|
||||
},
|
||||
"zero_rules": [
|
||||
@@ -1462,7 +1499,8 @@
|
||||
"60": "화분 돌보기 괜찮아요. 아침에 물 듬뿍!",
|
||||
"80": "12~25°의 보송한 아침, 분갈이까지 해도 되는 날 🌱"
|
||||
},
|
||||
"sort_order": 22
|
||||
"sort_order": 22,
|
||||
"priority": 3
|
||||
},
|
||||
{
|
||||
"code": "photo",
|
||||
@@ -1530,7 +1568,8 @@
|
||||
"60": "노을이 꽤 기대돼요. 해 지기 30분 전에 나가요.",
|
||||
"80": "노을 점수 높고 공기 맑음, 인생샷 각 📸"
|
||||
},
|
||||
"sort_order": 23
|
||||
"sort_order": 23,
|
||||
"priority": 2
|
||||
},
|
||||
{
|
||||
"code": "baseball",
|
||||
@@ -1596,7 +1635,8 @@
|
||||
"60": "직관 괜찮아요! 밤엔 선선하니 겉옷 하나.",
|
||||
"80": "15~25°에 비 걱정 없음, 응원가 목청껏 부르는 날 ⚾"
|
||||
},
|
||||
"sort_order": 24
|
||||
"sort_order": 24,
|
||||
"priority": 3
|
||||
},
|
||||
{
|
||||
"code": "study",
|
||||
@@ -1653,7 +1693,8 @@
|
||||
"60": "밖이 애매해서 책상에 앉을 만해요.",
|
||||
"80": "비 오고 춥거나 더워서 나갈 맛이 안 나요. 집중각 📚"
|
||||
},
|
||||
"sort_order": 25
|
||||
"sort_order": 25,
|
||||
"priority": 3
|
||||
},
|
||||
{
|
||||
"code": "netflix",
|
||||
@@ -1709,7 +1750,8 @@
|
||||
"60": "비 오거나 쌀쌀한 밤, 이불 속이 최고!",
|
||||
"80": "비 오는 주말 앞 밤, 정주행 시작각 🍿"
|
||||
},
|
||||
"sort_order": 26
|
||||
"sort_order": 26,
|
||||
"priority": 3
|
||||
},
|
||||
{
|
||||
"code": "chestnut",
|
||||
@@ -1763,6 +1805,524 @@
|
||||
"60": "손이 시려요. 따끈한 군밤 한 봉지!",
|
||||
"80": "영하 가까운 저녁, 군밤 품고 걷는 날 🌰"
|
||||
},
|
||||
"sort_order": 27
|
||||
"sort_order": 27,
|
||||
"priority": 3
|
||||
},
|
||||
{
|
||||
"code": "golf",
|
||||
"name": "골프각",
|
||||
"icon": "golf",
|
||||
"category": 1,
|
||||
"is_fun": false,
|
||||
"is_core": false,
|
||||
"has_detail": true,
|
||||
"description": "오전 7시~오후 5시, 필드에서 라운딩하기 좋은 정도",
|
||||
"windows": [
|
||||
{
|
||||
"from": 7,
|
||||
"to": 12
|
||||
},
|
||||
{
|
||||
"from": 12,
|
||||
"to": 17
|
||||
}
|
||||
],
|
||||
"weight_temp": 30,
|
||||
"weight_rain": 30,
|
||||
"weight_wind": 25,
|
||||
"weight_humidity": 5,
|
||||
"weight_air": 5,
|
||||
"weight_uv": 0,
|
||||
"weight_sun": 0,
|
||||
"weight_view": 0,
|
||||
"weight_time": 5,
|
||||
"factor_rules": {
|
||||
"temp": {
|
||||
"type": "range",
|
||||
"lo": 15,
|
||||
"hi": 24
|
||||
},
|
||||
"rain": {
|
||||
"dir": "dry"
|
||||
},
|
||||
"wind": {
|
||||
"type": "calm",
|
||||
"ok": 3,
|
||||
"limit": 9
|
||||
},
|
||||
"humidity": {
|
||||
"type": "range",
|
||||
"lo": 30,
|
||||
"hi": 60,
|
||||
"best": 35
|
||||
},
|
||||
"time": {
|
||||
"type": "weekday",
|
||||
"sat": 100,
|
||||
"sun": 100,
|
||||
"holiday": 100,
|
||||
"default": 70
|
||||
}
|
||||
},
|
||||
"zero_rules": [
|
||||
{
|
||||
"field": "rain_prob",
|
||||
"op": ">=",
|
||||
"value": 70
|
||||
},
|
||||
{
|
||||
"field": "wind_ms",
|
||||
"op": ">=",
|
||||
"value": 12
|
||||
},
|
||||
{
|
||||
"field": "warning",
|
||||
"op": "==",
|
||||
"value": "wind"
|
||||
}
|
||||
],
|
||||
"limit_description": "골프장 예약, 잔디 상태, 낙뢰는 반영하지 못해요",
|
||||
"sentences": {
|
||||
"0": "비 70% 넘거나 바람이 너무 세요. 오늘은 스크린으로!",
|
||||
"30": "춥거나 덥거나 바람이 공을 흔들어요. 타수는 기대 말기!",
|
||||
"60": "칠 만해요! 바람 방향만 잘 읽으면 돼요.",
|
||||
"80": "15~24°에 바람 잔잔, 인생 라운딩 노려볼 날 ⛳"
|
||||
},
|
||||
"sort_order": 28,
|
||||
"priority": 2
|
||||
},
|
||||
{
|
||||
"code": "jipkok",
|
||||
"name": "집콕각",
|
||||
"icon": "jipkok",
|
||||
"category": 3,
|
||||
"is_fun": true,
|
||||
"is_core": false,
|
||||
"has_detail": true,
|
||||
"description": "오전 10시~오후 6시, 나가기 싫어 집에 있고 싶은 정도",
|
||||
"windows": [
|
||||
{
|
||||
"from": 10,
|
||||
"to": 18
|
||||
}
|
||||
],
|
||||
"weight_temp": 30,
|
||||
"weight_rain": 30,
|
||||
"weight_wind": 10,
|
||||
"weight_humidity": 5,
|
||||
"weight_air": 20,
|
||||
"weight_uv": 0,
|
||||
"weight_sun": 0,
|
||||
"weight_view": 0,
|
||||
"weight_time": 5,
|
||||
"factor_rules": {
|
||||
"temp": {
|
||||
"type": "away",
|
||||
"lo": 15,
|
||||
"hi": 24
|
||||
},
|
||||
"rain": {
|
||||
"dir": "wet"
|
||||
},
|
||||
"wind": {
|
||||
"type": "strong"
|
||||
},
|
||||
"humidity": {
|
||||
"type": "higher"
|
||||
},
|
||||
"air": {
|
||||
"zero": 15,
|
||||
"full": 75
|
||||
},
|
||||
"time": {
|
||||
"type": "weekday",
|
||||
"sat": 100,
|
||||
"sun": 100,
|
||||
"holiday": 100,
|
||||
"default": 60
|
||||
}
|
||||
},
|
||||
"zero_rules": [],
|
||||
"limit_description": "재미로 보는 지수예요",
|
||||
"sentences": {
|
||||
"0": "밖이 너무 좋아요. 집에만 있기 아까운 날!",
|
||||
"30": "나갈까 말까, 소파와 밀당 중이에요.",
|
||||
"60": "덥거나 춥거나 공기가 탁해요. 집이 최고!",
|
||||
"80": "비 오고 공기까지 탁해요. 이불 밖은 위험해 🛋️"
|
||||
},
|
||||
"sort_order": 29,
|
||||
"priority": 3
|
||||
},
|
||||
{
|
||||
"code": "fishing",
|
||||
"name": "낚시각",
|
||||
"icon": "fishing",
|
||||
"category": 1,
|
||||
"is_fun": false,
|
||||
"is_core": false,
|
||||
"has_detail": true,
|
||||
"description": "새벽 5~9시·오후 4~7시, 물가에서 낚시하기 좋은 정도",
|
||||
"windows": [
|
||||
{
|
||||
"from": 5,
|
||||
"to": 9
|
||||
},
|
||||
{
|
||||
"from": 16,
|
||||
"to": 19
|
||||
}
|
||||
],
|
||||
"weight_temp": 25,
|
||||
"weight_rain": 25,
|
||||
"weight_wind": 35,
|
||||
"weight_humidity": 0,
|
||||
"weight_air": 5,
|
||||
"weight_uv": 0,
|
||||
"weight_sun": 0,
|
||||
"weight_view": 0,
|
||||
"weight_time": 10,
|
||||
"factor_rules": {
|
||||
"temp": {
|
||||
"type": "range",
|
||||
"lo": 12,
|
||||
"hi": 24
|
||||
},
|
||||
"rain": {
|
||||
"dir": "dry"
|
||||
},
|
||||
"wind": {
|
||||
"type": "calm",
|
||||
"ok": 4,
|
||||
"limit": 10
|
||||
},
|
||||
"humidity": {
|
||||
"type": "ignore"
|
||||
},
|
||||
"time": {
|
||||
"type": "weekday",
|
||||
"sat": 100,
|
||||
"sun": 100,
|
||||
"holiday": 100,
|
||||
"default": 60
|
||||
}
|
||||
},
|
||||
"zero_rules": [
|
||||
{
|
||||
"field": "rain_prob",
|
||||
"op": ">=",
|
||||
"value": 70
|
||||
},
|
||||
{
|
||||
"field": "wind_ms",
|
||||
"op": ">=",
|
||||
"value": 10
|
||||
},
|
||||
{
|
||||
"field": "warning",
|
||||
"op": "==",
|
||||
"value": "wind"
|
||||
}
|
||||
],
|
||||
"limit_description": "물때·수온·파도 높이는 반영하지 못해요",
|
||||
"sentences": {
|
||||
"0": "비 70% 넘거나 바람이 거세요. 물가는 위험, 오늘은 쉬어요!",
|
||||
"30": "바람에 찌가 흔들리거나 손이 시려요. 짧게 손맛만!",
|
||||
"60": "물가 나가볼 만해요! 새벽엔 쌀쌀하니 겉옷 챙기기.",
|
||||
"80": "12~24°에 물결 잔잔, 입질 기다리기 딱 좋은 날 🎣"
|
||||
},
|
||||
"sort_order": 30,
|
||||
"priority": 2
|
||||
},
|
||||
{
|
||||
"code": "drive",
|
||||
"name": "드라이브각",
|
||||
"icon": "drive",
|
||||
"category": 1,
|
||||
"is_fun": false,
|
||||
"is_core": false,
|
||||
"has_detail": true,
|
||||
"description": "오전 10시~오후 5시, 창문 열고 드라이브하기 좋은 정도",
|
||||
"windows": [
|
||||
{
|
||||
"from": 10,
|
||||
"to": 17
|
||||
}
|
||||
],
|
||||
"weight_temp": 20,
|
||||
"weight_rain": 30,
|
||||
"weight_wind": 5,
|
||||
"weight_humidity": 5,
|
||||
"weight_air": 15,
|
||||
"weight_uv": 0,
|
||||
"weight_sun": 0,
|
||||
"weight_view": 15,
|
||||
"weight_time": 10,
|
||||
"factor_rules": {
|
||||
"temp": {
|
||||
"type": "range",
|
||||
"lo": 15,
|
||||
"hi": 25
|
||||
},
|
||||
"rain": {
|
||||
"dir": "dry"
|
||||
},
|
||||
"wind": {
|
||||
"type": "calm",
|
||||
"ok": 6,
|
||||
"limit": 15
|
||||
},
|
||||
"humidity": {
|
||||
"type": "range",
|
||||
"lo": 30,
|
||||
"hi": 60,
|
||||
"best": 35
|
||||
},
|
||||
"time": {
|
||||
"type": "weekday",
|
||||
"sat": 100,
|
||||
"sun": 100,
|
||||
"holiday": 100,
|
||||
"default": 60
|
||||
},
|
||||
"view": {
|
||||
"zero": 5,
|
||||
"full": 20
|
||||
}
|
||||
},
|
||||
"zero_rules": [
|
||||
{
|
||||
"field": "rain_prob",
|
||||
"op": ">=",
|
||||
"value": 70,
|
||||
"cap": 20
|
||||
}
|
||||
],
|
||||
"limit_description": "길 막힘과 도로 공사는 반영하지 못해요",
|
||||
"sentences": {
|
||||
"0": "비가 쏟아져요. 와이퍼만 바쁜 날, 드라이브는 다음에!",
|
||||
"30": "하늘이 뿌옇거나 비 기운이 있어요. 가까운 곳만 슬쩍!",
|
||||
"60": "달릴 만해요! 창문 반쯤 열고 음악 크게.",
|
||||
"80": "공기 맑고 멀리까지 보여요. 해안도로 달리고 싶은 날 🚗"
|
||||
},
|
||||
"sort_order": 31,
|
||||
"priority": 1
|
||||
},
|
||||
{
|
||||
"code": "kite",
|
||||
"name": "연날리기각",
|
||||
"icon": "kite",
|
||||
"category": 1,
|
||||
"is_fun": false,
|
||||
"is_core": false,
|
||||
"has_detail": true,
|
||||
"description": "오전 11시~오후 4시, 연 날리기 좋은 정도",
|
||||
"windows": [
|
||||
{
|
||||
"from": 11,
|
||||
"to": 16
|
||||
}
|
||||
],
|
||||
"weight_temp": 20,
|
||||
"weight_rain": 25,
|
||||
"weight_wind": 45,
|
||||
"weight_humidity": 0,
|
||||
"weight_air": 5,
|
||||
"weight_uv": 0,
|
||||
"weight_sun": 0,
|
||||
"weight_view": 0,
|
||||
"weight_time": 5,
|
||||
"factor_rules": {
|
||||
"temp": {
|
||||
"type": "range",
|
||||
"lo": 8,
|
||||
"hi": 22
|
||||
},
|
||||
"rain": {
|
||||
"dir": "dry"
|
||||
},
|
||||
"wind": {
|
||||
"type": "moderate"
|
||||
},
|
||||
"humidity": {
|
||||
"type": "ignore"
|
||||
},
|
||||
"time": {
|
||||
"type": "weekday",
|
||||
"sat": 100,
|
||||
"sun": 100,
|
||||
"holiday": 100,
|
||||
"default": 70
|
||||
}
|
||||
},
|
||||
"zero_rules": [
|
||||
{
|
||||
"field": "rain_prob",
|
||||
"op": ">=",
|
||||
"value": 70
|
||||
},
|
||||
{
|
||||
"field": "gust_ms",
|
||||
"op": ">=",
|
||||
"value": 13
|
||||
},
|
||||
{
|
||||
"field": "wind_ms",
|
||||
"op": "<",
|
||||
"value": 1,
|
||||
"cap": 30
|
||||
}
|
||||
],
|
||||
"limit_description": "전깃줄·나무 없는 넓은 곳인지는 반영하지 못해요",
|
||||
"sentences": {
|
||||
"0": "비가 오거나 돌풍이 불어요. 연이 날아가 버려요!",
|
||||
"30": "바람이 너무 약하거나 너무 세요. 뛰어다녀야 겨우 떠요.",
|
||||
"60": "연 띄울 만해요! 실은 넉넉하게 감아 가요.",
|
||||
"80": "초속 2~5m 딱 좋은 바람, 연이 하늘 높이 쭉쭉 🪁"
|
||||
},
|
||||
"sort_order": 32,
|
||||
"priority": 3
|
||||
},
|
||||
{
|
||||
"code": "waterplay",
|
||||
"name": "물놀이각",
|
||||
"icon": "waterplay",
|
||||
"category": 1,
|
||||
"is_fun": false,
|
||||
"is_core": false,
|
||||
"has_detail": true,
|
||||
"description": "오전 11시~오후 5시, 바다·계곡에서 물놀이하기 좋은 정도",
|
||||
"windows": [
|
||||
{
|
||||
"from": 11,
|
||||
"to": 17
|
||||
}
|
||||
],
|
||||
"weight_temp": 40,
|
||||
"weight_rain": 25,
|
||||
"weight_wind": 10,
|
||||
"weight_humidity": 0,
|
||||
"weight_air": 0,
|
||||
"weight_uv": 0,
|
||||
"weight_sun": 20,
|
||||
"weight_view": 0,
|
||||
"weight_time": 5,
|
||||
"factor_rules": {
|
||||
"temp": {
|
||||
"type": "range",
|
||||
"lo": 27,
|
||||
"hi": 34,
|
||||
"best": 30
|
||||
},
|
||||
"rain": {
|
||||
"dir": "dry"
|
||||
},
|
||||
"wind": {
|
||||
"type": "calm",
|
||||
"ok": 4,
|
||||
"limit": 12
|
||||
},
|
||||
"humidity": {
|
||||
"type": "ignore"
|
||||
},
|
||||
"time": {
|
||||
"type": "weekday",
|
||||
"sat": 100,
|
||||
"sun": 100,
|
||||
"holiday": 100,
|
||||
"default": 60
|
||||
},
|
||||
"sun": {
|
||||
"zero": 0.2,
|
||||
"full": 0.8
|
||||
}
|
||||
},
|
||||
"zero_rules": [
|
||||
{
|
||||
"field": "rain_prob",
|
||||
"op": ">=",
|
||||
"value": 60
|
||||
},
|
||||
{
|
||||
"field": "feels_c",
|
||||
"op": "<",
|
||||
"value": 20
|
||||
}
|
||||
],
|
||||
"limit_description": "수온, 파도 높이, 계곡 물살은 반영하지 못해요",
|
||||
"sentences": {
|
||||
"0": "체감 20° 아래거나 비 소식이 있어요. 물놀이는 여름에!",
|
||||
"30": "물에 들어가면 으슬으슬해요. 발만 담그기!",
|
||||
"60": "물놀이 괜찮아요! 그늘막이랑 선크림 챙기기.",
|
||||
"80": "30° 안팎에 쨍쨍, 튜브 들고 풍덩 🏖️"
|
||||
},
|
||||
"sort_order": 33,
|
||||
"priority": 2
|
||||
},
|
||||
{
|
||||
"code": "kimjang",
|
||||
"name": "김장각",
|
||||
"icon": "kimchi",
|
||||
"category": 3,
|
||||
"is_fun": false,
|
||||
"is_core": false,
|
||||
"has_detail": true,
|
||||
"description": "오전 9시~오후 4시, 김장하기 좋은 정도",
|
||||
"windows": [
|
||||
{
|
||||
"from": 9,
|
||||
"to": 16
|
||||
}
|
||||
],
|
||||
"weight_temp": 50,
|
||||
"weight_rain": 25,
|
||||
"weight_wind": 10,
|
||||
"weight_humidity": 0,
|
||||
"weight_air": 5,
|
||||
"weight_uv": 0,
|
||||
"weight_sun": 0,
|
||||
"weight_view": 0,
|
||||
"weight_time": 10,
|
||||
"factor_rules": {
|
||||
"temp": {
|
||||
"type": "range",
|
||||
"lo": 0,
|
||||
"hi": 10,
|
||||
"best": 5
|
||||
},
|
||||
"rain": {
|
||||
"dir": "dry"
|
||||
},
|
||||
"wind": {
|
||||
"type": "calm",
|
||||
"ok": 4,
|
||||
"limit": 10
|
||||
},
|
||||
"humidity": {
|
||||
"type": "ignore"
|
||||
},
|
||||
"time": {
|
||||
"type": "weekday",
|
||||
"sat": 100,
|
||||
"sun": 100,
|
||||
"holiday": 100,
|
||||
"default": 50
|
||||
}
|
||||
},
|
||||
"zero_rules": [
|
||||
{
|
||||
"field": "feels_c",
|
||||
"op": ">=",
|
||||
"value": 18
|
||||
}
|
||||
],
|
||||
"limit_description": "배추 작황과 값, 집집마다 김장 날짜는 반영하지 못해요",
|
||||
"sentences": {
|
||||
"0": "아직 18° 넘어요. 지금 담그면 김치가 금방 쉬어요!",
|
||||
"30": "조금 이르거나 손이 꽁꽁 얼어요. 날을 다시 골라 봐요.",
|
||||
"60": "김장할 만해요! 고무장갑 안에 면장갑 하나 더.",
|
||||
"80": "0~10°에 비 없고 바람 잔잔, 김장 날 잡는 날 🥬"
|
||||
},
|
||||
"sort_order": 34,
|
||||
"priority": 3
|
||||
}
|
||||
]
|
||||
+11
-11
@@ -1,11 +1,11 @@
|
||||
region_name,area,name,is_outdoor,icon,reason,best_time,sort_order
|
||||
서울 성동구,성수,서울숲,1,picnic,돗자리 펴고 낮 피크닉,낮 12시~4시,1
|
||||
서울 성동구,성수,성수 갤러리 골목,0,photo,작은 전시와 팝업을 걸어서,비 오는 오후,2
|
||||
서울 마포구,연남·망원,경의선숲길,1,walk,해 질 녘 산책 데이트,저녁 6시 이후,3
|
||||
서울 마포구,연남·망원,망원한강공원,1,sunset,노을 명소 1위 강 건너 서쪽,노을 무렵,4
|
||||
서울 영등포구,여의도,여의도한강공원,1,chimaek,한강 치맥,저녁 7시,5
|
||||
서울 영등포구,여의도,더현대 서울,0,calendar,비 와도 하루 종일 실내,비 오는 날,6
|
||||
서울 송파구,잠실,석촌호수,1,walk,호수 한 바퀴 2.5km,선선한 저녁,7
|
||||
서울 송파구,잠실,롯데월드 아쿠아리움,0,rain,비 오는 날 실내 데이트,비 오는 오후,8
|
||||
서울 종로구,북촌·익선,북촌한옥마을,1,photo,맑은 날 한옥 골목 사진,오전 10시~,9
|
||||
서울 종로구,북촌·익선,국립현대미술관 서울관,0,bulb,비 오면 미술관으로,비 오는 날,10
|
||||
region_name,area,name,is_outdoor,icon,reason,best_time,sort_order,lat,lon,source
|
||||
서울 성동구,성수,서울숲,1,picnic,돗자리 펴고 낮 피크닉,낮 12시~4시,1,37.54307,127.04180,tourapi:128611
|
||||
서울 성동구,성수,성수 갤러리 골목,0,photo,작은 전시와 팝업을 걸어서,비 오는 오후,2,37.54320,127.05660,tourapi:2930901
|
||||
서울 마포구,연남·망원,경의선숲길,1,walk,해 질 녘 산책 데이트,저녁 6시 이후,3,37.56170,126.92306,tourapi:2553819
|
||||
서울 마포구,연남·망원,망원한강공원,1,sunset,노을 명소 1위 강 건너 서쪽,노을 무렵,4,37.55140,126.90050,tourapi:1059638
|
||||
서울 영등포구,여의도,여의도한강공원,1,chimaek,한강 치맥,저녁 7시,5,37.52640,126.93361,tourapi:1059479
|
||||
서울 영등포구,여의도,더현대 서울,0,calendar,비 와도 하루 종일 실내,비 오는 날,6,37.52710,126.92730,tourapi:2708109
|
||||
서울 송파구,잠실,석촌호수,1,walk,호수 한 바퀴 2.5km,선선한 저녁,7,37.50792,127.09894,tourapi:754052
|
||||
서울 송파구,잠실,롯데월드 아쿠아리움,0,rain,비 오는 날 실내 데이트,비 오는 오후,8,37.51417,127.10407,tourapi:2476731
|
||||
서울 종로구,북촌·익선,북촌한옥마을,1,photo,맑은 날 한옥 골목 사진,오전 10시~,9,37.57905,126.98671,tourapi:126537
|
||||
서울 종로구,북촌·익선,국립현대미술관 서울관,0,bulb,비 오면 미술관으로,비 오는 날,10,37.57865,126.98000,tourapi:1934593
|
||||
|
File diff suppressed because it is too large.
Load diff
@@ -154,3 +154,24 @@ region_name,name,description,lat,lon,west_open,source
|
||||
충남 홍성군,궁리포구,바다 너머 서쪽이 트임 · 충남 홍성군,36.58845,126.45721,1,tourapi:1937784
|
||||
충남 홍성군,남당노을전망대,바다 너머 서쪽이 트임 · 충남 홍성군,36.54428,126.4656,1,tourapi:3065226
|
||||
충남 홍성군,어사리 노을공원,바다 너머 서쪽이 트임 · 충남 홍성군,36.55615,126.46837,1,tourapi:2678991
|
||||
광주 동구,서석대,높은 곳에서 서쪽이 트임 · 광주 북구,35.14415,126.98900,1,tourapi:2614826
|
||||
세종 세종특별자치시,고운뜰공원,높은 곳에서 보는 도심 노을 · 세종,36.51255,127.23913,0,tourapi:2758467
|
||||
세종 세종특별자치시,청벽산,높은 곳에서 금강 너머 노을 · 충남 공주시,36.42857,127.22094,0,tourapi:2755172
|
||||
충남 금산군,대둔산도립공원(금산),낙조대까지 산행 · 충남 금산군,36.13746,127.34167,0,tourapi:128001
|
||||
충북 단양군,양방산전망대,높은 곳에서 남한강 너머 노을 · 충북 단양군,36.96837,128.38202,0,tourapi:1626685
|
||||
충북 음성군,백야둘레길,물가 노을 · 충북 음성군,36.96775,127.60332,0,tourapi:2782402
|
||||
강원 강릉시,강릉항여객터미널,육지 쪽 산으로 지는 해 · 강원 강릉시,37.77289,128.95289,0,tourapi:3546554
|
||||
경남 밀양시,낙동강철교전망대,물가 노을 · 경남 김해시,35.37512,128.82347,0,tourapi:2782619
|
||||
경북 영덕군,영덕조각공원,풍력단지 언덕 노을 · 경북 영덕군,36.42193,129.41761,0,tourapi:128718
|
||||
경기 연천군,임진강 주상절리,석양에 붉어지는 절벽 · 경기 연천군,38.01993,127.01545,0,tourapi:2569474
|
||||
강원 춘천시,구봉산 전망대 카페거리,높은 곳에서 서쪽이 트임 · 강원 춘천시,37.89250,127.77700,1,tourapi:129686
|
||||
경북 상주시,경천섬(경천섬공원),물가 노을 · 경북 상주시,36.45323,128.25506,0,tourapi:2756567
|
||||
강원 속초시,영랑호,물가 노을 · 강원 속초시,38.21422,128.58075,0,tourapi:127565;web:https://lady.khan.co.kr/finance/article/6492
|
||||
경남 함안군,함안 악양루,남강 절벽 위 노을 · 경남 함안군,35.33513,128.39847,0,tourapi:702331;web:https://www.knnews.co.kr/news/articleView.php?idxno=1425
|
||||
전북 완주군,비비정,만경강 낙조 · 전북 완주군,35.89901,127.06849,0,osm;web:https://jjan.kr/article/20251209500596
|
||||
경기 여주시,흥원창,남한강 물가 노을 · 강원 원주시,37.22665,127.75142,0,osm;web:https://xn--ok0b236bp0a.com/place/26309
|
||||
경북 영양군,선바위,강가 바위 위 석양 · 경북 영양군,36.60598,129.07461,0,osm;web:https://weekly.khan.co.kr/article/201111221629101
|
||||
경북 경주시,금장대,형산강 너머 서쪽 노을 · 경북 경주시,35.86066,129.20093,1,osm;web:https://www.telltrip.com/domestic-travel/gyeongju-geumjangdae-night-view-travel-tips/
|
||||
전남 강진군,강진만생태공원,물가 노을 · 전남 강진군,34.61961,126.77254,0,osm;web:https://m.seoul.co.kr/news/2022/11/24/20221124018005
|
||||
충북 영동군,함벽정,금강가 정자에서 보는 낙조 · 충북 영동군,36.13424,127.67067,0,osm;web:https://www.nhis.or.kr/static/alim/paper/oldpaper/202209/sub/14.html
|
||||
강원 평창군,육백마지기,높은 곳에서 서쪽이 트임 · 강원 평창군,37.41025,128.50836,1,osm;web:https://v.daum.net/v/Wr8Os0nbtv
|
||||
|
@@ -0,0 +1,27 @@
|
||||
from datetime import date, datetime, time, timedelta
|
||||
|
||||
from common.utils.kma_time import KST
|
||||
|
||||
SLOTS = ("morning", "day", "evening", "night")
|
||||
SLOT_LABEL = {"morning": "아침", "day": "낮", "evening": "저녁", "night": "밤"}
|
||||
NIGHT_AFTER_SUNSET = timedelta(hours=1) # 해 지고 이만큼 지나면 밤
|
||||
NIGHT_END_HOUR = 5
|
||||
|
||||
|
||||
def slot_of(now: datetime, sunset_at: datetime) -> str:
|
||||
"""아침 05–11 · 낮 11–일몰 2시간 전 · 저녁 일몰 2시간 전–일몰 1시간 뒤 · 밤 일몰 1시간 뒤–05. 밤은 계절 따라 18시대~21시대에 온다."""
|
||||
h = now.hour
|
||||
if NIGHT_END_HOUR <= h < 11:
|
||||
return "morning"
|
||||
if h >= 11 and now < sunset_at + NIGHT_AFTER_SUNSET:
|
||||
return "day" if now < sunset_at - timedelta(hours=2) else "evening"
|
||||
return "night"
|
||||
|
||||
|
||||
def slot_hours(day: date, sunset_at: datetime) -> dict[str, set[int]]:
|
||||
"""그날 5시~다음 날 5시를 구간별 시각으로 나눈다. 24 이상은 다음 날 시각. 한 시간은 그 30분 시점의 구간에 넣는다."""
|
||||
out: dict[str, set[int]] = {s: set() for s in SLOTS}
|
||||
start = datetime.combine(day, time(0), tzinfo=KST)
|
||||
for h in range(NIGHT_END_HOUR, 24 + NIGHT_END_HOUR):
|
||||
out[slot_of(start + timedelta(hours=h, minutes=30), sunset_at)].add(h)
|
||||
return out
|
||||
@@ -18,6 +18,13 @@ _FALL_FLOOR = exp(-0.5)
|
||||
# 편한 범위 안에서 최적값 ±이만큼은 100점 (기온 °, 습도 %p)
|
||||
_TEMP_PLATEAU = 2
|
||||
_HUMIDITY_PLATEAU = 5
|
||||
# 각 중요도(index_definition.priority)별 순위 가중치: 1=상 2=중 3=하. 순위만 바꾸고 보이는 점수는 그대로 둔다.
|
||||
PRIORITY_WEIGHT = {1: 1.0, 2: 0.85, 3: 0.7}
|
||||
|
||||
|
||||
def rank_score(score: int, priority: int) -> float:
|
||||
"""각 순위를 정하는 값 = 점수 × 중요도 가중치."""
|
||||
return score * PRIORITY_WEIGHT[priority]
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -108,7 +115,7 @@ def temp_score(rule: dict, feels: float) -> tuple[int, str]:
|
||||
shown = f"산 정상 기준 {round(t)}°" if rule.get("offset") else f"체감 {round(t)}°"
|
||||
if rule["type"] == "range":
|
||||
lo, hi = rule["lo"], rule["hi"]
|
||||
return _range(t, lo, hi, rule.get("best"), _TEMP_PLATEAU, 8), f"{shown}, 편한 범위 {lo}~{hi}° {'안' if lo <= t <= hi else '밖'}"
|
||||
return _range(t, lo, hi, rule.get("best"), rule.get("plateau", _TEMP_PLATEAU), 8), f"{shown}, 편한 범위 {lo}~{hi}° {'안' if lo <= t <= hi else '밖'}"
|
||||
if rule["type"] == "away":
|
||||
lo, hi = rule["lo"], rule["hi"]
|
||||
dist = 0 if lo <= t <= hi else min(abs(t - lo), abs(t - hi))
|
||||
@@ -154,10 +161,15 @@ def humidity_score(rule: dict, humidity: float) -> tuple[int, str]:
|
||||
return 50, f"{note}, 이 각엔 상관없어 50점으로 둬요"
|
||||
|
||||
|
||||
def air_score(pm25: Optional[int], label: Optional[str]) -> tuple[int, str]:
|
||||
_AIR_RULE = {"zero": 75, "full": 15}
|
||||
|
||||
|
||||
def air_score(pm25: Optional[int], label: Optional[str], rule: Optional[dict] = None) -> tuple[int, str]:
|
||||
"""rule 이 없으면 맑을수록 좋음. 집콕각처럼 탁할수록 좋은 각은 {"zero": 15, "full": 75} 로 뒤집는다."""
|
||||
if pm25 is None:
|
||||
return _UNKNOWN, f"미세먼지 정보가 없어 {_UNKNOWN}점으로 둬요"
|
||||
return _linear(pm25, 75, 15), f"초미세먼지 {pm25}㎍/㎥{', ' + label if label else ''}"
|
||||
rule = rule or _AIR_RULE
|
||||
return _linear(pm25, rule["zero"], rule["full"]), f"초미세먼지 {pm25}㎍/㎥{', ' + label if label else ''}"
|
||||
|
||||
|
||||
def uv_score(rule: dict, uv: Optional[float]) -> tuple[int, str]:
|
||||
@@ -208,7 +220,8 @@ def axis_label(axis: str, rules: dict) -> str:
|
||||
if axis == "rain":
|
||||
return "비 옴" if rules["rain"]["dir"] == "wet" else "비 안 옴"
|
||||
if axis == "air":
|
||||
return "공기 맑음"
|
||||
rule = rules.get("air", _AIR_RULE)
|
||||
return "공기 탁함" if rule["full"] > rule["zero"] else "공기 맑음"
|
||||
table = {"temp": _TEMP_LABEL, "wind": _WIND_LABEL, "humidity": _HUMIDITY_LABEL, "time": _TIME_LABEL}[axis]
|
||||
return table[rules[axis]["type"]]
|
||||
|
||||
@@ -304,7 +317,7 @@ def evaluate(definition, windows: list[list[Hour]], ctx: Context) -> Optional[Re
|
||||
"rain": rain_score(rules["rain"], max_prob, raining, until if max_prob > own_prob else ""),
|
||||
"wind": wind_score(rules["wind"], max(winds) if winds else None),
|
||||
"humidity": humidity_score(rules["humidity"], mean(h.humidity for h in hours)),
|
||||
"air": air_score(ctx.pm25, ctx.air_label),
|
||||
"air": air_score(ctx.pm25, ctx.air_label, rules.get("air")),
|
||||
"uv": uv_score(rules["uv"], max(uvs, default=None)) if weights["uv"] else (0, ""),
|
||||
"sun": sun_score(rules["sun"], mean(suns) if suns else None) if weights["sun"] else (0, ""),
|
||||
"view": view_score(rules["view"], min(views, default=None)) if weights["view"] else (0, ""),
|
||||
|
||||
@@ -5,10 +5,12 @@ from datetime import datetime, timedelta
|
||||
from common.enums import Confidence, SkyGrade, SkySituation, SkyType
|
||||
|
||||
DISTANCES_KM = (20, 100)
|
||||
# 물들 구름이 하나도 없을 때의 canvas 값. 50% 까지 곧게 올라가 맑은 날도 구름 몇 % 차이로 점수가 갈린다 (맑은 하늘 40점 = 은은함).
|
||||
_CLEAR_CANVAS = 0.2
|
||||
# 물들 구름이 하나도 없을 때의 canvas 값. 50% 까지 곧게 올라가 맑은 날도 구름 몇 % 차이로 점수가 갈린다 (맑은 하늘 55점 = 은은함).
|
||||
_CLEAR_CANVAS = 0.4
|
||||
# 해 지기(뜨기) 이만큼 전 사이에 비가 왔다가 그 시각엔 개면 공기가 맑고 구름이 남아 더 붉다.
|
||||
RAIN_BEFORE_HOURS = (2, 6)
|
||||
# 서쪽이 바다·강·전망대로 트여 해가 지평선까지 보이는 곳은 산·건물에 가리지 않아 노을이 더 잘 보인다.
|
||||
OPEN_WEST_BONUS = 1.1
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -25,6 +27,7 @@ class Air:
|
||||
humidity: float | None = None
|
||||
rain_before: int | None = None # RAIN_BEFORE_HOURS 사이 가장 높은 비 확률
|
||||
rain_now: int | None = None
|
||||
open_west: bool = False # 가까이 서쪽이 트인 노을 명소가 있음 (노을만)
|
||||
|
||||
|
||||
def score(near20: Layers, far100: Layers) -> int:
|
||||
@@ -36,21 +39,32 @@ def score(near20: Layers, far100: Layers) -> int:
|
||||
return round(100 * (0.75 * f_canvas + 0.25 * f_near) * (0.25 + 0.75 * light))
|
||||
|
||||
|
||||
def _ramp(v: float, bad: float, good: float, low: float) -> float:
|
||||
"""good 쪽은 1.0, bad 쪽은 low, 사이는 직선."""
|
||||
t = max(0.0, min(1.0, (v - bad) / (good - bad)))
|
||||
return low + (1 - low) * t
|
||||
# 공기 보정 기준점 (값, 배수). 평소 공기(가시거리 20km, 습도 60%)가 ×1.0 이고 좋으면 올리고 나쁘면 내린다. 양 끝 밖은 끝 값 그대로.
|
||||
_VISIBILITY_FACTOR = ((5, 0.8), (20, 1.0), (40, 1.12))
|
||||
_HUMIDITY_FACTOR = ((40, 1.06), (60, 1.0), (90, 0.85))
|
||||
|
||||
|
||||
def _interp(v: float, points: tuple[tuple[float, float], ...]) -> float:
|
||||
"""기준점 사이를 직선으로 잇는다."""
|
||||
if v <= points[0][0]:
|
||||
return points[0][1]
|
||||
for (x0, f0), (x1, f1) in zip(points, points[1:]):
|
||||
if v <= x1:
|
||||
return f0 + (f1 - f0) * (v - x0) / (x1 - x0)
|
||||
return points[-1][1]
|
||||
|
||||
|
||||
def air_factor(air: Air) -> float:
|
||||
"""공기로 구름 점수를 보정하는 배수. 뿌연 공기·높은 습도는 색을 흐리게 하고, 비 갠 뒤는 더 붉다."""
|
||||
"""공기로 구름 점수를 보정하는 배수. 맑고 건조하면 올리고 뿌옇거나 습하면 내린다. 비 갠 뒤는 더 붉다."""
|
||||
f = 1.0
|
||||
if air.visibility_km is not None:
|
||||
f *= _ramp(air.visibility_km, 5, 40, 0.6)
|
||||
f *= _interp(air.visibility_km, _VISIBILITY_FACTOR)
|
||||
if air.humidity is not None:
|
||||
f *= _ramp(air.humidity, 90, 50, 0.75)
|
||||
f *= _interp(air.humidity, _HUMIDITY_FACTOR)
|
||||
if air.rain_before is not None and air.rain_before >= 60 and (air.rain_now or 0) < 40:
|
||||
f *= 1.15
|
||||
if air.open_west:
|
||||
f *= OPEN_WEST_BONUS
|
||||
return f
|
||||
|
||||
|
||||
|
||||
+4
-2
@@ -8,6 +8,8 @@ from services.external.data_go_kr import get_all_items
|
||||
|
||||
REALTIME_URL = "https://apis.data.go.kr/B552584/ArpltnInforInqireSvc/getCtprvnRltmMesureDnsty"
|
||||
STATION_URL = "https://apis.data.go.kr/B552584/MsrstnInfoInqireSvc/getMsrstnList"
|
||||
# 전국 조회는 한 번에 15~20초 걸린다. 갱신은 피드 응답과 따로 돌아 기다리게 하지 않는다.
|
||||
BUDGET_SEC = 45.0
|
||||
|
||||
|
||||
def _int(v) -> Optional[int]:
|
||||
@@ -26,11 +28,11 @@ def _measured_at(text: str) -> datetime:
|
||||
|
||||
|
||||
async def fetch_realtime(client: httpx.AsyncClient) -> list[dict]:
|
||||
return await get_all_items(client, REALTIME_URL, {"returnType": "json", "sidoName": "전국", "ver": "1.0"})
|
||||
return await get_all_items(client, REALTIME_URL, {"returnType": "json", "sidoName": "전국", "ver": "1.0"}, budget_sec=BUDGET_SEC)
|
||||
|
||||
|
||||
async def fetch_stations(client: httpx.AsyncClient) -> list[dict]:
|
||||
return await get_all_items(client, STATION_URL, {"returnType": "json"})
|
||||
return await get_all_items(client, STATION_URL, {"returnType": "json"}, budget_sec=BUDGET_SEC)
|
||||
|
||||
|
||||
def parse_realtime(items: list[dict]) -> list[dict]:
|
||||
|
||||
+5
-4
@@ -1,4 +1,5 @@
|
||||
import asyncio
|
||||
from typing import Optional
|
||||
|
||||
import httpx
|
||||
|
||||
@@ -17,12 +18,12 @@ class DataGoKrRequestFailed(RuntimeError):
|
||||
pass
|
||||
|
||||
|
||||
async def get_body(client: httpx.AsyncClient, url: str, params: dict) -> dict:
|
||||
async def get_body(client: httpx.AsyncClient, url: str, params: dict, budget_sec: Optional[float] = None) -> dict:
|
||||
"""data.go.kr 공통 호출. 가끔 오는 504(SERVICETIMEOUT)는 다시 시도하고, 응답이 없으면 잠시 그 API 를 쉰다. 로그·예외에 키를 남기지 않는다."""
|
||||
if not settings.data_go_kr_service_key:
|
||||
raise DataGoKrNotConfigured("DATA_GO_KR_SERVICE_KEY is empty")
|
||||
op = url.rsplit("/", 1)[-1]
|
||||
return await guarded(f"datagokr:{op}", lambda: _get_body(client, url, op, params), DataGoKrRequestFailed)
|
||||
return await guarded(f"datagokr:{op}", lambda: _get_body(client, url, op, params), DataGoKrRequestFailed, budget_sec)
|
||||
|
||||
|
||||
async def _get_body(client: httpx.AsyncClient, url: str, op: str, params: dict) -> dict:
|
||||
@@ -44,11 +45,11 @@ async def _get_body(client: httpx.AsyncClient, url: str, op: str, params: dict)
|
||||
raise Unreachable(f"failed after {_ATTEMPTS} attempts: {last or 'unexpected body'}")
|
||||
|
||||
|
||||
async def get_all_items(client: httpx.AsyncClient, url: str, params: dict, page_size: int = 1000) -> list[dict]:
|
||||
async def get_all_items(client: httpx.AsyncClient, url: str, params: dict, page_size: int = 1000, budget_sec: Optional[float] = None) -> list[dict]:
|
||||
items: list[dict] = []
|
||||
page = 1
|
||||
while True:
|
||||
body = await get_body(client, url, {**params, "numOfRows": page_size, "pageNo": page})
|
||||
body = await get_body(client, url, {**params, "numOfRows": page_size, "pageNo": page}, budget_sec)
|
||||
raw = body.get("items") or []
|
||||
chunk = raw.get("item", []) if isinstance(raw, dict) else raw
|
||||
chunk = [chunk] if isinstance(chunk, dict) else chunk
|
||||
|
||||
Vendored
+21
-7
@@ -13,9 +13,19 @@ from common.enums import EVENT_ICON, EventKind
|
||||
SITEMAP_URL = "https://popga.co.kr/sitemap.xml"
|
||||
POPUP_URL = "https://popga.co.kr/popup/{id}"
|
||||
SOURCE_PREFIX = "popga:"
|
||||
STORE = "STORE" # 팝가 분류: STORE=팝업스토어, PERFORMANCE=공연, FESTIVAL=축제
|
||||
# 팝가 분류(STORE=팝업스토어, PERFORMANCE=공연, FESTIVAL=축제) 중 받는 것. 공연은 문화정보원에서 따로 받는다
|
||||
_KINDS = {"STORE": EventKind.POPUP, "FESTIVAL": EventKind.FESTIVAL}
|
||||
REQUEST_GAP_SEC = 0.3
|
||||
|
||||
# 팝가 '축제' 중 연극제·음악제의 공연 한 편. 극장·홀에서 하거나 이름이 공연이면 공연으로 넣는다
|
||||
_SHOW_PLACE = ("극장", "홀", "아트센터", "예술의전당", "씨어터", "시어터", "문화회관", "공연장")
|
||||
_SHOW_NAME = ("연극", "뮤지컬", "오페라", "독주회", "리사이틀", "콘서트")
|
||||
|
||||
|
||||
def is_show(name: str, place: str) -> bool:
|
||||
return any(w in place for w in _SHOW_PLACE) or any(w in name for w in _SHOW_NAME)
|
||||
|
||||
|
||||
_LOC = re.compile(r"<loc>\s*([^<\s]+)\s*</loc>")
|
||||
_URL = re.compile(r"<url>(.*?)</url>", re.S)
|
||||
_LASTMOD = re.compile(r"<lastmod>\s*([^<\s]+)\s*</lastmod>")
|
||||
@@ -86,10 +96,11 @@ def _coord(v) -> Optional[float]:
|
||||
|
||||
|
||||
def parse_popup(page: str, popup_id: int, since: date) -> Optional[dict]:
|
||||
"""팝업스토어이고 since 이후에 끝나면 event 행, 아니면 None."""
|
||||
kind = re.search(rf'\\?"id\\?":{popup_id},\\?"type\\?":\\?"([A-Z_]+)', page)
|
||||
"""팝업스토어·축제이고 since 이후에 끝나면 event 행, 아니면 None."""
|
||||
found = re.search(rf'\\?"id\\?":{popup_id},\\?"type\\?":\\?"([A-Z_]+)', page)
|
||||
kind = _KINDS.get(found.group(1)) if found else None
|
||||
ld = _event_ld(page)
|
||||
if kind is None or kind.group(1) != STORE or ld is None:
|
||||
if kind is None or ld is None:
|
||||
return None
|
||||
start, end = _date(ld.get("startDate")), _date(ld.get("endDate"))
|
||||
if start is None or end is None or end < since:
|
||||
@@ -99,9 +110,12 @@ def parse_popup(page: str, popup_id: int, since: date) -> Optional[dict]:
|
||||
if sido is None:
|
||||
return None
|
||||
geo = loc.get("geo") or {}
|
||||
name, place = html.unescape(ld.get("name") or ""), html.unescape(loc.get("name") or "")
|
||||
if kind is EventKind.FESTIVAL and is_show(name, place):
|
||||
kind = EventKind.CONCERT
|
||||
return {
|
||||
"source_id": f"{SOURCE_PREFIX}{popup_id}", "sido_code": sido, "name": html.unescape(ld.get("name") or "")[:60],
|
||||
"place_name": html.unescape(loc.get("name") or "")[:60], "start_date": start, "end_date": end, "is_confirmed": True,
|
||||
"source_id": f"{SOURCE_PREFIX}{popup_id}", "sido_code": sido, "name": name[:60],
|
||||
"place_name": place[:60], "start_date": start, "end_date": end, "is_confirmed": True,
|
||||
"source_url": POPUP_URL.format(id=popup_id), "image_url": None,
|
||||
"lat": _coord(geo.get("latitude")), "lon": _coord(geo.get("longitude")), "kind": EventKind.POPUP, "icon": EVENT_ICON[EventKind.POPUP],
|
||||
"lat": _coord(geo.get("latitude")), "lon": _coord(geo.get("longitude")), "kind": kind, "icon": EVENT_ICON[kind],
|
||||
}
|
||||
+68
@@ -0,0 +1,68 @@
|
||||
import asyncio
|
||||
import html
|
||||
import re
|
||||
from datetime import date, timedelta
|
||||
from typing import Optional
|
||||
|
||||
import httpx
|
||||
|
||||
from common.enums import EVENT_ICON, EventKind
|
||||
|
||||
# 서울문화포털 문화행사 중 축제. 공개 API 는 키가 따로 있어 robots.txt 가 허용하는 /culture/culture/ 목록을 읽는다.
|
||||
LIST_URL = "https://culture.seoul.go.kr/culture/culture/cultureEvent/jsonList.json"
|
||||
VIEW_URL = "https://culture.seoul.go.kr/culture/culture/cultureEvent/view.do?cultcode={code}&menuNo=200010"
|
||||
IMAGE_URL = "https://culture.seoul.go.kr/cmmn/file/getImage.do?atchFileId={id}&thumb=Y"
|
||||
IMAGE_CREDIT = "ⓒ서울문화포털"
|
||||
SOURCE_PREFIX = "seoul:"
|
||||
SEOUL = "11"
|
||||
REQUEST_GAP_SEC = 0.3
|
||||
_MAX_PAGES = 30
|
||||
# 이름 앞 주최 기관 "[서울시청] ", "[마포문화재단] " 은 카드 제목에서 뗀다
|
||||
_HOST_PREFIX = re.compile(r"^(\s*\[[^\]]*\]\s*)+")
|
||||
|
||||
|
||||
async def fetch_seoul_festivals(client: httpx.AsyncClient, since: date, days: int) -> list[dict]:
|
||||
"""since 부터 days 일 안에 열리는 서울 축제. 한 쪽에 10개씩, 빈 쪽이 나올 때까지."""
|
||||
form = {"menuNo": "200010", "searchCate": "FESTIVAL", "sdate": since.isoformat(), "edate": (since + timedelta(days=days)).isoformat()}
|
||||
items: list[dict] = []
|
||||
for page in range(1, _MAX_PAGES + 1):
|
||||
res = await client.post(LIST_URL, data={**form, "pageIndex": str(page)})
|
||||
res.raise_for_status()
|
||||
chunk = res.json().get("resultList") or []
|
||||
if not chunk:
|
||||
break
|
||||
items.extend(chunk)
|
||||
await asyncio.sleep(REQUEST_GAP_SEC)
|
||||
return items
|
||||
|
||||
|
||||
def _date(v) -> Optional[date]:
|
||||
try:
|
||||
return date.fromisoformat(str(v)[:10])
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
|
||||
def _coord(v) -> Optional[float]:
|
||||
try:
|
||||
return round(float(v), 5) if v not in (None, "") else None
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
|
||||
|
||||
def parse_seoul_festivals(items: list[dict]) -> list[dict]:
|
||||
rows = []
|
||||
for it in items:
|
||||
start, end = _date(it.get("strtdate")), _date(it.get("endDate"))
|
||||
name = _HOST_PREFIX.sub("", html.unescape(it.get("title") or "")).strip()
|
||||
if start is None or end is None or not name or it.get("cultcode") is None:
|
||||
continue
|
||||
rows.append({
|
||||
"source_id": f"{SOURCE_PREFIX}{it['cultcode']}", "sido_code": SEOUL, "name": name[:60],
|
||||
"place_name": html.unescape(it.get("facName") or it.get("addr") or "")[:60], "start_date": start, "end_date": end, "is_confirmed": True,
|
||||
"source_url": VIEW_URL.format(code=it["cultcode"]),
|
||||
"image_url": IMAGE_URL.format(id=it["atchFileId"]) if it.get("atchFileId") else None,
|
||||
# 이 목록은 xCoord 가 위도, yCoord 가 경도다
|
||||
"lat": _coord(it.get("xCoord")), "lon": _coord(it.get("yCoord")), "kind": EventKind.FESTIVAL, "icon": EVENT_ICON[EventKind.FESTIVAL],
|
||||
})
|
||||
return rows
|
||||
@@ -25,6 +25,8 @@ from router.v1.feed.protocol import (
|
||||
)
|
||||
from services.air_service import GRADE_LABEL as AIR_GRADE_LABEL
|
||||
from services.air_service import pm10_grade, pm25_grade
|
||||
from services.calc.day_slot import NIGHT_AFTER_SUNSET, slot_of
|
||||
from services.calc.index_calc import rank_score
|
||||
from services.calc.moon import illumination, nearest, phase_name
|
||||
from services.calc.sky_score import GRADE_LABEL, SITUATION_LINE
|
||||
from services.calc.sun import sun_times
|
||||
@@ -62,12 +64,25 @@ LINEUP = [
|
||||
(19, PostType.MOON, RefType.NONE, None),
|
||||
(20, PostType.UV, RefType.NONE, None),
|
||||
]
|
||||
# 좋아요·댓글 단위. 이 종류들은 전국이 같은 카드 하나, 나머지는 그 구 데이터로 채우는 카드라 시도마다 따로 만든다.
|
||||
NATIONAL_SCOPE = "00"
|
||||
NATIONAL_TYPES = frozenset({PostType.SEASON, PostType.TIP, PostType.QUOTE, PostType.MOON})
|
||||
|
||||
|
||||
def sido_of(region_code: str) -> str:
|
||||
"""구 행정코드의 시도 부분(앞 2자리)."""
|
||||
return region_code[:2]
|
||||
|
||||
|
||||
def post_scope(post_type: PostType, region_code: str) -> str:
|
||||
return NATIONAL_SCOPE if post_type in NATIONAL_TYPES else sido_of(region_code)
|
||||
|
||||
# 시간대별 순서. 목록에 없는 종류는 그 시간대에 꺼진다. '오늘 하루 날씨'는 히어로 바로 아래 고정이라 따로 둔다. 행사는 사이사이 무작위.
|
||||
ORDER = {
|
||||
"morning": [PostType.ALERT, PostType.AIR, PostType.UV, PostType.GAK, PostType.GAK, PostType.GAK, PostType.SEASON, PostType.SUNSET, PostType.TIP, PostType.WEEK, PostType.WEEKEND_PLAN, PostType.WEEKEND_PLAN, PostType.DAY_TRIP, PostType.MOON, PostType.QUOTE],
|
||||
"day": [PostType.GAK, PostType.ALERT, PostType.AIR, PostType.UV, PostType.GAK, PostType.GAK, PostType.SUNSET, PostType.WEEK, PostType.WEEKEND_PLAN, PostType.SEASON, PostType.WEEKEND_PLAN, PostType.DAY_TRIP, PostType.TIP, PostType.MOON, PostType.QUOTE],
|
||||
"evening": [PostType.SUNSET, PostType.GAK, PostType.ALERT, PostType.GAK, PostType.GAK, PostType.AIR, PostType.TOMORROW, PostType.WEEK, PostType.WEEKEND_PLAN, PostType.SEASON, PostType.WEEKEND_PLAN, PostType.DAY_TRIP, PostType.TIP, PostType.MOON, PostType.QUOTE],
|
||||
"night": [PostType.TOMORROW, PostType.ALERT, PostType.SUNSET, PostType.WEEK, PostType.GAK, PostType.WEEKEND_PLAN, PostType.GAK, PostType.GAK, PostType.WEEKEND_PLAN, PostType.DAY_TRIP, PostType.AIR, PostType.SEASON, PostType.TIP, PostType.MOON, PostType.QUOTE],
|
||||
"evening": [PostType.SUNSET, PostType.GAK, PostType.MOON, PostType.ALERT, PostType.GAK, PostType.GAK, PostType.AIR, PostType.TOMORROW, PostType.WEEK, PostType.WEEKEND_PLAN, PostType.SEASON, PostType.WEEKEND_PLAN, PostType.DAY_TRIP, PostType.TIP, PostType.QUOTE],
|
||||
"night": [PostType.TOMORROW, PostType.MOON, PostType.ALERT, PostType.SUNSET, PostType.WEEK, PostType.GAK, PostType.WEEKEND_PLAN, PostType.GAK, PostType.GAK, PostType.WEEKEND_PLAN, PostType.DAY_TRIP, PostType.AIR, PostType.SEASON, PostType.TIP, PostType.QUOTE],
|
||||
}
|
||||
_SKY_MODE = {"morning": "morning", "day": "day", "evening": "sunset", "night": "night"}
|
||||
_CATEGORY_META = {ArticleCategory.SEASON.value: "계절 소식", ArticleCategory.TIP.value: "날씨 상식", ArticleCategory.GAK.value: "각 원리", ArticleCategory.QUOTE.value: "한 문장"}
|
||||
@@ -139,22 +154,12 @@ def feed_day(now: datetime) -> date:
|
||||
return (now - timedelta(hours=_FEED_DAY_START)).date()
|
||||
|
||||
|
||||
def slot_of(now: datetime, sunset_at: datetime) -> str:
|
||||
"""아침 05–11 · 낮 11–일몰 2시간 전 · 저녁 일몰 2시간 전–21 · 밤 21–05."""
|
||||
h = now.hour
|
||||
if 5 <= h < 11:
|
||||
return "morning"
|
||||
if 11 <= h < 21:
|
||||
return "day" if now < sunset_at - timedelta(hours=2) else "evening"
|
||||
return "night"
|
||||
|
||||
|
||||
def feed_ttl_sec(now: datetime, sunset_at: datetime) -> int:
|
||||
"""다음에 피드가 달라지는 시각까지. 시간대 경계·일몰(노을 카드가 내일 것으로)·03:00·예보·미세먼지 갱신 중 가장 빠른 쪽."""
|
||||
day = now.date()
|
||||
at = lambda d, h: datetime.combine(d, time(h), tzinfo=KST) # noqa: E731
|
||||
sunset = sunset_at.astimezone(KST)
|
||||
changes = [at(day, _FEED_DAY_START), at(day, 5), at(day, 11), sunset - timedelta(hours=2), sunset, at(day, 21),
|
||||
changes = [at(day, _FEED_DAY_START), at(day, 5), at(day, 11), sunset - timedelta(hours=2), sunset, sunset + NIGHT_AFTER_SUNSET,
|
||||
at(day + timedelta(days=1), _FEED_DAY_START), next_vilage_available(now)]
|
||||
air = now.replace(minute=20, second=0, microsecond=0)
|
||||
changes.append(air if air > now else air + timedelta(hours=1))
|
||||
@@ -222,17 +227,33 @@ def arrange(cards: list[PostData], slot: str, now: datetime, sunset_at: datetime
|
||||
return head + rest
|
||||
|
||||
|
||||
def _by_position(posts: list[Post]) -> list[Post]:
|
||||
"""번호마다 하나. 전국 행과 시도 행이 같이 있으면 전국 행을 쓴다 (지역 카드라도 그날 전국 행이 있으면 전국이 그 행을 같이 쓴다)."""
|
||||
out: dict[int, Post] = {}
|
||||
for p in sorted(posts, key=lambda p: (p.position, p.scope != NATIONAL_SCOPE)):
|
||||
out.setdefault(p.position, p)
|
||||
return list(out.values())
|
||||
|
||||
|
||||
def _top(i: IndexItem) -> TopIndex:
|
||||
d = i.definition
|
||||
return TopIndex(index_id=d.index_id, code=d.code, name=d.name, icon=d.icon, score=i.score.score, rank=i.rank, summary=i.score.summary)
|
||||
return TopIndex(index_id=d.index_id, code=d.code, name=d.name, icon=d.icon, score=i.score.score, rank=i.rank, summary=i.score.summary, active=i.active)
|
||||
|
||||
|
||||
async def build_feed_day(day: date, crud: FeedCRUD, season_crud: SeasonCRUD) -> ErrorType:
|
||||
"""그날 피드 카드를 넣는다. 이미 있는 번호는 그대로 두고, 새로 생긴 종류만 더한다. 모든 카드는 03:00 부터 다음 날 03:00 까지 유효하다."""
|
||||
async def build_feed_day(day: date, crud: FeedCRUD, season_crud: SeasonCRUD, regions: RegionCRUD) -> ErrorType:
|
||||
"""그날 피드 카드를 전국 1벌·시도마다 1벌 넣는다. 이미 있는 (scope, 번호)는 그대로 두고, 빠진 것만 더한다.
|
||||
전국 행이 있는 번호는 모든 시도가 그 행을 쓰므로 시도 행을 만들지 않는다. 모든 카드는 03:00 부터 다음 날 03:00 까지 유효하다."""
|
||||
err, made = await DB_SESSION_MNG.execute_lambda(lambda s: crud.positions(s, day))
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return err
|
||||
lineup = [x for x in LINEUP if x[0] not in made]
|
||||
err, all_regions = await DB_SESSION_MNG.execute_lambda(lambda s: regions.search(s))
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return err
|
||||
sidos = sorted({sido_of(r.code) for r in all_regions})
|
||||
lineup = [
|
||||
(scope, *x) for x in LINEUP for scope in ([NATIONAL_SCOPE] if x[1] in NATIONAL_TYPES else sidos)
|
||||
if (scope, x[0]) not in made and (NATIONAL_SCOPE, x[0]) not in made
|
||||
]
|
||||
if not lineup:
|
||||
return err
|
||||
_, season = await DB_SESSION_MNG.execute_lambda(lambda s: season_crud.articles(s, day, ArticleCategory.SEASON.value))
|
||||
@@ -241,12 +262,12 @@ async def build_feed_day(day: date, crud: FeedCRUD, season_crud: SeasonCRUD) ->
|
||||
start = kst_midnight(day) + timedelta(hours=_FEED_DAY_START)
|
||||
end = start + timedelta(days=1)
|
||||
rows = []
|
||||
for position, post_type, ref_type, rank in lineup:
|
||||
for scope, position, post_type, ref_type, rank in lineup:
|
||||
ref = refs.get(post_type)
|
||||
if ref_type is RefType.ARTICLE and ref is None:
|
||||
continue
|
||||
rows.append({
|
||||
"feed_date": day, "position": position, "post_type": post_type.value, "ref_type": ref_type.value,
|
||||
"feed_date": day, "position": position, "scope": scope, "post_type": post_type.value, "ref_type": ref_type.value,
|
||||
"ref_id": ref.article_id if ref is not None else None, "index_rank": rank,
|
||||
"published_at": start, "end_at": end,
|
||||
})
|
||||
@@ -300,7 +321,7 @@ class FeedService:
|
||||
|
||||
day = feed_day(now)
|
||||
async with redis_lock("lock:feed:build", ttl_sec=20):
|
||||
await build_feed_day(day, self.crud, self.season_crud)
|
||||
await build_feed_day(day, self.crud, self.season_crud, self.regions)
|
||||
res, partial = await self._assemble(region, now, day, slot, sunset_at)
|
||||
try:
|
||||
await REDIS.conn.set(key, res.model_dump_json(), ex=_PARTIAL_TTL if partial else feed_ttl_sec(now, sunset_at))
|
||||
@@ -331,7 +352,8 @@ class FeedService:
|
||||
_, hourly = await DB_SESSION_MNG.execute_lambda(
|
||||
lambda s: self.weather_crud.hourly_between(s, region.code, hour, kst_midnight(now.date() + timedelta(days=2)))
|
||||
)
|
||||
_, posts = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.day(s, day))
|
||||
_, posts = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.day(s, day, [NATIONAL_SCOPE, sido_of(region.code)]))
|
||||
posts = _by_position(posts or [])
|
||||
_, articles = await DB_SESSION_MNG.execute_lambda(lambda s: self.season_crud.articles(s, now.date(), None))
|
||||
by_article = {a.article_id: a for a in articles or []}
|
||||
quotes = [a for a in articles or [] if a.category == ArticleCategory.QUOTE.value]
|
||||
@@ -339,7 +361,7 @@ class FeedService:
|
||||
days=days, events=events, sunsets=sunsets, hourly=hourly or [], articles=by_article, quotes=quotes, trip=trip,
|
||||
uv=await self._uv_today(region.code, now))
|
||||
|
||||
gak = sorted(board.items[:3], key=lambda i: _gak_key(i, now.hour)) if board else []
|
||||
gak = sorted(board.ranked[:3], key=lambda i: _gak_key(i, now.hour)) if board else []
|
||||
cards = []
|
||||
for p in posts or []:
|
||||
if PostType(p.post_type) is PostType.GAK:
|
||||
@@ -359,9 +381,10 @@ class FeedService:
|
||||
bands=Bands(
|
||||
events=[BandEvent(event_id=e.event.event_id, name=e.event.name, status_label=e.status_label, icon=e.event.icon,
|
||||
image=e.event.image_url, image_credit=image_credit(e.event)) for e in mix_kinds(events)[:4]],
|
||||
top5=[_top(i) for i in items[:5]],
|
||||
top5=[_top(i) for i in board.ranked[:5]] if board else [],
|
||||
season=[
|
||||
BandArticle(article_id=a.article_id, title=a.title, meta=f"{_CATEGORY_META[a.category]} · {a.read_minutes}분", icon=a.icon)
|
||||
BandArticle(article_id=a.article_id, title=a.title, meta=f"{_CATEGORY_META[a.category]} · {a.read_minutes}분", icon=a.icon,
|
||||
image=a.image_url, image_credit=a.image_credit)
|
||||
for a in articles or [] if a.category == ArticleCategory.SEASON.value
|
||||
],
|
||||
),
|
||||
@@ -401,7 +424,7 @@ class FeedService:
|
||||
|
||||
def _hero(self, now: datetime, slot: str, cur: Optional[WeatherHourly], now_w: Optional[NowWeather], board: Optional[IndexBoard],
|
||||
today: Optional[TodayWeather] = None, uv: Optional[float] = None) -> Hero:
|
||||
top = board.items[0] if board and board.items else None
|
||||
top = board.ranked[0] if board and board.ranked else None
|
||||
bubble = None
|
||||
if top is not None:
|
||||
bubble = f"오늘은 {top.definition.name}!" if top.score.score >= 70 else "오늘은 쉬어 가요"
|
||||
@@ -449,7 +472,8 @@ class FeedService:
|
||||
if t in (PostType.SEASON, PostType.TIP) and p.ref_id in c.articles:
|
||||
a = c.articles[p.ref_id]
|
||||
return PostData(**base, title=a.title, icon=a.icon, caption=" ".join(a.body[1:2]) or a.body[0],
|
||||
slides=[RowsSlide(kind="rows", eyebrow=_CATEGORY_META[a.category], line=a.body[0], icon=a.icon)], share_messages=[a.title])
|
||||
slides=[RowsSlide(kind="rows", eyebrow=_CATEGORY_META[a.category], line=a.body[0], icon=a.icon, image=a.image_url, image_credit=a.image_credit)],
|
||||
share_messages=[a.title])
|
||||
if t is PostType.EVENT:
|
||||
soon = mix_kinds([e for e in c.events if e.event.start_date <= c.now.date() + timedelta(days=7) and e.event.end_date >= c.now.date()])
|
||||
rank = p.index_rank or 1
|
||||
@@ -655,7 +679,7 @@ class FeedService:
|
||||
best = None
|
||||
for i in c.board.items if c.board else []:
|
||||
s = next((x for x in i.trend if x.score_date == tomorrow), None)
|
||||
if s is not None and (best is None or s.score > best[1].score):
|
||||
if s is not None and (best is None or rank_score(s.score, i.definition.priority) > rank_score(best[1].score, best[0].definition.priority)):
|
||||
best = (i, s)
|
||||
if best is not None:
|
||||
rows.append(Row(label="내일 1위 각", value=f"{best[0].definition.name} {best[1].score}점"))
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import asyncio
|
||||
from dataclasses import dataclass, replace
|
||||
from dataclasses import dataclass, field, replace
|
||||
from datetime import date, datetime, time, timedelta
|
||||
from types import SimpleNamespace
|
||||
from typing import Optional
|
||||
@@ -16,7 +16,8 @@ from crud.sky_crud import SkyCRUD
|
||||
from crud.weather_crud import WeatherCRUD
|
||||
from crud.week_crud import WeekCRUD
|
||||
from services.air_service import GRADE_LABEL, AirService
|
||||
from services.calc.index_calc import AXES, Context, DayForecast, Hour, Result, estimate, evaluate
|
||||
from services.calc.day_slot import NIGHT_END_HOUR, SLOTS, slot_hours, slot_of
|
||||
from services.calc.index_calc import AXES, Context, DayForecast, Hour, Result, estimate, evaluate, rank_score
|
||||
from services.calc.moon import illumination
|
||||
from services.calc.sun import sun_times
|
||||
from services.external.open_meteo import is_dark_slot
|
||||
@@ -28,14 +29,15 @@ DAYS = 3
|
||||
_LOOKAHEAD_HOURS = (9, 18)
|
||||
_WEEKDAY_KO = ("월", "화", "수", "목", "금", "토", "일")
|
||||
|
||||
# 메인 하늘 영역의 '오늘 날씨 점수': 낮 9~21시 밖에 나가기 좋은 정도.
|
||||
# 메인 하늘 영역의 '지금 날씨 점수': 지금 구간(아침·낮·저녁·밤) 밖에 나가기 좋은 정도.
|
||||
WEATHER_SCORE_DEF = SimpleNamespace(
|
||||
weight_temp=40, weight_rain=30, weight_wind=15, weight_humidity=0, weight_air=15, weight_time=0,
|
||||
weight_temp=30, weight_rain=25, weight_wind=10, weight_humidity=10, weight_air=10, weight_sun=15, weight_time=0,
|
||||
factor_rules={
|
||||
"temp": {"type": "range", "lo": 18, "hi": 24}, "rain": {"dir": "dry"}, "wind": {"type": "calm", "ok": 4, "limit": 12},
|
||||
"humidity": {"type": "ignore"}, "time": {"type": "fixed", "value": 100},
|
||||
"temp": {"type": "range", "lo": 18, "hi": 24, "best": 21, "plateau": 0.5}, "rain": {"dir": "dry"},
|
||||
"wind": {"type": "calm", "ok": 2, "limit": 10}, "humidity": {"type": "range", "lo": 40, "hi": 60, "best": 50},
|
||||
"air": {"zero": 75, "full": 10}, "sun": {"zero": 0.2, "full": 0.9}, "time": {"type": "fixed", "value": 100},
|
||||
},
|
||||
zero_rules=[], windows=[{"from": 9, "to": 21}],
|
||||
zero_rules=[], windows=[{"from": NIGHT_END_HOUR, "to": 24 + NIGHT_END_HOUR}],
|
||||
)
|
||||
|
||||
|
||||
@@ -45,6 +47,9 @@ class IndexItem:
|
||||
score: IndexScore
|
||||
rank: int
|
||||
trend: list[IndexScore]
|
||||
slot: Optional[str] = None
|
||||
slots: dict[str, int] = field(default_factory=dict)
|
||||
active: bool = True # 지금 구간이 이 각의 시간대와 겹치는지. 아니면 순위·피드에서 빼고 목록 끝에 하루 점수로 둔다
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -54,6 +59,11 @@ class IndexBoard:
|
||||
weather_score: Optional[int]
|
||||
items: list[IndexItem]
|
||||
|
||||
@property
|
||||
def ranked(self) -> list[IndexItem]:
|
||||
"""지금 구간에 해당하는 각만 (순위·피드용)."""
|
||||
return [i for i in self.items if i.active]
|
||||
|
||||
|
||||
def _hour(r: WeatherHourly) -> Hour:
|
||||
return Hour(
|
||||
@@ -118,13 +128,17 @@ def _om_fields(instant: Optional[OpenMeteoHourly], covering: Optional[OpenMeteoH
|
||||
|
||||
|
||||
def windows_for(
|
||||
defn, day: date, region: Region, by_at: dict[datetime, WeatherHourly], by_om: Optional[dict[datetime, OpenMeteoHourly]] = None
|
||||
defn, day: date, region: Region, by_at: dict[datetime, WeatherHourly], by_om: Optional[dict[datetime, OpenMeteoHourly]] = None,
|
||||
only: Optional[set[int]] = None,
|
||||
) -> list[list[Hour]]:
|
||||
"""시간대 정의를 그날의 시간별 날씨 목록으로 바꾼다. 24시 이후는 다음 날로 넘어간다. 시간마다 Open-Meteo 3시간 구간 값을 붙인다 (순간값은 가장 가까운 구간, 일조는 덮는 구간)."""
|
||||
"""시간대 정의를 그날의 시간별 날씨 목록으로 바꾼다. 24시 이후는 다음 날로 넘어간다. 시간마다 Open-Meteo 3시간 구간 값을 붙인다 (순간값은 가장 가까운 구간, 일조는 덮는 구간).
|
||||
only 가 있으면 그 시각만 남긴다."""
|
||||
by_om = by_om or {}
|
||||
start = kst_midnight(day)
|
||||
out = []
|
||||
for hours in window_hours(defn, day, region):
|
||||
if only is not None:
|
||||
hours = [h for h in hours if h in only]
|
||||
rows = [by_at.get(start + timedelta(hours=h)) for h in hours]
|
||||
out.append([
|
||||
replace(_hour(r), hour=h, **_om_fields(
|
||||
@@ -135,6 +149,44 @@ def windows_for(
|
||||
return out
|
||||
|
||||
|
||||
EARLY = "early" # 0~5시: 전날 밤 구간
|
||||
|
||||
|
||||
def current_slot(now: datetime, sunset_at: datetime) -> str:
|
||||
return EARLY if now.hour < NIGHT_END_HOUR else slot_of(now, sunset_at)
|
||||
|
||||
|
||||
def shown_slot(key: str) -> str:
|
||||
return "night" if key == EARLY else key
|
||||
|
||||
|
||||
def slot_results(
|
||||
defn, day: date, region: Region, by_at: dict[datetime, WeatherHourly], by_om: dict[datetime, OpenMeteoHourly], ctx: Context, sunset_at: datetime,
|
||||
) -> dict[str, Result]:
|
||||
"""그날 아침·낮·저녁·밤과 0~5시(전날 밤) 점수. 각 시간대와 겹치지 않는 구간은 빠진다."""
|
||||
parts = {k: windows_for(defn, day, region, by_at, by_om, only=hours) for k, hours in slot_hours(day, sunset_at).items()}
|
||||
parts[EARLY] = windows_for(defn, day - timedelta(days=1), region, by_at, by_om, only=set(range(24, 24 + NIGHT_END_HOUR)))
|
||||
out = {}
|
||||
for key, windows in parts.items():
|
||||
result = evaluate(defn, windows, ctx)
|
||||
if result is not None:
|
||||
out[key] = result
|
||||
return out
|
||||
|
||||
|
||||
def _slot_json(r: Result) -> dict:
|
||||
return {"score": r.score, "summary": r.summary, "factors": r.factors, "zero_reason": r.zero_reason, "notes": r.notes}
|
||||
|
||||
|
||||
def _with_slot(row: IndexScore, data: dict) -> IndexScore:
|
||||
"""저장된 하루 점수 행을 구간 점수로 바꾼 사본 (DB에 붙지 않음)."""
|
||||
out = IndexScore(**{c.key: getattr(row, c.key) for c in IndexScore.__table__.columns})
|
||||
out.score, out.summary, out.zero_reason, out.notes = data["score"], data["summary"], data["zero_reason"], data["notes"]
|
||||
for a in AXES:
|
||||
setattr(out, f"{a}_score", data["factors"].get(a, 0))
|
||||
return out
|
||||
|
||||
|
||||
def day_forecast(d: WeatherDaily) -> DayForecast:
|
||||
return DayForecast(
|
||||
temp_min_c=float(d.temp_min_c) if d.temp_min_c is not None else None,
|
||||
@@ -204,20 +256,44 @@ class IndexService:
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return err, None
|
||||
today = now.date()
|
||||
cur = current_slot(now, sun_times(today, float(region.lat), float(region.lon)).sunset_at)
|
||||
slots = slot_days(today)
|
||||
err, defs = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.definitions(s))
|
||||
err2, scores = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.scores(s, region.code, today, slots[-1]))
|
||||
if ErrorType.DB_ERROR in (err, err2):
|
||||
return ErrorType.DB_ERROR, None
|
||||
by_key = {(x.index_id, x.score_date): x for x in scores}
|
||||
ranked = sorted((d for d in defs if (d.index_id, today) in by_key), key=lambda d: by_key[(d.index_id, today)].score, reverse=True)
|
||||
items = [
|
||||
IndexItem(
|
||||
definition=d, score=by_key[(d.index_id, today)], rank=i + 1,
|
||||
trend=[by_key[k] for k in ((d.index_id, day) for day in slots) if k in by_key],
|
||||
)
|
||||
for i, d in enumerate(ranked)
|
||||
]
|
||||
# 오늘 점수는 지금 구간 점수. 구간 점수가 없는 행(예전 계산분)은 하루 점수 그대로, 지금 구간과 안 겹치는 각은 뺀다
|
||||
now_score: dict[int, IndexScore] = {}
|
||||
for d in defs:
|
||||
row = by_key.get((d.index_id, today))
|
||||
if row is None:
|
||||
continue
|
||||
if not row.slots:
|
||||
now_score[d.index_id] = row
|
||||
elif cur in row.slots:
|
||||
now_score[d.index_id] = _with_slot(row, row.slots[cur])
|
||||
ranked = sorted((d for d in defs if d.index_id in now_score), key=lambda d: rank_score(now_score[d.index_id].score, d.priority), reverse=True)
|
||||
items = []
|
||||
for i, d in enumerate(ranked):
|
||||
row = by_key[(d.index_id, today)]
|
||||
parts = {shown_slot(k): v["score"] for k, v in row.slots.items() if k != ("night" if cur == EARLY else EARLY)}
|
||||
items.append(IndexItem(
|
||||
definition=d, score=now_score[d.index_id], rank=i + 1,
|
||||
trend=[now_score[d.index_id] if day == today else by_key[(d.index_id, day)] for day in slots if (d.index_id, day) in by_key],
|
||||
slot=shown_slot(cur), slots={k: parts[k] for k in SLOTS if k in parts},
|
||||
))
|
||||
off = sorted(
|
||||
(d for d in defs if d.index_id not in now_score and (d.index_id, today) in by_key),
|
||||
key=lambda d: rank_score(by_key[(d.index_id, today)].score, d.priority), reverse=True,
|
||||
)
|
||||
for d in off:
|
||||
row = by_key[(d.index_id, today)]
|
||||
items.append(IndexItem(
|
||||
definition=d, score=row, rank=len(items) + 1,
|
||||
trend=[by_key[(d.index_id, day)] for day in slots if (d.index_id, day) in by_key],
|
||||
slots={shown_slot(k): v["score"] for k, v in row.slots.items() if k != ("night" if cur == EARLY else EARLY)}, active=False,
|
||||
))
|
||||
return ErrorType.SUCCESS, IndexBoard(region=region, day=today, weather_score=weather_score, items=items)
|
||||
|
||||
async def ensure(self, region: Region, now: datetime) -> tuple[ErrorType, Optional[int]]:
|
||||
@@ -250,7 +326,8 @@ class IndexService:
|
||||
wind_warning=any(w.warning_type is WarningType.WIND for w in warnings or []),
|
||||
)
|
||||
today_ctx = Context(day=today, is_holiday=False, moon=0, sunset_score=None, lookahead_rain_prob=0, **base_ctx)
|
||||
weather_result = evaluate(WEATHER_SCORE_DEF, windows_for(WEATHER_SCORE_DEF, today, region, by_at, by_om), today_ctx)
|
||||
sunset_at = sun_times(today, float(region.lat), float(region.lon)).sunset_at
|
||||
weather_result = slot_results(WEATHER_SCORE_DEF, today, region, by_at, by_om, today_ctx, sunset_at).get(current_slot(now, sunset_at))
|
||||
|
||||
issued = max([r.issued_at for r in rows] + [d.issued_at for d in daily_rows or []])
|
||||
inputs_at = max(issued, air.measured_at) if air else issued
|
||||
@@ -258,8 +335,9 @@ class IndexService:
|
||||
inputs_at = max(inputs_at, max(r.fetched_at for r in by_om.values()))
|
||||
err, computed = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.last_computed(s, region.code, today))
|
||||
_, scored = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.score_dates(s, region.code, today, days[-1]))
|
||||
_, unslotted = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.has_unslotted(s, region.code, today))
|
||||
wanted = {d for d in days if d >= today + timedelta(days=DAYS) and d in daily and None not in (daily[d].temp_min_c, daily[d].temp_max_c)}
|
||||
if err is ErrorType.SUCCESS and computed is not None and computed >= inputs_at and wanted <= (scored or set()):
|
||||
if err is ErrorType.SUCCESS and computed is not None and computed >= inputs_at and wanted <= (scored or set()) and unslotted is False:
|
||||
return ErrorType.SUCCESS, weather_result.score if weather_result else None
|
||||
|
||||
err, defs = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.definitions(s))
|
||||
@@ -278,10 +356,12 @@ class IndexService:
|
||||
result = day_result(d, day, region, by_at, daily, ctx, short=day < today + timedelta(days=DAYS), by_om=by_om)
|
||||
if result is None:
|
||||
continue
|
||||
parts = slot_results(d, day, region, by_at, by_om, ctx, sunset_at) if day == today else {}
|
||||
out.append({
|
||||
"region_code": region.code, "score_date": day, "index_id": d.index_id, "score": result.score, "summary": result.summary,
|
||||
**{f"{a}_score": result.factors[a] for a in AXES}, "zero_reason": result.zero_reason, "notes": result.notes,
|
||||
"estimated": result.estimated, "computed_at": now,
|
||||
"slots": {k: _slot_json(r) for k, r in parts.items()},
|
||||
})
|
||||
err = await DB_SESSION_MNG.execute_lambda_run([lambda s: self.crud.upsert_scores(s, out)])
|
||||
return err, weather_result.score if weather_result else None
|
||||
@@ -1,7 +1,7 @@
|
||||
import asyncio
|
||||
import math
|
||||
import statistics
|
||||
from dataclasses import dataclass
|
||||
from dataclasses import dataclass, replace
|
||||
from datetime import date, datetime, timedelta, timezone
|
||||
from typing import Optional
|
||||
|
||||
@@ -31,6 +31,7 @@ DAYS = 3
|
||||
SPOT_RADIUS_KM = EVENT_RADIUS_KM
|
||||
SPOT_LIMIT = 3
|
||||
_MARKER_TTL = 24 * 3600
|
||||
OPEN_WEST_KM = 20 # 이 안에 서쪽이 트인 명소가 있으면 노을 가산 (부안 채석강·진도 세방낙조가 구 중심에서 10km 넘게 떨어져 있어 20km)
|
||||
_background: set[asyncio.Task] = set()
|
||||
|
||||
|
||||
@@ -79,10 +80,12 @@ class RankItem:
|
||||
|
||||
|
||||
def nearest_spots(lat: float, lon: float, spots: list[SunsetSpot]) -> list[Spot]:
|
||||
"""반경 안에서 해 지는 쪽이 트인 곳(sort_order 0)을 먼저, 그 안에서는 가까운 순."""
|
||||
near = [Spot(spot=p, distance_km=round(haversine_km(lat, lon, float(p.lat), float(p.lon)), 1), direction=bearing_deg(lat, lon, float(p.lat), float(p.lon)))
|
||||
for p in spots]
|
||||
near = [x for x in near if x.distance_km <= SPOT_RADIUS_KM]
|
||||
"""반경 안에서 해 지는 쪽이 트인 곳(sort_order 0)을 먼저, 그 안에서는 가까운 순. 반경 안에 없으면 가장 가까운 한 곳."""
|
||||
every = [Spot(spot=p, distance_km=round(haversine_km(lat, lon, float(p.lat), float(p.lon)), 1), direction=bearing_deg(lat, lon, float(p.lat), float(p.lon)))
|
||||
for p in spots]
|
||||
near = [x for x in every if x.distance_km <= SPOT_RADIUS_KM]
|
||||
if not near:
|
||||
return sorted(every, key=lambda x: x.distance_km)[:1]
|
||||
return sorted(near, key=lambda x: (x.spot.sort_order, x.distance_km))[:SPOT_LIMIT]
|
||||
|
||||
|
||||
@@ -171,11 +174,19 @@ def _air(
|
||||
)
|
||||
|
||||
|
||||
def _open_west(region: Region, spots: list[SunsetSpot]) -> bool:
|
||||
"""구 중심 OPEN_WEST_KM 안에 서쪽이 트인 노을 명소가 있는지."""
|
||||
lat, lon = float(region.lat), float(region.lon)
|
||||
return any(haversine_km(lat, lon, float(p.lat), float(p.lon)) <= OPEN_WEST_KM for p in spots)
|
||||
|
||||
|
||||
def _score_rows(
|
||||
region: Region, today: date, clouds: dict, now: datetime,
|
||||
hourly: Optional[dict[tuple[str, datetime], WeatherHourly]] = None, om: Optional[dict[tuple[str, datetime], OpenMeteoHourly]] = None,
|
||||
open_west: bool = False,
|
||||
) -> list[dict]:
|
||||
"""구름 점수(모델 평균)에 공기 보정(가시거리·습도·비 갠 뒤)을 곱한다. 공기 값이 없으면 구름 점수 그대로."""
|
||||
"""구름 점수(모델 평균)에 공기 보정(가시거리·습도·비 갠 뒤)을 곱한다. 공기 값이 없으면 구름 점수 그대로.
|
||||
open_west 면 노을에만 서쪽이 트인 곳 가산을 더한다."""
|
||||
rows = []
|
||||
for kind in (SkyType.SUNSET, SkyType.SUNRISE):
|
||||
for i in range(DAYS):
|
||||
@@ -193,7 +204,7 @@ def _score_rows(
|
||||
model_layers.append(layers)
|
||||
if not per_model:
|
||||
continue
|
||||
value = min(100, round(statistics.mean(per_model) * air_factor(_air(region.code, sun_at, hourly or {}, om or {}))))
|
||||
value = min(100, round(statistics.mean(per_model) * air_factor(replace(_air(region.code, sun_at, hourly or {}, om or {}), open_west=open_west and kind is SkyType.SUNSET))))
|
||||
sit = situation(*(mean_layers([m[k] for m in model_layers]) for k in range(len(DISTANCES_KM))))
|
||||
rows.append({
|
||||
"region_code": region.code, "score_date": d, "sky_type": kind.value, "score": value, "grade": grade(value).value,
|
||||
@@ -362,7 +373,10 @@ class SkyService:
|
||||
LOG.error(f"[sky] air openmeteo: {err.name}")
|
||||
hourly = {(w.region_code, w.forecast_at): w for w in hourly_rows or []}
|
||||
om = {(o.region_code, o.forecast_at): o for o in om_rows or []}
|
||||
score_rows = [row for r in regions for row in _score_rows(r, today, clouds, now, hourly, om)]
|
||||
err, west_spots = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.west_open_spots(s))
|
||||
if err is not ErrorType.SUCCESS:
|
||||
LOG.error(f"[sky] west spots: {err.name}")
|
||||
score_rows = [row for r in regions for row in _score_rows(r, today, clouds, now, hourly, om, _open_west(r, west_spots or []))]
|
||||
err = await DB_SESSION_MNG.execute_lambda_run([
|
||||
lambda s: self.crud.upsert_clouds(s, cloud_rows),
|
||||
lambda s: self.crud.upsert_scores(s, score_rows),
|
||||
|
||||
@@ -170,19 +170,33 @@ class WeatherService:
|
||||
"""예보가 지났으면 새로 받는다. 이미 있으면 뒤에서 갱신하고, background=False 면 받을 때까지 기다린다."""
|
||||
latest = latest_vilage_base(now)
|
||||
err, issued = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.latest_issued(s, region.code))
|
||||
if err is not ErrorType.SUCCESS or (issued is not None and issued >= latest):
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return
|
||||
from_midnight = issued is None or await self._midnight_missing(region, now)
|
||||
if issued is not None and issued >= latest and not from_midnight:
|
||||
return
|
||||
if issued is None or not background:
|
||||
await self._refresh(region, now, latest, wait=issued is None)
|
||||
await self._refresh(region, now, latest, wait=issued is None, from_midnight=from_midnight)
|
||||
return
|
||||
task = asyncio.create_task(self._refresh(region, now, latest, wait=False))
|
||||
task = asyncio.create_task(self._refresh(region, now, latest, wait=False, from_midnight=from_midnight))
|
||||
_background.add(task)
|
||||
task.add_done_callback(_background.discard)
|
||||
|
||||
async def _refresh(self, region: Region, now: datetime, latest: datetime, wait: bool) -> None:
|
||||
async def _midnight_missing(self, region: Region, now: datetime) -> bool:
|
||||
"""오늘 0시 칸이 비었는지. 전날 23시 발표 받기가 실패했을 때 다시 받되, 10분에 한 번만 시도한다."""
|
||||
err, has = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.has_hourly_at(s, region.code, kst_midnight(now.date())))
|
||||
if err is not ErrorType.SUCCESS or has:
|
||||
return False
|
||||
try:
|
||||
return bool(await REDIS.conn.set(f"vilage0:{region.code}:{now:%Y%m%d}", "1", ex=600, nx=True))
|
||||
except RedisError as e:
|
||||
LOG.error(f"[weather] {region.code} midnight retry: {e}")
|
||||
return False
|
||||
|
||||
async def _refresh(self, region: Region, now: datetime, latest: datetime, wait: bool, from_midnight: bool) -> None:
|
||||
async with redis_lock(f"lock:vilage:{region.code}") as acquired:
|
||||
if acquired:
|
||||
bases = [day_start_base(now.date()), latest] if wait else [latest]
|
||||
bases = [day_start_base(now.date()), latest] if from_midnight else [latest]
|
||||
await self._fetch_and_store(region, sorted(set(bases)))
|
||||
return
|
||||
if wait:
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
import asyncio
|
||||
import math
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
from datetime import date, timedelta
|
||||
from typing import Optional
|
||||
@@ -20,11 +22,16 @@ from crud.index_crud import IndexCRUD
|
||||
from crud.region_crud import RegionCRUD
|
||||
from crud.weather_crud import WeatherCRUD
|
||||
from crud.week_crud import WeekCRUD
|
||||
from services.calc.index_calc import rank_score
|
||||
from services.external.culture_api import IMAGE_CREDIT as CULTURE_CREDIT
|
||||
from services.external.culture_api import SOURCE_PREFIX as CULTURE_PREFIX
|
||||
from services.external.culture_api import CONCERT, EXHIBITION, fetch_exhibitions, parse_exhibitions
|
||||
from services.external.data_go_kr import DataGoKrNotConfigured, DataGoKrRequestFailed
|
||||
from services.external.kasi import fetch_holidays
|
||||
from services.external.seoul_culture import IMAGE_CREDIT as SEOUL_CREDIT
|
||||
from services.external.seoul_culture import SEOUL
|
||||
from services.external.seoul_culture import SOURCE_PREFIX as SEOUL_PREFIX
|
||||
from services.external.seoul_culture import fetch_seoul_festivals, parse_seoul_festivals
|
||||
from services.external.tour_api import IMAGE_CREDIT as TOUR_CREDIT
|
||||
from services.external.tour_api import fetch_festivals, parse_festivals
|
||||
from services.index_service import IndexService
|
||||
@@ -36,6 +43,12 @@ MAX_EVENT_DAYS = 60
|
||||
EVENT_RADIUS_KM = 30
|
||||
# 행사는 시도 단위로 받는다. 구 중심이 이 거리 안에 있는 시도는 경계가 반경에 걸칠 수 있어 같이 받는다.
|
||||
_SIDO_REACH_KM = EVENT_RADIUS_KM + 20
|
||||
# 구 코드는 광주·전남을 한 시도(12)로 묶지만, 행사는 TourAPI·문화정보 시도 코드(광주 29 · 전남 46)로 받는다.
|
||||
_EVENT_SIDOS = {"12": ("29", "46")}
|
||||
PLACE_RADIUS_KM = EVENT_RADIUS_KM
|
||||
PLACE_LIMIT = 10
|
||||
# 반경 안에 명소가 하나도 없는 구는 가장 가까운 곳을 이만큼 거리와 함께 보여 준다.
|
||||
PLACE_FALLBACK = 3
|
||||
_ERRORS = (DataGoKrNotConfigured, DataGoKrRequestFailed, RedisError)
|
||||
_WEEKDAY_KO = ("월", "화", "수", "목", "금", "토", "일")
|
||||
_SKY_WORD = {Sky.CLEAR: "맑음", Sky.PARTLY: "구름 많음", Sky.CLOUDY: "흐림"}
|
||||
@@ -62,6 +75,7 @@ class DayPlan:
|
||||
class PlaceItem:
|
||||
place: Place
|
||||
is_good: bool
|
||||
distance_km: float
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -97,6 +111,8 @@ def image_credit(e: Event) -> Optional[str]:
|
||||
"""사진 출처 표기. 직접 넣은 행사(source_id 없음)는 출처를 모르니 None."""
|
||||
if not e.image_url or e.source_id is None:
|
||||
return None
|
||||
if e.source_id.startswith(SEOUL_PREFIX):
|
||||
return SEOUL_CREDIT
|
||||
return CULTURE_CREDIT if e.source_id.startswith(CULTURE_PREFIX) else TOUR_CREDIT
|
||||
|
||||
|
||||
@@ -115,11 +131,18 @@ def mix_kinds(items: list[EventItem]) -> list[EventItem]:
|
||||
return mixed
|
||||
|
||||
|
||||
def event_sidos(region_code: str) -> tuple[str, ...]:
|
||||
"""구가 속한 시도의 행사 시도 코드들."""
|
||||
sido = region_code[:2]
|
||||
return _EVENT_SIDOS.get(sido, (sido,))
|
||||
|
||||
|
||||
def nearby_sidos(region: Region, regions: list[Region]) -> list[str]:
|
||||
"""반경 안에 걸칠 수 있는 시도들. 자기 시도는 항상 앞에."""
|
||||
"""반경 안에 걸칠 수 있는 시도들(행사 시도 코드). 자기 시도는 항상 앞에."""
|
||||
lat, lon = float(region.lat), float(region.lon)
|
||||
near = {r.code[:2] for r in regions if haversine_km(lat, lon, float(r.lat), float(r.lon)) <= _SIDO_REACH_KM}
|
||||
return [region.code[:2]] + sorted(near - {region.code[:2]})
|
||||
own = event_sidos(region.code)
|
||||
near = {s for r in regions if haversine_km(lat, lon, float(r.lat), float(r.lon)) <= _SIDO_REACH_KM for s in event_sidos(r.code)}
|
||||
return list(own) + sorted(near - set(own))
|
||||
|
||||
|
||||
def event_distance(region: Region, e: Event) -> Optional[float]:
|
||||
@@ -134,7 +157,23 @@ def is_nearby(region: Region, e: Event, distance_km: Optional[float]) -> bool:
|
||||
return distance_km <= EVENT_RADIUS_KM
|
||||
if e.region_code is not None:
|
||||
return e.region_code == region.code
|
||||
return e.sido_code == region.code[:2]
|
||||
return e.sido_code in event_sidos(region.code)
|
||||
|
||||
|
||||
def pick_places(region: Region, places: list[Place], rainy: bool, area: Optional[str]) -> tuple[list[PlaceItem], list[str]]:
|
||||
"""구 중심에서 반경 안의 명소를 날씨에 맞는 것 먼저, 같으면 가까운 순으로. 반경 안에 없으면 가장 가까운 몇 곳."""
|
||||
lat, lon = float(region.lat), float(region.lon)
|
||||
dist = sorted(((p, round(haversine_km(lat, lon, float(p.lat), float(p.lon)), 1)) for p in places if p.lat is not None and p.lon is not None), key=lambda x: x[1])
|
||||
near = [x for x in dist if x[1] <= PLACE_RADIUS_KM] or dist[:PLACE_FALLBACK]
|
||||
areas = list(dict.fromkeys(p.area for p, _ in near))
|
||||
items = [PlaceItem(place=p, is_good=(not p.is_outdoor) if rainy else p.is_outdoor, distance_km=d) for p, d in near if area is None or p.area == area]
|
||||
items.sort(key=lambda i: (not i.is_good, i.distance_km))
|
||||
return items[:PLACE_LIMIT], areas
|
||||
|
||||
|
||||
def place_credit(p: Place) -> Optional[str]:
|
||||
"""명소 사진은 TourAPI 것만 넣는다."""
|
||||
return TOUR_CREDIT if p.image_url else None
|
||||
|
||||
|
||||
def _status(e: Event, today: date) -> tuple[str, str]:
|
||||
@@ -155,17 +194,59 @@ async def _culture(client: httpx.AsyncClient, sido: str, today: date, realm: str
|
||||
return []
|
||||
|
||||
|
||||
# 같은 축제를 두 출처가 다르게 적는다: "[성동문화재단] 2026 크리에이티브X성수" ↔ "2026 크리에이티브X성수"
|
||||
_NAME_NOISE = re.compile(r"\[[^\]]*\]|\([^)]*\)|20\d\d|제\s*\d+\s*회|[^\w]")
|
||||
|
||||
|
||||
def _name_key(name: str) -> str:
|
||||
return _NAME_NOISE.sub("", name).lower()
|
||||
|
||||
|
||||
async def drop_known(rows: list[dict]) -> list[dict]:
|
||||
"""다른 출처로 이미 들어 있는 행사(같은 시도, 이름이 같고 기간이 겹침)는 뺀다. 먼저 넣은 출처를 남긴다."""
|
||||
if not rows:
|
||||
return rows
|
||||
since, until = min(r["start_date"] for r in rows), max(r["end_date"] for r in rows)
|
||||
err, existing = await DB_SESSION_MNG.execute_lambda(lambda s: WeekCRUD().events(s, sorted({r["sido_code"] for r in rows}), since, until))
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return rows
|
||||
known: dict[tuple[str, str], list[Event]] = {}
|
||||
for e in existing or []:
|
||||
known.setdefault((e.sido_code, _name_key(e.name)), []).append(e)
|
||||
|
||||
def dup(r: dict) -> bool:
|
||||
key = _name_key(r["name"])
|
||||
return bool(key) and any(e.source_id != r["source_id"] and e.start_date <= r["end_date"] and r["start_date"] <= e.end_date
|
||||
for e in known.get((r["sido_code"], key), []))
|
||||
|
||||
return [r for r in rows if not dup(r)]
|
||||
|
||||
|
||||
async def _seoul(client: httpx.AsyncClient, sido: str, today: date, known: list[dict]) -> list[dict]:
|
||||
"""서울문화포털 축제(동네·구청·공원 행사). TourAPI 에 이미 있는 축제는 뺀다. 실패해도 다른 출처는 그대로 넣는다."""
|
||||
if sido != SEOUL:
|
||||
return []
|
||||
try:
|
||||
rows = parse_seoul_festivals(await fetch_seoul_festivals(client, today, EVENT_DAYS))
|
||||
except (httpx.HTTPError, ValueError) as e:
|
||||
LOG.error(f"[week] seoul festivals: {type(e).__name__} {e}")
|
||||
return []
|
||||
names = {_name_key(r["name"]) for r in known}
|
||||
return [r for r in rows if _name_key(r["name"]) not in names]
|
||||
|
||||
|
||||
async def collect_events(sido: str, today: date) -> tuple[ErrorType, dict[str, int]]:
|
||||
"""시도 하나의 축제·전시·콘서트를 받아 event 에 넣는다. 종류별 건수를 돌려준다."""
|
||||
try:
|
||||
async with httpx.AsyncClient(timeout=30) as client:
|
||||
festivals = parse_festivals(await fetch_festivals(client, sido, today), sido)
|
||||
festivals += await _seoul(client, sido, today, festivals)
|
||||
exhibitions = await _culture(client, sido, today, EXHIBITION)
|
||||
concerts = await _culture(client, sido, today, CONCERT)
|
||||
except (DataGoKrNotConfigured, DataGoKrRequestFailed) as e:
|
||||
LOG.error(f"[week] events {sido}: {e}")
|
||||
return ErrorType.EXTERNAL_API_ERROR, {}
|
||||
rows = list({r["source_id"]: r for r in festivals + exhibitions + concerts}.values())
|
||||
rows = await drop_known(list({r["source_id"]: r for r in festivals + exhibitions + concerts}.values()))
|
||||
err = await DB_SESSION_MNG.execute_lambda_run([lambda s: WeekCRUD().upsert_events(s, rows)])
|
||||
LOG.info(f"[week] events {sido} {len(rows)}: {err.name}")
|
||||
return err, {"festival": len(festivals), "exhibition": len(exhibitions), "concert": len(concerts)}
|
||||
@@ -205,11 +286,12 @@ class WeekService:
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return err, []
|
||||
names = {d.index_id: d.name for d in defs or []}
|
||||
priority = {d.index_id: d.priority for d in defs or []}
|
||||
plans = []
|
||||
for d in daily:
|
||||
rows = [r for r in hourly or [] if r.forecast_at.astimezone(KST).date() == d.forecast_date]
|
||||
rain_hours = _rain_hours(rows)
|
||||
top = sorted((x for x in scores or [] if x.score_date == d.forecast_date and not x.estimated), key=lambda x: x.score, reverse=True)[:2]
|
||||
top = sorted((x for x in scores or [] if x.score_date == d.forecast_date and not x.estimated), key=lambda x: rank_score(x.score, priority.get(x.index_id, 2)), reverse=True)[:2]
|
||||
holiday = (holidays or {}).get(d.forecast_date)
|
||||
weekday = _WEEKDAY_KO[d.forecast_date.weekday()]
|
||||
word = _weather_word(d, rain_hours)
|
||||
@@ -229,19 +311,21 @@ class WeekService:
|
||||
))
|
||||
return ErrorType.SUCCESS, plans
|
||||
|
||||
async def places(self, region_code: str, day: date, area: Optional[str]) -> tuple[ErrorType, list[PlaceItem], list[str]]:
|
||||
async def places(self, region_code: str, day: date, area: Optional[str]) -> tuple[ErrorType, list[PlaceItem], list[str], bool]:
|
||||
err, region = await self._region(region_code)
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return err, [], []
|
||||
err, places = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.places(s, region.code[:2]))
|
||||
return err, [], [], False
|
||||
lat, lon = float(region.lat), float(region.lon)
|
||||
dlat, dlon = PLACE_RADIUS_KM / 111, PLACE_RADIUS_KM / (111 * math.cos(math.radians(lat)))
|
||||
err, places = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.places_in_box(s, lat, lon, dlat, dlon))
|
||||
if err is ErrorType.SUCCESS and not any(haversine_km(lat, lon, float(p.lat), float(p.lon)) <= PLACE_RADIUS_KM for p in places):
|
||||
err, places = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.all_places(s))
|
||||
_, daily = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.daily(s, region.code, day, day))
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return err, [], []
|
||||
return err, [], [], False
|
||||
rainy = bool(daily) and daily[0].rain_type != RainType.NONE.value
|
||||
areas = list(dict.fromkeys(p.area for p in places))
|
||||
picked = [p for p in places if area is None or p.area == area]
|
||||
picked.sort(key=lambda p: (p.is_outdoor if rainy else not p.is_outdoor, p.sort_order))
|
||||
return ErrorType.SUCCESS, [PlaceItem(place=p, is_good=(not p.is_outdoor) if rainy else p.is_outdoor) for p in picked], areas
|
||||
items, areas = pick_places(region, places, rainy, area)
|
||||
return ErrorType.SUCCESS, items, areas, rainy
|
||||
|
||||
async def events(self, region_code: str, area: Optional[str]) -> tuple[ErrorType, list[EventItem]]:
|
||||
err, region = await self._region(region_code)
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
from datetime import date, datetime
|
||||
from typing import Optional
|
||||
|
||||
from common.enums import EventKind
|
||||
from common.utils.kma_time import KST
|
||||
from common.utils.text import day_range, short_day
|
||||
from services.week_service import DayPlan, EventItem, image_credit
|
||||
@@ -10,6 +12,8 @@ _HOT = 28
|
||||
_COLD = 10
|
||||
_BIG_GAP = 10
|
||||
_MAX_EVENTS = 2
|
||||
# 주말 동선은 축제를 먼저, 전시는 마지막. 가깝다고 미술관만 이어지지 않게
|
||||
_KIND_RANK = {EventKind.FESTIVAL: 0, EventKind.CONCERT: 1, EventKind.POPUP: 2, EventKind.EXHIBITION: 3}
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -77,11 +81,16 @@ def forecast(days: list[DayPlan]) -> WeekendForecast:
|
||||
|
||||
|
||||
def pick_events(d: date, events: list[EventItem], exclude: frozenset[int] = frozenset()) -> list[EventItem]:
|
||||
"""그날 열리는 행사 중 가까운 순. 일요일은 그날 끝나는 것을 먼저 (마지막 날 찬스)."""
|
||||
"""그날 열리는 행사를 축제→공연→팝업→전시 순으로 종류마다 하나씩, 같은 종류는 가까운 순. 일요일은 같은 종류 안에서 그날 끝나는 것을 먼저 (마지막 날 찬스)."""
|
||||
sunday = d.weekday() == 6
|
||||
open_ = [e for e in events if e.event.start_date <= d <= e.event.end_date and e.event.event_id not in exclude]
|
||||
open_.sort(key=lambda e: (sunday and e.event.end_date != d, e.distance_km if e.distance_km is not None else 9999))
|
||||
return open_[:_MAX_EVENTS]
|
||||
open_.sort(key=lambda e: (_KIND_RANK.get(e.event.kind, len(_KIND_RANK)), sunday and e.event.end_date != d,
|
||||
e.distance_km if e.distance_km is not None else 9999))
|
||||
first, rest, kinds = [], [], set()
|
||||
for e in open_:
|
||||
(rest if e.event.kind in kinds else first).append(e)
|
||||
kinds.add(e.event.kind)
|
||||
return (first + rest)[:_MAX_EVENTS]
|
||||
|
||||
|
||||
def _place(e: EventItem) -> str:
|
||||
@@ -150,7 +159,7 @@ def _sort(steps: list[Step]) -> list[Step]:
|
||||
def key(s: Step) -> float:
|
||||
t = s.time
|
||||
if t[0].isdigit():
|
||||
h = int(t.split("~")[0].split(":")[0])
|
||||
h = int(re.match(r"\d+", t).group())
|
||||
return 5.5 if h >= 17 else 1.5 if h < 12 else 3
|
||||
if t.startswith("~"):
|
||||
return 0
|
||||
|
||||
@@ -65,6 +65,14 @@ async def _async(v):
|
||||
return v
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _no_seoul_crawl(monkeypatch):
|
||||
"""서울문화포털은 키 없이 바로 긁어 오므로, 테스트가 실제 사이트를 부르지 않게 기본으로 막는다."""
|
||||
import services.week_service as week_service
|
||||
|
||||
monkeypatch.setattr(week_service, "fetch_seoul_festivals", lambda *a: _async([]))
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def offline(monkeypatch):
|
||||
"""외부 API 를 모두 맑고 잔잔한 가짜 값으로 바꾼다."""
|
||||
|
||||
@@ -5,7 +5,8 @@ import httpx
|
||||
import pytest
|
||||
|
||||
from config.settings import settings
|
||||
from services.external import data_go_kr, guard, open_meteo
|
||||
from services.external import airkorea, data_go_kr, guard, open_meteo
|
||||
from services.external.airkorea import fetch_realtime
|
||||
from services.external.data_go_kr import DataGoKrRequestFailed, get_body
|
||||
from services.external.open_meteo import OpenMeteoRequestFailed, fetch_clouds
|
||||
|
||||
@@ -93,3 +94,16 @@ async def test_open_meteo_down_is_skipped(monkeypatch):
|
||||
with pytest.raises(OpenMeteoRequestFailed):
|
||||
await fetch_clouds(client, [(37.5, 127.0)])
|
||||
assert len(calls) == 1
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_airkorea_nationwide_call_waits_past_default_budget(fast, monkeypatch):
|
||||
"""전국 미세먼지 조회는 15~20초 걸려 기본 한도로는 늘 실패한다."""
|
||||
monkeypatch.setattr(airkorea, "BUDGET_SEC", 2.0)
|
||||
|
||||
async def slow(req: httpx.Request) -> httpx.Response:
|
||||
await asyncio.sleep(0.5)
|
||||
return httpx.Response(200, json={"response": {"header": {"resultCode": "00"}, "body": {"items": [{"stationName": "x"}], "totalCount": 1}}})
|
||||
|
||||
async with _client(slow) as client:
|
||||
assert await fetch_realtime(client) == [{"stationName": "x"}]
|
||||
@@ -0,0 +1,63 @@
|
||||
from datetime import date, datetime, timedelta
|
||||
from types import SimpleNamespace
|
||||
|
||||
from common.enums import RainType, Sky
|
||||
from common.utils.kma_time import KST, kst_midnight
|
||||
from services.calc.day_slot import slot_hours
|
||||
from services.calc.index_calc import Context
|
||||
from services.index_service import EARLY, WEATHER_SCORE_DEF, current_slot, slot_results
|
||||
|
||||
DAY = date(2026, 10, 8)
|
||||
SUNSET = datetime(2026, 10, 8, 18, 0, tzinfo=KST)
|
||||
REGION = SimpleNamespace(lat=37.5, lon=127.0)
|
||||
CTX = Context(day=DAY, is_holiday=False, pm25=10, air_label="좋음", moon=0, sunset_score=None, wind_warning=False, lookahead_rain_prob=0)
|
||||
|
||||
|
||||
def _rows(rain_from: int = 99):
|
||||
start = kst_midnight(DAY)
|
||||
return {
|
||||
start + timedelta(hours=h): SimpleNamespace(
|
||||
forecast_at=start + timedelta(hours=h), feels_c=21.0, rain_type=RainType.RAIN.value if h >= rain_from else RainType.NONE.value,
|
||||
rain_prob=90 if h >= rain_from else 0, wind_ms=1.0, humidity=50, sky=Sky.CLEAR.value,
|
||||
)
|
||||
for h in range(0, 30)
|
||||
}
|
||||
|
||||
|
||||
def _defn(windows):
|
||||
return SimpleNamespace(
|
||||
weight_temp=50, weight_rain=50, weight_wind=0, weight_humidity=0, weight_air=0, weight_time=0,
|
||||
factor_rules={"temp": {"type": "range", "lo": 18, "hi": 24}, "rain": {"dir": "dry"}, "wind": {"type": "ignore"},
|
||||
"humidity": {"type": "ignore"}, "time": {"type": "fixed", "value": 100}},
|
||||
zero_rules=[], windows=windows,
|
||||
)
|
||||
|
||||
|
||||
def test_slot_hours_split_by_sunset():
|
||||
hours = slot_hours(DAY, SUNSET)
|
||||
assert hours["morning"] == set(range(5, 11))
|
||||
assert hours["day"] == set(range(11, 16))
|
||||
assert hours["evening"] == {16, 17, 18}
|
||||
assert hours["night"] == set(range(19, 29))
|
||||
|
||||
|
||||
def test_current_slot_before_5_is_previous_night():
|
||||
assert current_slot(datetime(2026, 10, 8, 2, 0, tzinfo=KST), SUNSET) == EARLY
|
||||
assert current_slot(datetime(2026, 10, 8, 16, 30, tzinfo=KST), SUNSET) == "evening"
|
||||
|
||||
|
||||
def test_gak_hidden_in_slots_outside_its_window():
|
||||
parts = slot_results(_defn([{"from": 18, "to": 24}]), DAY, REGION, _rows(), {}, CTX, SUNSET)
|
||||
assert set(parts) == {"evening", "night"}
|
||||
|
||||
|
||||
def test_rain_in_evening_lowers_only_later_slots():
|
||||
parts = slot_results(_defn([{"from": 7, "to": 23}]), DAY, REGION, _rows(rain_from=16), {}, CTX, SUNSET)
|
||||
assert parts["morning"].score > 80
|
||||
assert parts["evening"].score < parts["morning"].score
|
||||
assert parts["night"].score < parts["morning"].score
|
||||
|
||||
|
||||
def test_weather_score_covers_every_slot():
|
||||
parts = slot_results(WEATHER_SCORE_DEF, DAY, REGION, _rows(), {}, CTX, SUNSET)
|
||||
assert set(parts) == {"morning", "day", "evening", "night", EARLY}
|
||||
+17
-11
@@ -8,6 +8,7 @@ from common.database.db_session_manager import DB_SESSION_MNG
|
||||
from common.enums import PostType
|
||||
from common.utils.kma_time import now_kst
|
||||
from crud.feed_crud import FeedCRUD
|
||||
from crud.region_crud import RegionCRUD
|
||||
from crud.season_crud import SeasonCRUD
|
||||
from router.router import app
|
||||
from services.feed_service import build_feed_day
|
||||
@@ -16,17 +17,19 @@ from services.week_service import collect_events
|
||||
REGION = "1114000000"
|
||||
|
||||
|
||||
async def _posts(day: date):
|
||||
_, rows = await DB_SESSION_MNG.execute_lambda(lambda s: s.execute(text(f"SELECT post_type FROM post WHERE feed_date='{day}' ORDER BY position")))
|
||||
async def _posts(day: date, sido: str = REGION[:2]):
|
||||
"""한 시도가 보는 그날 카드 (전국 + 그 시도)."""
|
||||
_, rows = await DB_SESSION_MNG.execute_lambda(lambda s: s.execute(text(
|
||||
f"SELECT post_type FROM post WHERE feed_date='{day}' AND scope IN ('00', '{sido}') ORDER BY position")))
|
||||
return [r[0] for r in rows]
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_build_day_adds_weekend_post_every_day():
|
||||
monday, thursday = date(2026, 10, 12), date(2026, 10, 15)
|
||||
await build_feed_day(monday, FeedCRUD(), SeasonCRUD())
|
||||
await build_feed_day(thursday, FeedCRUD(), SeasonCRUD())
|
||||
await build_feed_day(thursday, FeedCRUD(), SeasonCRUD())
|
||||
await build_feed_day(monday, FeedCRUD(), SeasonCRUD(), RegionCRUD())
|
||||
await build_feed_day(thursday, FeedCRUD(), SeasonCRUD(), RegionCRUD())
|
||||
await build_feed_day(thursday, FeedCRUD(), SeasonCRUD(), RegionCRUD())
|
||||
assert (await _posts(monday)).count(PostType.WEEK.value) == 1
|
||||
assert (await _posts(thursday)).count(PostType.WEEK.value) == 1
|
||||
assert (await _posts(thursday))[0] == PostType.WEATHER.value
|
||||
@@ -36,10 +39,10 @@ async def test_build_day_adds_weekend_post_every_day():
|
||||
async def test_build_day_adds_new_card_types_to_existing_day():
|
||||
"""이미 만든 날에 새 종류(미세먼지)가 생기면 빠진 카드만 더한다."""
|
||||
thursday = date(2026, 10, 15)
|
||||
await build_feed_day(thursday, FeedCRUD(), SeasonCRUD())
|
||||
await build_feed_day(thursday, FeedCRUD(), SeasonCRUD(), RegionCRUD())
|
||||
await DB_SESSION_MNG.execute_lambda_run([lambda s: s.execute(text(f"DELETE FROM post WHERE feed_date='{thursday}' AND post_type={PostType.AIR.value}"))])
|
||||
before = len(await _posts(thursday))
|
||||
await build_feed_day(thursday, FeedCRUD(), SeasonCRUD())
|
||||
await build_feed_day(thursday, FeedCRUD(), SeasonCRUD(), RegionCRUD())
|
||||
after = await _posts(thursday)
|
||||
assert len(after) == before + 1 and after.count(PostType.AIR.value) == 1
|
||||
|
||||
@@ -58,7 +61,7 @@ async def test_feed_assembles_hero_stories_posts_and_bands(offline):
|
||||
body = (await client.get("/v1/feed", params={"region": REGION})).json()
|
||||
assert body["result"]["success"] is True
|
||||
assert body["hero"]["temp_c"] == 20 and body["hero"]["top1"]["rank"] == 1 and "top3" not in body["hero"]
|
||||
assert len(body["stories"]) == 27
|
||||
assert len(body["stories"]) == 34
|
||||
weather = next(p for p in body["posts"] if p["post_type"] == PostType.WEATHER.value)
|
||||
assert [s["kind"] for s in weather["slides"]] == ["hours", "hours"]
|
||||
assert len(weather["slides"][0]["hours"]) == 8
|
||||
@@ -100,8 +103,11 @@ def test_slot_follows_sunset():
|
||||
|
||||
sunset = datetime(2026, 10, 2, 18, 10, tzinfo=KST)
|
||||
at = lambda h, m=0: datetime(2026, 10, 2, h, m, tzinfo=KST) # noqa: E731
|
||||
assert [slot_of(at(h, m), sunset) for h, m in ((4, 59), (5, 0), (11, 0), (16, 9), (16, 10), (20, 59), (21, 0))] == [
|
||||
"night", "morning", "day", "day", "evening", "evening", "night"]
|
||||
assert [slot_of(at(h, m), sunset) for h, m in ((4, 59), (5, 0), (11, 0), (16, 9), (16, 10), (19, 9), (19, 10), (23, 0))] == [
|
||||
"night", "morning", "day", "day", "evening", "evening", "night", "night"]
|
||||
summer = datetime(2026, 6, 21, 19, 57, tzinfo=KST)
|
||||
assert slot_of(datetime(2026, 6, 21, 20, 30, tzinfo=KST), summer) == "evening"
|
||||
assert slot_of(datetime(2026, 6, 21, 20, 57, tzinfo=KST), summer) == "night"
|
||||
|
||||
|
||||
def test_arrange_orders_by_slot_and_keeps_same_types_apart():
|
||||
@@ -152,7 +158,7 @@ def test_arrange_scatters_up_to_three_events_same_spot_all_day():
|
||||
@pytest.mark.anyio
|
||||
async def test_build_day_makes_every_card_at_three():
|
||||
thursday = date(2026, 10, 15)
|
||||
await build_feed_day(thursday, FeedCRUD(), SeasonCRUD())
|
||||
await build_feed_day(thursday, FeedCRUD(), SeasonCRUD(), RegionCRUD())
|
||||
_, rows = await DB_SESSION_MNG.execute_lambda(lambda s: s.execute(text(f"SELECT post_type, published_at FROM post WHERE feed_date='{thursday}'")))
|
||||
rows = list(rows)
|
||||
assert {PostType.ALERT.value, PostType.TOMORROW.value, PostType.QUOTE.value} <= {r[0] for r in rows}
|
||||
|
||||
@@ -9,10 +9,13 @@ import services.warning_service as warning_service
|
||||
import services.weather_service as weather_service
|
||||
from common.database.db_session_manager import DB_SESSION_MNG
|
||||
from common.database.model.models import OpenMeteoHourly, WeatherHourly
|
||||
from common.enums import ErrorType
|
||||
from common.utils.kma_time import kst_midnight, now_kst
|
||||
from crud.region_crud import RegionCRUD
|
||||
from crud.weather_crud import WeatherCRUD
|
||||
from router.router import app
|
||||
from services.index_service import _nearest_slot_end_hour, _slot_end_hour, slot_days, slot_label, windows_for
|
||||
from services.calc.index_calc import rank_score
|
||||
from services.index_service import IndexService, _nearest_slot_end_hour, _slot_end_hour, slot_days, slot_label, windows_for
|
||||
|
||||
REGION = "1141000000"
|
||||
|
||||
@@ -51,13 +54,18 @@ def fakes(monkeypatch):
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_index_list_ranks_all_27_with_today_tomorrow_weekend_trend(fakes):
|
||||
async def test_index_list_ranks_all_34_with_today_tomorrow_weekend_trend(fakes):
|
||||
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
|
||||
body = (await client.get("/v1/index/list", params={"region": REGION})).json()
|
||||
assert body["result"]["success"] is True
|
||||
assert len(body["items"]) == 27 and len(body["top3"]) == 3
|
||||
scores = [i["score"] for i in body["items"]]
|
||||
assert scores == sorted(scores, reverse=True)
|
||||
assert len(body["items"]) == 34 and len(body["top3"]) == 3
|
||||
priority = {d["code"]: d["priority"] for d in _seed()}
|
||||
# 지금 구간에 해당하는 각이 먼저(순위), 해당 없는 각은 그 뒤. 각 묶음 안에서는 점수 × 중요도 순
|
||||
actives = [i["active"] for i in body["items"]]
|
||||
assert actives == sorted(actives, reverse=True) and all(i["active"] for i in body["top3"])
|
||||
for group in (True, False):
|
||||
weighted = [rank_score(i["score"], priority[i["code"]]) for i in body["items"] if i["active"] is group]
|
||||
assert weighted == sorted(weighted, reverse=True)
|
||||
today = now_kst().date()
|
||||
for i in body["items"]:
|
||||
assert [t["label"] for t in i["trend"]] == [slot_label(d, today) for d in slot_days(today)]
|
||||
@@ -95,13 +103,40 @@ async def test_index_detail_has_four_score_bands_with_today_marked(fakes):
|
||||
assert len(current) == 1 and current[0]["low"] <= body["index"]["score"] <= current[0]["high"]
|
||||
|
||||
|
||||
def test_every_index_has_four_band_sentences():
|
||||
def _seed() -> list[dict]:
|
||||
import json
|
||||
import os
|
||||
seed = json.load(open(os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "seed", "index_definition.json"), encoding="utf-8"))
|
||||
with open(os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "seed", "index_definition.json"), encoding="utf-8") as f:
|
||||
return json.load(f)
|
||||
|
||||
|
||||
def test_every_index_has_four_band_sentences():
|
||||
seed = _seed()
|
||||
assert all(sorted(d["sentences"], key=int) == ["0", "30", "60", "80"] and all(d["sentences"].values()) for d in seed)
|
||||
|
||||
|
||||
def test_every_index_has_priority():
|
||||
assert all(d["priority"] in (1, 2, 3) for d in _seed())
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_board_ranks_by_score_times_priority_weight(monkeypatch):
|
||||
today = now_kst().date()
|
||||
defs = [
|
||||
SimpleNamespace(index_id=1, code="low", priority=3),
|
||||
SimpleNamespace(index_id=2, code="mid", priority=2),
|
||||
SimpleNamespace(index_id=3, code="high", priority=1),
|
||||
]
|
||||
scores = [SimpleNamespace(index_id=x, score_date=today, score=v, slots={}) for x, v in ((1, 90), (2, 80), (3, 70))]
|
||||
crud = SimpleNamespace(definitions=lambda s: _async(defs), scores=lambda s, *a: _async(scores))
|
||||
service = IndexService(RegionCRUD(), crud, None, None, None, None, None, None)
|
||||
monkeypatch.setattr(service, "ensure", lambda *a: _async((ErrorType.SUCCESS, 50)))
|
||||
err, board = await service.board(REGION)
|
||||
assert err is ErrorType.SUCCESS
|
||||
# 하 90점(63) < 중 80점(68) < 상 70점(70). 보이는 점수는 그대로
|
||||
assert [(i.definition.code, i.score.score, i.rank) for i in board.items] == [("high", 70, 1), ("mid", 80, 2), ("low", 90, 3)]
|
||||
|
||||
|
||||
def _om_row(at, **over):
|
||||
row = {
|
||||
"region_code": REGION, "forecast_at": at, "fetched_at": now_kst(), "uv_index": 2.0, "uv_index_clear_sky": 2.0,
|
||||
|
||||
@@ -1,10 +1,14 @@
|
||||
import json
|
||||
from dataclasses import replace
|
||||
from datetime import date, datetime, timezone
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
from common.enums import RainType, Sky
|
||||
from services.calc.index_calc import (
|
||||
OUTING_HOURS, Context, DayForecast, Hour, axis_label, estimate, evaluate, hour_temp, outing, outing_estimate, rain_score, sun_score, temp_score,
|
||||
OUTING_HOURS, Context, DayForecast, Hour, air_score, axis_label, estimate, evaluate, hour_temp, outing, outing_estimate, rain_score, sun_score, temp_score,
|
||||
uv_score, view_score, zero_rules_text,
|
||||
)
|
||||
from services.calc.moon import illumination
|
||||
@@ -222,3 +226,51 @@ def test_outing_estimate_from_mid_forecast():
|
||||
assert r.reason.startswith("비 20% · 낮 ")
|
||||
assert outing_estimate(_fc(pm=60)).score <= 30
|
||||
assert outing_estimate(_fc(lo=None, hi=None)) is None
|
||||
|
||||
|
||||
def test_air_rule_can_reverse_so_dusty_air_scores_high():
|
||||
rule = {"zero": 15, "full": 75}
|
||||
assert air_score(80, None, rule)[0] == 100 and air_score(10, None, rule)[0] == 0
|
||||
assert air_score(10, None)[0] == 100
|
||||
assert axis_label("air", {"air": rule}) == "공기 탁함" and axis_label("air", {}) == "공기 맑음"
|
||||
|
||||
|
||||
_SEED = {x["code"]: SimpleNamespace(**x) for x in json.loads((Path(__file__).parents[1] / "seed" / "index_definition.json").read_text(encoding="utf-8"))}
|
||||
_SAT, _WED = date(2026, 10, 10), date(2026, 10, 7)
|
||||
|
||||
|
||||
def _seed_score(code, day=_SAT, pm25=10, **hour):
|
||||
d = _SEED[code]
|
||||
windows = [[_h(h, **hour) for h in range(w["from"], w["to"])] for w in d.windows]
|
||||
return evaluate(d, windows, replace(CTX, day=day, pm25=pm25)).score
|
||||
|
||||
|
||||
@pytest.mark.parametrize("code, good, bad", [
|
||||
("golf", dict(feels=19.0, wind=2.0, hum=45), dict(feels=18.0, prob=80, rain=RainType.RAIN)),
|
||||
("jipkok", dict(feels=4.0, prob=90, rain=RainType.RAIN, wind=7.0, hum=85), dict(feels=20.0, wind=1.0, hum=40)),
|
||||
("fishing", dict(feels=22.0, wind=3.0), dict(feels=17.0, wind=11.0)),
|
||||
("drive", dict(feels=23.0, wind=4.0, hum=45, visibility_km=18.0), dict(feels=18.0, prob=80, rain=RainType.RAIN, visibility_km=5.0)),
|
||||
("kite", dict(feels=19.0, wind=6.0), dict(feels=14.0, wind=0.5)),
|
||||
("waterplay", dict(feels=28.0, wind=3.0, sunshine_ratio=0.7), dict(feels=18.0, wind=2.0, sunshine_ratio=0.3)),
|
||||
("kimjang", dict(feels=9.0, wind=3.0), dict(feels=20.0, wind=2.0)),
|
||||
])
|
||||
def test_new_gak_good_day_high_bad_day_low(code, good, bad):
|
||||
assert 80 <= _seed_score(code, pm25=60 if code == "jipkok" else 10, **good) < 100
|
||||
assert _seed_score(code, **bad) <= 30
|
||||
|
||||
|
||||
def test_new_gak_100_only_when_every_factor_is_perfect():
|
||||
perfect = dict(feels=19.5, wind=1.0, hum=35)
|
||||
assert _seed_score("golf", **perfect) == 100
|
||||
assert _seed_score("golf", day=_WED, **perfect) < 100
|
||||
|
||||
|
||||
def test_weather_score_100_only_on_perfect_day():
|
||||
from services.index_service import WEATHER_SCORE_DEF
|
||||
|
||||
perfect = Context(day=date(2026, 10, 2), is_holiday=False, pm25=8, air_label="좋음", moon=0, sunset_score=None, wind_warning=False, lookahead_rain_prob=0)
|
||||
hours = [_h(h, feels=21.0, prob=0, wind=0.8, hum=50, sunshine_ratio=1.0) for h in range(9, 22)]
|
||||
assert evaluate(WEATHER_SCORE_DEF, [hours], perfect).score == 100
|
||||
|
||||
good = [_h(h, feels=22.5, prob=10, wind=2.5, hum=62, sunshine_ratio=0.7) for h in range(9, 22)]
|
||||
assert evaluate(WEATHER_SCORE_DEF, [good], replace(perfect, pm25=15)).score < 95
|
||||
@@ -28,6 +28,16 @@ def test_parse_popup_maps_store():
|
||||
}
|
||||
|
||||
|
||||
def test_parse_popup_maps_festival():
|
||||
row = parse_popup(_page(504, "FESTIVAL", "2026-10-02", "2026-10-11", "경기 수원시 팔달구 테스트로 1"), 504, date(2026, 10, 1))
|
||||
assert (row["kind"], row["icon"], row["sido_code"]) == (EventKind.FESTIVAL, "fireworks", "41")
|
||||
|
||||
|
||||
def test_parse_popup_moves_festival_shows_in_theaters_to_concert():
|
||||
page = _page(505, "FESTIVAL", "2026-10-02", "2026-10-11").replace("테스트 빌딩 1F", "대학로예술극장 소극장")
|
||||
assert parse_popup(page, 505, date(2026, 10, 1))["kind"] is EventKind.CONCERT
|
||||
|
||||
|
||||
@pytest.mark.parametrize("kind,end,address", [
|
||||
("PERFORMANCE", "2026-10-11", "서울 성동구 테스트로 1"),
|
||||
("STORE", "2026-09-30", "서울 성동구 테스트로 1"),
|
||||
|
||||
@@ -0,0 +1,112 @@
|
||||
import csv
|
||||
import os
|
||||
from collections import defaultdict
|
||||
from datetime import date
|
||||
|
||||
import pytest
|
||||
from httpx import ASGITransport, AsyncClient
|
||||
from sqlalchemy import text
|
||||
|
||||
from common.database.db_session_manager import DB_SESSION_MNG
|
||||
from common.enums import PostType
|
||||
from common.utils.kma_time import now_kst
|
||||
from crud.feed_crud import FeedCRUD
|
||||
from crud.region_crud import RegionCRUD
|
||||
from crud.season_crud import SeasonCRUD
|
||||
from router.router import app
|
||||
from services.feed_service import LINEUP, NATIONAL_SCOPE, NATIONAL_TYPES, build_feed_day, feed_day, sido_of
|
||||
|
||||
SEOUL_A, SEOUL_B, BUSAN = "1111000000", "1114000000", "2611000000"
|
||||
REGION_CSV = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "seed", "region.csv")
|
||||
|
||||
|
||||
def client():
|
||||
return AsyncClient(transport=ASGITransport(app=app), base_url="http://test")
|
||||
|
||||
|
||||
def _ids(feed: dict) -> dict[int, set[int]]:
|
||||
out: dict[int, set[int]] = defaultdict(set)
|
||||
for p in feed["posts"]:
|
||||
out[p["post_type"]].add(p["post_id"])
|
||||
return out
|
||||
|
||||
|
||||
def test_every_region_maps_to_one_sido():
|
||||
with open(REGION_CSV, encoding="utf-8") as f:
|
||||
regions = list(csv.DictReader(f))
|
||||
assert len(regions) == 256
|
||||
by_name: dict[str, set[str]] = defaultdict(set)
|
||||
for r in regions:
|
||||
by_name[r["name"].split()[0]].add(sido_of(r["code"]))
|
||||
assert all(len(codes) == 1 for codes in by_name.values()), by_name
|
||||
sidos = {sido_of(r["code"]) for r in regions}
|
||||
assert all(len(c) == 2 and c.isdigit() and c != NATIONAL_SCOPE for c in sidos)
|
||||
sejong = [r for r in regions if r["name"].startswith("세종")]
|
||||
assert len(sejong) == 1 and sido_of(sejong[0]["code"]) == "36"
|
||||
assert sum(1 for r in regions if sido_of(r["code"]) == "36") == 1
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_build_day_makes_national_once_and_regional_per_sido():
|
||||
day = date(2026, 10, 15)
|
||||
await build_feed_day(day, FeedCRUD(), SeasonCRUD(), RegionCRUD())
|
||||
await build_feed_day(day, FeedCRUD(), SeasonCRUD(), RegionCRUD())
|
||||
_, rows = await DB_SESSION_MNG.execute_lambda(lambda s: s.execute(text(f"SELECT scope, post_type FROM post WHERE feed_date='{day}'")))
|
||||
rows = list(rows)
|
||||
_, regions = await DB_SESSION_MNG.execute_lambda(lambda s: RegionCRUD().search(s))
|
||||
sidos = {sido_of(r.code) for r in regions}
|
||||
regional = [x for x in LINEUP if x[1] not in NATIONAL_TYPES]
|
||||
assert {scope for scope, t in rows if PostType(t) in NATIONAL_TYPES} == {NATIONAL_SCOPE}
|
||||
assert {scope for scope, t in rows if PostType(t) not in NATIONAL_TYPES} == sidos
|
||||
assert sum(1 for scope, t in rows if PostType(t) not in NATIONAL_TYPES) == len(regional) * len(sidos)
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_regional_posts_shared_within_sido_split_across_sido(offline):
|
||||
async with client() as c:
|
||||
a, b, busan = [(await c.get("/v1/feed", params={"region": r})).json() for r in (SEOUL_A, SEOUL_B, BUSAN)]
|
||||
ia, ib, ibusan = _ids(a), _ids(b), _ids(busan)
|
||||
regional = [t for t in ia if PostType(t) not in NATIONAL_TYPES]
|
||||
assert PostType.WEATHER.value in regional and PostType.GAK.value in regional
|
||||
for t in regional:
|
||||
if t in ib:
|
||||
assert ia[t] == ib[t], PostType(t)
|
||||
if t in ibusan:
|
||||
assert not ia[t] & ibusan[t], PostType(t)
|
||||
national = [t for t in ia if PostType(t) in NATIONAL_TYPES]
|
||||
assert PostType.MOON.value in national
|
||||
for t in national:
|
||||
assert ia[t] == ib[t] == ibusan[t], PostType(t)
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_like_in_one_sido_not_seen_in_another(offline):
|
||||
async with client() as c:
|
||||
token = (await c.post("/v1/auth/signup", json={"login_id": "scope_01", "password": "password1", "nickname": "시도테스트"})).json()["access_token"]
|
||||
h = {"Authorization": f"Bearer {token}"}
|
||||
seoul = (await c.get("/v1/feed", params={"region": SEOUL_A}, headers=h)).json()
|
||||
post_id = next(p["post_id"] for p in seoul["posts"] if p["post_type"] == PostType.WEATHER.value)
|
||||
assert (await c.post(f"/v1/reaction/post/{post_id}/like", headers=h)).json()["like_count"] == 1
|
||||
await c.post(f"/v1/reaction/post/{post_id}/comment", json={"body": "서울 맑음"}, headers=h)
|
||||
same = (await c.get("/v1/feed", params={"region": SEOUL_B}, headers=h)).json()
|
||||
busan = (await c.get("/v1/feed", params={"region": BUSAN}, headers=h)).json()
|
||||
mine = next(p for p in same["posts"] if p["post_id"] == post_id)
|
||||
assert mine["liked"] is True and mine["like_count"] == 1 and mine["comment_count"] == 1
|
||||
weather = next(p for p in busan["posts"] if p["post_type"] == PostType.WEATHER.value)
|
||||
assert weather["post_id"] != post_id and weather["like_count"] == 0 and weather["comment_count"] == 0 and not weather.get("liked")
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_day_built_before_split_keeps_national_rows_for_regional_cards(offline):
|
||||
"""그날 지역 카드가 이미 전국 행으로 있으면 시도 행을 만들지 않고, 모든 시도가 그 행(과 반응)을 같이 쓴다."""
|
||||
day = feed_day(now_kst())
|
||||
rows = ", ".join(f"('{day}', {pos}, '{NATIONAL_SCOPE}', {t.value}, {ref.value}, {rank if rank else 'NULL'}, now(), {5 if t is PostType.WEATHER else 0})"
|
||||
for pos, t, ref, rank in LINEUP if ref.value == 1)
|
||||
await DB_SESSION_MNG.execute_lambda_run([lambda s: s.execute(text(
|
||||
f"INSERT INTO post (feed_date, position, scope, post_type, ref_type, index_rank, published_at, like_count) VALUES {rows}"))])
|
||||
async with client() as c:
|
||||
seoul, busan = [(await c.get("/v1/feed", params={"region": r})).json() for r in (SEOUL_A, BUSAN)]
|
||||
_, n = await DB_SESSION_MNG.execute_lambda(lambda s: s.scalar(text(f"SELECT count(*) FROM post WHERE feed_date='{day}' AND scope <> '{NATIONAL_SCOPE}'")))
|
||||
assert n == 0
|
||||
ws, wb = [next(p for p in f["posts"] if p["post_type"] == PostType.WEATHER.value) for f in (seoul, busan)]
|
||||
assert ws["post_id"] == wb["post_id"] and ws["like_count"] == 5
|
||||
@@ -2,8 +2,10 @@ from datetime import timedelta
|
||||
|
||||
import pytest
|
||||
from httpx import ASGITransport, AsyncClient
|
||||
from sqlalchemy import text
|
||||
|
||||
import services.season_service as season_service
|
||||
from common.database.db_session_manager import DB_SESSION_MNG
|
||||
from common.utils.kma_time import now_kst
|
||||
from router.router import app
|
||||
|
||||
@@ -38,3 +40,15 @@ async def test_article_detail_and_not_found():
|
||||
missing = (await client.get("/v1/season/article/9999")).json()
|
||||
assert first["body"] and first["article"]["title"] == listed[0]["title"]
|
||||
assert missing["result"]["desc"] == "NOT_FOUND"
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_article_photo_only_when_seeded():
|
||||
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
|
||||
listed = {a["code"]: a for a in (await client.get("/v1/season/article/list")).json()["articles"]}
|
||||
umbrella = (await client.get(f"/v1/season/article/{listed['umbrella']['article_id']}")).json()["article"]
|
||||
_, maple_id = await DB_SESSION_MNG.execute_lambda(lambda s: s.scalar(text("SELECT article_id FROM article WHERE code = 'maple'")))
|
||||
maple = (await client.get(f"/v1/season/article/{maple_id}")).json()["article"]
|
||||
assert umbrella["image"] == "/season/umbrella.jpg" and "image_credit" not in umbrella
|
||||
assert maple["image"] == "/season/maple.jpg" and maple["image_credit"] == "ⓒJoycekim77 · CC BY-SA 3.0"
|
||||
assert "image" not in listed["howgak"] and "image" not in listed["di"]
|
||||
@@ -0,0 +1,83 @@
|
||||
from datetime import date
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
|
||||
import services.week_service as week_service
|
||||
from services.external.seoul_culture import LIST_URL, fetch_seoul_festivals, parse_seoul_festivals
|
||||
from services.week_service import _seoul
|
||||
|
||||
ITEM = {
|
||||
"cultcode": 159216, "title": "[중랑문화재단] 2026 중랑용마폭포축제", "strtdate": "2026-10-10", "endDate": "2026-10-10",
|
||||
"atchFileId": "abc", "xCoord": "37.5118239", "yCoord": "127.0591590", "facName": "용마폭포공원", "addr": "서울특별시 중랑구",
|
||||
}
|
||||
|
||||
|
||||
def test_parse_reads_lat_from_x_and_builds_image_and_link():
|
||||
[row] = parse_seoul_festivals([ITEM, {**ITEM, "cultcode": None}, {**ITEM, "cultcode": 2, "strtdate": ""}])
|
||||
assert row["source_id"] == "seoul:159216" and row["sido_code"] == "11"
|
||||
assert (row["lat"], row["lon"]) == (37.51182, 127.05916)
|
||||
assert row["name"] == "2026 중랑용마폭포축제"
|
||||
assert row["place_name"] == "용마폭포공원" and row["start_date"] == date(2026, 10, 10)
|
||||
assert row["image_url"].endswith("atchFileId=abc&thumb=Y") and "cultcode=159216" in row["source_url"]
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_fetch_pages_until_empty(monkeypatch):
|
||||
monkeypatch.setattr("services.external.seoul_culture.REQUEST_GAP_SEC", 0)
|
||||
pages = []
|
||||
|
||||
def handler(req: httpx.Request) -> httpx.Response:
|
||||
assert str(req.url) == LIST_URL
|
||||
page = int(dict(x.split("=") for x in req.content.decode().split("&"))["pageIndex"])
|
||||
pages.append(page)
|
||||
return httpx.Response(200, json={"resultList": [ITEM] * 10 if page < 3 else []})
|
||||
|
||||
async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
|
||||
items = await fetch_seoul_festivals(client, date(2026, 10, 8), 30)
|
||||
assert len(items) == 20 and pages == [1, 2, 3]
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_seoul_skips_festivals_tour_api_already_has_and_other_sidos(monkeypatch):
|
||||
other = {**ITEM, "cultcode": 2, "title": "2026 서울어텀페스타"}
|
||||
|
||||
async def fake(client, since, days):
|
||||
return [ITEM, other]
|
||||
|
||||
monkeypatch.setattr(week_service, "fetch_seoul_festivals", fake)
|
||||
known = [{"name": "제3회 중랑용마폭포축제"}]
|
||||
rows = await _seoul(None, "11", date(2026, 10, 8), known)
|
||||
assert [r["name"] for r in rows] == ["2026 서울어텀페스타"]
|
||||
assert await _seoul(None, "41", date(2026, 10, 8), known) == []
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_seoul_failure_keeps_other_sources(monkeypatch):
|
||||
async def broken(client, since, days):
|
||||
raise httpx.ConnectError("down")
|
||||
|
||||
monkeypatch.setattr(week_service, "fetch_seoul_festivals", broken)
|
||||
assert await _seoul(None, "11", date(2026, 10, 8), []) == []
|
||||
|
||||
|
||||
def _row(source_id, name, start, end, sido="11"):
|
||||
return {"source_id": source_id, "sido_code": sido, "name": name, "place_name": "", "start_date": start, "end_date": end,
|
||||
"is_confirmed": True, "source_url": None, "image_url": None, "lat": None, "lon": None, "kind": 1, "icon": "fireworks"}
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_drop_known_skips_same_festival_from_another_source():
|
||||
from common.database.db_session_manager import DB_SESSION_MNG
|
||||
from crud.week_crud import WeekCRUD
|
||||
from services.week_service import drop_known
|
||||
|
||||
tour = _row("9001", "경복궁 별빛야행", date(2026, 10, 1), date(2026, 10, 24))
|
||||
await DB_SESSION_MNG.execute_lambda_run([lambda s: WeekCRUD().upsert_events(s, [tour])])
|
||||
rows = [
|
||||
_row("popga:1", "2026 경복궁 별빛야행", date(2026, 10, 8), date(2026, 10, 10)),
|
||||
_row("popga:2", "경복궁 별빛야행", date(2026, 11, 1), date(2026, 11, 2)),
|
||||
_row("popga:3", "경복궁 별빛야행", date(2026, 10, 8), date(2026, 10, 10), sido="41"),
|
||||
_row("9001", "경복궁 별빛야행", date(2026, 10, 1), date(2026, 10, 25)),
|
||||
]
|
||||
assert [r["source_id"] for r in await drop_known(rows)] == ["popga:2", "popga:3", "9001"]
|
||||
@@ -93,7 +93,7 @@ async def test_sky_spots_by_distance(monkeypatch, clean, region, expected):
|
||||
assert [s["distance_km"] for s in spots] == sorted(s["distance_km"] for s in spots)
|
||||
|
||||
|
||||
def test_nearest_spots_west_first_and_empty_outside_radius():
|
||||
def test_nearest_spots_west_first_and_nearest_one_outside_radius():
|
||||
from decimal import Decimal
|
||||
|
||||
from common.database.model.models import SunsetSpot
|
||||
@@ -103,7 +103,7 @@ def test_nearest_spots_west_first_and_empty_outside_radius():
|
||||
|
||||
spots = [spot("가까운 동쪽", 37.01, False), spot("먼 서쪽", 37.1, True), spot("반경 밖", 37.5, True)]
|
||||
assert [x.spot.name for x in sky_service.nearest_spots(37.0, 127.0, spots)] == ["먼 서쪽", "가까운 동쪽"]
|
||||
assert sky_service.nearest_spots(33.0, 127.0, spots) == []
|
||||
assert [x.spot.name for x in sky_service.nearest_spots(36.0, 127.0, spots)] == ["가까운 동쪽"]
|
||||
|
||||
|
||||
def test_outlook_only_when_a_later_day_has_a_better_verdict():
|
||||
@@ -160,8 +160,8 @@ def test_score_rows_apply_air_at_sunset_and_keep_cloud_score_without_air():
|
||||
hourly = {("R", hour): SimpleNamespace(humidity=90, rain_prob=0)}
|
||||
om = {("R", sky_service._nearest_slot(hour)): SimpleNamespace(visibility_m=5000)}
|
||||
hazy = sky_service._score_rows(region, today, clouds, now, hourly, om)[0]["score"]
|
||||
assert hazy == round(plain * 0.6 * 0.75)
|
||||
rain = {("R", hour - timedelta(hours=3)): SimpleNamespace(humidity=50, rain_prob=80), ("R", hour): SimpleNamespace(humidity=50, rain_prob=10)}
|
||||
assert hazy == round(plain * 0.8 * 0.85)
|
||||
rain = {("R", hour - timedelta(hours=3)): SimpleNamespace(humidity=60, rain_prob=80), ("R", hour): SimpleNamespace(humidity=60, rain_prob=10)}
|
||||
assert sky_service._score_rows(region, today, clouds, now, rain, {})[0]["score"] == min(100, round(plain * 1.15))
|
||||
|
||||
|
||||
@@ -169,3 +169,30 @@ def test_nearest_slot_is_closest_three_hour_end():
|
||||
from datetime import datetime, timezone
|
||||
at = lambda h, m=0: datetime(2026, 10, 7, h, m, tzinfo=timezone.utc) # noqa: E731
|
||||
assert [sky_service._nearest_slot(at(h, m)).hour for h, m in ((8, 0), (9, 0), (10, 29), (10, 31))] == [9, 9, 9, 12]
|
||||
|
||||
|
||||
def test_open_west_bonus_applies_to_sunset_only_and_needs_a_spot_nearby():
|
||||
from datetime import date, datetime, timezone
|
||||
from types import SimpleNamespace
|
||||
|
||||
from common.enums import SkyType
|
||||
from services.calc.sky_score import Layers
|
||||
from services.calc.sun import sun_times
|
||||
|
||||
region = SimpleNamespace(code="R", lat=37.56, lon=126.91)
|
||||
today = date(2026, 10, 7)
|
||||
st = sun_times(today, region.lat, region.lon)
|
||||
clouds = {
|
||||
("R", kind.value, km, sky_service._nearest_hour(at), 3): Layers(0, 20, 0)
|
||||
for kind, at in ((SkyType.SUNSET, st.sunset_at), (SkyType.SUNRISE, st.sunrise_at)) for km in (20, 100)
|
||||
}
|
||||
now = datetime(2026, 10, 7, 3, tzinfo=timezone.utc)
|
||||
by = lambda rows: {(r["sky_type"], r["score_date"]): r["score"] for r in rows} # noqa: E731
|
||||
plain = by(sky_service._score_rows(region, today, clouds, now))
|
||||
west = by(sky_service._score_rows(region, today, clouds, now, open_west=True))
|
||||
assert west[(SkyType.SUNSET.value, today)] == min(100, round(plain[(SkyType.SUNSET.value, today)] * 1.1))
|
||||
assert west[(SkyType.SUNRISE.value, today)] == plain[(SkyType.SUNRISE.value, today)]
|
||||
|
||||
near = SimpleNamespace(lat=37.5555, lon=126.895) # 망원한강공원, 약 1.5km
|
||||
far = SimpleNamespace(lat=37.0, lon=126.0)
|
||||
assert sky_service._open_west(region, [near]) and not sky_service._open_west(region, [far]) and not sky_service._open_west(region, [])
|
||||
@@ -24,15 +24,21 @@ def test_score_rises_steadily_with_a_few_clouds():
|
||||
assert scores == sorted(scores) and len(set(scores)) == len(scores) # 맑은 날도 구름 몇 %로 갈리고 10%에서 꺾이지 않는다
|
||||
|
||||
|
||||
def test_air_factor_hazy_humid_lowers_and_clearing_rain_raises():
|
||||
def test_air_factor_centers_on_usual_air_and_clearing_rain_raises():
|
||||
assert air_factor(Air()) == 1.0
|
||||
assert air_factor(Air(visibility_km=40, humidity=50)) == 1.0
|
||||
assert air_factor(Air(visibility_km=5)) == 0.6 and air_factor(Air(humidity=90)) == 0.75
|
||||
assert 0.6 < air_factor(Air(visibility_km=30)) < 1.0
|
||||
assert air_factor(Air(visibility_km=20, humidity=60)) == 1.0 # 평소 공기
|
||||
assert air_factor(Air(visibility_km=5)) == 0.8 and air_factor(Air(humidity=90)) == 0.85
|
||||
assert air_factor(Air(visibility_km=40)) == 1.12 and air_factor(Air(humidity=40)) == 1.06 # 맑고 건조하면 올라간다
|
||||
assert 0.8 < air_factor(Air(visibility_km=12.5)) < 1.0 < air_factor(Air(visibility_km=30)) < 1.12
|
||||
assert air_factor(Air(rain_before=70, rain_now=10)) == 1.15
|
||||
assert air_factor(Air(rain_before=70, rain_now=60)) == 1.0 # 아직 비 오는 중이면 가산 없음
|
||||
|
||||
|
||||
def test_open_west_horizon_adds_bonus():
|
||||
assert air_factor(Air(open_west=True)) == 1.1
|
||||
assert air_factor(Air(open_west=True, rain_before=70, rain_now=10)) == 1.15 * 1.1
|
||||
|
||||
|
||||
def test_low_clouds_toward_sun_block_the_light():
|
||||
canvas = Layers(low=0, mid=20, high=50)
|
||||
assert grade(score(canvas, Layers(low=90, mid=50, high=0))) is SkyGrade.GRAY
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import asyncio
|
||||
from datetime import timedelta
|
||||
|
||||
import pytest
|
||||
@@ -5,8 +6,10 @@ from httpx import ASGITransport, AsyncClient
|
||||
from sqlalchemy import text
|
||||
|
||||
import services.weather_service as weather_service
|
||||
from common.cache.redis_client import REDIS
|
||||
from common.database.db_session_manager import DB_SESSION_MNG
|
||||
from common.utils.kma_time import kst_midnight, now_kst
|
||||
from common.utils.kma_time import kst_midnight, latest_vilage_base, now_kst
|
||||
from services.external.kma import day_start_base
|
||||
from router.router import app
|
||||
|
||||
REGION = "1144000000"
|
||||
@@ -32,6 +35,7 @@ async def clean_region():
|
||||
lambda s: s.execute(text(f"DELETE FROM weather_daily WHERE region_code='{REGION}'")),
|
||||
lambda s: s.execute(text(f"DELETE FROM sun_time WHERE region_code='{REGION}'")),
|
||||
])
|
||||
await REDIS.conn.delete(f"vilage0:{REGION}:{now_kst():%Y%m%d}")
|
||||
await wipe()
|
||||
yield
|
||||
await wipe()
|
||||
@@ -106,3 +110,34 @@ def test_slot_view_shows_sunset_only_when_clear():
|
||||
assert _slot_view(at, row(Sky.CLEAR), sun)[0::2] == ("sunset", "노을")
|
||||
assert _slot_view(at, row(Sky.CLOUDY), sun)[0::2] == ("cloud", "흐림")
|
||||
assert _slot_view(at, row(Sky.PARTLY), sun)[0::2] == ("cloud", "구름 많음")
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_today_refetches_midnight_when_first_fetch_missed_it(monkeypatch, clean_region):
|
||||
"""전날 23시 발표 받기가 실패해 0시~ 칸이 비면, 다음 요청 때 그 발표를 다시 받아 채운다."""
|
||||
midnight_base = day_start_base(now_kst().date())
|
||||
if latest_vilage_base(now_kst()) == midnight_base:
|
||||
pytest.skip("최신 발표가 전날 23시면 두 발표가 같다")
|
||||
calls = []
|
||||
fail_midnight = True
|
||||
|
||||
async def fake_fetch(client, nx, ny, base):
|
||||
from services.external.data_go_kr import DataGoKrRequestFailed
|
||||
|
||||
calls.append(base)
|
||||
if base == midnight_base and fail_midnight:
|
||||
raise DataGoKrRequestFailed("timeout")
|
||||
return [it for it in _fake_items(base) if base == midnight_base or it["fcstDate"] + it["fcstTime"] > base.strftime("%Y%m%d%H%M")]
|
||||
|
||||
monkeypatch.setattr(weather_service, "fetch_vilage", fake_fetch)
|
||||
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
|
||||
first = (await client.get("/v1/weather/today", params={"region": REGION})).json()
|
||||
assert first["slots"][0].get("temp_c") is None
|
||||
fail_midnight = False
|
||||
await REDIS.conn.delete(f"vilage0:{REGION}:{now_kst():%Y%m%d}")
|
||||
await client.get("/v1/weather/today", params={"region": REGION})
|
||||
await asyncio.gather(*weather_service._background)
|
||||
body = (await client.get("/v1/weather/today", params={"region": REGION})).json()
|
||||
|
||||
assert calls.count(midnight_base) == 2
|
||||
assert body["slots"][0]["temp_c"] == 18
|
||||
@@ -7,13 +7,13 @@ import services.air_service as air_service
|
||||
import services.warning_service as warning_service
|
||||
import services.weather_service as weather_service
|
||||
import services.week_service as week_service
|
||||
from common.database.model.models import Event
|
||||
from common.database.model.models import Event, Place, Region
|
||||
from common.enums import EventKind, RainType, Sky
|
||||
from common.utils.kma_time import KST, kst_midnight, now_kst
|
||||
from router.router import app
|
||||
from services.external.kma import latest_mid_base, mid_word, parse_mid
|
||||
from services.external.data_go_kr import DataGoKrRequestFailed
|
||||
from services.week_service import EventItem, _status, mix_kinds
|
||||
from services.week_service import PLACE_FALLBACK, PLACE_RADIUS_KM, EventItem, _status, mix_kinds, pick_places
|
||||
|
||||
REGION = "1144000000"
|
||||
|
||||
@@ -169,6 +169,22 @@ async def test_events_pick_within_30km_across_sido(fakes, monkeypatch):
|
||||
assert {e["name"] for e in body["events"]} == {"잠실 축제", "좌표 없는 경기 축제"}
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_gwangju_jeonnam_region_finds_events_saved_as_29_and_46(fakes, monkeypatch):
|
||||
"""구 코드는 광주·전남이 12로 묶이지만 행사는 광주 29 · 전남 46으로 저장된다. 광산구에서 둘 다 보여야 한다."""
|
||||
today = now_kst().date()
|
||||
span = {"eventstartdate": (today + timedelta(days=1)).strftime("%Y%m%d"), "eventenddate": (today + timedelta(days=3)).strftime("%Y%m%d")}
|
||||
by_sido = {
|
||||
"29": [{"contentid": "29", "title": "광주 축제", "addr1": "광주 광산구", "mapy": "35.1396", "mapx": "126.7937", **span}],
|
||||
"46": [{"contentid": "46", "title": "좌표 없는 전남 축제", "addr1": "전남", **span}],
|
||||
}
|
||||
monkeypatch.setattr(week_service, "fetch_festivals", lambda client, sido, since: _async(by_sido.get(sido, [])))
|
||||
await _collect("29", "46")
|
||||
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
|
||||
body = (await client.get("/v1/week/event/list", params={"region": "1233000000"})).json()
|
||||
assert {e["name"] for e in body["events"]} == {"광주 축제", "좌표 없는 전남 축제"}
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_places_put_indoor_first_on_rainy_day(fakes):
|
||||
rainy_day = (now_kst().date() + timedelta(days=2)).isoformat()
|
||||
@@ -179,6 +195,46 @@ async def test_places_put_indoor_first_on_rainy_day(fakes):
|
||||
assert body["places"][0]["is_outdoor"] is False and body["places"][0]["is_good"] is True
|
||||
|
||||
|
||||
def _place(name: str, lat: float, lon: float, outdoor: bool = True, area: str = "가") -> Place:
|
||||
return Place(name=name, lat=lat, lon=lon, is_outdoor=outdoor, area=area)
|
||||
|
||||
|
||||
def test_pick_places_within_radius_good_first_then_near():
|
||||
region = Region(lat=37.0, lon=127.0)
|
||||
places = [
|
||||
_place("먼 공원", 37.2, 127.0), _place("가까운 공원", 37.01, 127.0, area="나"),
|
||||
_place("미술관", 37.1, 127.0, outdoor=False), _place("반경 밖", 37.5, 127.0),
|
||||
]
|
||||
items, areas = pick_places(region, places, rainy=False, area=None)
|
||||
assert [i.place.name for i in items] == ["가까운 공원", "먼 공원", "미술관"]
|
||||
assert all(i.distance_km <= PLACE_RADIUS_KM for i in items) and items[0].distance_km == 1.1
|
||||
assert areas == ["나", "가"]
|
||||
items, _ = pick_places(region, places, rainy=True, area=None)
|
||||
assert [i.place.name for i in items][0] == "미술관" and items[0].is_good
|
||||
items, _ = pick_places(region, places, rainy=False, area="가")
|
||||
assert [i.place.name for i in items] == ["먼 공원", "미술관"]
|
||||
|
||||
|
||||
def test_pick_places_falls_back_to_nearest_when_none_in_radius():
|
||||
region = Region(lat=37.0, lon=127.0)
|
||||
places = [_place(f"{k}km", 37.0 + k / 111, 127.0) for k in (90, 40, 60, 200)]
|
||||
items, _ = pick_places(region, places, rainy=False, area=None)
|
||||
assert [i.place.name for i in items] == ["40km", "60km", "90km"][:PLACE_FALLBACK]
|
||||
assert items[0].distance_km > PLACE_RADIUS_KM
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
@pytest.mark.parametrize("region", ["2635000000", "5013000000", "4794000000"])
|
||||
async def test_places_outside_seoul_come_by_distance(fakes, region):
|
||||
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
|
||||
body = (await client.get("/v1/week/place/list", params={"region": region, "day": now_kst().date().isoformat()})).json()
|
||||
places = body["places"]
|
||||
assert places and all(p["distance_km"] <= PLACE_RADIUS_KM for p in places)
|
||||
good = [p["distance_km"] for p in places if p["is_good"]]
|
||||
assert good == sorted(good)
|
||||
assert all(p["image_credit"] == "ⓒ한국관광공사" for p in places if p.get("image"))
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_weekend_ranking_scores_30_spots_and_caches(fakes, monkeypatch):
|
||||
from services.weekend_rank import weekend_days
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
from datetime import date, datetime
|
||||
from types import SimpleNamespace
|
||||
|
||||
from common.enums import EventKind
|
||||
from common.utils.kma_time import KST
|
||||
from services.week_service import DayPlan, EventItem
|
||||
from services.weekend_plan import day_plan, forecast, pick_events
|
||||
@@ -14,8 +15,8 @@ def _day(d: date, lo=12.0, hi=26.0, rainy=False, rain_hours=None, prob=10) -> Da
|
||||
headline="", summary="", pick="", rain_hours=rain_hours, is_rainy=rainy, rain_prob=prob)
|
||||
|
||||
|
||||
def _event(name, start, end, dist, image="https://img/x.jpg") -> EventItem:
|
||||
e = SimpleNamespace(event_id=hash(name), name=name, icon="fireworks", start_date=start, end_date=end, place_name="경기도 고양시 일산동구 호수로 595", image_url=image, source_id="1")
|
||||
def _event(name, start, end, dist, image="https://img/x.jpg", kind=EventKind.FESTIVAL) -> EventItem:
|
||||
e = SimpleNamespace(event_id=hash(name), name=name, kind=kind, icon="fireworks", start_date=start, end_date=end, place_name="경기도 고양시 일산동구 호수로 595", image_url=image, source_id="1")
|
||||
return EventItem(event=e, status="live", status_label="진행 중", fit=None, distance_km=dist)
|
||||
|
||||
|
||||
@@ -54,6 +55,11 @@ def test_afternoon_rain_moves_outdoor_time_before_it():
|
||||
assert card.line.startswith("비 오는 토요일")
|
||||
|
||||
|
||||
def test_morning_rain_then_outdoor_after_it_ends():
|
||||
card = day_plan(_day(SAT, rainy=True, rain_hours=(9, 14), prob=60), None, [], None)
|
||||
assert [s.time for s in card.steps] == ["9~14시", "14시~"]
|
||||
|
||||
|
||||
def test_saturday_ignores_ending_hook_and_sunday_skips_saturday_events():
|
||||
near = _event("가까운 축제", SAT, SUN, 3.0)
|
||||
ends_sat = _event("토요일 끝", SAT, SAT, 50.0)
|
||||
@@ -64,6 +70,14 @@ def test_saturday_ignores_ending_hook_and_sunday_skips_saturday_events():
|
||||
assert pick_events(SUN, [near, far], frozenset(e.event.event_id for e in sat)) == []
|
||||
|
||||
|
||||
def test_festival_and_concert_come_before_nearer_galleries():
|
||||
events = [_event("옆 전시1", SAT, SUN, 0.5, kind=EventKind.EXHIBITION), _event("옆 전시2", SAT, SUN, 0.6, kind=EventKind.EXHIBITION),
|
||||
_event("먼 공연", SAT, SAT, 20.0, kind=EventKind.CONCERT), _event("먼 축제", SAT, SUN, 25.0)]
|
||||
assert [e.event.name for e in pick_events(SAT, events)] == ["먼 축제", "먼 공연"]
|
||||
only_galleries = events[:2]
|
||||
assert [e.event.name for e in pick_events(SAT, only_galleries)] == ["옆 전시1", "옆 전시2"]
|
||||
|
||||
|
||||
def test_cloudy_weekend_is_not_called_clear():
|
||||
cloudy = [_day(SAT), _day(SUN)]
|
||||
for d in cloudy:
|
||||
|
||||
@@ -0,0 +1,154 @@
|
||||
# 기능 QA 체크리스트 (휴대폰)
|
||||
|
||||
아이폰 Safari와 안드로이드 Chrome에서 http://172.30.1.36:30040 에 들어가 위에서부터 따라 하며 체크합니다. 기대 결과는 `frontend/src/b/` 코드 기준이고, 확실하지 않은 동작은 "(확인)"을 붙였습니다.
|
||||
|
||||
## 0. 처음 들어가기
|
||||
|
||||
- [ ] 사이트 데이터를 지우고 접속 → 위치 권한을 묻고, 상단 지역 버튼 자리에 스켈레톤 막대
|
||||
- [ ] 위치 허용 → 가장 가까운 구로 바뀐다 / 거부 → 기본 "서울 마포구"
|
||||
- [ ] 새로고침 → 위치를 다시 묻지 않고 마지막 지역 그대로
|
||||
|
||||
## 1. 공통: 상단 바·하단 탭
|
||||
|
||||
- [ ] 하단 탭이 노을 · 각 · 오늘(가운데 큰 주황 동그라미) · 주말·행사 · 계절·상식 순
|
||||
- [ ] 탭을 옮길 때마다 맨 위에서 시작하고, 제목이 오늘은 주황 "날씨각", 나머지는 노을 / 오늘의 각 / 주말·행사 / 계절·상식
|
||||
- [ ] 로그아웃 상태는 오른쪽 위 "로그인" 버튼, 로그인 상태는 내 캐릭터 동그라미(기분 이모지 포함)
|
||||
- [ ] 스크롤해도 상단 바·하단 탭이 고정되고 뒤 내용이 흐리게 비친다
|
||||
|
||||
## 2. 오늘 탭: 히어로
|
||||
|
||||
- [ ] 시간대 버튼 지금 · 아침 · 낮 · 저녁 · 밤, 처음엔 "지금", 날짜 줄은 "M월 D일 요일 · HH:MM"
|
||||
- [ ] 해 안에 "오늘 날씨 점수"와 큰 숫자, 아래 칩 한 줄: 첫 칸 "지금 + 기온·하늘", 나머지는 챙길 것(비·미세먼지 등)
|
||||
- [ ] "아침" → 시계 07:40, 첫 칩 이름 "아침", 기온이 7시 예보 값 (낮 13:20 · 저녁 18:25 · 밤 22:10도 같은 방식)
|
||||
- [ ] 저녁·밤 → 해 동그라미가 오늘 밤 달 모양으로 가려진다(달 정보가 있을 때), 밤은 캐릭터가 곰
|
||||
- [ ] 말풍선 누름 → 1위 각의 계산 근거 시트
|
||||
|
||||
## 3. 시간대 테마 (낮·노을·밤)
|
||||
|
||||
- [ ] 히어로에서 고른 시간대로 화면 전체 하늘 배경이 바뀐다
|
||||
- [ ] 밤 → 카드·시트·하단 탭까지 어두운 색, 글자 밝게, 별 반짝임과 별똥별
|
||||
- [ ] 저녁 → 노을색 배경, 히어로 칩 글자가 흰색으로 읽힌다
|
||||
- [ ] 고른 시간대가 다른 탭·새로고침에도 유지, 새 탭(새 창)에서 열면 "지금"으로 시작
|
||||
- [ ] "지금" → 실제 시각 기준(아침 05~11시, 일몰 2시간 전부터 저녁, 일몰 1시간 뒤부터 밤)
|
||||
|
||||
## 4. 오늘 탭: 각 줄·띠
|
||||
|
||||
- [ ] "오늘의 각" 동그라미 줄이 옆으로 밀리고, 1~3위 메달, 50점 미만은 회색 테두리, 누르면 계산 근거 시트
|
||||
- [ ] "전체 보기" → 각 탭
|
||||
- [ ] 3번째 글 뒤 "이번 주 가까운 행사"(카드 → 주말·행사 탭), 6번째 뒤 "지금 뜨는 각 TOP 5"(카드 → 계산 근거), 9번째 뒤 "이번 주 계절 이야기"(카드 → 읽을거리)
|
||||
- [ ] 글이 9개보다 적으면 남은 띠가 피드 맨 끝에 붙는다
|
||||
- [ ] 지역을 바꾸면 맨 위로 가고 넘겨 둔 슬라이드가 1장으로 돌아간다
|
||||
|
||||
## 5. 피드 포스트
|
||||
|
||||
- [ ] 머리줄 "날씨각" + 계정 이름(오늘 날씨, 오늘의 각, 노을, 계절 소식, 가까운 행사, 날씨 상식, 주말 예보, 생활 알림, 내일 미리보기, 오늘의 한 문장, 주말 플랜, 미세먼지, 당일치기, 오늘 밤 달, 자외선)
|
||||
- [ ] 2장 이상이면 오른쪽 위 "1/N", 밀면 숫자가 바뀐다. 1장짜리는 밀리지 않는다
|
||||
- [ ] 오늘 날씨: 시간별 4칸(주황 막대 높이가 기온 비례), 저녁 칸 살구색·밤 칸 보라색
|
||||
- [ ] 각: "오늘의 각 · N위", 큰 점수, "계산 근거 보기" → 계산 근거 시트
|
||||
- [ ] 노을: 노을 점수와 시각 칸들 / 주말 예보: 토·일 칸("비 N% · 일교차 N°") + 검은 팁 줄
|
||||
- [ ] 주말 플랜: 시간·아이콘·제목·설명 줄, 사진이 있으면 작은 사진과 맨 아래 "사진 출처"
|
||||
- [ ] 행사·당일치기 사진 슬라이드: 사진 위 글자, 오른쪽 위 출처
|
||||
- [ ] 점선 밑줄 장소 이름 → 네이버 지도 검색이 새 탭으로
|
||||
- [ ] 한 줄 카드(흐린 날 노을 등)는 아이콘·제목·설명만, 버튼 없음
|
||||
- [ ] 카드 아래 "좋아요 N개", 본문, "댓글 N개 모두 보기"(0개면 "첫 댓글 남기기")
|
||||
|
||||
## 6. 좋아요·댓글
|
||||
|
||||
- [ ] 로그아웃 상태에서 하트 또는 사진 두 번 탭 → 로그인 시트
|
||||
- [ ] 로그인 후 사진 두 번 탭 → 큰 하트 + 튀는 하트 + "좋아요했어요!", 하트 빨강, 숫자 +1
|
||||
- [ ] 이미 좋아요한 사진 두 번 탭 → 효과만 다시, 숫자 그대로 / 하트 버튼 → 취소, -1
|
||||
- [ ] 다른 탭에 다녀와도 하트·숫자 유지
|
||||
- [ ] (비행기 모드) 좋아요 → 원래대로 돌아가고 아래에 "좋아요를 반영하지 못했어요. 다시 해 주세요." 2.5초
|
||||
- [ ] 댓글 아이콘·"댓글 … 보기" → 댓글 시트, 없으면 "아직 댓글이 없어요. 첫 댓글을 남겨 보세요."
|
||||
- [ ] 빠른 이모지(☀️🌂🍻🌇😍👍) → 입력칸 끝에 붙고 포커스, 입력은 60자까지
|
||||
- [ ] 로그인 후 "게시" → "올리는 중…" 뒤 목록에 뜨고 입력칸이 비며, 피드 댓글 수도 늘어난다
|
||||
- [ ] 로그아웃 상태에서 "게시" → 로그인 시트로 바뀐다
|
||||
- [ ] 내 댓글에만 "지우기" → 흐려졌다 사라진다 / 댓글 작은 하트 → 좋아요 수 변경
|
||||
- [ ] 댓글이 많으면 "댓글 더 보기"로 더 불러온다 (확인: 한 번에 몇 개인지)
|
||||
|
||||
## 7. 로그인·내 정보
|
||||
|
||||
- [ ] 로그인 시트 "로그인 / 처음이에요" 전환, 처음이에요는 닉네임 칸 + "가입하고 시작하기"
|
||||
- [ ] 틀린 비밀번호 → "아이디나 비밀번호가 맞지 않아요." / 있는 아이디로 가입 → "이미 쓰고 있는 아이디예요."
|
||||
- [ ] 로그인 성공 → 시트가 닫히고 오른쪽 위가 내 캐릭터 / "나중에 할게요" → 닫힘
|
||||
- [ ] 캐릭터 누름 → "내 정보" 시트, "아이디(으)로 로그인했어요"
|
||||
- [ ] 캐릭터 6종·배경색 6개 누름 → 주황 테두리, 큰 캐릭터·상단 바 캐릭터가 바뀐다
|
||||
- [ ] 오늘 기분 8개 → 캐릭터 오른쪽 위 이모지, 같은 기분 다시 누르면 지워진다
|
||||
- [ ] 닉네임이 지금과 같으면 "바꾸기"가 막혀 있고, 바꾸면 "저장 중…" 뒤 저장, 댓글 목록에도 반영
|
||||
- [ ] "로그아웃" → 시트 닫힘, 오른쪽 위 "로그인", 좋아요 표시가 풀린다
|
||||
|
||||
## 8. 지역 바꾸기
|
||||
|
||||
- [ ] 지역 버튼 → "지역 바꾸기" 시트, 지금 지역은 주황 글자 + "지금 보는 곳"
|
||||
- [ ] "마포" 입력 → 목록이 걸러짐, 없는 이름 → "찾는 구가 없어요."
|
||||
- [ ] 다른 구 누름 → 시트가 닫히고 지역 이름·모든 탭 데이터가 바뀐다
|
||||
- [ ] "지금 위치로 찾기" → "위치를 찾는 중이에요…", 성공하면 지역이 바뀌고 시트는 열린 채 (확인)
|
||||
- [ ] 위치 권한 끈 상태 → "위치 권한이 꺼져 있어요. 아래 목록에서 골라 주세요."
|
||||
|
||||
## 9. 노을 탭
|
||||
|
||||
- [ ] 히어로 "오늘 노을 · 지역", 큰 해 지는 시각, 하늘 상황 한 줄, 상황에 따라 색이 다르고 아래 동네 실루엣
|
||||
- [ ] 흰 카드: 결론 + 이유, "예보 모델 N개 중 M개가 같은 예보 · 노을 점수 N"
|
||||
- [ ] "언제 보면 좋을까" 세 시각(해 짐 점만 주황), 더 나은 날이 있을 때만 분홍 안내 상자
|
||||
- [ ] 가까운 노을 명소 최대 3곳("방향쪽" · "Nkm", 이름 → 네이버 지도), 전국 노을 순위 8곳(내 지역 흰 바탕 + "내 지역")
|
||||
|
||||
## 10. 각 탭
|
||||
|
||||
- [ ] "오늘 1~3위" 부제 "M월 D일 기준 · 지역", 받침대 2위 · 1위(가장 크고 노란 바탕) · 3위, 누르면 계산 근거
|
||||
- [ ] 분야 칩 전체 · 밖에서 놀기 · 먹고 마시기 · 집안일 · 생활 고민 · 가을 각 → 3열 목록이 바뀐다
|
||||
- [ ] 목록 칸: 왼쪽 위 순위, 가을 핵심 각은 초록 "가을", 50점 미만 점수 회색
|
||||
- [ ] 맨 아래 "각 점수는 어떻게 매길까?" → 읽을거리 시트
|
||||
- [ ] 계산 근거 시트: 제목 "N위 이름", 지금 구간 설명, 레이더(요소 3개 이상), 날짜별 추이("예상" 표시), 구간 목록, 요소별 막대·비중, 계산 방법
|
||||
|
||||
## 11. 주말·행사 탭
|
||||
|
||||
- [ ] "열흘 날씨" 한 화면 7칸, 밀면 10일까지, 처음엔 이번 토요일 선택
|
||||
- [ ] 토·일·공휴일은 분홍 글자, 공휴일은 날짜 대신 이름
|
||||
- [ ] 날짜 누름 → 초록 추천 카드가 그날 것으로 바뀐다
|
||||
- [ ] 서울: 동네 고르기로 명소가 바뀌고, 부제가 날씨에 맞게("비가 와서 실내 명소를 먼저" / "맑아서 야외 명소를 먼저")
|
||||
- [ ] 명소 배지 "오늘 딱"(야외) / "비 와도 OK"(실내), 이름 → 네이버 지도
|
||||
- [ ] 서울이 아닌 지역 → 데이트 명소 칸이 통째로 숨는다, 지역을 바꾸면 동네 고르기가 "전체"로
|
||||
- [ ] 전국 날씨 순위: 토/일 칩 전환, 10위까지, 내 지역 표시, 추정은 "· 예상"
|
||||
- [ ] 축제·행사: 진행 중(초록)/곧 시작(주황) 배지, 기간·장소, 미확정 "· 일정 확인 필요", 날씨 줄(비면 분홍)
|
||||
- [ ] "이번 주말 일정 보내기" → 공유 시트(고른 날 추천 카드 이미지)
|
||||
|
||||
## 12. 계절·상식 탭
|
||||
|
||||
- [ ] 특집 상자: "이번 주 특집 · 기간", 제목, 시, 절기 막대
|
||||
- [ ] 특집 상자 → "이번 주 특집" 시트, 그 안 글 목록 → 읽을거리 시트로 바뀐다
|
||||
- [ ] 분류 칩 전체 · 계절 소식 · 날씨 상식 · 각 원리로 걸러지고, 줄 누름 → 읽을거리(제목이 분류 이름, "분류 · N분")
|
||||
|
||||
## 13. 공유하기
|
||||
|
||||
- [ ] 포스트 종이비행기 → "보내기" 시트, 9:16 선택된 채 "이미지 만드는 중" 뒤 미리보기
|
||||
- [ ] 4:5, 1:1로 바꾸면 비율이 바뀌고, 다시 돌아가면 바로 뜬다
|
||||
- [ ] 이미지: 위 "날씨각" + "지역 · 오늘 날짜", 슬라이드 최대 2장(2장이면 1·2 번호), 아래 "오늘 내 동네 각 보기 + 주소"
|
||||
- [ ] 이미지에 버튼("계산 근거 보기")·"1/N"·화살표가 빠져 있고, 밤 테마면 배경도 어두운 하늘
|
||||
- [ ] "공유하기" → 휴대폰 공유창에 이미지와 "제목 · 날씨각 주소" 글이 같이 넘어가고, 보내면 "보냈어요"(그냥 닫으면 안내 없음)
|
||||
- [ ] 카카오톡·인스타 스토리·사진 저장으로 실제 보내 본다 (확인: 앱마다 글이 빠질 수 있음)
|
||||
|
||||
## 14. 시트 공통
|
||||
|
||||
- [ ] 아래에서 올라오고 ×·바깥 어두운 곳 누름으로 닫힌다
|
||||
- [ ] 열린 동안 뒤 페이지가 스크롤되지 않고, 긴 내용은 시트 안에서만 스크롤된다
|
||||
- [ ] 안드로이드 뒤로 가기 → 시트만 닫힌다 (확인: 페이지가 뒤로 갈 수 있음)
|
||||
|
||||
## 15. 스켈레톤 · '?' · 실패
|
||||
|
||||
- [ ] 처음 열 때 각 화면·시트에 같은 틀의 회색 막대가 먼저 보이고, 데이터가 와도 덜컹이지 않는다
|
||||
- [ ] 값이 없는 칸은 흐린 '?'(히어로 점수·기온, 날짜 칸 기온, 시간별 "?°", 주말 "비 ?%")
|
||||
- [ ] 비행기 모드로 새로고침 → "정보를 불러오지 못했어요." + "다시 시도", 히어로 "앗, 날씨를 못 불러왔어요" / "점수를 못 불러왔어요"
|
||||
- [ ] 비행기 모드 해제 후 "다시 시도" → "다시 불러오는 중…" 뒤 정상 표시
|
||||
|
||||
## 16. 모바일에서 특히 볼 것
|
||||
|
||||
- [ ] 글자를 길게 눌러도 선택·돋보기·복사 메뉴가 안 뜬다, 사진·링크 길게 눌러도 미리보기 메뉴 없음(아이폰)
|
||||
- [ ] 입력칸(댓글·로그인·지역 검색·닉네임)은 글자 선택·붙여넣기가 되고, 눌러도 화면이 확대되지 않는다
|
||||
- [ ] 두 번 탭해도 확대되지 않는다, 두 손가락 확대 (확인: iOS는 막히지 않을 수 있음)
|
||||
- [ ] 아이폰 홈 막대가 하단 탭·댓글 입력줄을 가리지 않고, 좋아요 실패 알림은 하단 탭 위에 뜬다
|
||||
- [ ] 가로 모드에서 노치가 상단 바·카드 왼쪽 끝을 가리는지 (확인)
|
||||
- [ ] 어느 탭에서도 화면 전체가 옆으로 밀리지 않는다, 옆으로 미는 건 줄·슬라이드만
|
||||
- [ ] 슬라이드를 밀 때 페이지 위아래 스크롤이 같이 튀지 않는다
|
||||
- [ ] 작은 버튼이 잘 눌리는지: 포스트 하트·댓글·보내기, 댓글 하트, 시트 ×
|
||||
- [ ] 댓글 입력칸을 누르면 키보드 위로 입력칸·게시 버튼이 보인다 (확인)
|
||||
- [ ] 로그인 시트 비밀번호 칸·버튼, 지역 검색 목록이 키보드에 가려지지 않는다 (확인)
|
||||
+207
-57
@@ -8,47 +8,55 @@
|
||||
- 최종 점수 = 비중대로 섞은 점수 × (0.75 + 0.25 × 가장 낮은 요소 점수 ÷ 100). 비중 0%인 요소는 '가장 낮은 요소'에서 뺍니다. 가장 낮은 요소가 0점이면 25%가 깎입니다.
|
||||
- '0점 조건'에 걸리면 0점, '최대 N점' 조건에 걸리면 N점을 넘지 못합니다.
|
||||
- 시간대가 여러 개면 그중 가장 좋은 시간대 점수를 씁니다.
|
||||
- 미세먼지는 모든 각이 같은 규칙입니다: 초미세먼지 15㎍/㎥ 이하 100점 → 75㎍/㎥ 이상 0점.
|
||||
- 미세먼지는 초미세먼지 15㎍/㎥ 이하 100점 → 75㎍/㎥ 이상 0점입니다. 집콕각처럼 규칙을 따로 적은 각만 거꾸로(탁할수록 좋음) 셉니다.
|
||||
- 바람·미세먼지·노을 정보가 없으면 70점으로 둡니다.
|
||||
- 순위는 점수 × 중요도 가중치(상 1.0 · 중 0.85 · 하 0.7)로 정합니다. 화면에 보이는 점수는 그대로입니다.
|
||||
|
||||
## 한눈에 보기
|
||||
|
||||
| 순서 | 각 | 코드 | 분류 | 시간대 | 기온 | 비 | 바람 | 습도 | 미세먼지 | 시간 | 재미 각 | 계절 핵심 |
|
||||
|---:|---|---|---|---|---:|---:|---:|---:|---:|---:|:---:|:---:|
|
||||
| 1 | 야장각 | `yajang` | 먹고 마시기 | 18~24시 | 30% | 25% | 15% | 10% | 10% | 10% | ○ | |
|
||||
| 2 | 피크닉각 | `picnic` | 밖에서 놀기 | 11~16시 | 25% | 25% | 15% | 5% | 10% | 10% | | ○ |
|
||||
| 3 | 치맥각 | `chimaek` | 먹고 마시기 | 18~23시 | 30% | 20% | 15% | 15% | 10% | 10% | ○ | |
|
||||
| 4 | 산책각 | `walk` | 밖에서 놀기 | 18~22시 | 30% | 25% | 15% | 10% | 15% | 5% | | |
|
||||
| 5 | 환기각 | `vent` | 집안일 | 10~12시 / 12~14시 / 14~16시 / 16~18시 | 10% | 15% | 15% | 10% | 45% | 5% | | |
|
||||
| 6 | 등산각 | `hiking` | 밖에서 놀기 | 7~12시 | 25% | 25% | 20% | 5% | 10% | 5% | | ○ |
|
||||
| 7 | 세차각 | `carwash` | 집안일 | 9~18시 (비는 2일 뒤까지 봄) | 5% | 60% | 10% | 10% | 10% | 5% | | |
|
||||
| 8 | 캠핑각 | `camping` | 밖에서 놀기 | 18~다음 날 8시 | 30% | 25% | 15% | 15% | 10% | 5% | | ○ |
|
||||
| 9 | 러닝각 | `running` | 밖에서 놀기 | 6~8시 / 19~22시 | 35% | 20% | 10% | 15% | 10% | 5% | | |
|
||||
| 10 | 별보기각 | `stars` | 밖에서 놀기 | 21~다음 날 2시 | 5% | 10% | 5% | 5% | 15% | 45% | | ○ |
|
||||
| 11 | 짬뽕각 | `jjamppong` | 먹고 마시기 | 11~14시 / 17~20시 | 40% | 25% | 15% | 10% | 5% | 5% | ○ | |
|
||||
| 12 | 막걸리각 | `makgeolli` | 먹고 마시기 | 17~22시 | 15% | 50% | 10% | 15% | 5% | 5% | ○ | |
|
||||
| 13 | 뜨아각 | `iced_hot` | 먹고 마시기 | 7~10시 | 50% | 10% | 15% | 10% | 5% | 10% | ○ | |
|
||||
| 14 | 빨래각 | `laundry` | 집안일 | 9~16시 | 15% | 30% | 15% | 10% | 0% | 5% | | |
|
||||
| 15 | 자전거각 | `bike` | 밖에서 놀기 | 9~19시 | 25% | 25% | 25% | 5% | 10% | 5% | | |
|
||||
| 16 | 멍뭉산책각 | `dog` | 밖에서 놀기 | 7~9시 / 17~20시 | 35% | 25% | 10% | 5% | 15% | 5% | | |
|
||||
| 17 | 김서림각 | `glasses` | 생활 고민 | 7~9시 | 50% | 10% | 5% | 30% | 0% | 5% | | |
|
||||
| 18 | 화장붕괴각 | `makeup` | 생활 고민 | 10~18시 | 40% | 10% | 10% | 35% | 0% | 5% | | |
|
||||
| 19 | 냉면각 | `naengmyeon` | 먹고 마시기 | 11~14시 | 55% | 15% | 5% | 15% | 5% | 5% | ○ | |
|
||||
| 20 | 택시대란각 | `taxi` | 생활 고민 | 22~다음 날 2시 | 15% | 55% | 10% | 5% | 0% | 15% | | |
|
||||
| 21 | 배달폭주각 | `delivery` | 생활 고민 | 17~21시 | 20% | 50% | 10% | 5% | 5% | 10% | | |
|
||||
| 22 | 가드닝각 | `garden` | 집안일 | 7~10시 | 25% | 30% | 10% | 15% | 10% | 5% | | |
|
||||
| 23 | 사진산책각 | `photo` | 밖에서 놀기 | 일몰 앞뒤 1시간 | 10% | 25% | 10% | 5% | 10% | 30% | | |
|
||||
| 24 | 야구각 | `baseball` | 밖에서 놀기 | 18~22시 | 25% | 40% | 10% | 5% | 10% | 10% | ○ | |
|
||||
| 25 | 공부각 | `study` | 집안일 | 13~18시 | 35% | 35% | 10% | 5% | 5% | 10% | ○ | |
|
||||
| 26 | 넷플릭스각 | `netflix` | 집안일 | 20~24시 | 30% | 35% | 15% | 5% | 0% | 15% | ○ | |
|
||||
| 27 | 군밤각 | `chestnut` | 먹고 마시기 | 17~21시 | 55% | 25% | 10% | 0% | 5% | 5% | ○ | |
|
||||
| 순서 | 각 | 코드 | 분류 | 중요도 | 시간대 | 기온 | 비 | 바람 | 습도 | 미세먼지 | 시간 | 재미 각 | 계절 핵심 |
|
||||
|---:|---|---|---|:---:|---|---:|---:|---:|---:|---:|---:|:---:|:---:|
|
||||
| 1 | 야장각 | `yajang` | 먹고 마시기 | 중 | 18~24시 | 30% | 25% | 15% | 10% | 10% | 10% | ○ | |
|
||||
| 2 | 피크닉각 | `picnic` | 밖에서 놀기 | 상 | 11~16시 | 25% | 25% | 15% | 5% | 10% | 10% | | ○ |
|
||||
| 3 | 치맥각 | `chimaek` | 먹고 마시기 | 중 | 18~23시 | 30% | 20% | 15% | 15% | 10% | 10% | ○ | |
|
||||
| 4 | 산책각 | `walk` | 밖에서 놀기 | 상 | 18~22시 | 30% | 25% | 15% | 10% | 15% | 5% | | |
|
||||
| 5 | 환기각 | `vent` | 집안일 | 하 | 10~12시 / 12~14시 / 14~16시 / 16~18시 | 10% | 15% | 15% | 10% | 45% | 5% | | |
|
||||
| 6 | 등산각 | `hiking` | 밖에서 놀기 | 상 | 7~12시 | 25% | 25% | 20% | 5% | 10% | 5% | | ○ |
|
||||
| 7 | 세차각 | `carwash` | 집안일 | 하 | 9~18시 (비는 2일 뒤까지 봄) | 5% | 60% | 10% | 10% | 10% | 5% | | |
|
||||
| 8 | 캠핑각 | `camping` | 밖에서 놀기 | 상 | 18~다음 날 8시 | 30% | 25% | 15% | 15% | 10% | 5% | | ○ |
|
||||
| 9 | 러닝각 | `running` | 밖에서 놀기 | 상 | 6~8시 / 19~22시 | 35% | 20% | 10% | 15% | 10% | 5% | | |
|
||||
| 10 | 별보기각 | `stars` | 밖에서 놀기 | 중 | 21~다음 날 2시 | 5% | 10% | 5% | 5% | 15% | 45% | | ○ |
|
||||
| 11 | 짬뽕각 | `jjamppong` | 먹고 마시기 | 하 | 11~14시 / 17~20시 | 40% | 25% | 15% | 10% | 5% | 5% | ○ | |
|
||||
| 12 | 막걸리각 | `makgeolli` | 먹고 마시기 | 하 | 17~22시 | 15% | 50% | 10% | 15% | 5% | 5% | ○ | |
|
||||
| 13 | 뜨아각 | `iced_hot` | 먹고 마시기 | 하 | 7~10시 | 50% | 10% | 15% | 10% | 5% | 10% | ○ | |
|
||||
| 14 | 빨래각 | `laundry` | 집안일 | 상 | 9~16시 | 15% | 30% | 15% | 10% | 0% | 5% | | |
|
||||
| 15 | 자전거각 | `bike` | 밖에서 놀기 | 상 | 9~19시 | 25% | 25% | 25% | 5% | 10% | 5% | | |
|
||||
| 16 | 멍뭉산책각 | `dog` | 밖에서 놀기 | 중 | 7~9시 / 17~20시 | 35% | 25% | 10% | 5% | 15% | 5% | | |
|
||||
| 17 | 김서림각 | `glasses` | 생활 고민 | 중 | 7~9시 | 50% | 10% | 5% | 30% | 0% | 5% | | |
|
||||
| 18 | 화장붕괴각 | `makeup` | 생활 고민 | 중 | 10~18시 | 40% | 10% | 10% | 35% | 0% | 5% | | |
|
||||
| 19 | 냉면각 | `naengmyeon` | 먹고 마시기 | 하 | 11~14시 | 55% | 15% | 5% | 15% | 5% | 5% | ○ | |
|
||||
| 20 | 택시대란각 | `taxi` | 생활 고민 | 중 | 22~다음 날 2시 | 15% | 55% | 10% | 5% | 0% | 15% | | |
|
||||
| 21 | 배달폭주각 | `delivery` | 생활 고민 | 중 | 17~21시 | 20% | 50% | 10% | 5% | 5% | 10% | | |
|
||||
| 22 | 가드닝각 | `garden` | 집안일 | 하 | 7~10시 | 25% | 30% | 10% | 15% | 10% | 5% | | |
|
||||
| 23 | 사진산책각 | `photo` | 밖에서 놀기 | 중 | 일몰 앞뒤 1시간 | 10% | 25% | 10% | 5% | 10% | 30% | | |
|
||||
| 24 | 야구각 | `baseball` | 밖에서 놀기 | 하 | 18~22시 | 25% | 40% | 10% | 5% | 10% | 10% | ○ | |
|
||||
| 25 | 공부각 | `study` | 집안일 | 하 | 13~18시 | 35% | 35% | 10% | 5% | 5% | 10% | ○ | |
|
||||
| 26 | 넷플릭스각 | `netflix` | 집안일 | 하 | 20~24시 | 30% | 35% | 15% | 5% | 0% | 15% | ○ | |
|
||||
| 27 | 군밤각 | `chestnut` | 먹고 마시기 | 하 | 17~21시 | 55% | 25% | 10% | 0% | 5% | 5% | ○ | |
|
||||
| 28 | 골프각 | `golf` | 밖에서 놀기 | 중 | 7~12시 / 12~17시 | 30% | 30% | 25% | 5% | 5% | 5% | | |
|
||||
| 29 | 집콕각 | `jipkok` | 집안일 | 하 | 10~18시 | 30% | 30% | 10% | 5% | 20% | 5% | ○ | |
|
||||
| 30 | 낚시각 | `fishing` | 밖에서 놀기 | 중 | 5~9시 / 16~19시 | 25% | 25% | 35% | 0% | 5% | 10% | | |
|
||||
| 31 | 드라이브각 | `drive` | 밖에서 놀기 | 상 | 10~17시 | 20% | 30% | 5% | 5% | 15% | 10% | | |
|
||||
| 32 | 연날리기각 | `kite` | 밖에서 놀기 | 하 | 11~16시 | 20% | 25% | 45% | 0% | 5% | 5% | | |
|
||||
| 33 | 물놀이각 | `waterplay` | 밖에서 놀기 | 중 | 11~17시 | 40% | 25% | 10% | 0% | 0% | 5% | | |
|
||||
| 34 | 김장각 | `kimjang` | 집안일 | 하 | 9~16시 | 50% | 25% | 10% | 0% | 5% | 10% | | |
|
||||
|
||||
## 각별 자세히
|
||||
|
||||
### 야장각 (`yajang`)
|
||||
|
||||
- 설명: 저녁 6시~자정, 바깥 자리에 앉기 좋은 정도
|
||||
- 분류: 먹고 마시기 · 아이콘 `yajang` · 재미 각 예 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
||||
- 분류: 먹고 마시기 · 중요도 중 · 아이콘 `yajang` · 재미 각 예 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
||||
- 시간대: 18~24시
|
||||
- 요소별 규칙 (비중):
|
||||
- 기온 30%: 체감 18~24°가 좋음
|
||||
@@ -68,7 +76,7 @@
|
||||
### 피크닉각 (`picnic`)
|
||||
|
||||
- 설명: 낮 동안 돗자리 펴고 쉬기 좋은 정도
|
||||
- 분류: 밖에서 놀기 · 아이콘 `picnic` · 재미 각 아니오 · 계절 핵심 예 · 계산 근거 화면 있음
|
||||
- 분류: 밖에서 놀기 · 중요도 상 · 아이콘 `picnic` · 재미 각 아니오 · 계절 핵심 예 · 계산 근거 화면 있음
|
||||
- 시간대: 11~16시
|
||||
- 요소별 규칙 (비중):
|
||||
- 기온 25%: 체감 20~26°가 좋음
|
||||
@@ -89,7 +97,7 @@
|
||||
### 치맥각 (`chimaek`)
|
||||
|
||||
- 설명: 저녁에 바깥에서 치킨과 맥주가 당기는 정도
|
||||
- 분류: 먹고 마시기 · 아이콘 `chimaek` · 재미 각 예 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
||||
- 분류: 먹고 마시기 · 중요도 중 · 아이콘 `chimaek` · 재미 각 예 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
||||
- 시간대: 18~23시
|
||||
- 요소별 규칙 (비중):
|
||||
- 기온 30%: 체감 20~27°가 좋음
|
||||
@@ -109,7 +117,7 @@
|
||||
### 산책각 (`walk`)
|
||||
|
||||
- 설명: 걷기 좋은 정도 (해 진 뒤 기준)
|
||||
- 분류: 밖에서 놀기 · 아이콘 `walk` · 재미 각 아니오 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
||||
- 분류: 밖에서 놀기 · 중요도 상 · 아이콘 `walk` · 재미 각 아니오 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
||||
- 시간대: 18~22시
|
||||
- 요소별 규칙 (비중):
|
||||
- 기온 30%: 체감 15~23°가 좋음
|
||||
@@ -129,7 +137,7 @@
|
||||
### 환기각 (`vent`)
|
||||
|
||||
- 설명: 창문 열어 공기 바꾸기 좋은 정도
|
||||
- 분류: 집안일 · 아이콘 `vent` · 재미 각 아니오 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
||||
- 분류: 집안일 · 중요도 하 · 아이콘 `vent` · 재미 각 아니오 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
||||
- 시간대: 10~12시 / 12~14시 / 14~16시 / 16~18시
|
||||
- 요소별 규칙 (비중):
|
||||
- 기온 10%: 체감 15~26°가 좋음
|
||||
@@ -149,7 +157,7 @@
|
||||
### 등산각 (`hiking`)
|
||||
|
||||
- 설명: 산에 오르기 좋은 정도 (오전 기준)
|
||||
- 분류: 밖에서 놀기 · 아이콘 `hiking` · 재미 각 아니오 · 계절 핵심 예 · 계산 근거 화면 있음
|
||||
- 분류: 밖에서 놀기 · 중요도 상 · 아이콘 `hiking` · 재미 각 아니오 · 계절 핵심 예 · 계산 근거 화면 있음
|
||||
- 시간대: 7~12시
|
||||
- 요소별 규칙 (비중):
|
||||
- 기온 25%: 체감 10~20°가 좋음, 산 정상 보정 -6°
|
||||
@@ -171,7 +179,7 @@
|
||||
### 세차각 (`carwash`)
|
||||
|
||||
- 설명: 세차한 뒤 깨끗함이 오래가는 정도
|
||||
- 분류: 집안일 · 아이콘 `carwash` · 재미 각 아니오 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
||||
- 분류: 집안일 · 중요도 하 · 아이콘 `carwash` · 재미 각 아니오 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
||||
- 시간대: 9~18시 (비는 2일 뒤까지 봄)
|
||||
- 요소별 규칙 (비중):
|
||||
- 기온 5%: 체감 5~28°가 좋음
|
||||
@@ -191,7 +199,7 @@
|
||||
### 캠핑각 (`camping`)
|
||||
|
||||
- 설명: 하룻밤 캠핑하기 좋은 정도
|
||||
- 분류: 밖에서 놀기 · 아이콘 `camping` · 재미 각 아니오 · 계절 핵심 예 · 계산 근거 화면 있음
|
||||
- 분류: 밖에서 놀기 · 중요도 상 · 아이콘 `camping` · 재미 각 아니오 · 계절 핵심 예 · 계산 근거 화면 있음
|
||||
- 시간대: 18~다음 날 8시
|
||||
- 요소별 규칙 (비중):
|
||||
- 기온 30%: 체감 12~22°가 좋음
|
||||
@@ -211,7 +219,7 @@
|
||||
### 러닝각 (`running`)
|
||||
|
||||
- 설명: 뛰기 좋은 정도 (아침·저녁 중 좋은 쪽)
|
||||
- 분류: 밖에서 놀기 · 아이콘 `running` · 재미 각 아니오 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
||||
- 분류: 밖에서 놀기 · 중요도 상 · 아이콘 `running` · 재미 각 아니오 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
||||
- 시간대: 6~8시 / 19~22시
|
||||
- 요소별 규칙 (비중):
|
||||
- 기온 35%: 체감 8~18°가 좋음
|
||||
@@ -232,7 +240,7 @@
|
||||
### 별보기각 (`stars`)
|
||||
|
||||
- 설명: 밤하늘 별이 잘 보이는 정도
|
||||
- 분류: 밖에서 놀기 · 아이콘 `stars` · 재미 각 아니오 · 계절 핵심 예 · 계산 근거 화면 있음
|
||||
- 분류: 밖에서 놀기 · 중요도 중 · 아이콘 `stars` · 재미 각 아니오 · 계절 핵심 예 · 계산 근거 화면 있음
|
||||
- 시간대: 21~다음 날 2시
|
||||
- 요소별 규칙 (비중):
|
||||
- 기온 5%: 체감 5~25°가 좋음
|
||||
@@ -253,7 +261,7 @@
|
||||
### 짬뽕각 (`jjamppong`)
|
||||
|
||||
- 설명: 뜨끈한 국물이 당기는 정도
|
||||
- 분류: 먹고 마시기 · 아이콘 `jjamppong` · 재미 각 예 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
||||
- 분류: 먹고 마시기 · 중요도 하 · 아이콘 `jjamppong` · 재미 각 예 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
||||
- 시간대: 11~14시 / 17~20시
|
||||
- 요소별 규칙 (비중):
|
||||
- 기온 40%: 추울수록 좋음 (25°=0점 → 5°=100점)
|
||||
@@ -273,7 +281,7 @@
|
||||
### 막걸리각 (`makgeolli`)
|
||||
|
||||
- 설명: 비 오는 날 파전에 막걸리가 당기는 정도
|
||||
- 분류: 먹고 마시기 · 아이콘 `makgeolli` · 재미 각 예 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
||||
- 분류: 먹고 마시기 · 중요도 하 · 아이콘 `makgeolli` · 재미 각 예 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
||||
- 시간대: 17~22시
|
||||
- 요소별 규칙 (비중):
|
||||
- 기온 15%: 추울수록 좋음 (28°=0점 → 10°=100점)
|
||||
@@ -293,7 +301,7 @@
|
||||
### 뜨아각 (`iced_hot`)
|
||||
|
||||
- 설명: 아이스 대신 따뜻한 커피로 바꿀 때가 된 정도
|
||||
- 분류: 먹고 마시기 · 아이콘 `iced_hot` · 재미 각 예 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
||||
- 분류: 먹고 마시기 · 중요도 하 · 아이콘 `iced_hot` · 재미 각 예 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
||||
- 시간대: 7~10시
|
||||
- 요소별 규칙 (비중):
|
||||
- 기온 50%: 추울수록 좋음 (22°=0점 → 8°=100점)
|
||||
@@ -313,7 +321,7 @@
|
||||
### 빨래각 (`laundry`)
|
||||
|
||||
- 설명: 빨래가 잘 마르는 정도
|
||||
- 분류: 집안일 · 아이콘 `laundry` · 재미 각 아니오 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
||||
- 분류: 집안일 · 중요도 상 · 아이콘 `laundry` · 재미 각 아니오 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
||||
- 시간대: 9~16시
|
||||
- 요소별 규칙 (비중):
|
||||
- 기온 15%: 더울수록 좋음 (10°=0점 → 25°=100점)
|
||||
@@ -334,7 +342,7 @@
|
||||
### 자전거각 (`bike`)
|
||||
|
||||
- 설명: 자전거 타기 좋은 정도
|
||||
- 분류: 밖에서 놀기 · 아이콘 `bike` · 재미 각 아니오 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
||||
- 분류: 밖에서 놀기 · 중요도 상 · 아이콘 `bike` · 재미 각 아니오 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
||||
- 시간대: 9~19시
|
||||
- 요소별 규칙 (비중):
|
||||
- 기온 25%: 체감 15~24°가 좋음
|
||||
@@ -355,7 +363,7 @@
|
||||
### 멍뭉산책각 (`dog`)
|
||||
|
||||
- 설명: 반려견과 산책하기 좋은 정도
|
||||
- 분류: 밖에서 놀기 · 아이콘 `dog` · 재미 각 아니오 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
||||
- 분류: 밖에서 놀기 · 중요도 중 · 아이콘 `dog` · 재미 각 아니오 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
||||
- 시간대: 7~9시 / 17~20시
|
||||
- 요소별 규칙 (비중):
|
||||
- 기온 35%: 체감 5~22°가 좋음
|
||||
@@ -376,7 +384,7 @@
|
||||
### 김서림각 (`glasses`)
|
||||
|
||||
- 설명: 안경에 김이 서리기 쉬운 정도
|
||||
- 분류: 생활 고민 · 아이콘 `glasses` · 재미 각 아니오 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
||||
- 분류: 생활 고민 · 중요도 중 · 아이콘 `glasses` · 재미 각 아니오 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
||||
- 시간대: 7~9시
|
||||
- 요소별 규칙 (비중):
|
||||
- 기온 50%: 추울수록 좋음 (15°=0점 → -5°=100점)
|
||||
@@ -396,7 +404,7 @@
|
||||
### 화장붕괴각 (`makeup`)
|
||||
|
||||
- 설명: 화장이 무너지기 쉬운 정도
|
||||
- 분류: 생활 고민 · 아이콘 `makeup` · 재미 각 아니오 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
||||
- 분류: 생활 고민 · 중요도 중 · 아이콘 `makeup` · 재미 각 아니오 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
||||
- 시간대: 10~18시
|
||||
- 요소별 규칙 (비중):
|
||||
- 기온 40%: 더울수록 좋음 (20°=0점 → 32°=100점)
|
||||
@@ -416,7 +424,7 @@
|
||||
### 냉면각 (`naengmyeon`)
|
||||
|
||||
- 설명: 시원한 냉면이 당기는 정도
|
||||
- 분류: 먹고 마시기 · 아이콘 `naengmyeon` · 재미 각 예 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
||||
- 분류: 먹고 마시기 · 중요도 하 · 아이콘 `naengmyeon` · 재미 각 예 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
||||
- 시간대: 11~14시
|
||||
- 요소별 규칙 (비중):
|
||||
- 기온 55%: 더울수록 좋음 (18°=0점 → 32°=100점)
|
||||
@@ -436,7 +444,7 @@
|
||||
### 택시대란각 (`taxi`)
|
||||
|
||||
- 설명: 밤늦게 택시 잡기 어려운 정도
|
||||
- 분류: 생활 고민 · 아이콘 `taxi` · 재미 각 아니오 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
||||
- 분류: 생활 고민 · 중요도 중 · 아이콘 `taxi` · 재미 각 아니오 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
||||
- 시간대: 22~다음 날 2시
|
||||
- 요소별 규칙 (비중):
|
||||
- 기온 15%: 추울수록 좋음 (15°=0점 → -5°=100점)
|
||||
@@ -456,7 +464,7 @@
|
||||
### 배달폭주각 (`delivery`)
|
||||
|
||||
- 설명: 배달 주문이 몰리는 정도
|
||||
- 분류: 생활 고민 · 아이콘 `delivery` · 재미 각 아니오 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
||||
- 분류: 생활 고민 · 중요도 중 · 아이콘 `delivery` · 재미 각 아니오 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
||||
- 시간대: 17~21시
|
||||
- 요소별 규칙 (비중):
|
||||
- 기온 20%: 추울수록 좋음 (22°=0점 → 0°=100점)
|
||||
@@ -476,7 +484,7 @@
|
||||
### 가드닝각 (`garden`)
|
||||
|
||||
- 설명: 화분 돌보고 물 주기 좋은 정도
|
||||
- 분류: 집안일 · 아이콘 `garden` · 재미 각 아니오 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
||||
- 분류: 집안일 · 중요도 하 · 아이콘 `garden` · 재미 각 아니오 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
||||
- 시간대: 7~10시
|
||||
- 요소별 규칙 (비중):
|
||||
- 기온 25%: 체감 12~25°가 좋음
|
||||
@@ -497,7 +505,7 @@
|
||||
### 사진산책각 (`photo`)
|
||||
|
||||
- 설명: 노을 무렵 사진 찍으며 걷기 좋은 정도
|
||||
- 분류: 밖에서 놀기 · 아이콘 `photo` · 재미 각 아니오 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
||||
- 분류: 밖에서 놀기 · 중요도 중 · 아이콘 `photo` · 재미 각 아니오 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
||||
- 시간대: 일몰 앞뒤 1시간
|
||||
- 요소별 규칙 (비중):
|
||||
- 기온 10%: 체감 10~26°가 좋음
|
||||
@@ -518,7 +526,7 @@
|
||||
### 야구각 (`baseball`)
|
||||
|
||||
- 설명: 저녁 6~10시, 야구장 직관하기 좋은 정도
|
||||
- 분류: 밖에서 놀기 · 아이콘 `baseball` · 재미 각 예 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
||||
- 분류: 밖에서 놀기 · 중요도 하 · 아이콘 `baseball` · 재미 각 예 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
||||
- 시간대: 18~22시
|
||||
- 요소별 규칙 (비중):
|
||||
- 기온 25%: 체감 15~25°가 좋음
|
||||
@@ -538,7 +546,7 @@
|
||||
### 공부각 (`study`)
|
||||
|
||||
- 설명: 오후 1~6시, 밖에 나가기 싫어서 공부가 잘되는 정도
|
||||
- 분류: 집안일 · 아이콘 `study` · 재미 각 예 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
||||
- 분류: 집안일 · 중요도 하 · 아이콘 `study` · 재미 각 예 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
||||
- 시간대: 13~18시
|
||||
- 요소별 규칙 (비중):
|
||||
- 기온 35%: 체감이 15~24°에서 멀수록(덥거나 추울수록) 좋음
|
||||
@@ -558,7 +566,7 @@
|
||||
### 넷플릭스각 (`netflix`)
|
||||
|
||||
- 설명: 밤 8시~자정, 집에서 영화 보기 좋은 정도
|
||||
- 분류: 집안일 · 아이콘 `netflix` · 재미 각 예 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
||||
- 분류: 집안일 · 중요도 하 · 아이콘 `netflix` · 재미 각 예 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
||||
- 시간대: 20~24시
|
||||
- 요소별 규칙 (비중):
|
||||
- 기온 30%: 추울수록 좋음 (22°=0점 → 0°=100점)
|
||||
@@ -578,7 +586,7 @@
|
||||
### 군밤각 (`chestnut`)
|
||||
|
||||
- 설명: 저녁 5~9시, 길거리 군밤이 당기는 정도
|
||||
- 분류: 먹고 마시기 · 아이콘 `chestnut` · 재미 각 예 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
||||
- 분류: 먹고 마시기 · 중요도 하 · 아이콘 `chestnut` · 재미 각 예 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
||||
- 시간대: 17~21시
|
||||
- 요소별 규칙 (비중):
|
||||
- 기온 55%: 추울수록 좋음 (18°=0점 → 0°=100점)
|
||||
@@ -595,3 +603,145 @@
|
||||
- 60~79점: 손이 시려요. 따끈한 군밤 한 봉지!
|
||||
- 80~100점: 영하 가까운 저녁, 군밤 품고 걷는 날 🌰
|
||||
|
||||
### 골프각 (`golf`)
|
||||
|
||||
- 설명: 오전 7시~오후 5시, 필드에서 라운딩하기 좋은 정도
|
||||
- 분류: 밖에서 놀기 · 중요도 중 · 아이콘 `golf` · 재미 각 아니오 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
||||
- 시간대: 7~12시 / 12~17시
|
||||
- 요소별 규칙 (비중):
|
||||
- 기온 30%: 체감 15~24°가 좋음
|
||||
- 비 30%: 비 안 올수록 좋음
|
||||
- 바람 25%: 잔잔할수록 좋음 (초속 3m까지 괜찮음, 9m면 0점)
|
||||
- 습도 5%: 30~60%가 좋음 (최적 35%)
|
||||
- 미세먼지 5%: 초미세먼지 낮을수록 좋음
|
||||
- 시간·요일 5%: 요일별 점수: 토 100, 일 100, 공휴일 100, 그 외 70
|
||||
- 점수 깎이는 조건: 비 확률 70% 이상이면 0점, 바람 12m/s 이상이면 0점, wind 특보가 있으면
|
||||
- 반영 못 하는 것: 골프장 예약, 잔디 상태, 낙뢰는 반영하지 못해요
|
||||
- 점수 구간별 설명 (상세 창에 나옴):
|
||||
- 0~29점: 비 70% 넘거나 바람이 너무 세요. 오늘은 스크린으로!
|
||||
- 30~59점: 춥거나 덥거나 바람이 공을 흔들어요. 타수는 기대 말기!
|
||||
- 60~79점: 칠 만해요! 바람 방향만 잘 읽으면 돼요.
|
||||
- 80~100점: 15~24°에 바람 잔잔, 인생 라운딩 노려볼 날 ⛳
|
||||
|
||||
### 집콕각 (`jipkok`)
|
||||
|
||||
- 설명: 오전 10시~오후 6시, 나가기 싫어 집에 있고 싶은 정도
|
||||
- 분류: 집안일 · 중요도 하 · 아이콘 `jipkok` · 재미 각 예 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
||||
- 시간대: 10~18시
|
||||
- 요소별 규칙 (비중):
|
||||
- 기온 30%: 체감이 15~24°에서 멀수록(덥거나 추울수록) 좋음
|
||||
- 비 30%: 비 올수록 좋음
|
||||
- 바람 10%: 셀수록 좋음 (초속 8m=100점)
|
||||
- 습도 5%: 높을수록 좋음 (40%=0점 → 90%=100점)
|
||||
- 미세먼지 20%: 초미세먼지 높을수록 좋음 (15㎍/㎥=0점 → 75㎍/㎥=100점)
|
||||
- 시간·요일 5%: 요일별 점수: 토 100, 일 100, 공휴일 100, 그 외 60
|
||||
- 점수 깎이는 조건: 없음
|
||||
- 반영 못 하는 것: 재미로 보는 지수예요
|
||||
- 점수 구간별 설명 (상세 창에 나옴):
|
||||
- 0~29점: 밖이 너무 좋아요. 집에만 있기 아까운 날!
|
||||
- 30~59점: 나갈까 말까, 소파와 밀당 중이에요.
|
||||
- 60~79점: 덥거나 춥거나 공기가 탁해요. 집이 최고!
|
||||
- 80~100점: 비 오고 공기까지 탁해요. 이불 밖은 위험해 🛋️
|
||||
|
||||
### 낚시각 (`fishing`)
|
||||
|
||||
- 설명: 새벽 5~9시·오후 4~7시, 물가에서 낚시하기 좋은 정도
|
||||
- 분류: 밖에서 놀기 · 중요도 중 · 아이콘 `fishing` · 재미 각 아니오 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
||||
- 시간대: 5~9시 / 16~19시
|
||||
- 요소별 규칙 (비중):
|
||||
- 기온 25%: 체감 12~24°가 좋음
|
||||
- 비 25%: 비 안 올수록 좋음
|
||||
- 바람 35%: 잔잔할수록 좋음 (초속 4m까지 괜찮음, 10m면 0점)
|
||||
- 습도 0%: 상관없음 (50점 고정)
|
||||
- 미세먼지 5%: 초미세먼지 낮을수록 좋음
|
||||
- 시간·요일 10%: 요일별 점수: 토 100, 일 100, 공휴일 100, 그 외 60
|
||||
- 점수 깎이는 조건: 비 확률 70% 이상이면 0점, 바람 10m/s 이상이면 0점, wind 특보가 있으면
|
||||
- 반영 못 하는 것: 물때·수온·파도 높이는 반영하지 못해요
|
||||
- 점수 구간별 설명 (상세 창에 나옴):
|
||||
- 0~29점: 비 70% 넘거나 바람이 거세요. 물가는 위험, 오늘은 쉬어요!
|
||||
- 30~59점: 바람에 찌가 흔들리거나 손이 시려요. 짧게 손맛만!
|
||||
- 60~79점: 물가 나가볼 만해요! 새벽엔 쌀쌀하니 겉옷 챙기기.
|
||||
- 80~100점: 12~24°에 물결 잔잔, 입질 기다리기 딱 좋은 날 🎣
|
||||
|
||||
### 드라이브각 (`drive`)
|
||||
|
||||
- 설명: 오전 10시~오후 5시, 창문 열고 드라이브하기 좋은 정도
|
||||
- 분류: 밖에서 놀기 · 중요도 상 · 아이콘 `drive` · 재미 각 아니오 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
||||
- 시간대: 10~17시
|
||||
- 요소별 규칙 (비중):
|
||||
- 기온 20%: 체감 15~25°가 좋음
|
||||
- 비 30%: 비 안 올수록 좋음
|
||||
- 바람 5%: 잔잔할수록 좋음 (초속 6m까지 괜찮음, 15m면 0점)
|
||||
- 습도 5%: 30~60%가 좋음 (최적 35%)
|
||||
- 미세먼지 15%: 초미세먼지 낮을수록 좋음
|
||||
- 가시거리 15%: 20km 이상이면 만점, 5km 이하면 0점 (Open-Meteo)
|
||||
- 시간·요일 10%: 요일별 점수: 토 100, 일 100, 공휴일 100, 그 외 60
|
||||
- 점수 깎이는 조건: 비 확률 70% 이상이면 최대 20점
|
||||
- 반영 못 하는 것: 길 막힘과 도로 공사는 반영하지 못해요
|
||||
- 점수 구간별 설명 (상세 창에 나옴):
|
||||
- 0~29점: 비가 쏟아져요. 와이퍼만 바쁜 날, 드라이브는 다음에!
|
||||
- 30~59점: 하늘이 뿌옇거나 비 기운이 있어요. 가까운 곳만 슬쩍!
|
||||
- 60~79점: 달릴 만해요! 창문 반쯤 열고 음악 크게.
|
||||
- 80~100점: 공기 맑고 멀리까지 보여요. 해안도로 달리고 싶은 날 🚗
|
||||
|
||||
### 연날리기각 (`kite`)
|
||||
|
||||
- 설명: 오전 11시~오후 4시, 연 날리기 좋은 정도
|
||||
- 분류: 밖에서 놀기 · 중요도 하 · 아이콘 `kite` · 재미 각 아니오 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
||||
- 시간대: 11~16시
|
||||
- 요소별 규칙 (비중):
|
||||
- 기온 20%: 체감 8~22°가 좋음
|
||||
- 비 25%: 비 안 올수록 좋음
|
||||
- 바람 45%: 적당한 바람(초속 2~5m)이 좋음
|
||||
- 습도 0%: 상관없음 (50점 고정)
|
||||
- 미세먼지 5%: 초미세먼지 낮을수록 좋음
|
||||
- 시간·요일 5%: 요일별 점수: 토 100, 일 100, 공휴일 100, 그 외 70
|
||||
- 점수 깎이는 조건: 비 확률 70% 이상이면 0점, 돌풍 13m/s 이상이면 0점, 바람 1m/s 미만이면 최대 30점
|
||||
- 반영 못 하는 것: 전깃줄·나무 없는 넓은 곳인지는 반영하지 못해요
|
||||
- 점수 구간별 설명 (상세 창에 나옴):
|
||||
- 0~29점: 비가 오거나 돌풍이 불어요. 연이 날아가 버려요!
|
||||
- 30~59점: 바람이 너무 약하거나 너무 세요. 뛰어다녀야 겨우 떠요.
|
||||
- 60~79점: 연 띄울 만해요! 실은 넉넉하게 감아 가요.
|
||||
- 80~100점: 초속 2~5m 딱 좋은 바람, 연이 하늘 높이 쭉쭉 🪁
|
||||
|
||||
### 물놀이각 (`waterplay`)
|
||||
|
||||
- 설명: 오전 11시~오후 5시, 바다·계곡에서 물놀이하기 좋은 정도
|
||||
- 분류: 밖에서 놀기 · 중요도 중 · 아이콘 `waterplay` · 재미 각 아니오 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
||||
- 시간대: 11~17시
|
||||
- 요소별 규칙 (비중):
|
||||
- 기온 40%: 체감 27~34°가 좋음
|
||||
- 비 25%: 비 안 올수록 좋음
|
||||
- 바람 10%: 잔잔할수록 좋음 (초속 4m까지 괜찮음, 12m면 0점)
|
||||
- 습도 0%: 상관없음 (50점 고정)
|
||||
- 미세먼지 0%: 초미세먼지 낮을수록 좋음
|
||||
- 햇빛 20%: 해 난 비율 80% 이상이면 만점, 20% 이하면 0점 (Open-Meteo)
|
||||
- 시간·요일 5%: 요일별 점수: 토 100, 일 100, 공휴일 100, 그 외 60
|
||||
- 점수 깎이는 조건: 비 확률 60% 이상이면 0점, 체감 20° 미만이면 0점
|
||||
- 반영 못 하는 것: 수온, 파도 높이, 계곡 물살은 반영하지 못해요
|
||||
- 점수 구간별 설명 (상세 창에 나옴):
|
||||
- 0~29점: 체감 20° 아래거나 비 소식이 있어요. 물놀이는 여름에!
|
||||
- 30~59점: 물에 들어가면 으슬으슬해요. 발만 담그기!
|
||||
- 60~79점: 물놀이 괜찮아요! 그늘막이랑 선크림 챙기기.
|
||||
- 80~100점: 30° 안팎에 쨍쨍, 튜브 들고 풍덩 🏖️
|
||||
|
||||
### 김장각 (`kimjang`)
|
||||
|
||||
- 설명: 오전 9시~오후 4시, 김장하기 좋은 정도
|
||||
- 분류: 집안일 · 중요도 하 · 아이콘 `kimchi` · 재미 각 아니오 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
||||
- 시간대: 9~16시
|
||||
- 요소별 규칙 (비중):
|
||||
- 기온 50%: 체감 0~10°가 좋음
|
||||
- 비 25%: 비 안 올수록 좋음
|
||||
- 바람 10%: 잔잔할수록 좋음 (초속 4m까지 괜찮음, 10m면 0점)
|
||||
- 습도 0%: 상관없음 (50점 고정)
|
||||
- 미세먼지 5%: 초미세먼지 낮을수록 좋음
|
||||
- 시간·요일 10%: 요일별 점수: 토 100, 일 100, 공휴일 100, 그 외 50
|
||||
- 점수 깎이는 조건: 체감 18° 이상이면 0점
|
||||
- 반영 못 하는 것: 배추 작황과 값, 집집마다 김장 날짜는 반영하지 못해요
|
||||
- 점수 구간별 설명 (상세 창에 나옴):
|
||||
- 0~29점: 아직 18° 넘어요. 지금 담그면 김치가 금방 쉬어요!
|
||||
- 30~59점: 조금 이르거나 손이 꽁꽁 얼어요. 날을 다시 골라 봐요.
|
||||
- 60~79점: 김장할 만해요! 고무장갑 안에 면장갑 하나 더.
|
||||
- 80~100점: 0~10°에 비 없고 바람 잔잔, 김장 날 잡는 날 🥬
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
# 이벤트 추적 (GA4)
|
||||
|
||||
기준: `frontend/index.html`, `frontend/src/lib/analytics.ts`, `frontend/src/b/Sheets.tsx`, `frontend/src/b/region.tsx` (2026-10-08)
|
||||
|
||||
## 한 줄 요약
|
||||
|
||||
GA4 태그(`gtag.js`, 측정 ID `G-D378J4X373`)를 `index.html`에 심고, 화면에서는 `track(이벤트, 값)`으로 GA4에 이벤트를 바로 보낸다. GTM은 쓰지 않는다.
|
||||
|
||||
```
|
||||
[화면] track('share', {...})
|
||||
└─ window.gtag('event', 'share', {...}) → GA4
|
||||
```
|
||||
|
||||
- 왜 GTM이 아니라 GA4 직접인가: 이벤트를 코드(`analytics.ts`)에서 정하므로, GTM을 쓰면 이벤트마다 트리거·태그를 한 번 더 만들어야 한다. 광고 픽셀도, 마케터가 직접 손볼 일도 아직 없다.
|
||||
- 개발 서버(`npm run dev`)에서는 `track()`이 이벤트를 보내지 않는다. 단 `index.html`의 페이지 조회(`page_view`)는 개발 서버에서도 나가므로 GA4에서 `localhost`를 걸러 본다.
|
||||
- 이벤트 이름은 영어 snake_case. GA4 추천 이벤트(`share`, `login`, `sign_up`, `select_content`)는 이름을 그대로 써야 GA4 기본 보고서에 잡힌다.
|
||||
- 값은 사람이 읽을 수 있게 한글 그대로 둔다 (예: `gak_name: '야장각'`).
|
||||
- 개인정보(아이디, 닉네임 등)는 값에 넣지 않는다.
|
||||
- 페이지 이동은 코드로 보내지 않는다. GA4 향상된 측정의 "브라우저 기록 이벤트 기반 페이지 변경"이 잡는다(기본 켜짐). 모든 이벤트에 GA4가 `page_location`을 붙이므로 어느 탭에서 일어났는지는 따로 보내지 않는다.
|
||||
|
||||
## 이벤트 목록
|
||||
|
||||
| 이벤트 | 언제 | 값 | 코드 |
|
||||
|---|---|---|---|
|
||||
| `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` | 로그인 성공 | `method: 'id'` | `Sheets.tsx` `LoginSheet` `done` |
|
||||
| `sign_up` | 가입 성공 | `method: 'id'` | `Sheets.tsx` `LoginSheet` `done` |
|
||||
| `region_change` | 지역 목록에서 고름, 또는 위치로 가까운 구를 찾음 | `region_name`, `method: 'list' \| 'location'` | `Sheets.tsx` `RegionSheet`, `region.tsx` `findNearest` |
|
||||
|
||||
- 공유창에서 사용자가 취소하면 `share`를 보내지 않는다.
|
||||
- `region_change`의 `location`은 처음 온 사람의 자동 위치 맞춤도 포함한다.
|
||||
- 새 이벤트는 `analytics.ts`의 `Events` 타입에 먼저 더한다. 타입에 없는 이름은 빌드에서 걸린다.
|
||||
|
||||
## GA4 설정
|
||||
|
||||
- 맞춤 값(`gak_name`, `ratio`, `region_name` 등)으로 보고서를 나눠 보려면 GA4 관리 → 맞춤 정의에서 이벤트 범위 측정기준으로 등록한다. 등록 전 값은 보고서에 소급되지 않는다.
|
||||
- 확인은 GA4 보고서 → 실시간, 또는 관리 → DebugView에서 한다. 운영 빌드(`docker compose up --build frontend`, http://localhost:8080)나 운영 사이트에서 눌러 본다.
|
||||
+145
@@ -0,0 +1,145 @@
|
||||
# 점수 계산식
|
||||
|
||||
화면에 나오는 점수·판정의 계산식을 한곳에 모은 문서입니다. 각별 비중·시간대는 [각_계산기준.md](각_계산기준.md)에 있습니다.
|
||||
|
||||
| 점수 | 화면 | 코드 |
|
||||
|---|---|---|
|
||||
| 오늘 날씨 점수 | 오늘 탭 히어로 큰 숫자 | `backend/services/index_service.py` (`WEATHER_SCORE_DEF`) |
|
||||
| 각 점수 | 각 탭, 피드 각 카드 | `backend/services/calc/index_calc.py` (`evaluate`) |
|
||||
| 나들이 점수 | 주말 탭 전국 순위, 당일치기 카드 | `backend/services/calc/index_calc.py` (`outing`) |
|
||||
| 노을 점수·판정 | 노을 탭, 피드 노을 카드, 노을 순위 | `backend/services/calc/sky_score.py`, `backend/services/sky_service.py` |
|
||||
| 노을 시각 | 노을 탭 시간표 | `backend/services/calc/sun.py`, `sky_score.py` (`best_times`) |
|
||||
| 달 밝기 | 밤 히어로 | `backend/services/calc/moon.py` |
|
||||
| 불쾌지수 | 히어로 칸 | `backend/services/calc/weather_calc.py` |
|
||||
|
||||
## 1. 공통 — 요소 점수와 섞는 법
|
||||
|
||||
오늘 날씨·각·나들이 점수는 모두 같은 방식입니다.
|
||||
|
||||
1. 요소(기온·비·바람·습도·미세먼지·햇빛 등)마다 0~100점을 매깁니다.
|
||||
2. 비중(합 100%)대로 섞습니다.
|
||||
3. 가장 낮은 요소로 깎습니다: **최종 = 섞은 점수 × (0.75 + 0.25 × 가장 낮은 요소 ÷ 100)**. 비중 0%인 요소는 빼고 봅니다. 한 요소가 0점이면 최대 25% 깎입니다.
|
||||
4. 0점 조건·최대 N점 조건이 있으면 적용합니다.
|
||||
|
||||
그래서 100점은 **비중이 있는 요소가 모두 100점**일 때만 나옵니다.
|
||||
|
||||
### 내려가는 곡선
|
||||
|
||||
만점 구간을 벗어나면 정규분포 곡선 모양으로 내려갑니다. 만점 근처는 천천히, 멀어질수록 빨리 떨어집니다.
|
||||
|
||||
`곡선(t) = (e^(−t²/2) − e^(−0.5)) ÷ (1 − e^(−0.5))` — t=0이면 1, t=1이면 0.
|
||||
|
||||
### 요소별 점수
|
||||
|
||||
| 요소 | 규칙 | 계산 |
|
||||
|---|---|---|
|
||||
| 기온(체감) | 편한 범위 lo~hi, 최적 best | 최적 ± 만점폭(기본 2°, 범위 끝까지 거리의 1/3 넘지 않음)은 100 → 범위 끝에서 85 → 범위 밖은 1°마다 8점 꼴로 곡선을 따라 0 (약 10.6° 벗어나면 0) |
|
||||
| 기온 | 높을수록·낮을수록 | zero에서 0, full에서 100, 사이는 곡선 |
|
||||
| 비 (마른 날이 좋음) | | 비 소식이 있으면 0. 아니면 비 확률 0%=100 → 100%=0, 곡선 |
|
||||
| 비 (비 오면 좋음) | 막걸리·배달폭주각 등 | 비 소식이 있으면 100. 아니면 비 확률 0%=0 → 100%=100 |
|
||||
| 바람 (잔잔할수록) | ok, limit | ok/2 이하 100 → ok에서 85 (직선) → limit에서 0 (곡선). 시간대 중 가장 센 바람 기준 |
|
||||
| 습도 | 편한 범위 | 기온과 같은 모양, 만점폭 5%, 범위 밖은 1%마다 2점 꼴 |
|
||||
| 미세먼지 | | 초미세먼지 15㎍/㎥ 이하 100 → 75 이상 0, 곡선. 집콕각은 거꾸로 |
|
||||
| 자외선·햇빛·가시거리 | zero, full | 직선 대신 곡선으로 zero→full |
|
||||
| 정보 없음 | | 바람·미세먼지·자외선·햇빛·가시거리 정보가 없으면 70점 |
|
||||
|
||||
## 2. 오늘 날씨 점수
|
||||
|
||||
오늘 낮 **9~21시**가 밖에 나가기 좋은 정도. 1의 방식으로 계산합니다.
|
||||
|
||||
| 요소 | 비중 | 100점 조건 |
|
||||
|---|---:|---|
|
||||
| 체감온도 (시간 평균) | 30% | 20.5~21.5° (편한 범위 18~24°, 최적 21°, 만점폭 0.5°) |
|
||||
| 비 | 25% | 비 소식 없음, 비 확률 0%대 |
|
||||
| 바람 (가장 센 값) | 10% | 초속 1m 이하 (2m에서 85점, 10m에서 0점) |
|
||||
| 습도 (시간 평균) | 10% | 45~55% (편한 범위 40~60%) |
|
||||
| 초미세먼지 | 10% | 10㎍/㎥ 이하 (75에서 0점) |
|
||||
| 해 난 비율 (Open-Meteo) | 15% | 90% 이상 (20%에서 0점), 정보 없으면 70점 |
|
||||
|
||||
여섯 가지가 동시에 맞아야 100점입니다. 기준값은 눈대중으로 잡은 것이며, 실제로 1년에 며칠 나오는지는 확인하지 않았습니다.
|
||||
|
||||
예: 체감 22.5°, 비 10%, 바람 2.5m, 습도 62%, 초미세먼지 15, 해 70% → 95점 미만.
|
||||
|
||||
## 3. 각 점수
|
||||
|
||||
- 1의 방식. 요소·비중·시간대·0점 조건은 각마다 다르며 [각_계산기준.md](각_계산기준.md)에 있습니다.
|
||||
- **시간대가 여러 개면 그중 가장 좋은 시간대 점수**를 그날 점수로 씁니다. 그래서 하루 동안 바뀌지 않습니다.
|
||||
- 순위는 점수 × 중요도(상 1.0 · 중 0.85 · 하 0.7). 화면 숫자는 점수 그대로입니다.
|
||||
- 단기예보가 닿지 않는 날(토·일 등)은 중기예보의 최저·최고 기온으로 시각별 기온을 어림하고(새벽 6시 최저, 오후 3시 최고, 코사인 곡선), 바람·습도·미세먼지는 정보 없음으로 둔 '예상 점수'입니다.
|
||||
|
||||
## 4. 나들이 점수 (주말 순위·당일치기)
|
||||
|
||||
토·일 **10~17시** 기준.
|
||||
|
||||
| 요소 | 비중 | 계산 |
|
||||
|---|---:|---|
|
||||
| 비 | 40% | 마른 날 규칙 (1 참고) |
|
||||
| 체감온도 | 35% | 편한 범위 17~24°, 최적 21° |
|
||||
| 하늘 | 15% | 시간마다 맑음 100 · 구름많음 80 · 흐림 50의 평균 |
|
||||
| 바람 | 10% | 4m/s 이하 100 → 12m/s 0 |
|
||||
|
||||
- 1처럼 가장 낮은 요소로 깎습니다.
|
||||
- 비 소식이 있거나 비 확률 60% 이상이면 **최대 30점**.
|
||||
- 중기예보뿐인 날은 기온을 어림하고 바람은 70점입니다.
|
||||
- 전국 순위: 노을 순위 대표 30곳을 점수순으로 정렬합니다.
|
||||
- 당일치기: 내 지역에서 직선 20~200km 안 후보 도시 중 토·일 중 더 좋은 날 점수가 가장 높은 곳입니다. 동점이면 비 확률이 낮은 곳 → 이른 날 → 가까운 곳 순입니다. 1위가 50점 미만이면 카드를 보이지 않습니다.
|
||||
|
||||
## 5. 노을 점수
|
||||
|
||||
해 지는(뜨는) 시각에 가장 가까운 정시의 구름을, 해 지는 방향 **20km(머리 위)**와 **100km(먼 쪽)** 두 지점에서 봅니다. 예보 모델마다 계산해 평균합니다.
|
||||
|
||||
### 구름 점수
|
||||
|
||||
- 물들 구름 = 20km 지점의 중층·상층 구름 중 큰 값(%)
|
||||
- **물들 정도** = 물들 구름 0%면 0.2 → 50%에서 1.0까지 직선 → 100%에서 0까지 직선
|
||||
- **머리 위 막힘** = 1 − 0.8 × 20km 낮은 구름 ÷ 100
|
||||
- **빛 들어옴** = 1 − min(100km 낮은 구름 + 0.5 × 100km 중층 구름, 100) ÷ 100
|
||||
- **구름 점수 = 100 × (0.75 × 물들 정도 + 0.25 × 머리 위 막힘) × (0.25 + 0.75 × 빛 들어옴)**
|
||||
|
||||
### 공기 보정 (곱함)
|
||||
|
||||
| 조건 | 배수 |
|
||||
|---|---|
|
||||
| 가시거리 (Open-Meteo) | 40km 이상 1.0 → 5km 이하 0.6, 사이 직선 |
|
||||
| 습도 | 50% 이하 1.0 → 90% 이상 0.75, 사이 직선 |
|
||||
| 비 갠 뒤 | 해 지기 2~6시간 전 비 확률 60% 이상이고 그 시각 40% 미만이면 × 1.15 |
|
||||
|
||||
**노을 점수 = min(100, 모델 평균 구름 점수 × 공기 보정)**. 값이 없는 보정은 건너뜁니다.
|
||||
|
||||
### 등급·판정
|
||||
|
||||
- 등급: 80↑ 붉음 · 60↑ 고움 · 40↑ 은은함 · 그 아래 잿빛
|
||||
- 하늘 상황 (모델 평균 구름으로, 위에서부터 먼저 걸리는 것):
|
||||
|
||||
| 상황 | 조건 | 판정 |
|
||||
|---|---|---|
|
||||
| 구름에 가려요 | 100km 낮은 구름 + 0.5 × 중층 ≥ 60 | 쉬어요 |
|
||||
| 낮은 구름이 덮어요 | 20km 낮은 구름 ≥ 60 | 쉬어요 |
|
||||
| 구름이 적어 짧게 끝나요 | 물들 구름 < 25 | 애매해요 |
|
||||
| 구름이 두꺼워 색이 약해요 | 물들 구름 > 75 | 애매해요 |
|
||||
| 하늘이 넓게 물들 수 있어요 | 그 밖 (25~75) | 나가 볼 만해요 |
|
||||
|
||||
- 화면 결론(나가 볼 만해요·애매해요·쉬어요)은 **하늘 상황 기준**입니다. 상황이 없을 때만 점수로 정합니다(60↑ 나가 볼 만해요, 40↑ 애매해요).
|
||||
- 확신도: 모델별 점수의 표준편차가 8 미만이면 높음, 15 미만이면 보통, 그 이상이거나 모델이 1개면 낮음.
|
||||
- 노을 순위: 대표 30곳을 노을 점수순으로 정렬합니다. 70% 이상이 같은 상황이면 한 줄 요약을 붙입니다.
|
||||
|
||||
## 6. 노을 시각
|
||||
|
||||
| 시각 | 정의 |
|
||||
|---|---|
|
||||
| 골든아워 | 해 고도가 **6°**로 내려온 때부터 해 질 때까지. 햇빛이 낮게 비쳐 금빛으로 보이는 시간 |
|
||||
| 해 져요 | 일몰 |
|
||||
| 가장 붉을 때 | 일몰 + 10분 + (20km 상층 구름 % ÷ 10)분. 상층 구름이 많을수록 늦게까지 물듦 |
|
||||
| 블루아워 | 해가 진 뒤 해 고도 **−6°**(시민박명 끝)가 되는 때. 해는 졌지만 하늘이 푸르게 남는 시간 |
|
||||
|
||||
일출은 순서가 거꾸로입니다(블루아워 → 가장 붉을 때 → 해 떠요).
|
||||
|
||||
## 7. 달 밝기
|
||||
|
||||
- **밝기 = (1 − cos(2π × 삭에서 지난 비율)) ÷ 2**. 0이면 그믐(안 보임), 1이면 보름입니다. 삭 시각은 Meeus 계산(오차 2분 안)입니다.
|
||||
- 달 모양에서 **빛나는 면의 비율**일 뿐, 구름·달 고도·월출 시각은 반영하지 않습니다.
|
||||
|
||||
## 8. 불쾌지수
|
||||
|
||||
- **불쾌지수 = 0.81 × 기온 + 0.01 × 습도 × (0.99 × 기온 − 14.3) + 46.3**
|
||||
- 68 미만 쾌적 · 75 미만 보통 · 80 미만 불쾌 · 그 이상 매우 불쾌
|
||||
+5
-5
@@ -140,7 +140,7 @@ td .note{display:block;color:var(--muted);font-size:12px;margin-top:3px;line-hei
|
||||
|
||||
<article class="card">
|
||||
<header><h3>주말 플랜</h3><span class="kind">계획 · 날마다 1장</span><span class="state always">매일</span></header>
|
||||
<dl><dt>켜지는 때</dt><dd>이번 주말 토·일 각각 독립 카드(포스트는 최대한 나눈다, 10/6). 그날 시간대별 동선: 아침 기온(일교차 크면 겉옷) → 12~16시 바깥 골든타임(비 오는 시간이 있으면 그 시간은 실내, 앞뒤로 바깥) → 그날 열리는 행사 최대 2곳(사진·장소) → 토요일은 일몰 시각에 노을, 일요일은 월요일 아침 기온과 함께 일찍 귀가. 행사는 가까운 순, 일요일은 그날 끝나는 행사 먼저("마지막 날 찬스"). 토요일에 고른 행사는 일요일에 다시 안 나옵니다.</dd></dl>
|
||||
<dl><dt>켜지는 때</dt><dd>이번 주말 토·일 각각 독립 카드(포스트는 최대한 나눈다, 10/6). 그날 시간대별 동선: 아침 기온(일교차 크면 겉옷) → 12~16시 바깥 골든타임(비 오는 시간이 있으면 그 시간은 실내, 앞뒤로 바깥) → 그날 열리는 행사 최대 2곳(사진·장소) → 토요일은 일몰 시각에 노을, 일요일은 월요일 아침 기온과 함께 일찍 귀가. 행사는 축제→공연→팝업→전시 순으로 종류마다 하나씩, 같은 종류 안에서는 가까운 순이고 일요일은 그날 끝나는 행사 먼저("마지막 날 찬스"). 가깝다고 전시만 이어지지 않게 합니다(10/7). 토요일에 고른 행사는 일요일에 다시 안 나옵니다.</dd></dl>
|
||||
<dl><dt>① 유저</dt><dd>"주말에 뭐 하지"에 시간표째로 답을 얻습니다.</dd></dl>
|
||||
<dl><dt>② 운영</dt><dd>날마다 내용이 달라 주말 직전까지 볼 이유가 생기고, "토요일 이렇게 놀자" 공유 카드가 됩니다.</dd></dl>
|
||||
</article>
|
||||
@@ -184,8 +184,8 @@ td .note{display:block;color:var(--muted);font-size:12px;margin-top:3px;line-hei
|
||||
<th>카드</th>
|
||||
<th class="m">아침<small>05–11시</small></th>
|
||||
<th class="d">낮<small>11시–일몰 2시간 전</small></th>
|
||||
<th class="e">저녁<small>일몰 2시간 전–21시</small></th>
|
||||
<th class="n">밤<small>21–05시</small></th>
|
||||
<th class="e">저녁<small>일몰 2시간 전–일몰 1시간 뒤</small></th>
|
||||
<th class="n">밤<small>일몰 1시간 뒤–05시</small></th>
|
||||
</tr></thead>
|
||||
<tbody>
|
||||
<tr><td class="name">지금 날씨<small>히어로</small></td><td><span class="pos top">고정</span></td><td><span class="pos top">고정</span></td><td><span class="pos top">고정</span></td><td><span class="pos top">고정</span><span class="note">밤에는 내일 아침 기온을 함께</span></td></tr>
|
||||
@@ -210,8 +210,8 @@ td .note{display:block;color:var(--muted);font-size:12px;margin-top:3px;line-hei
|
||||
<div><span class="n">1</span><p>히어로는 맨 위 고정. 히어로에는 날씨와 오늘 1위 각만 작게 두고, 1~3위 상세는 카드에서 보여 줍니다(확정).</p></div>
|
||||
<div><span class="n">2</span><p>같은 종류 카드는 붙이지 않습니다(확정). 각 3장 사이에는 다른 카드가 하나씩 끼어듭니다.</p></div>
|
||||
<div><span class="n">3</span><p>조건이 안 맞는 카드는 아예 빼고, 빈 카드나 "오늘은 없어요" 카드는 만들지 않습니다.<small>예외: 노을은 흐린 날에도 한 줄로 남깁니다(확정).</small></p></div>
|
||||
<div><span class="n">4</span><p>좋아요·댓글은 카드에 붙고, 전국 사용자가 같이 봅니다. 순서가 바뀌어도 같은 카드면 좋아요가 이어집니다.</p></div>
|
||||
<div><span class="n">5</span><p>시간대가 바뀌는 순간(05·11·16·21시)과 일몰 시각, 예보 갱신 때 피드가 새로 짜입니다.<small>앞에서 문제가 됐던 "새 칸이 늦게 보이는 문제"가 생기지 않습니다.</small></p></div>
|
||||
<div><span class="n">4</span><p>좋아요·댓글은 카드에 붙습니다. 지역 데이터 카드는 같은 시도 사용자끼리, 계절 소식·날씨 상식·한 문장·달은 전국 사용자가 같이 봅니다. 순서가 바뀌어도 같은 카드면 좋아요가 이어집니다.</p></div>
|
||||
<div><span class="n">5</span><p>시간대가 바뀌는 순간(05·11시, 일몰 2시간 전·일몰 1시간 뒤)과 일몰 시각, 예보 갱신 때 피드가 새로 짜입니다.<small>앞에서 문제가 됐던 "새 칸이 늦게 보이는 문제"가 생기지 않습니다.</small></p></div>
|
||||
<div><span class="n">6</span><p>카드마다 보낼 문구가 있고, 보내면 카드 그대로 이미지+링크로 갑니다(확정).</p></div>
|
||||
<div><span class="n">7</span><p>UI는 따로 고민하지 않고 인스타그램·페이스북 방식을 그대로 따릅니다(확정, 10/2).</p></div>
|
||||
<div><span class="n">8</span><p>지역은 날씨를 가져오는 시군구 단위 그대로입니다. 수원시 장안구 같은 일반구도 따로 봅니다(확정, 10/2, 256곳).</p></div>
|
||||
|
||||
+15
-12
@@ -1,13 +1,13 @@
|
||||
# 피드 동작 방식: 만들기 · 순서 · 갱신
|
||||
|
||||
기준: `backend/services/feed_service.py`, `backend/services/index_service.py`, `backend/scheduler/jobs.py`, `backend/router/v1/feed/feed.py` (2026-10-07)
|
||||
기준: `backend/services/feed_service.py`, `backend/services/index_service.py`, `backend/scheduler/jobs.py`, `backend/router/v1/feed/feed.py` (2026-10-08)
|
||||
|
||||
## 한 줄 요약
|
||||
|
||||
새벽 3시에 **전국 공통 틀(칸 19개)**을 DB에 만들고, 누가 피드를 열 때 **그 구의 데이터로 칸을 채워** Redis에 잠깐 둔다. 좋아요·댓글 수는 매번 DB에서 새로 읽어 덮어쓴다.
|
||||
새벽 3시에 **틀(칸 19개)**을 DB에 만들고(계절 소식·날씨 상식·한 문장·달은 전국 한 벌, 나머지는 시도마다 한 벌), 누가 피드를 열 때 **그 구의 데이터로 칸을 채워** Redis에 잠깐 둔다. 좋아요·댓글 수는 매번 DB에서 새로 읽어 덮어쓴다.
|
||||
|
||||
```
|
||||
[03:00 worker] ── 틀 19칸 → PostgreSQL post
|
||||
[03:00 worker] ── 틀 19칸(전국 칸 + 시도별 칸) → PostgreSQL post
|
||||
└─ Redis feed:* 전부 삭제
|
||||
|
||||
[사용자가 /v1/feed?region=구]
|
||||
@@ -18,11 +18,14 @@
|
||||
⑤ 좋아요·댓글 수, 내가 누른 표시를 DB에서 읽어 덮어쓴다 → 응답
|
||||
```
|
||||
|
||||
## 1. 틀 만들기 (하루 한 번, 전국 공통)
|
||||
## 1. 틀 만들기 (하루 한 번)
|
||||
|
||||
- **언제**: 매일 03:00 worker가 `build_feed_day`를 돌린다. 하루는 03:00에 시작해 다음 날 03:00에 끝난다.
|
||||
피드 요청이 올 때마다 같은 함수가 한 번 더 돈다. 이미 있는 칸은 그대로 두고, 빠진 칸(03:00 작업을 놓쳤거나 배포로 새 종류가 생긴 경우)만 더한다.
|
||||
- **어디에**: PostgreSQL `post` 테이블에 하루 19줄.
|
||||
- **어디에**: PostgreSQL `post` 테이블. 줄마다 `scope`가 있다 — `'00'`은 전국, 그 밖은 시도 코드(`region.code` 앞 2자리).
|
||||
계절 소식·날씨 상식·한 문장·달 칸은 전국 한 줄, 나머지 칸은 시도마다 한 줄(시도 16곳, 광주·전남이 같은 `12`). 하루 약 260줄.
|
||||
같은 날짜·칸·`scope`는 한 줄만(`uq_post_feed_scope`).
|
||||
- **피드에서 읽을 때**: 그 구의 시도 줄과 전국 줄을 같이 읽는다. 같은 칸에 둘 다 있으면 전국 줄을 쓴다(시도 나누기 전에 만든 날을 위해).
|
||||
- **한 줄에 들어가는 것**: 글 번호, 날짜, 칸 번호, 종류, 같은 종류 중 몇 번째인지, 유효 시간, 좋아요·댓글 수.
|
||||
계절 소식·날씨 상식 칸만 그날 보여줄 글 번호를 미리 정해 둔다(날짜마다 돌아가며).
|
||||
- **들어가지 않는 것**: 점수, 문장, 숫자 같은 내용. 내용은 구마다 다르므로 열 때 채운다.
|
||||
@@ -73,8 +76,8 @@
|
||||
|---|---|---|
|
||||
| 아침 | 05:00~11:00 | 05:00~11:00 |
|
||||
| 낮 | 11:00~일몰 2시간 전 | 11:00~16:05 |
|
||||
| 저녁 | 일몰 2시간 전~21:00 | 16:05~21:00 |
|
||||
| 밤 | 21:00~다음 날 05:00 | 21:00~05:00 |
|
||||
| 저녁 | 일몰 2시간 전~일몰 1시간 뒤 | 16:05~19:05 |
|
||||
| 밤 | 일몰 1시간 뒤~다음 날 05:00 (계절 따라 18시대~21시대 시작) | 19:05~05:00 |
|
||||
|
||||
시간대가 바뀌면 캐시 키(`feed:{구}:{시간대}`)가 달라져서 그 순간 새 순서로 다시 만들어진다.
|
||||
|
||||
@@ -84,10 +87,10 @@
|
||||
|---|---|
|
||||
| 아침 | 특보 → 미세먼지 → 각 1·2·3 → 계절 소식 → 노을 → 날씨 상식 → 주말 예보 → 주말 플랜(토) → 주말 플랜(일) → 당일치기 → 달 → 한 문장 |
|
||||
| 낮 | 각 → 특보 → 미세먼지 → 각 → 각 → 노을 → 주말 예보 → 주말 플랜 → 계절 소식 → 주말 플랜 → 당일치기 → 날씨 상식 → 달 → 한 문장 |
|
||||
| 저녁 | 노을 → 각 → 특보 → 각 → 각 → 미세먼지 → 내일 미리보기 → 주말 예보 → 주말 플랜 → 계절 소식 → 주말 플랜 → 당일치기 → 날씨 상식 → 달 → 한 문장 |
|
||||
| 밤 | 내일 미리보기 → 특보 → 노을 → 주말 예보 → 각 → 주말 플랜 → 각 → 각 → 주말 플랜 → 당일치기 → 미세먼지 → 계절 소식 → 날씨 상식 → 달 → 한 문장 |
|
||||
| 저녁 | 노을 → 각 → 달 → 특보 → 각 → 각 → 미세먼지 → 내일 미리보기 → 주말 예보 → 주말 플랜 → 계절 소식 → 주말 플랜 → 당일치기 → 날씨 상식 → 한 문장 |
|
||||
| 밤 | 내일 미리보기 → 달 → 특보 → 노을 → 주말 예보 → 각 → 주말 플랜 → 각 → 각 → 주말 플랜 → 당일치기 → 미세먼지 → 계절 소식 → 날씨 상식 → 한 문장 |
|
||||
|
||||
뜻: 아침엔 "나가기 전에 볼 것"(특보·공기·오늘 각), 낮엔 각을 맨 위로, 저녁엔 노을을 맨 위로, 밤엔 내일 준비(내일 미리보기)와 주말 계획을 앞으로. 내일 미리보기는 저녁·밤에만 나온다.
|
||||
뜻: 아침엔 "나가기 전에 볼 것"(특보·공기·오늘 각), 낮엔 각을 맨 위로, 저녁엔 노을을 맨 위로, 밤엔 내일 준비(내일 미리보기)와 주말 계획을 앞으로. 저녁·밤엔 하늘을 볼 시간이라 달을 위로. 내일 미리보기는 저녁·밤에만 나온다.
|
||||
|
||||
**기본 순서 위에 덧붙는 규칙**
|
||||
1. **특보가 있으면** 맨 위(히어로 바로 아래), 그다음 오늘·내일 날씨. 특보가 없으면 날씨가 맨 위.
|
||||
@@ -119,7 +122,7 @@
|
||||
- 키: `feed:{구 코드}:{시간대}` (예: `feed:4113500000:morning`)
|
||||
- DB에는 완성본을 저장하지 않는다. Redis가 비어도 DB의 틀과 재료로 다시 만든다.
|
||||
- **얼마나 두나**: 다음에 내용이 바뀌는 시각까지, 최대 1시간.
|
||||
바뀌는 시각 = 03:00, 05시, 11시, 일몰 2시간 전, 일몰, 21시, 다음 단기예보 제공 시각, 매시 20분(미세먼지)
|
||||
바뀌는 시각 = 03:00, 05시, 11시, 일몰 2시간 전, 일몰, 일몰 1시간 뒤, 다음 단기예보 제공 시각, 매시 20분(미세먼지)
|
||||
- **재료 중 하나라도 못 가져왔으면 60초**만 둔다. 다음 요청이 다시 채우게 하려고.
|
||||
|
||||
### 언제 새로 만들어지나
|
||||
@@ -136,6 +139,6 @@
|
||||
|
||||
## 4. 알아 둘 점
|
||||
|
||||
- **좋아요·댓글은 전국이 같은 글에 쌓인다.** 글 번호가 전국 공통이라, 분당구의 "각 1위(환기각)"와 마포구의 "각 1위(야장각)"가 같은 글 번호를 쓴다.
|
||||
- **좋아요·댓글은 같은 시도끼리 같은 글에 쌓인다.** 지역 카드는 시도마다 글 번호가 따로라, 강남구와 마포구의 "각 1위"는 같은 글 번호(서울)를, 부산 구는 다른 글 번호를 쓴다. 계절 소식·날씨 상식·한 문장·달은 전국이 같은 글 번호.
|
||||
- **공유 링크(`/v1/feed/post/{id}`)는 지금 그 구의 피드에서 글을 찾는다.** 어제 글이나 지금 꺼진 글은 "없는 글"이 된다. 공유한 글을 다시 보여줄 계획이 생기면 그때 공유한 글만 따로 저장한다.
|
||||
- **아무도 안 여는 구는 만들지 않는다.** 외부 API 호출도 그 구를 누가 열 때만 일어난다.
|
||||
+27
-5
@@ -1,21 +1,43 @@
|
||||
<!doctype html>
|
||||
<html lang="ko">
|
||||
<head>
|
||||
<!-- Google tag (gtag.js) -->
|
||||
<script async src="https://www.googletagmanager.com/gtag/js?id=G-D378J4X373"></script>
|
||||
<script>
|
||||
window.dataLayer = window.dataLayer || [];
|
||||
function gtag(){dataLayer.push(arguments);}
|
||||
gtag('js', new Date());
|
||||
|
||||
gtag('config', 'G-D378J4X373');
|
||||
</script>
|
||||
<meta charset="UTF-8" />
|
||||
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
|
||||
<link rel="apple-touch-icon" href="/apple-touch-icon.png" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />
|
||||
<meta name="description" content="오늘 날씨를 지수로. 노을, 야장각, 주말 계획까지 날씨각에서 확인하세요." />
|
||||
<title>날씨각</title>
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1, user-scalable=no, viewport-fit=cover" />
|
||||
<meta name="theme-color" content="#d6ebff" />
|
||||
<meta name="description" content="세차각·빨래각·러닝각처럼 오늘 날씨에 맞는 일을 점수로. 노을이 예쁜 시간과 명소, 이번 주말 가까운 축제까지 날씨각에서 확인하세요." />
|
||||
<title>날씨각 · 오늘 날씨 지수, 노을, 주말 행사</title>
|
||||
<meta property="og:type" content="website" />
|
||||
<meta property="og:site_name" content="날씨각" />
|
||||
<meta property="og:title" content="날씨각" />
|
||||
<meta property="og:description" content="오늘 날씨를 지수로. 노을, 야장각, 주말 계획까지 날씨각에서 확인하세요." />
|
||||
<meta property="og:title" content="날씨각 · 오늘 날씨 지수, 노을, 주말 행사" />
|
||||
<meta property="og:description" content="세차각·빨래각·러닝각처럼 오늘 날씨에 맞는 일을 점수로. 노을이 예쁜 시간과 명소, 이번 주말 가까운 축제까지 날씨각에서 확인하세요." />
|
||||
<meta property="og:url" content="%VITE_SITE_URL%/" />
|
||||
<link rel="canonical" href="%VITE_SITE_URL%/" />
|
||||
<meta property="og:image" content="%VITE_SITE_URL%/og.png" />
|
||||
<meta property="og:image:width" content="1200" />
|
||||
<meta property="og:image:height" content="630" />
|
||||
<meta name="twitter:card" content="summary_large_image" />
|
||||
<meta property="og:locale" content="ko_KR" />
|
||||
<meta name="google-site-verification" content="ageFc5cYyqCTlRxsQTu4d3uetA4WG7y7yUPR1f7muVk" />
|
||||
<script type="application/ld+json">
|
||||
{
|
||||
"@context": "https://schema.org",
|
||||
"@type": "WebSite",
|
||||
"name": "날씨각",
|
||||
"url": "%VITE_SITE_URL%/",
|
||||
"inLanguage": "ko-KR"
|
||||
}
|
||||
</script>
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com" />
|
||||
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
|
||||
<link
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 33 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 28 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 28 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 25 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 29 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 37 KiB |
@@ -0,0 +1,4 @@
|
||||
User-agent: *
|
||||
Allow: /
|
||||
|
||||
Sitemap: https://weather.o2o.kr/sitemap.xml
|
||||
@@ -0,0 +1,4 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
|
||||
<url><loc>https://weather.o2o.kr/</loc></url>
|
||||
</urlset>
|
||||
@@ -222,7 +222,7 @@ export const getWeekRankingOptions = (options?: Options<GetWeekRankingData>) =>
|
||||
export const listPlacesQueryKey = (options: Options<ListPlacesData>) => createQueryKey('listPlaces', options);
|
||||
|
||||
/**
|
||||
* 날씨 맞춤 데이트 명소
|
||||
* 날씨 맞춤 데이트 명소 (구 중심 30km 안, 없으면 가장 가까운 곳)
|
||||
*/
|
||||
export const listPlacesOptions = (options: Options<ListPlacesData>) => queryOptions<ListPlacesResponse, ListPlacesError, ListPlacesResponse, ReturnType<typeof listPlacesQueryKey>>({
|
||||
queryFn: async ({ queryKey, signal }) => {
|
||||
|
||||
@@ -69,7 +69,7 @@ export const getWeek = <ThrowOnError extends boolean = true>(options: Options<Ge
|
||||
export const getWeekRanking = <ThrowOnError extends boolean = true>(options?: Options<GetWeekRankingData, ThrowOnError>): RequestResult<GetWeekRankingResponses, unknown, ThrowOnError> => (options?.client ?? client).get<GetWeekRankingResponses, unknown, ThrowOnError>({ url: '/v1/week/ranking', ...options });
|
||||
|
||||
/**
|
||||
* 날씨 맞춤 데이트 명소
|
||||
* 날씨 맞춤 데이트 명소 (구 중심 30km 안, 없으면 가장 가까운 곳)
|
||||
*/
|
||||
export const listPlaces = <ThrowOnError extends boolean = true>(options: Options<ListPlacesData, ThrowOnError>): RequestResult<ListPlacesResponses, ListPlacesErrors, ThrowOnError> => (options.client ?? client).get<ListPlacesResponses, ListPlacesErrors, ThrowOnError>({ url: '/v1/week/place/list', ...options });
|
||||
|
||||
|
||||
@@ -110,6 +110,14 @@ export type ArticleSummary = {
|
||||
* Icon
|
||||
*/
|
||||
icon: string;
|
||||
/**
|
||||
* Image
|
||||
*/
|
||||
image?: string | null;
|
||||
/**
|
||||
* Image Credit
|
||||
*/
|
||||
image_credit?: string | null;
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -148,6 +156,14 @@ export type BandArticle = {
|
||||
* Icon
|
||||
*/
|
||||
icon: string;
|
||||
/**
|
||||
* Image
|
||||
*/
|
||||
image?: string | null;
|
||||
/**
|
||||
* Image Credit
|
||||
*/
|
||||
image_credit?: string | null;
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -792,6 +808,18 @@ export type PlaceData = {
|
||||
* Is Good
|
||||
*/
|
||||
is_good: boolean;
|
||||
/**
|
||||
* Distance Km
|
||||
*/
|
||||
distance_km: number;
|
||||
/**
|
||||
* Image
|
||||
*/
|
||||
image?: string | null;
|
||||
/**
|
||||
* Image Credit
|
||||
*/
|
||||
image_credit?: string | null;
|
||||
};
|
||||
|
||||
/**
|
||||
|
||||
+58
-11
@@ -1,4 +1,4 @@
|
||||
import { useEffect, useMemo, useState, type ReactNode } from 'react'
|
||||
import { useCallback, useEffect, useMemo, useState, type ReactNode } from 'react'
|
||||
import { NavLink, Outlet, useLocation } from 'react-router'
|
||||
import { cx } from '../lib/utils'
|
||||
import { kindOfHour, kst, type TimeKind } from './lib'
|
||||
@@ -30,7 +30,7 @@ function TopBar() {
|
||||
const tab = TABS.find((t) => t.to !== '/' && pathname.startsWith(t.to))
|
||||
|
||||
return (
|
||||
<header className="sticky top-0 z-20 flex h-[54px] items-center justify-between gap-2.5 px-4">
|
||||
<header className="sticky top-0 z-20 flex h-[calc(54px+env(safe-area-inset-top,0px))] items-center justify-between gap-2.5 px-4 pt-[env(safe-area-inset-top,0px)]">
|
||||
{tab?.title ? <h1 className="font-jua text-[22px] font-normal">{tab.title}</h1> : <h1 className="font-jua text-[25px] font-normal text-(--orange)">날씨각</h1>}
|
||||
<button
|
||||
type="button"
|
||||
@@ -103,8 +103,32 @@ function SkyBg() {
|
||||
)
|
||||
}
|
||||
|
||||
const PREVIEW_KEY = 'nalssigak.b.skyPreview'
|
||||
const KINDS: readonly string[] = ['morning', 'day', 'sunset', 'night'] satisfies TimeKind[]
|
||||
|
||||
function readPreview(): TimeKind | null {
|
||||
try {
|
||||
const v = sessionStorage.getItem(PREVIEW_KEY)
|
||||
return v && KINDS.includes(v) ? (v as TimeKind) : null
|
||||
} catch {
|
||||
// 저장소가 막힌 브라우저는 '지금'으로 시작한다
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
function SkyProvider({ children }: { children: ReactNode }) {
|
||||
const [preview, setPreview] = useState<TimeKind | null>(null)
|
||||
// 고른 시간대는 탭을 옮겨도 이 창에서 유지한다
|
||||
const [preview, setPreviewState] = useState<TimeKind | null>(readPreview)
|
||||
const setPreview = useCallback((k: TimeKind | null) => {
|
||||
setPreviewState(k)
|
||||
try {
|
||||
if (k) sessionStorage.setItem(PREVIEW_KEY, k)
|
||||
else sessionStorage.removeItem(PREVIEW_KEY)
|
||||
} catch {
|
||||
// 저장이 막혀도 이번 화면에서는 메모리 값으로 쓴다
|
||||
return
|
||||
}
|
||||
}, [])
|
||||
const [serverKind, setServerKind] = useState<TimeKind | null>(null)
|
||||
const [now, setNow] = useState(() => new Date())
|
||||
useEffect(() => {
|
||||
@@ -113,35 +137,58 @@ function SkyProvider({ children }: { children: ReactNode }) {
|
||||
}, [])
|
||||
const t = kst(now)
|
||||
const kind = preview ?? serverKind ?? kindOfHour(t.h, t.mo, t.mi)
|
||||
const api = useMemo(() => ({ kind, setPreview, setServerKind }), [kind])
|
||||
const api = useMemo(() => ({ kind, preview, setPreview, setServerKind }), [kind, preview, setPreview])
|
||||
return (
|
||||
<SkyContext value={api}>{children}</SkyContext>
|
||||
)
|
||||
}
|
||||
|
||||
// 노치 띠·상태바 색: 하늘 맨 위 색에 .b-topbg 를 겹친 색
|
||||
const NOTCH_BG: Record<TimeKind, string> = {
|
||||
morning: '#ffe6cf',
|
||||
day: '#d6ebff',
|
||||
sunset: '#ffd8c2',
|
||||
night: '#0e1433',
|
||||
}
|
||||
|
||||
function Shell() {
|
||||
const { pathname } = useLocation()
|
||||
const { kind } = useSky()
|
||||
useEffect(() => {
|
||||
window.scrollTo({ top: 0 })
|
||||
}, [pathname])
|
||||
useEffect(() => {
|
||||
document.querySelector('meta[name="theme-color"]')?.setAttribute('content', NOTCH_BG[kind])
|
||||
}, [kind])
|
||||
|
||||
return (
|
||||
<div className="min-h-dvh text-(--ink)">
|
||||
<SkyBg />
|
||||
{/* 위·아래 바: 띠는 화면 끝까지, 내용은 가운데 440px 안 */}
|
||||
<div className="b-topbg fixed inset-x-0 top-0 z-[19] h-[54px] backdrop-blur-md" aria-hidden="true" />
|
||||
<div className="b-topbg fixed inset-x-0 top-0 z-[19] h-[calc(54px+env(safe-area-inset-top,0px))] backdrop-blur-md" aria-hidden="true" />
|
||||
<div className="fixed inset-x-0 top-0 z-[19] h-[env(safe-area-inset-top,0px)] transition-colors duration-1400" style={{ backgroundColor: NOTCH_BG[kind] }} aria-hidden="true" />
|
||||
<div className="relative mx-auto min-h-dvh max-w-[440px] overflow-x-clip pb-[calc(70px+env(safe-area-inset-bottom,0px))]">
|
||||
<TopBar />
|
||||
<main className="relative z-[1]">
|
||||
<Outlet />
|
||||
</main>
|
||||
<nav aria-label="주요 메뉴" className="b-tabbar fixed inset-x-0 bottom-0 z-30 grid grid-cols-5 border-t px-[max(4px,calc((100%-432px)/2))] pt-[7px] pb-[calc(8px+env(safe-area-inset-bottom,0px))] backdrop-blur-[10px]">
|
||||
{TABS.map((t) => (
|
||||
<NavLink key={t.key} to={t.to} end={t.to === '/'} className={({ isActive }) => cx('flex flex-col items-center gap-0.5 text-[11px] font-extrabold', isActive ? 'text-(--ink) [&_svg]:stroke-[2.4]' : 'text-(--ink3) [&_svg]:stroke-[1.9]')}>
|
||||
<TabIcon name={t.key} className="size-[25px]" />
|
||||
{t.label}
|
||||
</NavLink>
|
||||
))}
|
||||
{TABS.map((t) =>
|
||||
t.key === 'today' ? (
|
||||
// 메인 탭: 막대 위로 솟은 큰 주황 동그라미
|
||||
<NavLink key={t.key} to={t.to} end className={({ isActive }) => cx('b-tab-main relative -mt-6 flex flex-col items-center gap-1 text-[12px] font-extrabold', isActive ? 'text-(--orange)' : 'text-(--ink3)')}>
|
||||
<span className="grid size-[60px] place-items-center rounded-full bg-[linear-gradient(160deg,#ffb067,var(--orange)_55%,var(--orange-deep))] text-white shadow-[0_8px_18px_rgb(255_122_69/0.45),inset_0_-4px_0_rgb(0_0_0/0.12)] ring-4 ring-white/85 [&_svg]:stroke-[2.6]">
|
||||
<TabIcon name={t.key} className="size-[30px]" />
|
||||
</span>
|
||||
{t.label}
|
||||
</NavLink>
|
||||
) : (
|
||||
<NavLink key={t.key} to={t.to} className={({ isActive }) => cx('flex flex-col items-center gap-0.5 text-[11px] font-extrabold', isActive ? 'text-(--ink) [&_svg]:stroke-[2.4]' : 'text-(--ink3) [&_svg]:stroke-[1.9]')}>
|
||||
<TabIcon name={t.key} className="size-[25px]" />
|
||||
{t.label}
|
||||
</NavLink>
|
||||
),
|
||||
)}
|
||||
</nav>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
+8
-10
@@ -11,8 +11,7 @@ import { useAuth } from './authContext'
|
||||
import { useSheet } from './sheetContext'
|
||||
import { CommentIcon, HeartIcon, SendIcon } from './svg'
|
||||
import { useCarousel } from './carousel'
|
||||
import { shareLink } from './shareLink'
|
||||
import { Arrows, Credit, Ic, Rows, ScreenNote, Skel, Thumb } from './ui'
|
||||
import { Arrows, Credit, Ic, Rows, Skel, TAP44, Thumb } from './ui'
|
||||
|
||||
const ACCOUNTS: Record<PostType, readonly [string, string]> = {
|
||||
[PostType.WEATHER]: ['오늘 날씨', 'sun'],
|
||||
@@ -311,11 +310,11 @@ function FullCard({ post }: PostProps) {
|
||||
const [pop, setPop] = useState(0)
|
||||
const [likeFailed, setLikeFailed] = useState(0)
|
||||
const lastTap = useRef(0)
|
||||
const trackRef = useRef<HTMLDivElement>(null)
|
||||
const [account, avatar] = ACCOUNTS[post.post_type]
|
||||
const n = post.slides.length
|
||||
const bgs = post.slides.map((sl) => slideBg(post, sl))
|
||||
const [note, setNote] = useState('')
|
||||
const share = () => void shareLink().then((m) => m && setNote(m))
|
||||
const share = () => open({ type: 'share', share: { title: post.title, slides: Array.from(trackRef.current?.children ?? []).filter((c) => c instanceof HTMLElement) } })
|
||||
const comments = () => open({ type: 'comments', postId: post.post_id })
|
||||
const patch = (values: Partial<PostData>) => patchFeed(queryClient, post.post_id, values)
|
||||
|
||||
@@ -373,7 +372,7 @@ function FullCard({ post }: PostProps) {
|
||||
</div>
|
||||
<div className="relative aspect-[4/5] overflow-hidden" onClick={onTap}>
|
||||
{n > 1 && (
|
||||
<span className="absolute top-3 right-3 z-[2] rounded-full bg-[rgb(30_36_56/0.55)] px-[9px] py-[3px] text-xs font-extrabold text-white" aria-hidden="true">
|
||||
<span data-noshot className="absolute top-3 right-3 z-[2] rounded-full bg-[rgb(30_36_56/0.55)] px-[9px] py-[3px] text-xs font-extrabold text-white" aria-hidden="true">
|
||||
{index + 1}/{n}
|
||||
</span>
|
||||
)}
|
||||
@@ -388,7 +387,7 @@ function FullCard({ post }: PostProps) {
|
||||
if (e.key === 'ArrowRight') slider?.scrollNext()
|
||||
}}
|
||||
>
|
||||
<div className="flex h-full">
|
||||
<div ref={trackRef} className="flex h-full">
|
||||
{post.slides.map((s, i) => (
|
||||
<SlideView key={i} slide={s} bg={bgs[i]} />
|
||||
))}
|
||||
@@ -416,7 +415,6 @@ function FullCard({ post }: PostProps) {
|
||||
</div>,
|
||||
document.body,
|
||||
)}
|
||||
<ScreenNote text={note} setText={setNote} />
|
||||
{likeFailed > 0 && createPortal(
|
||||
<p role="alert" className="pointer-events-none fixed inset-x-0 bottom-[calc(88px+env(safe-area-inset-bottom,0px))] z-50 m-0 flex justify-center px-4">
|
||||
<span className="rounded-full bg-[rgb(30_36_56/0.82)] px-3.5 py-2 text-[13px] font-bold text-white">{liked ? '좋아요를 취소하지 못했어요' : '좋아요를 반영하지 못했어요'}. 다시 해 주세요.</span>
|
||||
@@ -425,13 +423,13 @@ function FullCard({ post }: PostProps) {
|
||||
)}
|
||||
</div>
|
||||
<div className="flex items-center gap-3.5 px-3 pt-2.5 pb-1 [&_svg]:size-[26px] [&_svg]:stroke-[1.9]">
|
||||
<button type="button" onClick={() => setLike(!liked)} aria-pressed={liked} aria-label="좋아요" className="grid size-7 cursor-pointer place-items-center">
|
||||
<button type="button" onClick={() => setLike(!liked)} aria-pressed={liked} aria-label="좋아요" className={cx('relative grid size-7 cursor-pointer place-items-center', TAP44)}>
|
||||
<HeartIcon className={liked ? 'fill-(--heart) stroke-(--heart)' : 'fill-none stroke-(--ink)'} />
|
||||
</button>
|
||||
<button type="button" onClick={comments} aria-label="댓글 보기" className="grid size-7 cursor-pointer place-items-center">
|
||||
<button type="button" onClick={comments} aria-label="댓글 보기" className={cx('relative grid size-7 cursor-pointer place-items-center', TAP44)}>
|
||||
<CommentIcon className="fill-none stroke-(--ink) [stroke-linejoin:round]" />
|
||||
</button>
|
||||
<button type="button" onClick={share} aria-label="보내기" className="grid size-7 cursor-pointer place-items-center">
|
||||
<button type="button" onClick={share} aria-label="보내기" className={cx('relative grid size-7 cursor-pointer place-items-center', TAP44)}>
|
||||
<SendIcon className="fill-none stroke-(--ink) [stroke-linecap:round] [stroke-linejoin:round]" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
@@ -5,7 +5,7 @@ import { ArticleCategory } from '../api/client/types.gen'
|
||||
import { cx } from '../lib/utils'
|
||||
import { ARTICLE_CAT, cardBg, dateRange, fall, loadOf, shortDay } from './lib'
|
||||
import { useSheet } from './sheetContext'
|
||||
import { Chips, Ic, Skel, StateBox } from './ui'
|
||||
import { Chips, Ic, Skel, StateBox, Thumb } from './ui'
|
||||
|
||||
const CATS = [
|
||||
['all', '전체'],
|
||||
@@ -126,9 +126,7 @@ export function SeasonPage() {
|
||||
<b className="mt-0.5 block font-jua text-[17.5px] leading-snug font-normal">{a.title}</b>
|
||||
<small className="mt-1 block text-xs font-semibold text-(--ink3)">{a.read_minutes}분 읽기</small>
|
||||
</span>
|
||||
<span className={cx('grid h-[84px] place-items-center rounded-[18px]', `b-bg-${cardBg(a.icon, a.article_id)}`)}>
|
||||
<Ic name={a.icon} className="w-[54px]" />
|
||||
</span>
|
||||
<Thumb image={a.image} icon={a.icon} credit={a.image_credit} className={cx('h-[84px] rounded-[18px]', `b-bg-${cardBg(a.icon, a.article_id)}`)} iconClassName="w-[54px]" creditClassName="right-1 bottom-1 max-w-[calc(100%-8px)] whitespace-normal!" />
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
+172
-21
@@ -1,6 +1,7 @@
|
||||
import { useInfiniteQuery, useMutation, useQuery, useQueryClient, type InfiniteData } from '@tanstack/react-query'
|
||||
import { useCallback, useDeferredValue, useEffect, useMemo, useRef, useState, type FormEvent, type ReactNode } from 'react'
|
||||
import { setTokens, subscribeAuth } from '../api/auth'
|
||||
import { SITE_URL } from '../api/setup'
|
||||
import {
|
||||
addCommentMutation,
|
||||
deleteCommentMutation,
|
||||
@@ -19,23 +20,48 @@ import {
|
||||
updateMeMutation,
|
||||
} from '../api/client/@tanstack/react-query.gen'
|
||||
import type { CommentData, Factor, ResAuth, ResCommentList, ResIndexDetail } from '../api/client/types.gen'
|
||||
import { track } from '../lib/analytics'
|
||||
import { cx } from '../lib/utils'
|
||||
import { useAuth } from './authContext'
|
||||
import { ago, ARTICLE_CAT, articleMeta, AVATAR_COLORS, cardBg, CHARACTERS, dateRange, loadOf, MOODS, shortDay } from './lib'
|
||||
import { useRegion } from './regionContext'
|
||||
import { useSky } from './skyContext'
|
||||
import { SheetContext, useSheet, type SheetState } from './sheetContext'
|
||||
import { SHARE_SIZES, shareImage, type ShareSize } from './storyImage'
|
||||
import { SheetContext, useSheet, type SharePayload, type SheetState } from './sheetContext'
|
||||
import { HeartIcon } from './svg'
|
||||
import { Avatar, Ic, Skel, StateBox } from './ui'
|
||||
import { Avatar, Ic, Skel, StateBox, TAP44, Thumb } from './ui'
|
||||
|
||||
export function SheetProvider({ children }: { children: ReactNode }) {
|
||||
const [state, setState] = useState<SheetState>(null)
|
||||
const open = useCallback((s: Exclude<SheetState, null>) => setState(s), [])
|
||||
const close = useCallback(() => setState(null), [])
|
||||
// 창이 열려 있는 동안 방문 기록을 하나 쌓아 두어 뒤로 가기가 창만 닫게 한다
|
||||
const pushed = useRef(false)
|
||||
const open = useCallback((s: Exclude<SheetState, null>) => {
|
||||
if (!pushed.current) {
|
||||
window.history.pushState({ ...window.history.state, sheet: true }, '')
|
||||
pushed.current = true
|
||||
}
|
||||
setState(s)
|
||||
}, [])
|
||||
const close = useCallback(() => {
|
||||
setState(null)
|
||||
if (!pushed.current) return
|
||||
pushed.current = false
|
||||
window.history.back()
|
||||
}, [])
|
||||
const api = useMemo(() => ({ open, close }), [open, close])
|
||||
|
||||
useEffect(() => {
|
||||
const onPop = () => {
|
||||
if (!pushed.current) return
|
||||
pushed.current = false
|
||||
setState(null)
|
||||
}
|
||||
window.addEventListener('popstate', onPop)
|
||||
return () => window.removeEventListener('popstate', onPop)
|
||||
}, [])
|
||||
|
||||
// 로그인이 필요한 요청이 401을 받으면 로그인 창을 띄운다
|
||||
useEffect(() => subscribeAuth((reason) => reason === 'required' && setState({ type: 'login' })), [])
|
||||
useEffect(() => subscribeAuth((reason) => reason === 'required' && open({ type: 'login' })), [open])
|
||||
|
||||
return (
|
||||
<SheetContext value={api}>
|
||||
@@ -45,12 +71,13 @@ export function SheetProvider({ children }: { children: ReactNode }) {
|
||||
)
|
||||
}
|
||||
|
||||
const TITLES = { article: '읽을거리', seasonWeek: '이번 주 특집', comments: '댓글', login: '로그인', me: '내 정보', region: '지역 바꾸기' } as const
|
||||
const TITLES = { article: '읽을거리', seasonWeek: '이번 주 특집', share: '보내기', comments: '댓글', login: '로그인', me: '내 정보', region: '지역 바꾸기' } as const
|
||||
|
||||
/** 아래에서 올라오는 창: 네이티브 <dialog>라 ESC·포커스 가두기·포커스 되돌리기가 기본으로 된다 */
|
||||
function SheetHost({ state, onClose }: { state: SheetState; onClose: () => void }) {
|
||||
const ref = useRef<HTMLDialogElement>(null)
|
||||
const { kind } = useSky()
|
||||
const { open } = useSheet()
|
||||
const [gakTitle, setGakTitle] = useState('')
|
||||
const [articleTitle, setArticleTitle] = useState('')
|
||||
|
||||
@@ -73,6 +100,7 @@ function SheetHost({ state, onClose }: { state: SheetState; onClose: () => void
|
||||
}
|
||||
}, [isOpen])
|
||||
|
||||
const then = state?.type === 'login' ? state.then : undefined
|
||||
const title = !state ? '' : state.type === 'gak' ? gakTitle : state.type === 'article' ? articleTitle || TITLES.article : TITLES[state.type]
|
||||
|
||||
return (
|
||||
@@ -87,19 +115,20 @@ function SheetHost({ state, onClose }: { state: SheetState; onClose: () => void
|
||||
className="b-sheet-dialog b-app fixed inset-x-0 top-auto bottom-0 m-0 mx-auto max-h-[86dvh] w-full max-w-[440px] overflow-visible bg-transparent p-0 text-(--ink)"
|
||||
>
|
||||
{state && (
|
||||
<div className="b-sheet flex max-h-[86dvh] flex-col rounded-t-[22px] bg-white">
|
||||
<div className="b-sheet flex max-h-[86dvh] flex-col rounded-t-[22px] bg-white pb-[env(safe-area-inset-bottom,0px)]">
|
||||
<div className="relative border-b border-(--line) px-4 pt-2 pb-2.5 text-center">
|
||||
<div className="mx-auto mb-2.5 h-1 w-10 rounded-full bg-(--line)" aria-hidden="true" />
|
||||
<h3 className="m-0 text-[15px] font-extrabold">{title}</h3>
|
||||
<button type="button" onClick={onClose} aria-label="닫기" className="absolute right-3 bottom-2 grid size-[30px] cursor-pointer place-items-center text-xl text-(--ink2)">
|
||||
<button type="button" onClick={onClose} aria-label="닫기" className={cx('absolute right-3 bottom-2 grid size-[30px] cursor-pointer place-items-center text-xl text-(--ink2)', TAP44)}>
|
||||
×
|
||||
</button>
|
||||
</div>
|
||||
{state.type === 'gak' && <GakSheet indexId={state.indexId} onTitle={setGakTitle} />}
|
||||
{state.type === 'article' && <ArticleSheet articleId={state.articleId} onTitle={setArticleTitle} />}
|
||||
{state.type === 'seasonWeek' && <SeasonWeekSheet />}
|
||||
{state.type === 'comments' && <CommentsSheet postId={state.postId} />}
|
||||
{state.type === 'login' && <LoginSheet onDone={onClose} />}
|
||||
{state.type === 'share' && <ShareSheet share={state.share} />}
|
||||
{state.type === 'comments' && <CommentsSheet postId={state.postId} draft={state.draft} />}
|
||||
{state.type === 'login' && <LoginSheet onDone={onClose} onLoggedIn={then ? () => open(then) : onClose} />}
|
||||
{state.type === 'me' && <MeSheet onDone={onClose} />}
|
||||
{state.type === 'region' && <RegionSheet onDone={onClose} />}
|
||||
</div>
|
||||
@@ -298,6 +327,14 @@ function GakSheet({ indexId, onTitle }: { indexId: number; onTitle: (t: string)
|
||||
onTitle(g ? `${g.rank}위 ${g.name}` : '계산 근거')
|
||||
}, [g, onTitle])
|
||||
|
||||
// 지역이 바뀌어 다시 받아도 한 번만 보낸다
|
||||
const tracked = useRef(0)
|
||||
useEffect(() => {
|
||||
if (!g || tracked.current === g.index_id) return
|
||||
tracked.current = g.index_id
|
||||
track('view_gak', { index_id: g.index_id, gak_name: g.name, score: g.score, rank: g.rank })
|
||||
}, [g])
|
||||
|
||||
const load = loadOf(q)
|
||||
if (!g) return <Body>{load === 'loading' ? <GakSkel /> : <StateBox load={load} onRetry={() => q.refetch()} empty="이 각의 계산 근거가 아직 없어요." hold={<GakSkel />} className="inset-0" />}</Body>
|
||||
const factors = d.factors ?? []
|
||||
@@ -390,13 +427,18 @@ function ArticleSheet({ articleId, onTitle }: { articleId: number; onTitle: (t:
|
||||
onTitle(a ? (ARTICLE_CAT[a.category]?.[0] ?? '') : '')
|
||||
}, [a, onTitle])
|
||||
|
||||
const tracked = useRef(0)
|
||||
useEffect(() => {
|
||||
if (!a || tracked.current === a.article_id) return
|
||||
tracked.current = a.article_id
|
||||
track('select_content', { content_type: 'article', item_id: a.article_id, category: ARTICLE_CAT[a.category]?.[0] ?? a.category })
|
||||
}, [a])
|
||||
|
||||
const load = loadOf(q)
|
||||
if (!a) return <Body>{load === 'loading' ? <ArticleSkel /> : <StateBox load={load} onRetry={() => q.refetch()} empty="글을 찾지 못했어요." hold={<ArticleSkel />} className="inset-0" />}</Body>
|
||||
return (
|
||||
<Body>
|
||||
<div className={cx('mb-3.5 grid h-[150px] place-items-center rounded-[20px]', `b-bg-${cardBg(a.icon, a.article_id)}`)}>
|
||||
<Ic name={a.icon} className="w-24" />
|
||||
</div>
|
||||
<Thumb image={a.image} icon={a.icon} credit={a.image_credit} className={cx('mb-3.5 h-[150px] rounded-[20px]', `b-bg-${cardBg(a.icon, a.article_id)}`)} iconClassName="w-24" />
|
||||
<p className="text-[13px] font-extrabold text-(--ink2)">{articleMeta(a)}</p>
|
||||
<h4 className="mt-1.5 mb-2.5 font-jua text-2xl leading-tight font-normal">{a.title}</h4>
|
||||
{(q.data?.body ?? []).map((t) => (
|
||||
@@ -443,6 +485,106 @@ function SeasonWeekSheet() {
|
||||
)
|
||||
}
|
||||
|
||||
/* ---------- 보내기 ---------- */
|
||||
const SIZE_KEYS = Object.keys(SHARE_SIZES) as ShareSize[]
|
||||
|
||||
function ShareSheet({ share }: { share: SharePayload }) {
|
||||
const { region } = useRegion()
|
||||
const { kind } = useSky()
|
||||
const [size, setSize] = useState<ShareSize>('story')
|
||||
const [images, setImages] = useState<Partial<Record<ShareSize, { blob: Blob; src: string }>>>({})
|
||||
const [failed, setFailed] = useState<Partial<Record<ShareSize, boolean>>>({})
|
||||
const srcs = useRef<string[]>([])
|
||||
const [toast, setToast] = useState('')
|
||||
const image = images[size]
|
||||
const text = `${share.title} · 날씨각 ${SITE_URL}`
|
||||
|
||||
// 고른 크기의 이미지를 미리 만들어 둔다. 누를 때 만들면 아이폰이 공유창을 막는다
|
||||
useEffect(() => {
|
||||
if (images[size] || failed[size]) return
|
||||
let alive = true
|
||||
const today = new Date().toLocaleDateString('ko-KR', { month: 'long', day: 'numeric', weekday: 'long' })
|
||||
shareImage(share.slides, { size, sky: kind, sub: `${region.name} · ${today}`, host: new URL(SITE_URL).host }).then(
|
||||
(blob) => {
|
||||
if (!alive) return
|
||||
const src = URL.createObjectURL(blob)
|
||||
srcs.current.push(src)
|
||||
setImages((m) => ({ ...m, [size]: { blob, src } }))
|
||||
},
|
||||
(e: unknown) => {
|
||||
console.error('[share] image', e)
|
||||
if (alive) setFailed((m) => ({ ...m, [size]: true }))
|
||||
},
|
||||
)
|
||||
return () => {
|
||||
alive = false
|
||||
}
|
||||
}, [size, images, failed, share.slides, kind, region.name])
|
||||
|
||||
useEffect(() => {
|
||||
const list = srcs.current
|
||||
return () => list.forEach((s) => URL.revokeObjectURL(s))
|
||||
}, [])
|
||||
|
||||
// 휴대폰은 공유창에 이미지와 링크를 같이 넘기고, 공유창이 없으면 이미지를 내려받고 링크를 복사한다
|
||||
const send = () => {
|
||||
if (!image) return
|
||||
const file = new File([image.blob], `nalssigak-${SHARE_SIZES[size].ratio.replace(':', 'x')}.png`, { type: 'image/png' })
|
||||
if (navigator.canShare?.({ files: [file], text })) {
|
||||
navigator.share({ files: [file], title: share.title, text }).then(
|
||||
() => {
|
||||
setToast('보냈어요')
|
||||
track('share', { content_type: 'image', item_id: share.title, method: 'share_sheet', ratio: SHARE_SIZES[size].ratio })
|
||||
},
|
||||
(e: unknown) => {
|
||||
if (e instanceof DOMException && e.name === 'AbortError') return
|
||||
console.error('[share] send', e)
|
||||
setToast('보내지 못했어요. 한 번 더 눌러 주세요')
|
||||
},
|
||||
)
|
||||
return
|
||||
}
|
||||
const a = document.createElement('a')
|
||||
a.href = image.src
|
||||
a.download = file.name
|
||||
a.click()
|
||||
track('share', { content_type: 'image', item_id: share.title, method: 'download', ratio: SHARE_SIZES[size].ratio })
|
||||
if (!navigator.clipboard) {
|
||||
setToast('이미지를 내려받았어요')
|
||||
return
|
||||
}
|
||||
navigator.clipboard.writeText(text).then(
|
||||
() => setToast('이미지를 내려받고 링크를 복사했어요'),
|
||||
() => setToast('이미지를 내려받았어요. 링크 복사는 막혀 있어요'),
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<Body>
|
||||
<div className="grid grid-cols-3 gap-1.5 rounded-[16px] bg-[#f3f6fb] p-1" role="radiogroup" aria-label="이미지 크기">
|
||||
{SIZE_KEYS.map((k) => (
|
||||
<button key={k} type="button" role="radio" aria-checked={size === k} aria-label={`${SHARE_SIZES[k].ratio} 비율`} onClick={() => setSize(k)} className={cx('flex cursor-pointer items-center justify-center gap-2 rounded-[12px] py-2 text-sm font-extrabold', size === k ? 'bg-white text-(--ink) shadow-[0_2px_6px_rgb(40_48_74/0.12)]' : 'text-(--ink3)')}>
|
||||
<i className="h-4 rounded-[3px] border-2 border-current" style={{ aspectRatio: `${SHARE_SIZES[k].w} / ${SHARE_SIZES[k].hr}` }} aria-hidden="true" />
|
||||
{SHARE_SIZES[k].ratio}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<div className="mt-3 flex h-[300px] items-center justify-center rounded-[18px] bg-[#f3f6fb] p-3">
|
||||
{image ? (
|
||||
<img src={image.src} alt={`${SHARE_SIZES[size].ratio} 공유 이미지 미리보기`} className="max-h-full max-w-full rounded-[10px] shadow-[0_4px_12px_rgb(40_48_74/0.18)]" />
|
||||
) : (
|
||||
<span className="text-sm font-bold text-(--ink3)">{failed[size] ? '이미지를 만들지 못했어요' : '이미지 만드는 중'}</span>
|
||||
)}
|
||||
</div>
|
||||
<button type="button" onClick={send} disabled={!image} className="mt-3.5 block w-full cursor-pointer rounded-[16px] bg-(--orange) py-3 font-jua text-base text-white shadow-[inset_0_-4px_0_var(--orange-deep)] disabled:opacity-50">
|
||||
공유하기
|
||||
</button>
|
||||
<p className="mt-3 min-h-5 text-center text-[13px] font-bold text-[#1f9d62]" aria-live="polite">
|
||||
{toast}
|
||||
</p>
|
||||
</Body>
|
||||
)
|
||||
}
|
||||
|
||||
/* ---------- 댓글 ---------- */
|
||||
const NOT_FOUND = 3001 // 서버 ErrorType.NOT_FOUND
|
||||
@@ -535,14 +677,14 @@ function CommentRow({ c, postId }: { c: CommentData; postId: number }) {
|
||||
)}
|
||||
</small>
|
||||
</div>
|
||||
<button type="button" onClick={toggle} aria-pressed={liked} aria-label="댓글 좋아요" className="cursor-pointer pt-1">
|
||||
<button type="button" onClick={toggle} aria-pressed={liked} aria-label="댓글 좋아요" className={cx('relative cursor-pointer pt-1', TAP44)}>
|
||||
<HeartIcon className={cx('size-4 stroke-2', liked ? 'fill-(--heart) stroke-(--heart)' : 'fill-none stroke-(--ink3)')} />
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function CommentsSheet({ postId }: { postId: number }) {
|
||||
function CommentsSheet({ postId, draft }: { postId: number; draft?: string }) {
|
||||
const { region } = useRegion()
|
||||
const { open } = useSheet()
|
||||
const { loggedIn, me } = useAuth()
|
||||
@@ -554,13 +696,13 @@ function CommentsSheet({ postId }: { postId: number }) {
|
||||
})
|
||||
const add = useMutation(addCommentMutation())
|
||||
const [addFailed, setAddFailed] = useState(false)
|
||||
const [text, setText] = useState('')
|
||||
const [text, setText] = useState(draft ?? '')
|
||||
const inputRef = useRef<HTMLInputElement>(null)
|
||||
const comments = list.data?.pages.flatMap((p) => p.comments ?? []) ?? []
|
||||
|
||||
const submit = (e: FormEvent) => {
|
||||
e.preventDefault()
|
||||
if (!loggedIn) return open({ type: 'login' })
|
||||
if (!loggedIn) return open({ type: 'login', then: { type: 'comments', postId, draft: text } })
|
||||
const body = text.trim()
|
||||
if (!body || add.isPending) return
|
||||
setAddFailed(false)
|
||||
@@ -617,7 +759,7 @@ function CommentsSheet({ postId }: { postId: number }) {
|
||||
<p className="h-4 px-4 text-center text-xs leading-4 font-bold text-(--heart)" role="alert">
|
||||
{addFailed && '댓글을 올리지 못했어요. 다시 해 주세요.'}
|
||||
</p>
|
||||
<form onSubmit={submit} className="flex items-center gap-2.5 border-t border-(--line) px-3 pt-2.5 pb-[calc(10px+env(safe-area-inset-bottom,0px))]">
|
||||
<form onSubmit={submit} className="flex items-center gap-2.5 border-t border-(--line) px-3 pt-2.5 pb-2.5">
|
||||
<input ref={inputRef} value={text} onChange={(e) => setText(e.target.value)} readOnly={add.isPending} maxLength={60} placeholder={me ? `${me.nickname}(으)로 댓글 달기…` : '댓글 달기…'} aria-label="댓글" className="min-w-0 flex-1 rounded-full border border-[#dfe5ee] bg-[#f7f9fc] px-3.5 py-2.5" />
|
||||
<button type="submit" disabled={add.isPending || (loggedIn && !text.trim())} className="cursor-pointer font-extrabold text-(--rain) disabled:opacity-40">
|
||||
<Swap labels={['게시', '올리는 중…']} at={add.isPending ? 1 : 0} />
|
||||
@@ -634,7 +776,7 @@ const AUTH_ERRORS: Record<string, string> = {
|
||||
INVALID_INPUT: '아이디는 영어 소문자·숫자·_ 4~20자, 비밀번호는 8~64자, 닉네임은 2~12자로 써 주세요.',
|
||||
}
|
||||
|
||||
function LoginSheet({ onDone }: { onDone: () => void }) {
|
||||
function LoginSheet({ onDone, onLoggedIn }: { onDone: () => void; onLoggedIn: () => void }) {
|
||||
const { me } = useAuth()
|
||||
const [mode, setMode] = useState<'login' | 'signup'>('login')
|
||||
const [loginId, setLoginId] = useState('')
|
||||
@@ -651,7 +793,8 @@ function LoginSheet({ onDone }: { onDone: () => void }) {
|
||||
return
|
||||
}
|
||||
setTokens(res.access_token, res.refresh_token ?? null)
|
||||
onDone()
|
||||
track(mode === 'login' ? 'login' : 'sign_up', { method: 'id' })
|
||||
onLoggedIn()
|
||||
}
|
||||
const fail = () => setError('서버에 닿지 못했어요. 잠시 뒤에 다시 해 주세요.')
|
||||
|
||||
@@ -828,6 +971,13 @@ function RegionSheet({ onDone }: { onDone: () => void }) {
|
||||
const { region, setRegion, locate, locateStatus } = useRegion()
|
||||
const { me, logout } = useAuth()
|
||||
const { open } = useSheet()
|
||||
const alive = useRef(true)
|
||||
useEffect(() => {
|
||||
alive.current = true
|
||||
return () => {
|
||||
alive.current = false
|
||||
}
|
||||
}, [])
|
||||
const [q, setQ] = useState('')
|
||||
const deferred = useDeferredValue(q.trim())
|
||||
const list = useQuery(listRegionsOptions(deferred ? { query: { q: deferred } } : undefined))
|
||||
@@ -836,7 +986,7 @@ function RegionSheet({ onDone }: { onDone: () => void }) {
|
||||
|
||||
return (
|
||||
<Body>
|
||||
<button type="button" onClick={locate} disabled={locateStatus === 'locating'} className="w-full cursor-pointer rounded-full bg-(--orange) p-3 font-jua text-[17px] text-white shadow-[inset_0_-5px_0_var(--orange-deep)] disabled:opacity-60">
|
||||
<button type="button" onClick={() => locate(() => alive.current && onDone())} disabled={locateStatus === 'locating'} className="w-full cursor-pointer rounded-full bg-(--orange) p-3 font-jua text-[17px] text-white shadow-[inset_0_-5px_0_var(--orange-deep)] disabled:opacity-60">
|
||||
지금 위치로 찾기
|
||||
</button>
|
||||
<p className="mt-2 min-h-5 text-center text-[13px] font-bold text-(--ink2)" aria-live="polite">
|
||||
@@ -853,6 +1003,7 @@ function RegionSheet({ onDone }: { onDone: () => void }) {
|
||||
aria-current={r.code === region.code ? 'true' : undefined}
|
||||
onClick={() => {
|
||||
setRegion(r)
|
||||
track('region_change', { region_name: r.name, method: 'list' })
|
||||
onDone()
|
||||
}}
|
||||
className={cx('flex w-full cursor-pointer items-center justify-between border-b-[1.5px] border-(--line) px-1 py-3 text-left font-jua text-[17px]', r.code === region.code && 'text-(--orange)')}
|
||||
|
||||
@@ -73,6 +73,22 @@ function Timeline({ rows }: { rows?: BestTime[] }) {
|
||||
</li>
|
||||
))}
|
||||
</ol>
|
||||
{rows && (
|
||||
<dl className="mx-2 mt-3 flex flex-col gap-1 border-t-[1.5px] border-(--line) pt-2.5 text-[12px] leading-snug text-(--ink2)">
|
||||
{rows.some((t) => t.kind === 'golden') && (
|
||||
<div>
|
||||
<dt className="inline font-extrabold text-(--ink)">골든아워</dt>
|
||||
<dd className="ml-1.5 inline">해가 낮게 떠 햇빛이 금빛으로 물드는 시간, 해 지기 전 약 30분~1시간</dd>
|
||||
</div>
|
||||
)}
|
||||
{rows.some((t) => t.kind === 'blue') && (
|
||||
<div>
|
||||
<dt className="inline font-extrabold text-(--ink)">블루아워</dt>
|
||||
<dd className="ml-1.5 inline">해가 진 뒤 하늘이 짙은 푸른빛으로 남는 시간, 적힌 시각쯤 어두워져요</dd>
|
||||
</div>
|
||||
)}
|
||||
</dl>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -30,6 +30,9 @@ const PREVIEW: Record<TimeKind, { label: string; clock: string; hour: number }>
|
||||
night: { label: '밤', clock: '22:10', hour: 22 },
|
||||
}
|
||||
|
||||
// 히어로 칸을 받아 오는 동안 자리만 잡아 둔다
|
||||
const STAT_HOLD = ['a', 'b']
|
||||
|
||||
const STARS = Array.from({ length: 26 }, (_, i) => ({ left: `${(i * 37) % 100}%`, top: `${(i * 53) % 60}%`, opacity: 0.4 + ((i * 7) % 6) / 10 }))
|
||||
// 별똥별 셋: 위치·길이·주기를 엇갈려 하나씩 떨어지게
|
||||
const SHOOTS = [
|
||||
@@ -71,15 +74,14 @@ type HeroProps = { hero?: HeroData | null; today?: ResWeatherToday; feedLoad: Lo
|
||||
|
||||
function Hero({ hero, today, feedLoad, todayLoad }: HeroProps) {
|
||||
const { open } = useSheet()
|
||||
const [mode, setMode] = useState<Mode>('now')
|
||||
const { preview, setServerKind, setPreview } = useSky()
|
||||
const mode: Mode = preview ?? 'now'
|
||||
const setMode = (m: Mode) => setPreview(m === 'now' ? null : m)
|
||||
const clock = useNow()
|
||||
const t = kst(clock)
|
||||
const kind = mode === 'now' ? (hero?.sky_mode ?? kindOfHour(t.h, t.mo, t.mi)) : mode
|
||||
const { setServerKind, setPreview } = useSky()
|
||||
// 화면 전체 하늘 배경도 같은 시간대로 맞춘다
|
||||
useEffect(() => setServerKind(hero?.sky_mode ?? null), [hero?.sky_mode, setServerKind])
|
||||
useEffect(() => setPreview(mode === 'now' ? null : mode), [mode, setPreview])
|
||||
useEffect(() => () => setPreview(null), [setPreview])
|
||||
const slots = today?.slots ?? []
|
||||
const slot = slots.length ? slotAt(slots, mode === 'now' ? t.h : PREVIEW[mode].hour) : undefined
|
||||
// 지금은 /v1/feed hero 값을, 미리보기는 그 시각의 예보 칸을 쓴다
|
||||
@@ -94,7 +96,7 @@ function Hero({ hero, today, feedLoad, todayLoad }: HeroProps) {
|
||||
|
||||
// 시안 A: 점수 해가 주인공. 위에 시간대 탭과 날짜, 가운데 큰 해, 아래 칩 한 줄과 캐릭터 말풍선(1위 각)
|
||||
return (
|
||||
<div className="b-hero relative mx-3 mt-1 overflow-hidden rounded-[32px] px-[18px] pt-4 pb-4" data-t={kind}>
|
||||
<div className="b-hero relative mx-3 mt-1 overflow-hidden rounded-[28px] px-4 pt-3 pb-3" data-t={kind}>
|
||||
<div className="b-stars pointer-events-none absolute inset-0" aria-hidden="true">
|
||||
{STARS.map((s, i) => (
|
||||
<i key={i} className="absolute size-[3px] rounded-full shadow-[0_0_6px_#fff]" style={s} />
|
||||
@@ -105,17 +107,17 @@ function Hero({ hero, today, feedLoad, todayLoad }: HeroProps) {
|
||||
</div>
|
||||
<div className="relative z-[3] grid grid-cols-5 rounded-full bg-white/45 p-1" role="tablist" aria-label="시간대 배경 미리보기">
|
||||
{MODES.map(([m, l]) => (
|
||||
<button key={m} type="button" role="tab" aria-selected={mode === m} onClick={() => setMode(m)} className={cx('cursor-pointer rounded-full py-[6px] text-[13px] font-bold', mode === m ? 'bg-white text-(--ink) shadow-[0_2px_6px_rgb(40_48_74/0.12)]' : 'text-(--ink) opacity-70')}>
|
||||
<button key={m} type="button" role="tab" aria-selected={mode === m} onClick={() => setMode(m)} className={cx('cursor-pointer rounded-full py-[5px] text-[13px] font-bold', mode === m ? 'bg-white text-(--ink) shadow-[0_2px_6px_rgb(40_48_74/0.12)]' : 'text-(--ink) opacity-70')}>
|
||||
{l}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<p className="relative z-[3] mt-3 mb-0 text-[15px] font-bold opacity-90">
|
||||
{t.mo}월 {t.d}일 {WEEKDAYS[t.wd]} · <b className="font-bagel text-[22px] font-normal">{mode === 'now' ? `${String(t.h).padStart(2, '0')}:${String(t.mi).padStart(2, '0')}` : PREVIEW[mode].clock}</b>
|
||||
<p className="relative z-[3] mt-2 mb-0 text-[14px] font-bold opacity-90">
|
||||
{t.mo}월 {t.d}일 {WEEKDAYS[t.wd]} · <b className="font-bagel text-[19px] font-normal">{mode === 'now' ? `${String(t.h).padStart(2, '0')}:${String(t.mi).padStart(2, '0')}` : PREVIEW[mode].clock}</b>
|
||||
</p>
|
||||
<div className="relative h-[262px]">
|
||||
<span className="b-cloud b-fall top-6 left-[2%] h-9 w-[100px]" style={fall('.1s', '6s')} aria-hidden="true" />
|
||||
<div className="b-sun b-fall absolute top-4 left-1/2 -ml-[115px] grid aspect-square w-[230px] place-items-center rounded-full text-center" style={fall('0s', '5.6s', '8px')}>
|
||||
<div className="relative h-[196px]">
|
||||
<span className="b-cloud b-fall top-3 left-[4%] h-8 w-[84px]" style={fall('.1s', '6s')} aria-hidden="true" />
|
||||
<div className="b-sun b-fall absolute top-2 left-1/2 -ml-[90px] grid aspect-square w-[180px] place-items-center rounded-full text-center" style={fall('0s', '5.6s', '8px')}>
|
||||
{/* 안 보이는 쪽을 덮어 오늘 밤 달 모양으로 */}
|
||||
{moon && (
|
||||
<svg viewBox="-1 -1 2 2" className="pointer-events-none absolute inset-0 size-full" aria-hidden="true">
|
||||
@@ -123,44 +125,45 @@ function Hero({ hero, today, feedLoad, todayLoad }: HeroProps) {
|
||||
</svg>
|
||||
)}
|
||||
<span className={cx('relative', moon && '[text-shadow:0_0_6px_#fff,0_0_12px_#fff]')}>
|
||||
<small className="block font-jua text-[15px]">{failed(feedLoad) ? '점수를 못 불러왔어요' : '오늘 날씨 점수'}</small>
|
||||
<b className="block font-bagel text-[96px] leading-[0.95] font-normal">{heroVal(feedLoad, hero?.weather_score, 'w-[120px]')}</b>
|
||||
<small className="block font-jua text-[13px]">{failed(feedLoad) ? '점수를 못 불러왔어요' : '오늘 날씨 점수'}</small>
|
||||
<b className="block font-bagel text-[74px] leading-[0.95] font-normal">{heroVal(feedLoad, hero?.weather_score, 'w-[120px]')}</b>
|
||||
</span>
|
||||
</div>
|
||||
<span className="b-cloud b-fall top-[188px] left-[58%] h-11 w-[118px]" style={fall('.25s', '6.4s')} aria-hidden="true" />
|
||||
<span className="b-cloud b-fall top-[140px] left-[58%] h-9 w-[96px]" style={fall('.25s', '6.4s')} aria-hidden="true" />
|
||||
</div>
|
||||
{/* 기온 + 서버가 고른 챙길 것(비·미세먼지·자외선·일교차 등)을 한 줄 칩으로 */}
|
||||
<div className="relative z-[3] mt-2 flex flex-wrap justify-center gap-2">
|
||||
<Chip>{heroVal(tempLoad, tempChip, 'w-16')}</Chip>
|
||||
{/* 기온 + 서버가 고른 챙길 것(비·미세먼지·자외선·일교차 등)을 한 줄 세 칸으로. 휴대폰에서 두 줄로 넘치지 않게 칸 안에서 위아래로 */}
|
||||
<div className="relative z-[3] mt-1 grid auto-cols-fr grid-flow-col gap-1.5">
|
||||
<Stat label={mode === 'now' ? '지금' : PREVIEW[mode].label}>{heroVal(tempLoad, tempChip, 'w-12')}</Stat>
|
||||
{hero?.stats?.length
|
||||
? hero.stats.map((s) => (
|
||||
<Chip key={s.label} tone={s.tone}>
|
||||
{s.label} {s.value}
|
||||
</Chip>
|
||||
<Stat key={s.label} label={s.label} tone={s.tone}>
|
||||
{s.value}
|
||||
</Stat>
|
||||
))
|
||||
: feedLoad === 'loading' && <Chip>{heroVal(feedLoad, null, 'w-20')}</Chip>}
|
||||
: feedLoad === 'loading' && STAT_HOLD.map((k) => <Stat key={k} label="">{heroVal(feedLoad, null, 'w-12')}</Stat>)}
|
||||
</div>
|
||||
<div className="relative z-[3] mt-3 flex items-center gap-2">
|
||||
<Ic name={who} alt={who === 'rabbit' ? '토끼' : '곰'} className="w-[52px] shrink-0 drop-shadow-[0_8px_10px_rgb(40_48_74/0.15)]" />
|
||||
<div className="relative z-[3] mt-2 flex items-center gap-2">
|
||||
<Ic name={who} alt={who === 'rabbit' ? '토끼' : '곰'} className="w-[44px] shrink-0 drop-shadow-[0_8px_10px_rgb(40_48_74/0.15)]" />
|
||||
{top1 ? (
|
||||
<button type="button" onClick={() => open({ type: 'gak', indexId: top1.index_id })} aria-label={`${bubble ?? ''} 1위 ${top1.name} ${top1.score}점, 계산 근거 보기`} className="b-bubble flex min-w-0 flex-1 cursor-pointer items-center gap-2 rounded-[20px] px-3.5 py-2.5 text-left">
|
||||
<span className="min-w-0 flex-1 truncate font-jua text-[17px]">{bubble}</span>
|
||||
<Ic name={top1.icon} className="w-8 shrink-0" />
|
||||
<button type="button" onClick={() => open({ type: 'gak', indexId: top1.index_id })} aria-label={`${bubble ?? ''} 1위 ${top1.name} ${top1.score}점, 계산 근거 보기`} className="b-bubble flex min-w-0 flex-1 cursor-pointer items-center gap-2 rounded-[18px] px-3 py-2 text-left">
|
||||
<span className="min-w-0 flex-1 truncate font-jua text-[16px]">{bubble}</span>
|
||||
<Ic name={top1.icon} className="w-7 shrink-0" />
|
||||
<em className="font-bagel text-[17px] text-(--orange) not-italic">{top1.score}</em>
|
||||
</button>
|
||||
) : (
|
||||
<span className="b-bubble min-w-0 flex-1 rounded-[20px] px-3.5 py-2.5 font-jua text-[17px]">{bubble ?? <Skel className="w-[120px]" />}</span>
|
||||
<span className="b-bubble min-w-0 flex-1 rounded-[18px] px-3 py-2 font-jua text-[16px]">{bubble ?? <Skel className="w-[120px]" />}</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/** 히어로 아래 한 줄 칩. tone 은 서버가 정한 상태(비·경고)로 색을 바꾼다 */
|
||||
function Chip({ tone = 'normal', children }: { tone?: HeroStatData['tone']; children: ReactNode }) {
|
||||
/** 히어로 아래 한 칸: 작은 이름 위, 값 아래. tone 은 서버가 정한 상태(비·경고)로 색을 바꾼다 */
|
||||
function Stat({ label, tone = 'normal', children }: { label: string; tone?: HeroStatData['tone']; children: ReactNode }) {
|
||||
return (
|
||||
<span className="b-stat rounded-full px-4 py-2 font-jua text-[16px] break-keep" data-tone={tone}>
|
||||
{children}
|
||||
<span className="b-stat flex min-w-0 flex-col items-center rounded-2xl px-1.5 pt-1.5 pb-2 text-center break-keep" data-tone={tone}>
|
||||
<small className="text-[11.5px] font-bold opacity-75">{label}</small>
|
||||
<b className="font-jua text-[14.5px] leading-tight font-normal">{children}</b>
|
||||
</span>
|
||||
)
|
||||
}
|
||||
@@ -281,9 +284,7 @@ function SeasonBand({ news }: { news: BandArticle[] }) {
|
||||
<Rail>
|
||||
{news.map((a) => (
|
||||
<button key={a.article_id} type="button" onClick={() => open({ type: 'article', articleId: a.article_id })} className="w-[200px] cursor-pointer overflow-hidden rounded-[22px] bg-white text-left shadow-[inset_0_-5px_0_var(--shade),0_8px_16px_rgb(40_48_74/0.06)]">
|
||||
<span className={cx('grid h-[116px] place-items-center', `b-bg-${cardBg(a.icon, a.article_id)}`)}>
|
||||
<Ic name={a.icon} className="w-[76px]" />
|
||||
</span>
|
||||
<Thumb image={a.image} icon={a.icon} credit={a.image_credit} className={cx('h-[116px]', `b-bg-${cardBg(a.icon, a.article_id)}`)} iconClassName="w-[76px]" />
|
||||
<span className="block px-3 pt-2.5 pb-3">
|
||||
<b className="block font-jua text-[16.5px] leading-snug font-normal">{a.title}</b>
|
||||
<small className="text-[12.5px] font-semibold text-(--ink2)">{a.meta}</small>
|
||||
|
||||
+18
-17
@@ -1,11 +1,11 @@
|
||||
import { useState, type ReactNode } from 'react'
|
||||
import { useRef, useState, type ReactNode } from 'react'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { getWeekOptions, getWeekRankingOptions, listEventsOptions, listPlacesOptions } from '../api/client/@tanstack/react-query.gen'
|
||||
import { cx } from '../lib/utils'
|
||||
import { cardBg, dateRange, loadOf, shortDay, sidoOf } from './lib'
|
||||
import { cardBg, dateRange, loadOf, shortDay } from './lib'
|
||||
import { useRegion } from './regionContext'
|
||||
import { shareLink } from './shareLink'
|
||||
import { Arrows, Chips, Ic, MapLink, Rail, ScreenNote, Sec, Skel, SkelRail, StateBox, Thumb } from './ui'
|
||||
import { useSheet } from './sheetContext'
|
||||
import { Arrows, Chips, Ic, MapLink, Rail, Sec, Skel, SkelRail, StateBox, Thumb } from './ui'
|
||||
import { useCarousel } from './carousel'
|
||||
|
||||
const TEN = Array.from({ length: 10 }, (_, i) => i)
|
||||
@@ -138,6 +138,7 @@ const PLACE_BG: Record<string, string> = { picnic: 'mint', walk: 'mint', sunset:
|
||||
|
||||
export function WeekPage() {
|
||||
const { region } = useRegion()
|
||||
const { open } = useSheet()
|
||||
const week = useQuery(getWeekOptions({ query: { region: region.code } }))
|
||||
const days = week.data?.days ?? []
|
||||
const [picked, setPicked] = useState<string | null>(null)
|
||||
@@ -154,7 +155,6 @@ export function WeekPage() {
|
||||
const rankDay = rankDays.find((d) => d.day === rankPick) ?? rankDays[0]
|
||||
const rankItems = (rankDay?.items ?? []).slice(0, 10)
|
||||
const rankLoad = loadOf(ranking)
|
||||
const sido = sidoOf(region.name)
|
||||
const areas = places.data?.areas ?? []
|
||||
const rainy = places.data?.rainy ?? sel?.is_rainy
|
||||
const placeList = places.data?.places ?? []
|
||||
@@ -164,12 +164,14 @@ export function WeekPage() {
|
||||
// 날씨(고른 날)가 와야 명소를 부를 수 있다
|
||||
const placeLoad = sel ? loadOf(places) : weekLoad === 'loading' ? 'loading' : 'ready'
|
||||
|
||||
const [note, setNote] = useState('')
|
||||
const sendPlan = () => void shareLink().then((m) => m && setNote(m))
|
||||
const pickRef = useRef<HTMLDivElement>(null)
|
||||
const sendPlan = () => {
|
||||
if (!sel || !pickRef.current) return
|
||||
open({ type: 'share', share: { title: `${sel.weekday}요일 일정`, slides: [pickRef.current] } })
|
||||
}
|
||||
|
||||
return (
|
||||
<section aria-label="주말·행사" aria-busy={weekLoad === 'loading'}>
|
||||
<ScreenNote text={note} setText={setNote} />
|
||||
<Sec title="열흘 날씨" sub="날짜를 누르면 그날 추천이 바뀌어요" />
|
||||
{days.length ? (
|
||||
<DayStrip dim={week.isPlaceholderData}>
|
||||
@@ -212,7 +214,7 @@ export function WeekPage() {
|
||||
/>
|
||||
)}
|
||||
{sel && (
|
||||
<div className="mx-3 mt-3 flex items-center gap-3.5 rounded-3xl bg-[linear-gradient(180deg,#e9fbf2,#fff)] p-4 shadow-[inset_0_-5px_0_var(--shade)]" aria-live="polite">
|
||||
<div ref={pickRef} className="mx-3 mt-3 flex items-center gap-3.5 rounded-3xl bg-[linear-gradient(180deg,#e9fbf2,#fff)] p-4 shadow-[inset_0_-5px_0_var(--shade)]" aria-live="polite">
|
||||
<Ic name={sel.icon} className="w-16" />
|
||||
<div>
|
||||
<b className="block font-jua text-[19px] font-normal">{sel.headline}</b>
|
||||
@@ -224,7 +226,7 @@ export function WeekPage() {
|
||||
{(sel || weekLoad !== 'ready') && (
|
||||
<div className="mx-3 mt-3.5 flex items-center justify-between">
|
||||
<label htmlFor="b-area" className="text-[13.5px] font-bold text-(--ink2)">
|
||||
{sido} · 데이트 명소
|
||||
30km 안 · 데이트 명소
|
||||
</label>
|
||||
<select id="b-area" value={area} onChange={(e) => setAreaPick({ region: region.code, area: e.target.value })} disabled={!areas.length} className="rounded-full bg-white px-3 py-[7px] font-bold text-(--ink) shadow-[inset_0_-3px_0_var(--shade)] disabled:opacity-60">
|
||||
{['전체', ...areas].map((a) => (
|
||||
@@ -233,7 +235,7 @@ export function WeekPage() {
|
||||
</select>
|
||||
</div>
|
||||
)}
|
||||
{/* 명소 데이터가 없는 지역은 칸 전체를 숨긴다 (지금은 서울만 있음) */}
|
||||
{/* 명소 데이터가 없으면 칸 전체를 숨긴다 */}
|
||||
{!(placeLoad === 'ready' && !placeList.length) && (
|
||||
<>
|
||||
<Sec title="날씨 맞춤 데이트 명소" sub={sel ? `${sel.weekday}요일은 ${rainy ? '비가 와서 실내 명소를 먼저' : sel.icon === 'sun' ? '맑아서 야외 명소를 먼저' : '비 소식이 없어 야외 명소를 먼저'} 보여 줘요` : weekLoad === 'loading' ? <Skel className="w-56" /> : '날씨에 맞춰 골라 보여 줘요'} className="pt-3" />
|
||||
@@ -241,13 +243,12 @@ export function WeekPage() {
|
||||
<Rail className={cx('transition-opacity', places.isPlaceholderData && 'opacity-60')}>
|
||||
{placeList.map((p, i) => (
|
||||
<div key={p.place_id} className={PLACE_CARD}>
|
||||
<span className={cx('relative grid h-[104px] place-items-center', `b-bg-${PLACE_BG[p.icon] ?? (p.is_outdoor ? 'mint' : cardBg(p.icon, i))}`)}>
|
||||
<Thumb image={p.image} icon={p.icon} credit={p.image_credit} className={cx('h-[104px]', `b-bg-${PLACE_BG[p.icon] ?? (p.is_outdoor ? 'mint' : cardBg(p.icon, i))}`)} iconClassName="w-[62px]">
|
||||
{p.is_good && <span className={cx('absolute top-2.5 left-2.5 rounded-full px-2 py-[3px] text-[11.5px] font-extrabold text-white', p.is_outdoor ? 'bg-[#1f9d62]' : 'bg-(--rain)')}>{p.is_outdoor ? '오늘 딱' : '비 와도 OK'}</span>}
|
||||
<Ic name={p.icon} className="w-[62px]" />
|
||||
</span>
|
||||
</Thumb>
|
||||
<span className="block px-3 pt-2.5 pb-3">
|
||||
<span className="text-[11.5px] font-extrabold text-(--ink3)">
|
||||
{p.area} · {p.is_outdoor ? '야외' : '실내'}
|
||||
{p.area} · {p.distance_km}km · {p.is_outdoor ? '야외' : '실내'}
|
||||
</span>
|
||||
<b className="block font-jua text-[16.5px] font-normal">
|
||||
<MapLink place={p.name}>{p.name}</MapLink>
|
||||
@@ -264,7 +265,7 @@ export function WeekPage() {
|
||||
) : placeLoad === 'loading' ? (
|
||||
<PlacesSkel />
|
||||
) : (
|
||||
<StateBox load={placeLoad} onRetry={() => places.refetch()} empty={sel ? `${sido} 데이트 명소는 아직 준비 중이에요.` : '날씨를 불러오면 명소를 골라 드려요.'} hold={<PlacesSkel />} className="inset-x-3 top-3 bottom-1" />
|
||||
<StateBox load={placeLoad} onRetry={() => places.refetch()} empty={sel ? '30km 안에 데이트 명소가 아직 없어요.' : '날씨를 불러오면 명소를 골라 드려요.'} hold={<PlacesSkel />} className="inset-x-3 top-3 bottom-1" />
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
@@ -272,7 +273,7 @@ export function WeekPage() {
|
||||
{rankDays.length ? (
|
||||
<Chips label="순위 볼 날" items={rankDays.map((d) => [d.day, `${d.weekday}요일 ${shortDay(d.day)}`] as const)} value={rankDay?.day ?? ''} onChange={setRankPick} />
|
||||
) : (
|
||||
<Chips label="순위 볼 날" items={RANK_TABS_HOLD} value="토" onChange={() => {}} />
|
||||
<Chips label="순위 볼 날" items={RANK_TABS_HOLD} value="토" onChange={() => {}} disabled />
|
||||
)}
|
||||
{rankItems.length ? (
|
||||
<ul className={cx('mx-3 mt-1.5 flex flex-col transition-opacity', ranking.isPlaceholderData && 'opacity-60')}>
|
||||
|
||||
@@ -501,6 +501,7 @@
|
||||
}
|
||||
.b-tabbar {
|
||||
background: rgb(255 255 255 / 0.6);
|
||||
overflow: visible;
|
||||
border-color: rgb(255 255 255 / 0.4);
|
||||
}
|
||||
.b-app[data-t='night'] .b-topbg {
|
||||
@@ -593,3 +594,8 @@
|
||||
.b-app[data-t='night'] .b-band-3 {
|
||||
background: linear-gradient(180deg, rgb(110 230 180 / 0.12), rgb(255 255 255 / 0));
|
||||
}
|
||||
|
||||
/* 밤엔 메인 탭 동그라미 테두리를 막대 색에 맞춘다 */
|
||||
.b-app[data-t='night'] .b-tab-main > span {
|
||||
--tw-ring-color: rgb(18 24 60 / 0.9);
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
import type { CSSProperties } from 'react'
|
||||
|
||||
const SHARED = new Set(['bear', 'bike', 'bronze', 'camping', 'carwash', 'chimaek', 'cloud', 'coldwind', 'delivery', 'dog', 'garden', 'glasses', 'gold', 'hiking', 'iced_hot', 'jjamppong', 'laundry', 'letter', 'makeup', 'makgeolli', 'maple', 'moon', 'muggy', 'naengmyeon', 'photo', 'picnic', 'rabbit', 'rain', 'running', 'silver', 'snow', 'stars', 'sun_cloud', 'sun', 'sunset', 'taxi', 'umbrella', 'vent', 'walk', 'yajang', 'baseball', 'study', 'netflix', 'chestnut', 'peanut', 'tangerine', 'sweet_potato', 'fallen_leaf', 'kimchi', 'apple', 'mask'])
|
||||
const SHARED = new Set(['bear', 'bike', 'bronze', 'camping', 'carwash', 'chimaek', 'cloud', 'coldwind', 'delivery', 'dog', 'garden', 'glasses', 'gold', 'hiking', 'iced_hot', 'jjamppong', 'laundry', 'letter', 'makeup', 'makgeolli', 'maple', 'moon', 'muggy', 'naengmyeon', 'photo', 'picnic', 'rabbit', 'rain', 'running', 'silver', 'snow', 'stars', 'sun_cloud', 'sun', 'sunset', 'taxi', 'umbrella', 'vent', 'walk', 'yajang', 'baseball', 'study', 'netflix', 'chestnut', 'peanut', 'tangerine', 'sweet_potato', 'fallen_leaf', 'kimchi', 'apple', 'mask', 'golf', 'jipkok', 'fishing', 'drive', 'kite', 'waterplay'])
|
||||
const OWN = new Set(['fireworks', 'bulb', 'calendar', 'thermo', 'sheaf', 'popup', 'exhibition', 'concert'])
|
||||
|
||||
/** 아이콘 이름 → 파일 경로 (공용 public/icons, B 전용 public/b/icons). 'none'(데이터 없는 칸)은 그림 없음 */
|
||||
@@ -97,11 +97,12 @@ export type TimeKind = 'morning' | 'day' | 'sunset' | 'night'
|
||||
// 서울 월별 대략 일몰 시각(시). 서버 값(/v1/feed hero.sky_mode)이 없을 때만 쓴다
|
||||
const SUNSET_HOUR = [17.7, 18.2, 18.6, 19.1, 19.5, 19.9, 19.9, 19.5, 18.9, 18.2, 17.6, 17.3]
|
||||
|
||||
/** 피드와 같은 시간대: 아침 05–11 · 낮 11–일몰 2시간 전 · 저녁(sunset) 일몰 2시간 전–21 · 밤 21–05 */
|
||||
/** 피드와 같은 시간대: 아침 05–11 · 낮 11–일몰 2시간 전 · 저녁(sunset) 일몰 2시간 전–일몰 1시간 뒤 · 밤 일몰 1시간 뒤–05 */
|
||||
export function kindOfHour(h: number, month = new Date().getMonth() + 1, minute = 0): TimeKind {
|
||||
const at = h + minute / 60
|
||||
const sunset = SUNSET_HOUR[month - 1]
|
||||
if (at >= 5 && at < 11) return 'morning'
|
||||
if (at >= 11 && at < 21) return at < SUNSET_HOUR[month - 1] - 2 ? 'day' : 'sunset'
|
||||
if (at >= 11 && at < sunset + 1) return at < sunset - 2 ? 'day' : 'sunset'
|
||||
return 'night'
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { useCallback, useEffect, useMemo, useState, type ReactNode } from 'react'
|
||||
import { nearestRegion } from '../api/client/sdk.gen'
|
||||
import type { RegionData } from '../api/client/types.gen'
|
||||
import { track } from '../lib/analytics'
|
||||
import { DEFAULT_REGION, RegionContext, type LocateStatus } from './regionContext'
|
||||
|
||||
const KEY = 'nalssigak.b.region'
|
||||
@@ -35,7 +36,7 @@ export function RegionProvider({ children }: { children: ReactNode }) {
|
||||
writeStored(r)
|
||||
}, [])
|
||||
|
||||
const findNearest = useCallback(() => {
|
||||
const findNearest = useCallback((onFound?: () => void) => {
|
||||
navigator.geolocation.getCurrentPosition(
|
||||
(pos) => {
|
||||
nearestRegion({ query: { lat: pos.coords.latitude, lon: pos.coords.longitude } })
|
||||
@@ -43,6 +44,8 @@ export function RegionProvider({ children }: { children: ReactNode }) {
|
||||
if (!res.region) throw new Error('가까운 구를 찾지 못함')
|
||||
setRegion(res.region)
|
||||
setLocateStatus('idle')
|
||||
track('region_change', { region_name: res.region.name, method: 'location' })
|
||||
onFound?.()
|
||||
})
|
||||
.catch(() => setLocateStatus('error'))
|
||||
},
|
||||
@@ -51,13 +54,13 @@ export function RegionProvider({ children }: { children: ReactNode }) {
|
||||
)
|
||||
}, [setRegion])
|
||||
|
||||
const locate = useCallback(() => {
|
||||
const locate = useCallback((onFound?: () => void) => {
|
||||
if (!canLocate) {
|
||||
setLocateStatus('error')
|
||||
return
|
||||
}
|
||||
setLocateStatus('locating')
|
||||
findNearest()
|
||||
findNearest(onFound)
|
||||
}, [canLocate, findNearest])
|
||||
|
||||
// 처음 온 사람만 위치 권한을 물어 가장 가까운 구로 맞춘다
|
||||
|
||||
@@ -3,7 +3,7 @@ import type { RegionData } from '../api/client/types.gen'
|
||||
|
||||
export type LocateStatus = 'idle' | 'locating' | 'denied' | 'error'
|
||||
|
||||
export type RegionApi = { region: RegionData; setRegion: (r: RegionData) => void; locate: () => void; locateStatus: LocateStatus }
|
||||
export type RegionApi = { region: RegionData; setRegion: (r: RegionData) => void; locate: (onFound?: () => void) => void; locateStatus: LocateStatus }
|
||||
|
||||
export const DEFAULT_REGION: RegionData = { code: '1144000000', name: '서울 마포구', short_name: '마포구', lat: 37.56071, lon: 126.91053 }
|
||||
|
||||
|
||||
@@ -1,22 +0,0 @@
|
||||
import { SITE_URL } from '../api/setup'
|
||||
|
||||
/** 날씨각 주소만 보낸다 (메신저가 미리보기 그림을 붙인다). 휴대폰은 공유창, 없으면 주소 복사. 화면에 띄울 문구를 돌려주고, 공유창에서 보냈거나 취소했으면 null */
|
||||
export async function shareLink(): Promise<string | null> {
|
||||
const url = `${SITE_URL}/`
|
||||
if (navigator.share) {
|
||||
try {
|
||||
await navigator.share({ url })
|
||||
return null
|
||||
} catch (e) {
|
||||
if (e instanceof DOMException && e.name === 'AbortError') return null
|
||||
console.error('[share] link', e)
|
||||
}
|
||||
}
|
||||
try {
|
||||
await navigator.clipboard.writeText(url)
|
||||
return '링크를 복사했어요'
|
||||
} catch (e) {
|
||||
console.error('[share] copy', e)
|
||||
return '링크를 복사하지 못했어요'
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,15 @@
|
||||
import { createContext, use } from 'react'
|
||||
export type SharePayload = { title: string; slides: HTMLElement[] }
|
||||
|
||||
type CommentsState = { type: 'comments'; postId: number; draft?: string }
|
||||
|
||||
export type SheetState =
|
||||
| { type: 'gak'; indexId: number }
|
||||
| { type: 'article'; articleId: number }
|
||||
| { type: 'comments'; postId: number }
|
||||
| { type: 'share'; share: SharePayload }
|
||||
| CommentsState
|
||||
| { type: 'seasonWeek' }
|
||||
| { type: 'login' }
|
||||
| { type: 'login'; then?: CommentsState }
|
||||
| { type: 'me' }
|
||||
| { type: 'region' }
|
||||
| null
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import { createContext, use } from 'react'
|
||||
import type { TimeKind } from './lib'
|
||||
|
||||
/** 화면 전체 하늘 배경의 시간대. 히어로의 미리보기 버튼이 잠시 바꿀 수 있다 */
|
||||
export type SkyApi = { kind: TimeKind; setServerKind: (k: TimeKind | null) => void; setPreview: (k: TimeKind | null) => void }
|
||||
/** 화면 전체 하늘 배경의 시간대. 히어로의 미리보기 버튼으로 고른 값은 탭을 옮겨도 유지된다 */
|
||||
export type SkyApi = { kind: TimeKind; preview: TimeKind | null; setServerKind: (k: TimeKind | null) => void; setPreview: (k: TimeKind | null) => void }
|
||||
|
||||
export const SkyContext = createContext<SkyApi | null>(null)
|
||||
|
||||
|
||||
@@ -0,0 +1,229 @@
|
||||
import { domToCanvas } from 'modern-screenshot'
|
||||
import { API_BASE_URL } from '../api/setup'
|
||||
|
||||
const W = 1080
|
||||
const SIDE = 60
|
||||
|
||||
// 시간대별 배경 (화면 하늘 배경과 같은 색)
|
||||
const SKY: Record<string, [string, string, string]> = {
|
||||
morning: ['#ffe0c4', '#fff0e2', '#e4f2ff'],
|
||||
day: ['#cde7ff', '#e9f5ff', '#f7fbff'],
|
||||
sunset: ['#ffd0b5', '#f9c3cf', '#ddd2f6'],
|
||||
night: ['#0e1433', '#1b2356', '#2a2e6e'],
|
||||
}
|
||||
|
||||
/** 공유 이미지 크기. 위: 로고·지역 날짜, 가운데: 카드, 아래: 주소 */
|
||||
export const SHARE_SIZES = {
|
||||
story: { ratio: '9:16', w: 9, hr: 16, h: 1920, logoY: 250, logoPx: 96, subY: 325, subPx: 40, pillY: 1760, pillH: 100, labelPx: 34, hostPx: 46 },
|
||||
feed: { ratio: '4:5', w: 4, hr: 5, h: 1350, logoY: 140, logoPx: 76, subY: 200, subPx: 34, pillY: 1250, pillH: 84, labelPx: 30, hostPx: 40 },
|
||||
square: { ratio: '1:1', w: 1, hr: 1, h: 1080, logoY: 115, logoPx: 64, subY: 168, subPx: 30, pillY: 990, pillH: 80, labelPx: 28, hostPx: 38 },
|
||||
} as const
|
||||
export type ShareSize = keyof typeof SHARE_SIZES
|
||||
|
||||
const LOGO = (px: number) => `${px}px Jua, sans-serif`
|
||||
const SANS = (px: number) => `bold ${px}px "Pretendard Variable", sans-serif`
|
||||
const PILL_LABEL = '오늘 내 동네 각 보기'
|
||||
|
||||
// 버튼·조작 표시(data-noshot)는 이미지에 넣지 않는다. 링크(장소 등)는 글자라 남긴다
|
||||
const keep = (n: Node) => !(n instanceof HTMLButtonElement || (n instanceof HTMLElement && n.dataset.noshot != null))
|
||||
|
||||
function roundRect(ctx: CanvasRenderingContext2D, x: number, y: number, w: number, h: number, r: number) {
|
||||
ctx.beginPath()
|
||||
ctx.roundRect(x, y, w, h, r)
|
||||
}
|
||||
|
||||
const URL_RE = /url\((['"]?)([^'")]+)\1\)/g
|
||||
const dataUrls = new Map<string, Promise<string>>()
|
||||
|
||||
function dataUrl(url: string): Promise<string> {
|
||||
let p = dataUrls.get(url)
|
||||
if (!p) {
|
||||
p = fetch(url)
|
||||
.then((r) => {
|
||||
if (!r.ok) throw new Error(`font ${r.status} ${url}`)
|
||||
return r.blob()
|
||||
})
|
||||
.then((b) => new Promise<string>((resolve, reject) => {
|
||||
const fr = new FileReader()
|
||||
fr.onload = () => resolve(fr.result as string)
|
||||
fr.onerror = () => reject(fr.error)
|
||||
fr.readAsDataURL(b)
|
||||
}))
|
||||
p.catch(() => dataUrls.delete(url))
|
||||
dataUrls.set(url, p)
|
||||
}
|
||||
return p
|
||||
}
|
||||
|
||||
// "U+AC00-AC5F, U+4??" 가 text 의 글자를 하나라도 덮는지
|
||||
function covers(range: string, codes: number[]) {
|
||||
if (!range) return true
|
||||
return range.split(',').some((part) => {
|
||||
const [a, b] = part.trim().replace(/^u\+/i, '').split('-')
|
||||
const lo = parseInt(a.replace(/\?/g, '0'), 16)
|
||||
const hi = parseInt((b ?? a).replace(/\?/g, 'f'), 16)
|
||||
return codes.some((c) => c >= lo && c <= hi)
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 카드 글자에 필요한 웹폰트 조각만 data URL 로 넣은 @font-face.
|
||||
* 이미지는 SVG 로 그려져 문서 폰트를 못 쓰므로 직접 넣어야 글꼴이 안 깨진다 (한글 폰트는 조각 수백 개라 전부 넣지 않는다).
|
||||
*/
|
||||
async function fontCss(text: string): Promise<string> {
|
||||
const codes = [...new Set(Array.from(text, (ch) => ch.codePointAt(0) ?? 0))]
|
||||
const rules: { css: string; base: string }[] = []
|
||||
for (const sheet of Array.from(document.styleSheets)) {
|
||||
let list: CSSRuleList
|
||||
try {
|
||||
list = sheet.cssRules
|
||||
} catch (e) {
|
||||
console.warn('[share] font css unreadable', sheet.href, e)
|
||||
continue
|
||||
}
|
||||
for (const r of Array.from(list)) {
|
||||
if (r instanceof CSSFontFaceRule && covers(r.style.getPropertyValue('unicode-range'), codes)) rules.push({ css: r.cssText, base: sheet.href ?? location.href })
|
||||
}
|
||||
}
|
||||
const out = await Promise.all(
|
||||
rules.map(async ({ css, base }) => {
|
||||
const urls = [...css.matchAll(URL_RE)].map((m) => m[2])
|
||||
const data = await Promise.all(urls.map((u) => dataUrl(new URL(u, base).href)))
|
||||
let i = 0
|
||||
return css.replace(URL_RE, () => `url("${data[i++]}")`)
|
||||
}),
|
||||
)
|
||||
return out.join('\n')
|
||||
}
|
||||
|
||||
// 다른 사이트 사진은 브라우저가 픽셀을 못 읽는 경우가 있어 백엔드가 대신 받아 준다. 허용 여부는 백엔드(IMAGE_PROXY_HOSTS)가 정한다
|
||||
function viaProxy(url: string): Promise<string | false> {
|
||||
if (!URL.canParse(url)) return Promise.resolve(false)
|
||||
const u = new URL(url)
|
||||
if (u.origin === location.origin || !u.protocol.startsWith('http')) return Promise.resolve(false)
|
||||
return dataUrl(`${API_BASE_URL}/v1/image?url=${encodeURIComponent(url)}`).catch((e: unknown) => {
|
||||
console.warn('[share] image proxy', url, e)
|
||||
return false as const
|
||||
})
|
||||
}
|
||||
|
||||
type Box = { x: number; y: number; w: number; h: number }
|
||||
|
||||
// 카드 자리. 2장이면 세로 이미지는 지그재그, 나머지는 나란히(오른쪽을 조금 내려) 놓는다
|
||||
function place(n: number, aspect: number, top: number, bottom: number): Box[] {
|
||||
const room = bottom - top
|
||||
if (n === 1) {
|
||||
const w = Math.min(W - SIDE * 3, room / aspect)
|
||||
const h = w * aspect
|
||||
return [{ x: (W - w) / 2, y: top + (room - h) / 2, w, h }]
|
||||
}
|
||||
if (room / W > 1.1) {
|
||||
const h = Math.min(room / 2, ((W - SIDE * 2) * 0.52) * aspect)
|
||||
const w = h / aspect
|
||||
const y = top + (room - h * 2) / 2
|
||||
return [{ x: SIDE, y, w, h }, { x: W - SIDE - w, y: y + h, w, h }]
|
||||
}
|
||||
const gap = 40
|
||||
const w = Math.min((W - SIDE * 2 - gap) / 2, room / aspect / 1.08)
|
||||
const h = w * aspect
|
||||
const y = top + (room - h * 1.08) / 2
|
||||
return [{ x: W / 2 - gap / 2 - w, y, w, h }, { x: W / 2 + gap / 2, y: y + h * 0.08, w, h }]
|
||||
}
|
||||
|
||||
function badge(ctx: CanvasRenderingContext2D, x: number, y: number, n: number) {
|
||||
ctx.beginPath()
|
||||
ctx.arc(x, y, 30, 0, Math.PI * 2)
|
||||
ctx.fillStyle = '#ff7a45'
|
||||
ctx.fill()
|
||||
ctx.fillStyle = '#fff'
|
||||
ctx.font = LOGO(36)
|
||||
ctx.textBaseline = 'middle'
|
||||
ctx.fillText(String(n), x, y + 2)
|
||||
ctx.textBaseline = 'alphabetic'
|
||||
}
|
||||
|
||||
/** 게시물 슬라이드(최대 2장)를 고른 크기의 PNG 한 장으로 만든다 */
|
||||
export async function shareImage(slides: HTMLElement[], opts: { size: ShareSize; sky: string; sub: string; host: string }): Promise<Blob> {
|
||||
const z = SHARE_SIZES[opts.size]
|
||||
const cards = slides.slice(0, 2)
|
||||
if (!cards.length) throw new Error('no slide to capture')
|
||||
await Promise.all([
|
||||
document.fonts.load(LOGO(z.logoPx), '날씨각'),
|
||||
document.fonts.load(LOGO(z.hostPx), opts.host),
|
||||
document.fonts.load(LOGO(36), '12'),
|
||||
document.fonts.load(SANS(z.subPx), opts.sub),
|
||||
document.fonts.load(SANS(z.labelPx), PILL_LABEL),
|
||||
])
|
||||
const css = await fontCss(cards.map((c) => c.textContent ?? '').join(''))
|
||||
const aspect = cards[0].offsetHeight / cards[0].offsetWidth
|
||||
const boxes = place(cards.length, aspect, z.subY + 60, z.pillY - z.pillH / 2 - 50)
|
||||
const shots = await Promise.all(cards.map((c, i) => domToCanvas(c, { scale: boxes[i].w / c.offsetWidth, filter: keep, font: css ? { cssText: css } : false, fetchFn: viaProxy })))
|
||||
|
||||
const canvas = document.createElement('canvas')
|
||||
canvas.width = W
|
||||
canvas.height = z.h
|
||||
const ctx = canvas.getContext('2d')
|
||||
if (!ctx) throw new Error('canvas 2d context unavailable')
|
||||
const dark = opts.sky === 'night'
|
||||
const [c1, c2, c3] = SKY[opts.sky] ?? SKY.day
|
||||
const bg = ctx.createLinearGradient(0, 0, 0, z.h)
|
||||
bg.addColorStop(0, c1)
|
||||
bg.addColorStop(0.45, c2)
|
||||
bg.addColorStop(1, c3)
|
||||
ctx.fillStyle = bg
|
||||
ctx.fillRect(0, 0, W, z.h)
|
||||
|
||||
ctx.textAlign = 'center'
|
||||
ctx.fillStyle = '#ff7a45'
|
||||
ctx.font = LOGO(z.logoPx)
|
||||
ctx.fillText('날씨각', W / 2, z.logoY)
|
||||
ctx.fillStyle = dark ? '#bcc3ea' : '#5a6380'
|
||||
ctx.font = SANS(z.subPx)
|
||||
ctx.fillText(opts.sub, W / 2, z.subY, W - SIDE * 2)
|
||||
|
||||
const r = 40 * (boxes[0].w / 900)
|
||||
shots.forEach((shot, i) => {
|
||||
const b = boxes[i]
|
||||
ctx.save()
|
||||
ctx.shadowColor = 'rgb(40 48 74 / 0.25)'
|
||||
ctx.shadowBlur = 50
|
||||
ctx.shadowOffsetY = 20
|
||||
roundRect(ctx, b.x, b.y, b.w, b.h, r)
|
||||
ctx.fillStyle = '#fff'
|
||||
ctx.fill()
|
||||
ctx.restore()
|
||||
ctx.save()
|
||||
roundRect(ctx, b.x, b.y, b.w, b.h, r)
|
||||
ctx.clip()
|
||||
ctx.drawImage(shot, b.x, b.y, b.w, b.h)
|
||||
ctx.restore()
|
||||
})
|
||||
if (shots.length > 1) boxes.forEach((b, i) => badge(ctx, b.x + 6, b.y + 6, i + 1))
|
||||
|
||||
// 주소 알약: [오늘 내 동네 각 보기 host]
|
||||
ctx.font = SANS(z.labelPx)
|
||||
const lw = ctx.measureText(PILL_LABEL).width
|
||||
ctx.font = LOGO(z.hostPx)
|
||||
const hw = ctx.measureText(opts.host).width
|
||||
const gap = 20
|
||||
const pw = Math.min(W - SIDE * 2, lw + gap + hw + 96)
|
||||
const px = (W - pw) / 2
|
||||
ctx.save()
|
||||
ctx.shadowColor = 'rgb(40 48 74 / 0.14)'
|
||||
ctx.shadowBlur = 30
|
||||
ctx.shadowOffsetY = 10
|
||||
roundRect(ctx, px, z.pillY - z.pillH / 2, pw, z.pillH, z.pillH / 2)
|
||||
ctx.fillStyle = '#fff'
|
||||
ctx.fill()
|
||||
ctx.restore()
|
||||
ctx.textAlign = 'left'
|
||||
ctx.textBaseline = 'middle'
|
||||
ctx.fillStyle = '#5a6380'
|
||||
ctx.font = SANS(z.labelPx)
|
||||
ctx.fillText(PILL_LABEL, px + 48, z.pillY + 2)
|
||||
ctx.fillStyle = '#ff7a45'
|
||||
ctx.font = LOGO(z.hostPx)
|
||||
ctx.fillText(opts.host, px + 48 + lw + gap, z.pillY + 4, pw - 96 - lw - gap)
|
||||
|
||||
return new Promise((resolve, reject) => canvas.toBlob((b) => (b ? resolve(b) : reject(new Error('toBlob failed'))), 'image/png'))
|
||||
}
|
||||
+14
-27
@@ -1,5 +1,4 @@
|
||||
import { useEffect, useState, type CSSProperties, type ReactNode } from 'react'
|
||||
import { createPortal } from 'react-dom'
|
||||
import { useState, type CSSProperties, type ReactNode } from 'react'
|
||||
import { Link } from 'react-router'
|
||||
import { cx } from '../lib/utils'
|
||||
import { useCarousel, type Carousel } from './carousel'
|
||||
@@ -18,16 +17,16 @@ export function Credit({ text, className = 'right-1 bottom-1' }: { text: string;
|
||||
return <small className={cx('pointer-events-none absolute z-[1] rounded-[5px] bg-[rgb(16_20_34/0.5)] px-1 py-px text-[9px] leading-tight font-semibold whitespace-nowrap text-white', className)}>{text}</small>
|
||||
}
|
||||
|
||||
type ThumbProps = { image?: string | null; icon: string; credit?: string | null; className?: string; iconClassName?: string; children?: ReactNode }
|
||||
type ThumbProps = { image?: string | null; icon: string; credit?: string | null; className?: string; iconClassName?: string; creditClassName?: string; children?: ReactNode }
|
||||
|
||||
/** 사진이 있으면 사진(+출처), 없거나 못 불러오면 아이콘 */
|
||||
export function Thumb({ image, icon, credit, className, iconClassName, children }: ThumbProps) {
|
||||
export function Thumb({ image, icon, credit, className, iconClassName, creditClassName, children }: ThumbProps) {
|
||||
const [failed, setFailed] = useState<string | null>(null)
|
||||
const photo = image && image !== failed ? image : null
|
||||
return (
|
||||
<span className={cx('relative grid place-items-center overflow-hidden', className)}>
|
||||
{photo ? <img src={photo} alt="" loading="lazy" decoding="async" onError={() => setFailed(photo)} className="absolute inset-0 size-full object-cover" /> : <Ic name={icon} className={iconClassName} />}
|
||||
{photo && credit && <Credit text={credit} />}
|
||||
{photo && credit && <Credit text={credit} className={creditClassName} />}
|
||||
{children}
|
||||
</span>
|
||||
)
|
||||
@@ -70,16 +69,16 @@ export function Sec({ title, sub, more, className }: SecProps) {
|
||||
|
||||
/** PC(마우스)에서만 보이는 좌우 화살표 */
|
||||
export function Arrows({ api, prev, next, className }: { api: Carousel; prev: boolean; next: boolean; className?: string }) {
|
||||
const btn = 'absolute top-1/2 z-[3] hidden size-8 -translate-y-1/2 cursor-pointer place-items-center rounded-full bg-white/90 text-lg font-extrabold text-[#28304a] shadow-[0_4px_10px_rgb(40_48_74/0.18)] pointer-fine:grid'
|
||||
const btn = 'absolute top-1/2 z-[3] grid size-8 -translate-y-1/2 cursor-pointer place-items-center rounded-full bg-white/90 text-lg font-extrabold text-[#28304a] shadow-[0_4px_10px_rgb(40_48_74/0.18)]'
|
||||
return (
|
||||
<>
|
||||
{prev && (
|
||||
<button type="button" onClick={() => api?.scrollPrev()} aria-label="이전" className={cx(btn, 'left-1.5', className)}>
|
||||
<button type="button" data-noshot onClick={() => api?.scrollPrev()} aria-label="이전" className={cx(btn, 'left-1.5', className)}>
|
||||
‹
|
||||
</button>
|
||||
)}
|
||||
{next && (
|
||||
<button type="button" onClick={() => api?.scrollNext()} aria-label="다음" className={cx(btn, 'right-1.5', className)}>
|
||||
<button type="button" data-noshot onClick={() => api?.scrollNext()} aria-label="다음" className={cx(btn, 'right-1.5', className)}>
|
||||
›
|
||||
</button>
|
||||
)}
|
||||
@@ -110,9 +109,12 @@ export function Rail({ children, className, label }: { children: ReactNode; clas
|
||||
)
|
||||
}
|
||||
|
||||
type ChipsProps<K extends string> = { items: readonly (readonly [K, string])[]; value: K; onChange: (k: K) => void; label: string }
|
||||
// 보이는 크기는 두고 누르는 영역만 가운데 44×44로 넓힌다 (위치 지정된 요소에 붙인다)
|
||||
export const TAP44 = 'after:absolute after:top-1/2 after:left-1/2 after:size-11 after:-translate-1/2'
|
||||
|
||||
export function Chips<K extends string>({ items, value, onChange, label }: ChipsProps<K>) {
|
||||
type ChipsProps<K extends string> = { items: readonly (readonly [K, string])[]; value: K; onChange: (k: K) => void; label: string; disabled?: boolean }
|
||||
|
||||
export function Chips<K extends string>({ items, value, onChange, label, disabled }: ChipsProps<K>) {
|
||||
return (
|
||||
<ChipStrip label={label}>
|
||||
{items.map(([k, l]) => (
|
||||
@@ -120,8 +122,9 @@ export function Chips<K extends string>({ items, value, onChange, label }: Chips
|
||||
key={k}
|
||||
type="button"
|
||||
aria-pressed={value === k}
|
||||
disabled={disabled}
|
||||
onClick={() => onChange(k)}
|
||||
className={cx('shrink-0 cursor-pointer rounded-full px-3.5 py-[7px] text-[13.5px] font-bold', value === k ? 'bg-(--ink) text-white' : 'bg-white text-(--ink2) shadow-[inset_0_-3px_0_var(--shade)]')}
|
||||
className={cx('shrink-0 cursor-pointer rounded-full disabled:cursor-default px-3.5 py-[7px] text-[13.5px] font-bold', value === k ? 'bg-(--ink) text-white' : 'bg-white text-(--ink2) shadow-[inset_0_-3px_0_var(--shade)]')}
|
||||
>
|
||||
{l}
|
||||
</button>
|
||||
@@ -203,22 +206,6 @@ export function MapLink({ place, children, className }: { place: string; childre
|
||||
)
|
||||
}
|
||||
|
||||
/** 화면 아래에 잠깐 뜨는 알림. 2.5초 뒤 setText('') 로 지운다 (useState 의 setter 를 그대로 넘긴다) */
|
||||
export function ScreenNote({ text, setText }: { text: string; setText: (t: string) => void }) {
|
||||
useEffect(() => {
|
||||
if (!text) return
|
||||
const t = setTimeout(() => setText(''), 2500)
|
||||
return () => clearTimeout(t)
|
||||
}, [text, setText])
|
||||
if (!text) return null
|
||||
return createPortal(
|
||||
<p role="status" className="pointer-events-none fixed inset-x-0 bottom-[calc(88px+env(safe-area-inset-bottom,0px))] z-50 m-0 flex justify-center px-4">
|
||||
<span className="rounded-full bg-[rgb(30_36_56/0.82)] px-3.5 py-2 text-[13px] font-bold text-white">{text}</span>
|
||||
</p>,
|
||||
document.body,
|
||||
)
|
||||
}
|
||||
|
||||
export function Rows({ rows, dark = false }: { rows: { label: string; value: string; place?: string | null }[]; dark?: boolean }) {
|
||||
return (
|
||||
<div className="mt-auto flex flex-col">
|
||||
|
||||
@@ -16,6 +16,7 @@
|
||||
word-break: keep-all;
|
||||
overflow-wrap: break-word;
|
||||
-webkit-text-size-adjust: 100%;
|
||||
touch-action: manipulation;
|
||||
}
|
||||
body {
|
||||
@apply bg-page font-sans text-ink antialiased;
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
/** GA4로 보내는 이벤트와 값. 목록은 docs/이벤트_추적.md */
|
||||
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' }
|
||||
sign_up: { method: 'id' }
|
||||
region_change: { region_name: string; method: 'list' | 'location' }
|
||||
}
|
||||
|
||||
declare global {
|
||||
interface Window {
|
||||
gtag?: (command: 'event', name: string, params: Record<string, unknown>) => void
|
||||
}
|
||||
}
|
||||
|
||||
export function track<E extends keyof Events>(event: E, params: Events[E]) {
|
||||
if (import.meta.env.DEV) return
|
||||
window.gtag?.('event', event, params)
|
||||
}
|
||||
@@ -5,6 +5,9 @@ import './index.css'
|
||||
import './api/setup'
|
||||
import App from './App.tsx'
|
||||
|
||||
// iOS는 user-scalable=no를 무시해서 두 손가락 확대를 직접 막는다
|
||||
for (const type of ['gesturestart', 'gesturechange']) document.addEventListener(type, (e) => e.preventDefault(), { passive: false })
|
||||
|
||||
// 칩·지역·검색어를 바꿔 다시 받는 동안 이전 결과를 그대로 두어 화면이 비거나 접히지 않게 한다
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: { queries: { staleTime: 5 * 60 * 1000, retry: 1, refetchOnWindowFocus: false, placeholderData: keepPreviousData } },
|
||||
|
||||
Reference in new issue
Block a user