Compare commits
93
Commits
main-2
...
0b8eb84b55
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0b8eb84b55 | ||
|
|
0a4b210e6c | ||
|
|
934566d45c | ||
|
|
57cad25f32 | ||
|
|
b023d55901 | ||
|
|
aa774c2a44 | ||
|
|
4cdc8b274f | ||
|
|
6b8236d1cd | ||
|
|
aa05d870a2 | ||
|
|
cac6ea236f | ||
|
|
902fb4c070 | ||
|
|
0f614dd82f | ||
|
|
52b79c6de9 | ||
|
|
118a7b29ff | ||
|
|
81f84cee05 | ||
|
|
6e4babc610 | ||
|
|
b346838054 | ||
|
|
f5575711fe | ||
|
|
c30fac20a6 | ||
|
|
8422829f9d | ||
|
|
0a98fb8879 | ||
|
|
f4fe3e965c | ||
|
|
ef57a47e29 | ||
|
|
fcf199031a | ||
|
|
a4bb2e98c8 | ||
|
|
c0d53b8708 | ||
|
|
fb47f59d57 | ||
|
|
3a73a44cb0 | ||
|
|
97ebfe2d36 | ||
|
|
5c4f23c01a | ||
|
|
5a5f585bda | ||
|
|
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=
|
DATA_GO_KR_SERVICE_KEY=
|
||||||
# 행사 수집(7일마다) 완료 알림 — Microsoft Teams Workflows 수신 webhook. 비우면 보내지 않는다.
|
# 행사 수집(7일마다) 완료 알림 — Microsoft Teams Workflows 수신 webhook. 비우면 보내지 않는다.
|
||||||
TEAMS_WEBHOOK_URL=
|
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·Redis (네이티브 실행 기준. compose 안에서는 compose.yaml 이 host·port 를 덮어쓴다)
|
||||||
DB_HOST=localhost
|
DB_HOST=localhost
|
||||||
|
|||||||
@@ -1,5 +1,20 @@
|
|||||||
# TODO
|
# 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] | 행사 독립 카드 최대 3장, 피드 무작위 노출 (하루 같은 자리) | 10/2 회의 | `backend/services/feed_service.py` |
|
||||||
| [x] | 계절 소식 제철 7개 추가 (햇밤·햇땅콩·은행·고구마·귤·부사·김장) — 피드백 대기 | 10/2 회의 | `backend/seed/article.json` |
|
| [x] | 계절 소식 제철 7개 추가 (햇밤·햇땅콩·은행·고구마·귤·부사·김장) — 피드백 대기 | 10/2 회의 | `backend/seed/article.json` |
|
||||||
| [x] | 새 각 추가 (야구·공부·넷플릭스·군밤) | 10/2 회의 | `backend/seed/index_definition.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] | 주말 전국 지역 랭킹 — 노을 순위 대표 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` |
|
| [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` |
|
| [x] | 명소 '서쪽이 트임'(west_open)·설명 꼬리말은 TourAPI 개요를 보고 사람이 붙인 값 — 현장 확인 안 됨. 분당구는 가장 가까운 곳이 17~18km(일자산·반포·광나루)라 수도권 동남부 명소 보강 필요 → 화면에서 설명을 빼고 방향·거리만 보여줌. 현장 확인은 여전히 안 됨 | 명소 확충 결과 | `backend/seed/sunset_spot.csv` |
|
||||||
| [ ] | TourAPI 좌표 오류로 뺀 곳: 기흥레스피아호수공원(용인)·급치산전망대(진도) — 좌표가 (19.69, 117.99). 좌표를 직접 넣어 추가할지 결정 | 명소 확충 결과 | `backend/seed/sunset_spot_tourapi.csv` |
|
| [ ] | TourAPI 좌표 오류로 뺀 곳: 기흥레스피아호수공원(용인)·급치산전망대(진도) — 좌표가 (19.69, 117.99). 좌표를 직접 넣어 추가할지 결정 | 명소 확충 결과 | `backend/seed/sunset_spot_tourapi.csv` |
|
||||||
| [x] | 서울·경기 반영 범위 확인 — 서울 25구·경기 31시군(구 있는 시는 구 단위, 부천 3구·화성 4구 포함) 모두 있고 코드도 기상청 격자표(2607) 현행 코드와 일치 | 10/2 회의 확인 필요 | `backend/seed/region.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` |
|
| [ ] | 월요일 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` |
|
| [ ] | 주말 점수 계산이 대표 지역·후보 도시 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` |
|
| [ ] | 기상청 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] | 각 상세 창 점수 칸을 오늘/내일/토/일로 — 단기예보(시간별)는 약 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` |
|
| [x] | 그날 밤 달 모양 — 밤 히어로에 달 모양·밝기, 보름·삭인 밤엔 '오늘 밤 달' 포스트 (사용자 결정 1·4안). 보름·삭 시각은 Meeus 계산(오차 2분 안) — 계산은 `moon.py`로 외부 API 없이 가능 | 사용자 질문 | `backend/services/calc/moon.py` |
|
||||||
| [ ] | **[결정 필요]** 각과 상관없는 요소 비중 — 김서림각 바람, 택시대란·배달폭주·넷플릭스각 습도가 '상관없음'인데 비중 5%라 항상 50점으로 섞임. 0으로 할지 / 짬뽕·배달폭주각에 '공기 맑음' 5%가 좋은 쪽으로 들어가는 게 맞는지 | 6각 차트 수정 중 발견 | `backend/seed/index_definition.json` |
|
| [ ] | **[결정 필요]** 각과 상관없는 요소 비중 — 김서림각 바람, 택시대란·배달폭주·넷플릭스각 습도가 '상관없음'인데 비중 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] | 포스트 본문이 슬라이드 내용 반복 — 축제("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] | 아이콘 오용 — 밤 '한 문장' 카드에 망원경(`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` |
|
| [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` |
|
| [ ] | 문화정보 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` |
|
| [ ] | **[결정 필요]** 두 달 넘는 전시가 `MAX_EVENT_DAYS = 60` 필터에 걸려 빠짐 — 전시는 기준을 따로 둘지 | 전시 연결 중 발견 | `backend/services/week_service.py` |
|
||||||
| [ ] | 전시 썸네일 저작권 확인 — 데이터셋은 '이용허락범위 제한 없음'이나 원저작권이 주최 기관에 있을 수 있음 | 전시 연결 중 발견 | `backend/services/week_service.py` (`image_credit`) |
|
| [ ] | 전시 썸네일 저작권 확인 — 데이터셋은 '이용허락범위 제한 없음'이나 원저작권이 주최 기관에 있을 수 있음 | 전시 연결 중 발견 | `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` |
|
| [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` |
|
| [ ] | **[결정 필요]** 확정 시안(`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` |
|
| [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,11 +90,12 @@
|
|||||||
| [ ] | 한 문장 8개(`quote-clear-2·3`, `quote-cloud-1·2`, `quote-rain-1·2`, `quote-any-1`, `quote-night-3`) 문구 검수 — 직접 쓴 예시 문장이라 출처 없이 나감 | 출처 줄 '날씨각 (검수 전 예시)' 삭제하며 메모 옮김 | `backend/seed/article.json` |
|
| [ ] | 한 문장 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`) |
|
| [ ] | 미세먼지 포스트에 오늘 시간대별 예보 추가 — 지금은 실시간 측정값만. 에어코리아 예보 API(`getMinuDustFrcstDspth`, 권역별 오늘·내일 등급) 연결 필요 | 미세먼지 포스트 작업 중 발견 | `backend/services/external/airkorea.py`, `backend/services/feed_service.py` (`_air`) |
|
||||||
| [ ] | 마스크 아이콘 없음 — 미세먼지 포스트가 좋음·보통은 `vent`, 나쁨 이상은 `cloud`를 씀 | 미세먼지 포스트 작업 중 발견 | `frontend/public/icons/`, `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` |
|
| [ ] | 행사 수집이 사용자 한 명당 주변 시도 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` |
|
| [ ] | 다른 문서의 포스트 종류 목록·행사 시도 기준 설명 갱신 (`PostType` 12 미세먼지, 30km 행사) — `docs/포스트_종류별_내용.html`만 고침 | 문서 점검 | `backend/docs/`, `docs/화면별_데이터_출처.html`, `docs/데이터_흐름.html`, `docs/콘텐츠_설계서.md` |
|
||||||
| [ ] | **[결정 필요]** 스켈레톤 작업에서 바뀐 디자인 — 댓글 없음 안내가 글자 두 줄 → 상자(스켈레톤 3줄 크기) | 스켈레톤 작업 중 발견 | `frontend/src/b/Sheets.tsx` (`CommentsSheet`) |
|
| [ ] | **[결정 필요]** 스켈레톤 작업에서 바뀐 디자인 — 댓글 없음 안내가 글자 두 줄 → 상자(스켈레톤 3줄 크기) | 스켈레톤 작업 중 발견 | `frontend/src/b/Sheets.tsx` (`CommentsSheet`) |
|
||||||
| [ ] | **[결정 필요]** 히어로 시안 A/B/C 중 선택 — 지금은 이전 히어로로 롤백 | 히어로 다듬기 | `frontend/src/b/TodayPage.tsx`, `frontend/src/b/b.css` |
|
| [x] | **[결정 필요]** 히어로 시안 A/B/C 중 선택 — 지금은 이전 히어로로 롤백 → 10/12 D4-2로 결정(해 안 점수 + 문장 두 줄은 서버 값 그대로 + 상태 한 줄 + 하루 흐름 칸, 높이는 지금 그대로 약 400px) | 히어로 다듬기 | `frontend/src/b/TodayPage.tsx`, `frontend/src/b/b.css` |
|
||||||
|
| [x] | **[결정 필요]** 히어로 D4-2 상태 한 줄 — ① 습도는 서버가 %만 줘서 단계 기준을 새로 정해야 함 ② 불쾌지수 '불쾌'처럼 판정 이름을 그대로 쓸지 ③ 미세먼지·자외선은 늘 보일지, 조심할 때만 보일지 → 10/12 결정: 습도 건조(30% 미만)·보통(60% 이하)·습함, 불쾌지수 단계 이름 그대로, 늘 4개(밤엔 자외선 빼기) | 히어로 D4-2 시안 | `backend/services/hero_stats.py`, `backend/services/feed_service.py`, `frontend/src/b/TodayPage.tsx` |
|
||||||
| [x] | 댓글 좋아요 실패 시 알림 없음 (연결·서버 오류면 줄에 안내, 지워진 댓글이면 목록 새로고침) (화면은 되돌아감) | 댓글 대기 표시 작업 중 발견 | `frontend/src/b/Sheets.tsx` (`CommentRow`) |
|
| [x] | 댓글 좋아요 실패 시 알림 없음 (연결·서버 오류면 줄에 안내, 지워진 댓글이면 목록 새로고침) (화면은 되돌아감) | 댓글 대기 표시 작업 중 발견 | `frontend/src/b/Sheets.tsx` (`CommentRow`) |
|
||||||
| [x] | **[결정 필요]** 노을 탭 재정리에서 정한 것 — ① 노을 등급 '흐림' → '잿빛'(피드 노을 포스트 문구도 같이 바뀜) ② 히어로에 '가장 붉을 때' 시각 하나는 결론('몇 시에')으로 남기고 나머지 시각은 시간표 한 곳에만 ③ '나가 볼 만해요/애매해요/쉬어요' 기준 60·40점, 내일·모레는 10점 넘게 높을 때만 '더 나아요' ④ '쉬어요'면 명소 추천 안 함 ⑤ 블루아워 시각은 시민박명 끝(-6°), 골든아워는 해 고도 6° → 10/7 노을 탭 다시 기획으로 대체: 점수 대신 하늘 상황 5가지, 결론은 상황 기준 | 노을 탭 재정리 | `backend/services/calc/sky_score.py`, `backend/services/sky_service.py`, `frontend/src/b/SkyPage.tsx` |
|
| [x] | **[결정 필요]** 노을 탭 재정리에서 정한 것 — ① 노을 등급 '흐림' → '잿빛'(피드 노을 포스트 문구도 같이 바뀜) ② 히어로에 '가장 붉을 때' 시각 하나는 결론('몇 시에')으로 남기고 나머지 시각은 시간표 한 곳에만 ③ '나가 볼 만해요/애매해요/쉬어요' 기준 60·40점, 내일·모레는 10점 넘게 높을 때만 '더 나아요' ④ '쉬어요'면 명소 추천 안 함 ⑤ 블루아워 시각은 시민박명 끝(-6°), 골든아워는 해 고도 6° → 10/7 노을 탭 다시 기획으로 대체: 점수 대신 하늘 상황 5가지, 결론은 상황 기준 | 노을 탭 재정리 | `backend/services/calc/sky_score.py`, `backend/services/sky_service.py`, `frontend/src/b/SkyPage.tsx` |
|
||||||
| [x] | 노을 히어로 맨 윗줄("오늘 노을 · 구")이 보라 배경 위 흰 13px라 대비 약 3.9:1 (AA 4.5 미달) — 결론·근거·시각·점수는 어두운 상자 안으로 옮김, → 어두운 바탕을 깔아 6.7:1 | 노을 탭 재정리 중 발견 | `frontend/src/b/SkyPage.tsx` |
|
| [x] | 노을 히어로 맨 윗줄("오늘 노을 · 구")이 보라 배경 위 흰 13px라 대비 약 3.9:1 (AA 4.5 미달) — 결론·근거·시각·점수는 어두운 상자 안으로 옮김, → 어두운 바탕을 깔아 6.7:1 | 노을 탭 재정리 중 발견 | `frontend/src/b/SkyPage.tsx` |
|
||||||
@@ -94,13 +113,43 @@
|
|||||||
| [x] | 문화정보원 API 가 `23 LIMITED_NUMBER_OF_SERVICE_REQUESTS_PER_SECOND_EXCEEDS_ERROR` 를 냄 — 쪽 사이 1초, 시도 사이 1초 간격을 둬 17개 시도 수집에서 오류 없음 | 콘서트 수집 점검 중 발견 | `backend/services/external/culture_api.py` |
|
| [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] | `event.kind` 칸 추가(1=축제 2=전시 3=콘서트 4=팝업). 행사 종류(축제·전시·콘서트·팝업)를 구분하는 칸이 없음 — 지금은 `source_id` 접두어로만 구분하고 전시·콘서트는 둘 다 `kcis:` 라 섞임 | 콘서트 수집 | `backend/postgres-init/init.sql` (`event`) |
|
||||||
| [x] | 히어로 두 칸을 상황별로 고름(비→미세먼지→자외선→일교차→체감→불쾌지수, 모자라면 기본값), 아이콘·색도 상태별 (시안 A, 사용자 결정). 히어로 내용 전체 다시 보기 — 아이콘이 뜻과 안 맞음: 불쾌지수에 온도계(불쾌지수는 기온+습도), '지금 비'는 비가 안 와도 우산. 칸마다 무엇을 보여줄지(불쾌지수가 필요한지 포함)부터 다시 정하기 | 사용자 지적 | `frontend/src/b/TodayPage.tsx` (`HeroStat`) |
|
| [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] | 세션 여러 개가 같은 테스트 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` |
|
| [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] | 공유 이미지: 행사 카드의 장소(지도 링크)가 빠짐 — 버튼과 함께 `<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] | 공유 이미지: 행사 사진은 백엔드 `/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] | 공유 이미지: 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] | 공유 이미지: 카드 아래 긴 제목이 한 줄 폭에 눌려 찌그러짐 — 두 줄 나눔 또는 말줄임 | 공유 이미지 점검 (10/7) | `frontend/src/b/storyImage.ts` (`fillText`) |
|
||||||
| [x] | 공유 이미지: 카드 아래 제목을 빼고 주소 알약으로 바꿈 (시안 A, 사용자 결정). 카드 안 제목과 카드 아래 제목이 같아 두 번 보임. 아래 줄을 뺄지, 다른 말(지역·날짜)로 바꿀지 정하기 | 공유 이미지 점검 (10/7) | `frontend/src/b/storyImage.ts` |
|
| [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:45~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` 3) | 10/8 회의 결정 | `backend/services/index_service.py:203` |
|
||||||
|
| [x] | 각 점수를 아침·낮·저녁·밤 시간대별로 → 지금 구간 점수로 순위, 안 겹치는 각은 순위·피드에서 빼고 스토리·전체엔 '지금 아님'. 히어로는 '지금 날씨 점수'(지금 구간). 운영 DB에 `index_score.slots` 칸 추가 필요(배포 때 `init.sql`의 ALTER) | 10/8 회의 결정 | `backend/services/calc/index_calc.py:297` |
|
||||||
|
| [x] | 히어로에 습도·불쾌지수 항상 표시 → 4칸(지금·습도·불쾌지수·상황 1칸, 사용자 결정). 불쾌지수 75 이상이면 경고 색, 상황 칸 후보에서 불쾌지수 뺌 | 10/8 회의 결정 | `frontend/src/b/TodayPage.tsx` (`HeroStat`) |
|
||||||
|
| [x] | 달: '밝기 %' 표시 뺌 → 모양 + 잘 보이는지(구름·뜨고 지는 시각). 모양은 실제 해·달 황경 차이로(예전 계산은 보름을 반나절 일찍 판정). 별보기각은 빛나는 면 × 떠 있는 비율 (사용자 결정) | 10/8 회의 | `backend/services/calc/moon.py` |
|
||||||
|
| [x] | 노을: 점수 강조(히어로에 점수 크게) → 사용자가 '29점이 키포인트 정보냐'고 해 히어로는 다시 시각 크게, 점수는 결론 카드 아래 줄로(10/12). 골든아워·블루아워 설명. 결론은 다음에 오는 것(해 뜨기 전·밤엔 일출, 그 사이엔 노을)으로, 피드 노을 카드도 같이 (사용자 결정 '각·노을도 지금 기준') | 10/8 회의, 사용자 결정 | `frontend/src/b/SkyPage.tsx`, `backend/services/sky_service.py` |
|
||||||
|
| [x] | 주말 예보 UI 개선 → 피드 주말 예보 카드: 토·일 칸을 제목 바로 아래로(칸이 바닥에 붙어 가운데가 비어 오류처럼 보였음), 칸마다 '이날 할 만한 각' 3개 (사용자 의견) | 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` |
|
||||||
|
| [ ] | **[결정 필요]** 각 순위가 점수 순이 아니라 보임 — 순위가 점수 × 중요도라 환기각 92점(하)이 5위, 골프각 89점이 3위, 빨래각 83점이 2위. 각 탭 받침대·스토리에서 높은 점수가 뒤에 있어 어색함. 점수를 순위대로 보여줄지, 중요도 가중을 줄일지 | 화면 직접 확인 중 발견 (10/12) | `backend/services/calc/index_calc.py` (`PRIORITY_WEIGHT`), `frontend/src/b/GakPage.tsx` |
|
||||||
|
| [x] | 노을 점수 29점(잿빛)인데 결론 '나가 볼 만해요' — 결론이 구름 분포만 보고 공기 보정(가시거리·습도)을 안 봤음 → 공기 보정 0.7배 미만이면 결론 한 단계 낮추고 이유에 공기 표시, '해 질 무렵(N시) 예보 기준' 표시. 운영 DB에 `sky_score.air` 칸 추가 필요(배포 때 `init.sql`의 ALTER) | 사용자 지적 (10/12, 분당구) | `backend/services/sky_service.py` (`day_verdict`, `build_plan`), `backend/services/calc/sky_score.py` (`air_note`) |
|
||||||
|
| [x] | 노을 탭 다시 짜기 → 시안 A(사용자 선택): 히어로 '오늘은 애매해요 / 18:10쯤 가장 붉어요 / 쉬운 이유', 내일 안내 바로 아래, 숫자는 '자세히', 시간표에 가장 붉을 때 — 처음 보면 '그래서 가?'에서 멈춤: 히어로 18:00이 무슨 시각인지 없음, 결론 카드가 좋은 말·나쁜 말을 섞음, 구름 %·예보 모델 수 같은 전문 용어, '가장 붉을 때'가 시간표에 없음, '내일이 더 나아요'가 맨 아래. 시안 먼저 보고 결정 | 사용자 지적 (10/12) | `frontend/src/b/SkyPage.tsx`, `backend/services/calc/sky_score.py` (`reason`) |
|
||||||
@@ -142,6 +142,7 @@ class SkyScore(Base):
|
|||||||
situation: Mapped[Optional[int]] = mapped_column(SmallInteger, nullable=True)
|
situation: Mapped[Optional[int]] = mapped_column(SmallInteger, nullable=True)
|
||||||
models_total: Mapped[Optional[int]] = mapped_column(SmallInteger, nullable=True)
|
models_total: Mapped[Optional[int]] = mapped_column(SmallInteger, nullable=True)
|
||||||
models_agree: Mapped[Optional[int]] = mapped_column(SmallInteger, nullable=True)
|
models_agree: Mapped[Optional[int]] = mapped_column(SmallInteger, nullable=True)
|
||||||
|
air: Mapped[Optional[dict]] = mapped_column(JSONB, nullable=True)
|
||||||
|
|
||||||
|
|
||||||
class SunsetSpot(Base):
|
class SunsetSpot(Base):
|
||||||
@@ -183,6 +184,7 @@ class IndexDefinition(Base):
|
|||||||
limit_description: Mapped[Optional[str]] = mapped_column(String(200), nullable=True)
|
limit_description: Mapped[Optional[str]] = mapped_column(String(200), nullable=True)
|
||||||
sentences: Mapped[dict] = mapped_column(JSONB)
|
sentences: Mapped[dict] = mapped_column(JSONB)
|
||||||
sort_order: Mapped[int] = mapped_column(SmallInteger)
|
sort_order: Mapped[int] = mapped_column(SmallInteger)
|
||||||
|
priority: Mapped[int] = mapped_column(SmallInteger, default=2, server_default="2")
|
||||||
|
|
||||||
|
|
||||||
class IndexScore(Base):
|
class IndexScore(Base):
|
||||||
@@ -205,6 +207,7 @@ class IndexScore(Base):
|
|||||||
zero_reason: Mapped[Optional[str]] = mapped_column(String(100), nullable=True)
|
zero_reason: Mapped[Optional[str]] = mapped_column(String(100), nullable=True)
|
||||||
notes: Mapped[dict] = mapped_column(JSONB)
|
notes: Mapped[dict] = mapped_column(JSONB)
|
||||||
estimated: Mapped[bool] = mapped_column(Boolean, default=False)
|
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))
|
computed_at: Mapped[datetime] = mapped_column(DateTime(timezone=True))
|
||||||
|
|
||||||
|
|
||||||
@@ -227,6 +230,9 @@ class Place(Base):
|
|||||||
reason: Mapped[str] = mapped_column(String(60))
|
reason: Mapped[str] = mapped_column(String(60))
|
||||||
best_time: Mapped[str] = mapped_column(String(30))
|
best_time: Mapped[str] = mapped_column(String(30))
|
||||||
sort_order: Mapped[int] = mapped_column(SmallInteger, default=0)
|
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):
|
class Event(Base):
|
||||||
@@ -280,6 +286,8 @@ class Article(Base):
|
|||||||
show_from: Mapped[Optional[date]] = mapped_column(Date, nullable=True)
|
show_from: Mapped[Optional[date]] = mapped_column(Date, nullable=True)
|
||||||
show_until: 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)
|
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):
|
class Post(Base):
|
||||||
@@ -288,6 +296,7 @@ class Post(Base):
|
|||||||
post_id: Mapped[int] = mapped_column(BigInteger, primary_key=True)
|
post_id: Mapped[int] = mapped_column(BigInteger, primary_key=True)
|
||||||
feed_date: Mapped[date] = mapped_column(Date)
|
feed_date: Mapped[date] = mapped_column(Date)
|
||||||
position: Mapped[int] = mapped_column(SmallInteger)
|
position: Mapped[int] = mapped_column(SmallInteger)
|
||||||
|
scope: Mapped[str] = mapped_column(String(2), default="00")
|
||||||
post_type: Mapped[int] = mapped_column(SmallInteger)
|
post_type: Mapped[int] = mapped_column(SmallInteger)
|
||||||
ref_type: Mapped[int] = mapped_column(SmallInteger, default=1)
|
ref_type: Mapped[int] = mapped_column(SmallInteger, default=1)
|
||||||
ref_id: Mapped[Optional[int]] = mapped_column(BigInteger, nullable=True)
|
ref_id: Mapped[Optional[int]] = mapped_column(BigInteger, nullable=True)
|
||||||
|
|||||||
@@ -29,7 +29,7 @@ class Settings(BaseSettings):
|
|||||||
data_go_kr_service_key: str = ""
|
data_go_kr_service_key: str = ""
|
||||||
teams_webhook_url: 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_access_secret: str = ""
|
||||||
jwt_refresh_secret: str = ""
|
jwt_refresh_secret: str = ""
|
||||||
|
|||||||
@@ -9,13 +9,13 @@ from common.database.model.models import Post
|
|||||||
|
|
||||||
|
|
||||||
class FeedCRUD:
|
class FeedCRUD:
|
||||||
async def day(self, s: AsyncSession, day: date) -> list[Post]:
|
async def day(self, s: AsyncSession, day: date, scopes: list[str]) -> list[Post]:
|
||||||
stmt = select(Post).where(Post.feed_date == day, Post.deleted.is_(False)).order_by(Post.position)
|
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())
|
return list((await s.scalars(stmt)).all())
|
||||||
|
|
||||||
async def positions(self, s: AsyncSession, day: date) -> set[int]:
|
async def positions(self, s: AsyncSession, day: date) -> set[tuple[str, int]]:
|
||||||
"""그날 이미 만든 카드 번호. 지운 카드도 넣어 다시 만들지 않게 한다."""
|
"""그날 이미 만든 (scope, 카드 번호). 지운 카드도 넣어 다시 만들지 않게 한다."""
|
||||||
return set((await s.scalars(select(Post.position).where(Post.feed_date == day))).all())
|
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:
|
async def insert_day(self, s: AsyncSession, rows: list[dict]) -> None:
|
||||||
if rows:
|
if rows:
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
from datetime import date
|
from datetime import date
|
||||||
|
|
||||||
from sqlalchemy import func, select
|
from sqlalchemy import func, select, text
|
||||||
from sqlalchemy.dialects.postgresql import insert
|
from sqlalchemy.dialects.postgresql import insert
|
||||||
from sqlalchemy.ext.asyncio import AsyncSession
|
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)
|
stmt = select(func.min(IndexScore.computed_at)).where(IndexScore.region_code == region_code, IndexScore.score_date == day)
|
||||||
return await s.scalar(stmt)
|
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:
|
async def upsert_scores(self, s: AsyncSession, rows: list[dict]) -> None:
|
||||||
if not rows:
|
if not rows:
|
||||||
return
|
return
|
||||||
|
|||||||
@@ -58,5 +58,9 @@ class SkyCRUD:
|
|||||||
)
|
)
|
||||||
return list((await s.scalars(stmt)).all())
|
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]:
|
async def ranking_regions(self, s: AsyncSession) -> list[Region]:
|
||||||
return list((await s.scalars(select(Region).where(Region.is_ranking_spot.is_(True)))).all())
|
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]:
|
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))
|
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]:
|
async def hourly_between(self, s: AsyncSession, region_code: str, start: datetime, end: datetime) -> list[WeatherHourly]:
|
||||||
stmt = (
|
stmt = (
|
||||||
select(WeatherHourly)
|
select(WeatherHourly)
|
||||||
|
|||||||
@@ -26,14 +26,18 @@ class WeekCRUD:
|
|||||||
if rows:
|
if rows:
|
||||||
await s.execute(insert(Holiday).values(rows).on_conflict_do_nothing(index_elements=["holiday_date", "name"]))
|
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]:
|
async def places_in_box(self, s: AsyncSession, lat: float, lon: float, dlat: float, dlon: float) -> list[Place]:
|
||||||
stmt = select(Place).where(Place.region_code.startswith(sido_code)).order_by(Place.sort_order)
|
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())
|
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:
|
async def replace_places(self, s: AsyncSession, rows: list[dict]) -> None:
|
||||||
await s.execute(delete(Place))
|
await s.execute(delete(Place))
|
||||||
if rows:
|
# asyncpg 는 한 문장에 인자 32767개까지라 나눠 넣는다.
|
||||||
await s.execute(insert(Place).values(rows))
|
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]:
|
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)
|
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)
|
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
|
f_near = 1 - 0.8 × low20 / 100
|
||||||
light = 1 - min(low100 + 0.5×mid100, 100) / 100
|
light = 1 - min(low100 + 0.5×mid100, 100) / 100
|
||||||
구름 점수 = 100 × (0.75×f_canvas + 0.25×f_near) × (0.25 + 0.75×light)
|
구름 점수 = 100 × (0.75×f_canvas + 0.25×f_near) × (0.25 + 0.75×light)
|
||||||
점수 = min(100, round(모델 평균 구름 점수 × 공기 보정))
|
점수 = min(100, round(모델 평균 구름 점수 × 공기 보정))
|
||||||
```
|
```
|
||||||
|
|
||||||
- 맑은 하늘(구름 0%)은 40점(은은함)이고, 구름이 몇 %만 있어도 점수가 갈린다. 예전에는 10% 미만을 0.3으로 고정해 맑은 날 전국이 48점에 몰리고, 10%에서 점수가 오히려 떨어졌다.
|
- 맑은 하늘(구름 0%)은 55점(은은함)이고, 구름이 몇 %만 있어도 점수가 갈린다. 예전에는 10% 미만을 0.3으로 고정해 맑은 날 전국이 48점에 몰리고, 10%에서 점수가 오히려 떨어졌다.
|
||||||
- 공기 보정 (`air_factor`, 구 중심 해 질·뜰 무렵 값. 값이 없으면 ×1.0):
|
- 공기 보정 (`air_factor`, 구 중심 해 질·뜰 무렵 값. 값이 없으면 ×1.0). 평소 공기(가시거리 20km·습도 60%)를 ×1.0 으로 두고 좋으면 올리고 나쁘면 내린다. 맑은 날 전국이 한 점수(구름 0% = 55점)에 몰리지 않게 하려는 것:
|
||||||
- 가시거리(`openmeteo_hourly.visibility_m`, 가장 가까운 3시간 구간): 40km 이상 ×1.0 ~ 5km 이하 ×0.6. 뿌연 공기는 색을 흐린다.
|
- 가시거리(`openmeteo_hourly.visibility_m`, 가장 가까운 3시간 구간): 5km 이하 ×0.8 · 20km ×1.0 · 40km 이상 ×1.12, 사이는 직선. 뿌연 공기는 색을 흐리고 맑은 공기는 더 선명하다.
|
||||||
- 습도(`weather_hourly.humidity`, 가장 가까운 정시): 50% 이하 ×1.0 ~ 90% 이상 ×0.75.
|
- 습도(`weather_hourly.humidity`, 가장 가까운 정시): 40% 이하 ×1.06 · 60% ×1.0 · 90% 이상 ×0.85, 사이는 직선.
|
||||||
- 비 갠 뒤: 2~6시간 전 비 확률 60% 이상이고 그 시각 비 확률 40% 미만이면 ×1.15.
|
- 비 갠 뒤: 2~6시간 전 비 확률 60% 이상이고 그 시각 비 확률 40% 미만이면 ×1.15.
|
||||||
|
- 서쪽이 트인 곳 (노을만): 구 중심 20km 안에 서쪽이 트인 노을 명소(`sunset_spot.sort_order` 0 = `sunset_spot.csv`의 `west_open` 1)가 있으면 ×1.1. 산·건물에 가리지 않고 해가 지평선까지 보이는 곳이라서. 명소에는 바다뿐 아니라 강변·높은 전망대도 있어 서울 마포·강남, 대구 수성 같은 내륙 구도 받는다. 일출은 동쪽이 트였는지 데이터가 없어 넣지 않는다.
|
||||||
- 모델마다 따로 계산해 **평균**을 최종 점수로 쓰고, 모델 점수의 표준편차로 신뢰도를 정한다 (8 미만 높음, 15 미만 보통, 그 이상 낮음). 모델이 2개 미만이면 낮음. 신뢰도는 공기 보정 전 구름 점수로 본다.
|
- 모델마다 따로 계산해 **평균**을 최종 점수로 쓰고, 모델 점수의 표준편차로 신뢰도를 정한다 (8 미만 높음, 15 미만 보통, 그 이상 낮음). 모델이 2개 미만이면 낮음. 신뢰도는 공기 보정 전 구름 점수로 본다.
|
||||||
- 등급: 80 이상 붉음, 60 이상 고움, 40 이상 은은함, 그 미만 흐림.
|
- 등급: 80 이상 붉음, 60 이상 고움, 40 이상 은은함, 그 미만 흐림.
|
||||||
|
|
||||||
@@ -140,17 +141,19 @@ light = 1 - min(low100 + 0.5×mid100, 100) / 100
|
|||||||
| 지수 | 새 비중 | 바뀐 기존 비중 (기온·비·바람·습도·공기) | 추가 0점 조건 |
|
| 지수 | 새 비중 | 바뀐 기존 비중 (기온·비·바람·습도·공기) | 추가 0점 조건 |
|
||||||
|---|---|---|---|
|
|---|---|---|---|
|
||||||
| 빨래각 | 햇빛 25 | 15·30·15·10·0 | |
|
| 빨래각 | 햇빛 25 | 15·30·15·10·0 | |
|
||||||
| 멍뭉산책각 | 자외선 5 | 35·25·10·5·15 | 지표면 온도 45° 이상 |
|
| 피크닉각 | 자외선 10, 햇빛 10 | 20·20·15·5·10 | |
|
||||||
| 피크닉각 | 자외선 10 | 25·25·15·5·10 | |
|
| 등산각 | 자외선 10, 햇빛 10, 가시거리 5 | 20·20·15·5·10 | |
|
||||||
| 등산각 | 자외선 5, 가시거리 5 | 25·25·20·5·10 | |
|
| 자전거각 | 자외선 10, 햇빛 10 | 20·20·20·5·10 | 돌풍 15m/s 이상 |
|
||||||
| 러닝각 | 자외선 5 | 35·20·10·15·10 | |
|
| 가드닝각 | 자외선 10, 햇빛 10 | 20·25·10·10·10 | |
|
||||||
| 가드닝각 | 자외선 5 | 25·30·10·15·10 | |
|
| 세차각 | 자외선 10, 햇빛 10 | 5·40·10·10·10 | |
|
||||||
| 별보기각 | 가시거리 15 | 5·10·5·5·15 (시간대 45 그대로) | |
|
| 별보기각 | 가시거리 15 | 5·10·5·5·15 (시간대 45 그대로) | |
|
||||||
| 사진산책각 | 가시거리 10 | 10·25·10·5·10 (시간대 30 그대로) | |
|
| 사진산책각 | 가시거리 10 | 10·25·10·5·10 (시간대 30 그대로) | |
|
||||||
| 자전거각 | | 변경 없음 | 돌풍 15m/s 이상 |
|
| 멍뭉산책각 | | 40·25·10·5·15 | 지표면 온도 45° 이상 |
|
||||||
|
| 러닝각 | | 35·20·10·15·15 | |
|
||||||
| 캠핑각 | | 변경 없음 | 돌풍 15m/s 이상 |
|
| 캠핑각 | | 변경 없음 | 돌풍 15m/s 이상 |
|
||||||
|
|
||||||
- 나머지 17개 지수는 점수가 바뀌지 않는다 (적용 전후 비교로 확인).
|
- 해가 떠 있는 시간대의 야외 활동(피크닉·등산·자전거·가드닝·세차)은 햇빛과 자외선을 **같은 비중(10씩)으로 함께** 둔다. 햇빛은 많을수록, 자외선은 낮을수록 점수가 높다. 자외선만 있으면 흐린 날이 "자외선 낮음 = 좋음"으로 맑은 날보다 높게 나오고, 햇빛만 있으면 한여름 강한 자외선을 놓친다.
|
||||||
|
- 러닝각(6~8·19~22시)·멍뭉산책각(7~9·17~20시)은 자외선을 뺐다. 이른 아침·저녁이라 자외선이 늘 0이라 점수를 가르지 못했다. 그 비중은 러닝은 공기, 멍뭉산책은 기온으로 옮겼다. 사진산책각(일몰 무렵)도 같은 이유로 햇빛·자외선을 두지 않는다.
|
||||||
- 비중·기준값은 초안이다. 수치는 `seed/index_definition.json`에서 바꾸고 `load_seed.py`로 다시 넣는다.
|
- 비중·기준값은 초안이다. 수치는 `seed/index_definition.json`에서 바꾸고 `load_seed.py`로 다시 넣는다.
|
||||||
|
|
||||||
### 3시간 구간을 계산 창에 연결하는 규칙
|
### 3시간 구간을 계산 창에 연결하는 규칙
|
||||||
|
|||||||
@@ -133,6 +133,7 @@ CREATE TABLE IF NOT EXISTS public.sky_score (
|
|||||||
ALTER TABLE public.sky_score ADD COLUMN IF NOT EXISTS situation SMALLINT NULL; -- SkySituation: 1=가려짐 2=낮은 구름 3=물들 구름 적음 4=넓게 물듦 5=두꺼움
|
ALTER TABLE public.sky_score ADD COLUMN IF NOT EXISTS situation SMALLINT NULL; -- SkySituation: 1=가려짐 2=낮은 구름 3=물들 구름 적음 4=넓게 물듦 5=두꺼움
|
||||||
ALTER TABLE public.sky_score ADD COLUMN IF NOT EXISTS models_total SMALLINT NULL; -- 계산에 쓴 예보 모델 수
|
ALTER TABLE public.sky_score ADD COLUMN IF NOT EXISTS models_total SMALLINT NULL; -- 계산에 쓴 예보 모델 수
|
||||||
ALTER TABLE public.sky_score ADD COLUMN IF NOT EXISTS models_agree SMALLINT NULL; -- 그중 같은 하늘 상황을 낸 모델 수
|
ALTER TABLE public.sky_score ADD COLUMN IF NOT EXISTS models_agree SMALLINT NULL; -- 그중 같은 하늘 상황을 낸 모델 수
|
||||||
|
ALTER TABLE public.sky_score ADD COLUMN IF NOT EXISTS air JSONB NULL; -- 해 질(뜰) 무렵 공기 보정 {"factor": 0.5, "visibility_km": 6.5, "humidity": 80}. 결론·이유에 쓴다
|
||||||
|
|
||||||
-- 구별 지수 점수. 오늘·내일·모레와 이번 주말을 날짜별 줄로 둔다 (각 상세 창 칸: 오늘·내일·토·일).
|
-- 구별 지수 점수. 오늘·내일·모레와 이번 주말을 날짜별 줄로 둔다 (각 상세 창 칸: 오늘·내일·토·일).
|
||||||
CREATE TABLE IF NOT EXISTS public.index_score (
|
CREATE TABLE IF NOT EXISTS public.index_score (
|
||||||
@@ -153,12 +154,14 @@ CREATE TABLE IF NOT EXISTS public.index_score (
|
|||||||
zero_reason VARCHAR(100) NULL, -- 0점이 된 이유 (걸리지 않았으면 NULL)
|
zero_reason VARCHAR(100) NULL, -- 0점이 된 이유 (걸리지 않았으면 NULL)
|
||||||
notes JSONB NOT NULL, -- 요소별 근거 문장 {"temp": "체감 21°, 편한 범위 18~24° 안", ...}
|
notes JSONB NOT NULL, -- 요소별 근거 문장 {"temp": "체감 21°, 편한 범위 18~24° 안", ...}
|
||||||
estimated BOOLEAN NOT NULL DEFAULT false, -- 시간별 예보가 없어 중기예보로 낸 예상 점수
|
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(),
|
computed_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||||
PRIMARY KEY (region_code, score_date, index_id)
|
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 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 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 view_score SMALLINT NOT NULL DEFAULT 0;
|
||||||
|
ALTER TABLE public.index_score ADD COLUMN IF NOT EXISTS slots JSONB NOT NULL DEFAULT '{}';
|
||||||
|
|
||||||
-- 피드 카드. 매일 03:00 스케줄러가 그날 카드를 전부 만들고, 볼 때 시간대에 따라 켜고 끄고 순서를 정해 그 구 데이터로 채운다.
|
-- 피드 카드. 매일 03:00 스케줄러가 그날 카드를 전부 만들고, 볼 때 시간대에 따라 켜고 끄고 순서를 정해 그 구 데이터로 채운다.
|
||||||
CREATE TABLE IF NOT EXISTS public.post (
|
CREATE TABLE IF NOT EXISTS public.post (
|
||||||
@@ -175,7 +178,9 @@ CREATE TABLE IF NOT EXISTS public.post (
|
|||||||
end_at TIMESTAMPTZ NULL, -- NULL = 그날 끝까지
|
end_at TIMESTAMPTZ NULL, -- NULL = 그날 끝까지
|
||||||
deleted BOOLEAN NOT NULL DEFAULT FALSE
|
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 +291,13 @@ CREATE TABLE IF NOT EXISTS public.index_definition (
|
|||||||
zero_rules JSONB NOT NULL DEFAULT '[]', -- 바로 0점 조건 [{"field": "rain_prob", "op": ">=", "value": 80}]. 화면 문장은 여기서 만든다
|
zero_rules JSONB NOT NULL DEFAULT '[]', -- 바로 0점 조건 [{"field": "rain_prob", "op": ">=", "value": 80}]. 화면 문장은 여기서 만든다
|
||||||
limit_description VARCHAR(200) NULL, -- 반영 못 한 것
|
limit_description VARCHAR(200) NULL, -- 반영 못 한 것
|
||||||
sentences JSONB NOT NULL DEFAULT '{}', -- 문장 틀 {summary, headline, rabbit, bear, notes}
|
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_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_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 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 (
|
CREATE TABLE IF NOT EXISTS public.sunset_spot (
|
||||||
@@ -303,18 +310,24 @@ CREATE TABLE IF NOT EXISTS public.sunset_spot (
|
|||||||
sort_order SMALLINT NOT NULL DEFAULT 0 -- 0 해 지는 쪽이 트인 곳(먼저), 1 그 밖
|
sort_order SMALLINT NOT NULL DEFAULT 0 -- 0 해 지는 쪽이 트인 곳(먼저), 1 그 밖
|
||||||
);
|
);
|
||||||
|
|
||||||
-- 날씨 맞춤 데이트 명소 (주말·행사 탭).
|
-- 날씨 맞춤 데이트 명소 (주말·행사 탭). 구 중심에서 가까운 곳을 고른다.
|
||||||
CREATE TABLE IF NOT EXISTS public.place (
|
CREATE TABLE IF NOT EXISTS public.place (
|
||||||
place_id SERIAL PRIMARY KEY,
|
place_id SERIAL PRIMARY KEY,
|
||||||
region_code VARCHAR(10) NOT NULL,
|
region_code VARCHAR(10) NOT NULL,
|
||||||
area VARCHAR(20) NOT NULL, -- 동네 묶음 ("성수", "연남·망원")
|
area VARCHAR(20) NOT NULL, -- 동네 묶음 ("성수", "연남·망원") 또는 구 이름
|
||||||
name VARCHAR(40) NOT NULL,
|
name VARCHAR(40) NOT NULL,
|
||||||
is_outdoor BOOLEAN NOT NULL, -- 맑으면 야외, 비 오면 실내를 먼저
|
is_outdoor BOOLEAN NOT NULL, -- 맑으면 야외, 비 오면 실내를 먼저
|
||||||
icon VARCHAR(30) NOT NULL,
|
icon VARCHAR(30) NOT NULL,
|
||||||
reason VARCHAR(60) NOT NULL, -- "돗자리 펴고 낮 피크닉"
|
reason VARCHAR(60) NOT NULL, -- "돗자리 펴고 낮 피크닉"
|
||||||
best_time VARCHAR(30) NOT NULL, -- "낮 12시~4시"
|
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 (
|
CREATE TABLE IF NOT EXISTS public.event (
|
||||||
@@ -374,5 +387,9 @@ CREATE TABLE IF NOT EXISTS public.article (
|
|||||||
body JSONB NOT NULL, -- 문단 목록
|
body JSONB NOT NULL, -- 문단 목록
|
||||||
show_from DATE NULL, -- 계절 소식이 보이는 기간 (NULL = 늘)
|
show_from DATE NULL, -- 계절 소식이 보이는 기간 (NULL = 늘)
|
||||||
show_until DATE 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;
|
||||||
@@ -11,6 +11,7 @@ class Row(WebPacketProtocol):
|
|||||||
label: str
|
label: str
|
||||||
value: str
|
value: str
|
||||||
place: Optional[str] = Field(default=None, description="위치가 정해진 장소면 지도에서 찾을 이름 (앱이 네이버 지도 링크를 건다)")
|
place: Optional[str] = Field(default=None, description="위치가 정해진 장소면 지도에서 찾을 이름 (앱이 네이버 지도 링크를 건다)")
|
||||||
|
level: Optional[int] = Field(default=None, description="자외선 단계 1 낮음 ~ 5 위험. 있으면 앱이 값을 단계 색 칩으로 그린다")
|
||||||
|
|
||||||
|
|
||||||
class HourCell(WebPacketProtocol):
|
class HourCell(WebPacketProtocol):
|
||||||
@@ -64,6 +65,15 @@ class SunsetSlide(WebPacketProtocol):
|
|||||||
grade_label: str
|
grade_label: str
|
||||||
cuts: list[Cut]
|
cuts: list[Cut]
|
||||||
situation: Optional[SkySituation] = Field(default=None, description="하늘 상황. 앱이 카드 하늘 색을 고른다")
|
situation: Optional[SkySituation] = Field(default=None, description="하늘 상황. 앱이 카드 하늘 색을 고른다")
|
||||||
|
headline: Optional[str] = Field(default=None, description="결론 (나가 볼 만해요 · 애매해요 · 쉬어요). 카드 맨 위에 크게")
|
||||||
|
peak_at: Optional[datetime] = Field(default=None, description="가장 붉을 때")
|
||||||
|
|
||||||
|
|
||||||
|
class WeekGak(WebPacketProtocol):
|
||||||
|
index_id: int
|
||||||
|
name: str
|
||||||
|
icon: str
|
||||||
|
score: int
|
||||||
|
|
||||||
|
|
||||||
class WeekDay(WebPacketProtocol):
|
class WeekDay(WebPacketProtocol):
|
||||||
@@ -74,6 +84,7 @@ class WeekDay(WebPacketProtocol):
|
|||||||
temp_min_c: Optional[float] = None
|
temp_min_c: Optional[float] = None
|
||||||
temp_max_c: Optional[float] = None
|
temp_max_c: Optional[float] = None
|
||||||
rain_prob: Optional[int] = None
|
rain_prob: Optional[int] = None
|
||||||
|
gaks: list[WeekGak] = Field(default_factory=list, description="그날 대표 각 (점수 × 중요도 순 3개). 각 점수가 아직 없는 날은 비어 있음")
|
||||||
|
|
||||||
|
|
||||||
class WeekSlide(WebPacketProtocol):
|
class WeekSlide(WebPacketProtocol):
|
||||||
@@ -131,6 +142,9 @@ class TopIndex(WebPacketProtocol):
|
|||||||
score: int
|
score: int
|
||||||
rank: int
|
rank: int
|
||||||
summary: Optional[str] = None
|
summary: Optional[str] = None
|
||||||
|
active: bool = Field(default=True, description="지금 구간이 이 각의 시간대와 겹침. false 면 순위 밖, score 는 하루 점수")
|
||||||
|
slots: dict[str, int] = Field(default_factory=dict, description="오늘 구간별 점수 {morning·day·evening·night: 점수}. 각 시간대와 안 겹치는 구간은 없음")
|
||||||
|
slot_ranks: dict[str, int] = Field(default_factory=dict, description="오늘 구간별 순위 (점수 × 중요도 가중치). 각 시간대와 안 겹치는 구간은 없음")
|
||||||
|
|
||||||
|
|
||||||
class HeroStat(WebPacketProtocol):
|
class HeroStat(WebPacketProtocol):
|
||||||
@@ -145,16 +159,19 @@ class Hero(WebPacketProtocol):
|
|||||||
sky_mode: Literal["morning", "day", "sunset", "night"]
|
sky_mode: Literal["morning", "day", "sunset", "night"]
|
||||||
temp_c: Optional[float] = None
|
temp_c: Optional[float] = None
|
||||||
feels_c: Optional[float] = None
|
feels_c: Optional[float] = None
|
||||||
discomfort: Optional[int] = None
|
humidity: Optional[int] = Field(default=None, description="지금 습도 %. 히어로에 늘 보인다")
|
||||||
|
discomfort: Optional[int] = Field(default=None, description="지금 불쾌지수. 히어로에 늘 보인다")
|
||||||
discomfort_label: Optional[str] = None
|
discomfort_label: Optional[str] = None
|
||||||
rain_2h_text: Optional[str] = None
|
rain_2h_text: Optional[str] = None
|
||||||
will_rain_2h: Optional[bool] = None
|
will_rain_2h: Optional[bool] = None
|
||||||
weather_score: Optional[int] = None
|
weather_score: Optional[int] = None
|
||||||
|
weather_slots: dict[str, int] = Field(default_factory=dict, description="오늘 구간별 날씨 점수 {morning·day·evening·night: 점수}")
|
||||||
top1: Optional[TopIndex] = None
|
top1: Optional[TopIndex] = None
|
||||||
bubble: Optional[str] = None
|
bubble: Optional[str] = None
|
||||||
moon_name: Optional[str] = Field(default=None, description="오늘 밤 달 모양: 삭·초승달·상현달·차오르는 달·보름달·기우는 달·하현달·그믐달")
|
moon_name: Optional[str] = Field(default=None, description="오늘 밤 달 모양: 삭·초승달·상현달·차오르는 달·보름달·기우는 달·하현달·그믐달")
|
||||||
moon_pct: Optional[int] = Field(default=None, description="달이 밝게 보이는 비율 0~100")
|
moon_pct: Optional[int] = Field(default=None, description="달에서 빛나는 면의 비율 0~100 (모양 그림용, 밝기 아님)")
|
||||||
stats: list[HeroStat] = Field(default_factory=list, description="히어로 두 칸. 지금 챙길 것(비·미세먼지·자외선·일교차·체감·불쾌지수) 먼저")
|
stats: list[HeroStat] = Field(default_factory=list, description="히어로 상황 칸 1개. 지금 챙길 것(비·미세먼지·자외선·일교차·체감) 먼저")
|
||||||
|
status: list[HeroStat] = Field(default_factory=list, description="히어로 상태 한 줄: 습도·불쾌지수·자외선(낮에만)·미세먼지 단계 이름. tone=warn 이면 조심(앱이 주황 글자로)")
|
||||||
|
|
||||||
|
|
||||||
class BandEvent(WebPacketProtocol):
|
class BandEvent(WebPacketProtocol):
|
||||||
@@ -171,6 +188,8 @@ class BandArticle(WebPacketProtocol):
|
|||||||
title: str
|
title: str
|
||||||
meta: str
|
meta: str
|
||||||
icon: str
|
icon: str
|
||||||
|
image: Optional[str] = None
|
||||||
|
image_credit: Optional[str] = None
|
||||||
|
|
||||||
|
|
||||||
class Bands(WebPacketProtocol):
|
class Bands(WebPacketProtocol):
|
||||||
|
|||||||
@@ -5,7 +5,8 @@ from fastapi import APIRouter, Depends, Path, Query
|
|||||||
|
|
||||||
from common.enums import ErrorType, IndexCategory
|
from common.enums import ErrorType, IndexCategory
|
||||||
from common.models.errors import error_info
|
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.calc.index_calc import AXES, axis_label, zero_rules_text
|
||||||
from services.index_service import IndexItem, IndexService, slot_label
|
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,
|
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,
|
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],
|
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(
|
async def list_indices(
|
||||||
region: str = Query(..., description="구 행정코드"),
|
region: str = Query(..., description="구 행정코드"),
|
||||||
category: Optional[IndexCategory] = Query(None),
|
category: Optional[IndexCategory] = Query(None),
|
||||||
@@ -32,8 +34,9 @@ async def list_indices(
|
|||||||
if err is not ErrorType.SUCCESS:
|
if err is not ErrorType.SUCCESS:
|
||||||
return Res_IndexList(result=error_info(err))
|
return Res_IndexList(result=error_info(err))
|
||||||
items = [_summary(i, board.day) for i in board.items]
|
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)]
|
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="지수 계산 근거")
|
@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="시간별 예보가 없어 중기예보로 낸 예상 점수")
|
estimated: bool = Field(description="시간별 예보가 없어 중기예보로 낸 예상 점수")
|
||||||
|
|
||||||
|
|
||||||
|
class SlotPoint(WebPacketProtocol):
|
||||||
|
slot: str = Field(description="morning / day / evening / night")
|
||||||
|
label: str = Field(description="아침 / 낮 / 저녁 / 밤")
|
||||||
|
score: int
|
||||||
|
|
||||||
|
|
||||||
class IndexSummary(WebPacketProtocol):
|
class IndexSummary(WebPacketProtocol):
|
||||||
index_id: int
|
index_id: int
|
||||||
code: str
|
code: str
|
||||||
@@ -26,12 +32,15 @@ class IndexSummary(WebPacketProtocol):
|
|||||||
rank: int
|
rank: int
|
||||||
summary: str
|
summary: str
|
||||||
trend: list[TrendPoint] = []
|
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):
|
class Res_IndexList(Res_WebPacketProtocol):
|
||||||
region_code: Optional[str] = None
|
region_code: Optional[str] = None
|
||||||
day: Optional[date] = None
|
day: Optional[date] = None
|
||||||
weather_score: Optional[int] = None
|
weather_score: Optional[int] = Field(default=None, description="지금 날씨 점수 (지금 구간 기준)")
|
||||||
top3: list[IndexSummary] = []
|
top3: list[IndexSummary] = []
|
||||||
items: list[IndexSummary] = []
|
items: list[IndexSummary] = []
|
||||||
|
|
||||||
|
|||||||
@@ -17,6 +17,8 @@ class ArticleSummary(WebPacketProtocol):
|
|||||||
title: str
|
title: str
|
||||||
read_minutes: int
|
read_minutes: int
|
||||||
icon: str
|
icon: str
|
||||||
|
image: Optional[str] = None # 있으면 아이콘 대신 사진
|
||||||
|
image_credit: Optional[str] = None # 사진 출처 표기 ("ⓒ저작자 · CC BY-SA 4.0")
|
||||||
|
|
||||||
|
|
||||||
class Res_SeasonWeek(Res_WebPacketProtocol):
|
class Res_SeasonWeek(Res_WebPacketProtocol):
|
||||||
|
|||||||
@@ -12,7 +12,8 @@ router = APIRouter(prefix="/v1/season", tags=["season"])
|
|||||||
|
|
||||||
|
|
||||||
def _summary(a: Article) -> ArticleSummary:
|
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="이번 주 계절 책: 시, 절기, 계절 소식")
|
@router.get("/week", response_model=Res_SeasonWeek, response_model_exclude_none=True, summary="이번 주 계절 책: 시, 절기, 계절 소식")
|
||||||
|
|||||||
@@ -11,6 +11,7 @@ class BestTime(WebPacketProtocol):
|
|||||||
at: datetime
|
at: datetime
|
||||||
kind: str
|
kind: str
|
||||||
label: str
|
label: str
|
||||||
|
end: Optional[datetime] = Field(default=None, description="구간이면 끝 시각 (골든아워·블루아워)")
|
||||||
|
|
||||||
|
|
||||||
class SkyScoreData(WebPacketProtocol):
|
class SkyScoreData(WebPacketProtocol):
|
||||||
@@ -42,6 +43,8 @@ class PlanSpot(WebPacketProtocol):
|
|||||||
|
|
||||||
|
|
||||||
class SkyPlanData(WebPacketProtocol):
|
class SkyPlanData(WebPacketProtocol):
|
||||||
|
kind: Literal["sunset", "sunrise"] = Field(description="다음에 오는 것: 해 뜨기 전·밤엔 일출, 그 사이엔 노을")
|
||||||
|
title: str = Field(description="하늘이 어떻게 보일지 한 문장 (오늘 노을은 물들긴 하는데 색이 흐릴 거예요). 히어로 제목")
|
||||||
day: date
|
day: date
|
||||||
when: str
|
when: str
|
||||||
verdict: Literal["go", "maybe", "rest"]
|
verdict: Literal["go", "maybe", "rest"]
|
||||||
@@ -66,6 +69,7 @@ class Res_Sky(Res_WebPacketProtocol):
|
|||||||
days: list[SkyScoreData] = []
|
days: list[SkyScoreData] = []
|
||||||
spots: list[SpotData] = []
|
spots: list[SpotData] = []
|
||||||
plan: Optional[SkyPlanData] = None
|
plan: Optional[SkyPlanData] = None
|
||||||
|
plans: list[SkyPlanData] = Field(default=[], description="plan 과 같은 종류로 아직 안 끝난 날 최대 3일 (날짜 타일, 누르면 그날로)")
|
||||||
|
|
||||||
|
|
||||||
class RankData(WebPacketProtocol):
|
class RankData(WebPacketProtocol):
|
||||||
|
|||||||
@@ -26,6 +26,7 @@ def _situation(x: SkyScore) -> str | None:
|
|||||||
|
|
||||||
def _plan(p: SkyPlan) -> SkyPlanData:
|
def _plan(p: SkyPlan) -> SkyPlanData:
|
||||||
return SkyPlanData(
|
return SkyPlanData(
|
||||||
|
kind="sunrise" if p.kind is SkyType.SUNRISE else "sunset", title=p.title,
|
||||||
day=p.day, when=p.when, verdict=p.verdict, headline=p.headline, reason=p.reason, score=p.score, grade_label=p.grade_label,
|
day=p.day, when=p.when, verdict=p.verdict, headline=p.headline, reason=p.reason, score=p.score, grade_label=p.grade_label,
|
||||||
situation_label=p.situation_label, models_total=p.models_total, models_agree=p.models_agree,
|
situation_label=p.situation_label, models_total=p.models_total, models_agree=p.models_agree,
|
||||||
best_at=p.best_at, spot=PlanSpot(name=p.spot.spot.name, distance_km=p.spot.distance_km) if p.spot else None,
|
best_at=p.best_at, spot=PlanSpot(name=p.spot.spot.name, distance_km=p.spot.distance_km) if p.spot else None,
|
||||||
@@ -48,6 +49,7 @@ async def get_sky(region: str = Query(..., description="구 행정코드"), serv
|
|||||||
for i, s in enumerate(view.spots)
|
for i, s in enumerate(view.spots)
|
||||||
],
|
],
|
||||||
plan=_plan(view.plan) if view.plan else None,
|
plan=_plan(view.plan) if view.plan else None,
|
||||||
|
plans=[_plan(p) for p in view.plans],
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -97,7 +97,7 @@ async def get_watch_summary(
|
|||||||
res.warning = now_w.warnings[0].text if now_w.warnings else None
|
res.warning = now_w.warnings[0].text if now_w.warnings else None
|
||||||
|
|
||||||
if board is not 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]
|
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}
|
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]
|
res.picks = [_top(by_code[c]) for c in codes if c in by_code]
|
||||||
|
|||||||
@@ -32,6 +32,9 @@ class PlaceData(WebPacketProtocol):
|
|||||||
reason: str
|
reason: str
|
||||||
best_time: str
|
best_time: str
|
||||||
is_good: bool
|
is_good: bool
|
||||||
|
distance_km: float # 구 중심에서 떨어진 거리
|
||||||
|
image: Optional[str] = None
|
||||||
|
image_credit: Optional[str] = None # 사진 출처 표기 ("ⓒ한국관광공사")
|
||||||
|
|
||||||
|
|
||||||
class Res_PlaceList(Res_WebPacketProtocol):
|
class Res_PlaceList(Res_WebPacketProtocol):
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ from common.utils.kma_time import now_kst
|
|||||||
from router.v1.week.protocol import (
|
from router.v1.week.protocol import (
|
||||||
DayData, EventData, PlaceData, Res_EventList, Res_PlaceList, Res_Week, Res_WeekRanking, WeekRankDay, WeekRankItem,
|
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
|
from services.weekend_rank import WeekendRank, rank_days, weekend_days
|
||||||
|
|
||||||
router = APIRouter(prefix="/v1/week", tags=["week"])
|
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(
|
async def list_places(
|
||||||
region: str = Query(...), day: Optional[date] = Query(None, description="기본은 오늘"), area: Optional[str] = Query(None),
|
region: str = Query(...), day: Optional[date] = Query(None, description="기본은 오늘"), area: Optional[str] = Query(None),
|
||||||
service: WeekService = Depends(),
|
service: WeekService = Depends(),
|
||||||
) -> Res_PlaceList:
|
) -> Res_PlaceList:
|
||||||
target = day or now_kst().date()
|
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:
|
if err is not ErrorType.SUCCESS:
|
||||||
return Res_PlaceList(result=error_info(err))
|
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=[
|
return Res_PlaceList(areas=areas, rainy=rainy, places=[
|
||||||
PlaceData(
|
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,
|
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
|
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.data_go_kr import DataGoKrNotConfigured, DataGoKrRequestFailed
|
||||||
from services.external.open_meteo import OpenMeteoRequestFailed, fetch_weather, parse_weather
|
from services.external.open_meteo import OpenMeteoRequestFailed, fetch_weather, parse_weather
|
||||||
from services.feed_service import build_feed_day, clear_feed_cache
|
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
|
from services.weekend_rank import WeekendRank
|
||||||
|
|
||||||
_POPGA_SEEN = "popga:lastmod" # {팝업 id: 마지막으로 읽은 lastmod}, 바뀐 페이지만 다시 읽는다
|
_POPGA_SEEN = "popga:lastmod:v2" # {팝업 id: 마지막으로 읽은 lastmod}, 바뀐 페이지만 다시 읽는다. 받는 분류가 바뀌면 이름을 바꿔 처음부터 읽는다
|
||||||
_POPGA_BATCH = 100
|
_POPGA_BATCH = 100
|
||||||
EVENTS_DONE = "events:collected" # 행사 수집을 마친 표시. 7일 유지, 없으면 worker 가 켜질 때 한 번 돈다
|
EVENTS_DONE = "events:collected" # 행사 수집을 마친 표시. 7일 유지, 없으면 worker 가 켜질 때 한 번 돈다
|
||||||
_EVENTS_TTL_SEC = 7 * 86400
|
_EVENTS_TTL_SEC = 7 * 86400
|
||||||
@@ -98,13 +98,14 @@ async def refresh_openmeteo_weather() -> ErrorType:
|
|||||||
|
|
||||||
|
|
||||||
async def build_today_feed() -> 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()
|
await clear_feed_cache()
|
||||||
return err
|
return err
|
||||||
|
|
||||||
|
|
||||||
async def _save_popups(rows: list[dict], seen: dict[str, str]) -> ErrorType:
|
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)])
|
err = await DB_SESSION_MNG.execute_lambda_run([lambda s: WeekCRUD().upsert_events(s, rows)])
|
||||||
if err is ErrorType.SUCCESS and seen:
|
if err is ErrorType.SUCCESS and seen:
|
||||||
await REDIS.conn.hset(_POPGA_SEEN, mapping=seen)
|
await REDIS.conn.hset(_POPGA_SEEN, mapping=seen)
|
||||||
@@ -147,7 +148,7 @@ async def refresh_popups() -> ErrorType:
|
|||||||
|
|
||||||
|
|
||||||
async def _popup_count() -> int:
|
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))
|
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
|
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 json
|
||||||
import os
|
import os
|
||||||
|
import sys
|
||||||
|
|
||||||
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
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")
|
SEED = os.path.join(ROOT, "seed", "index_definition.json")
|
||||||
OUT = os.path.join(os.path.dirname(ROOT), "docs", "각_계산기준.md")
|
OUT = os.path.join(os.path.dirname(ROOT), "docs", "각_계산기준.md")
|
||||||
|
|
||||||
CAT = {1: "밖에서 놀기", 2: "먹고 마시기", 3: "집안일", 4: "생활 고민"}
|
CAT = {1: "밖에서 놀기", 2: "먹고 마시기", 3: "집안일", 4: "생활 고민"}
|
||||||
|
PRIO = {1: "상", 2: "중", 3: "하"}
|
||||||
WD = {"mon": "월", "tue": "화", "wed": "수", "thu": "목", "fri": "금", "sat": "토", "sun": "일", "holiday": "공휴일", "default": "그 외"}
|
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": ("지면 온도", "°")}
|
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점")
|
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)"),
|
("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)"),
|
("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)"),
|
("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.75 + 0.25 × 가장 낮은 요소 점수 ÷ 100). 비중 0%인 요소는 '가장 낮은 요소'에서 뺍니다. 가장 낮은 요소가 0점이면 25%가 깎입니다.")
|
||||||
P("- '0점 조건'에 걸리면 0점, '최대 N점' 조건에 걸리면 N점을 넘지 못합니다.")
|
P("- '0점 조건'에 걸리면 0점, '최대 N점' 조건에 걸리면 N점을 넘지 못합니다.")
|
||||||
P("- 시간대가 여러 개면 그중 가장 좋은 시간대 점수를 씁니다.")
|
P("- 시간대가 여러 개면 그중 가장 좋은 시간대 점수를 씁니다.")
|
||||||
P("- 미세먼지는 모든 각이 같은 규칙입니다: 초미세먼지 15㎍/㎥ 이하 100점 → 75㎍/㎥ 이상 0점.")
|
P("- 미세먼지는 초미세먼지 15㎍/㎥ 이하 100점 → 75㎍/㎥ 이상 0점입니다. 집콕각처럼 규칙을 따로 적은 각만 거꾸로(탁할수록 좋음) 셉니다.")
|
||||||
P("- 바람·미세먼지·노을 정보가 없으면 70점으로 둡니다.\n")
|
P("- 바람·미세먼지·노을 정보가 없으면 70점으로 둡니다.")
|
||||||
|
P("- 순위는 점수 × 중요도 가중치(" + " · ".join(f"{PRIO[k]} {v}" for k, v in PRIORITY_WEIGHT.items()) + ")로 정합니다. 화면에 보이는 점수는 그대로입니다.\n")
|
||||||
P("## 한눈에 보기\n")
|
P("## 한눈에 보기\n")
|
||||||
P("| 순서 | 각 | 코드 | 분류 | 시간대 | 기온 | 비 | 바람 | 습도 | 미세먼지 | 시간 | 재미 각 | 계절 핵심 |")
|
P("| 순서 | 각 | 코드 | 분류 | 중요도 | 시간대 | 기온 | 비 | 바람 | 습도 | 미세먼지 | 시간 | 재미 각 | 계절 핵심 |")
|
||||||
P("|---:|---|---|---|---|---:|---:|---:|---:|---:|---:|:---:|:---:|")
|
P("|---:|---|---|---|:---:|---|---:|---:|---:|---:|---:|---:|:---:|:---:|")
|
||||||
for x in sorted(d, key=lambda x: x["sort_order"]):
|
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"))
|
+ " | ".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 ''} |")
|
+ f" | {'○' if x['is_fun'] else ''} | {'○' if x['is_core'] else ''} |")
|
||||||
P("\n## 각별 자세히\n")
|
P("\n## 각별 자세히\n")
|
||||||
for x in sorted(d, key=lambda x: x["sort_order"]):
|
for x in sorted(d, key=lambda x: x["sort_order"]):
|
||||||
P(f"### {x['name']} (`{x['code']}`)\n")
|
P(f"### {x['name']} (`{x['code']}`)\n")
|
||||||
P(f"- 설명: {x['description']}")
|
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(f"- 시간대: {' / '.join(win(w) for w in x['windows'])}")
|
||||||
P("- 요소별 규칙 (비중):")
|
P("- 요소별 규칙 (비중):")
|
||||||
for key, label, fn in AX:
|
for key, label, fn in AX:
|
||||||
w = x.get("weight_" + key, 0)
|
w = x.get("weight_" + key, 0)
|
||||||
if key in _OPTIONAL and not w:
|
if key in _OPTIONAL and not w:
|
||||||
continue
|
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}")
|
P(f" - {label} {w}%: {rule}")
|
||||||
zs = [zero(z) for z in x["zero_rules"]]
|
zs = [zero(z) for z in x["zero_rules"]]
|
||||||
P(f"- 점수 깎이는 조건: {', '.join(zs) if zs else '없음'}")
|
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}
|
"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")
|
for r in _read("sunset_spot.csv")
|
||||||
]
|
]
|
||||||
|
# 손으로 고른 place.csv 와 TourAPI 에서 모은 place_tourapi.csv (scripts/fetch_date_places.py). source 는 출처 기록용.
|
||||||
places = [
|
places = [
|
||||||
{"region_code": code_by_name[r["region_name"]], "area": r["area"], "name": r["name"], "is_outdoor": r["is_outdoor"] == "1",
|
{"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"])}
|
"icon": r["icon"], "reason": r["reason"], "best_time": r["best_time"], "sort_order": int(r.get("sort_order") or 0),
|
||||||
for r in _read("place.csv")
|
"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 가 없는 줄만 이 파일로 바꿔 넣는다.
|
# 직접 넣는 행사 (TourAPI 에 없는 것). source_id 가 없는 줄만 이 파일로 바꿔 넣는다.
|
||||||
events = [
|
events = [
|
||||||
@@ -70,7 +72,8 @@ async def main() -> int:
|
|||||||
]
|
]
|
||||||
articles = [
|
articles = [
|
||||||
{**a, "show_from": date.fromisoformat(a["show_from"]) if a["show_from"] else None,
|
{**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")
|
for a in _json("article.json")
|
||||||
]
|
]
|
||||||
weeks = _json("season_week.json")
|
weeks = _json("season_week.json")
|
||||||
|
|||||||
@@ -5,6 +5,8 @@
|
|||||||
"title": "설악산 첫 단풍, 절정은 언제?",
|
"title": "설악산 첫 단풍, 절정은 언제?",
|
||||||
"read_minutes": 3,
|
"read_minutes": 3,
|
||||||
"icon": "maple",
|
"icon": "maple",
|
||||||
|
"image_url": "/season/maple.jpg",
|
||||||
|
"image_credit": "ⓒJoycekim77 · CC BY-SA 3.0",
|
||||||
"show_from": "2026-09-20",
|
"show_from": "2026-09-20",
|
||||||
"show_until": "2026-10-25",
|
"show_until": "2026-10-25",
|
||||||
"body": [
|
"body": [
|
||||||
@@ -20,6 +22,8 @@
|
|||||||
"title": "하늘공원 억새가 반짝이는 시간",
|
"title": "하늘공원 억새가 반짝이는 시간",
|
||||||
"read_minutes": 2,
|
"read_minutes": 2,
|
||||||
"icon": "sheaf",
|
"icon": "sheaf",
|
||||||
|
"image_url": "/season/reed.jpg",
|
||||||
|
"image_credit": "ⓒJocelyndurrey · CC BY-SA 4.0",
|
||||||
"show_from": "2026-09-25",
|
"show_from": "2026-09-25",
|
||||||
"show_until": "2026-10-31",
|
"show_until": "2026-10-31",
|
||||||
"body": [
|
"body": [
|
||||||
@@ -34,6 +38,8 @@
|
|||||||
"title": "대관령 첫서리, 서울은 한 달 뒤",
|
"title": "대관령 첫서리, 서울은 한 달 뒤",
|
||||||
"read_minutes": 2,
|
"read_minutes": 2,
|
||||||
"icon": "snow",
|
"icon": "snow",
|
||||||
|
"image_url": "/season/frost.jpg",
|
||||||
|
"image_credit": "ⓒSally V · CC BY-SA 4.0",
|
||||||
"show_from": "2026-10-01",
|
"show_from": "2026-10-01",
|
||||||
"show_until": "2026-11-15",
|
"show_until": "2026-11-15",
|
||||||
"body": [
|
"body": [
|
||||||
@@ -77,6 +83,7 @@
|
|||||||
"title": "노을은 왜 해 지고 15분 뒤가 더 붉을까?",
|
"title": "노을은 왜 해 지고 15분 뒤가 더 붉을까?",
|
||||||
"read_minutes": 3,
|
"read_minutes": 3,
|
||||||
"icon": "sunset",
|
"icon": "sunset",
|
||||||
|
"image_url": "/season/sunset.jpg",
|
||||||
"show_from": null,
|
"show_from": null,
|
||||||
"show_until": null,
|
"show_until": null,
|
||||||
"body": [
|
"body": [
|
||||||
@@ -91,6 +98,7 @@
|
|||||||
"title": "비 확률 30%면 우산을 챙겨야 할까?",
|
"title": "비 확률 30%면 우산을 챙겨야 할까?",
|
||||||
"read_minutes": 2,
|
"read_minutes": 2,
|
||||||
"icon": "umbrella",
|
"icon": "umbrella",
|
||||||
|
"image_url": "/season/umbrella.jpg",
|
||||||
"show_from": null,
|
"show_from": null,
|
||||||
"show_until": null,
|
"show_until": null,
|
||||||
"body": [
|
"body": [
|
||||||
@@ -251,6 +259,7 @@
|
|||||||
"title": "햇밤, 바로 먹을까 두었다 먹을까?",
|
"title": "햇밤, 바로 먹을까 두었다 먹을까?",
|
||||||
"read_minutes": 2,
|
"read_minutes": 2,
|
||||||
"icon": "chestnut",
|
"icon": "chestnut",
|
||||||
|
"image_url": "/season/chestnut_new.jpg",
|
||||||
"show_from": "2026-09-15",
|
"show_from": "2026-09-15",
|
||||||
"show_until": "2026-10-31",
|
"show_until": "2026-10-31",
|
||||||
"body": [
|
"body": [
|
||||||
@@ -281,6 +290,8 @@
|
|||||||
"title": "은행 냄새 나는 길, 언제까지일까",
|
"title": "은행 냄새 나는 길, 언제까지일까",
|
||||||
"read_minutes": 2,
|
"read_minutes": 2,
|
||||||
"icon": "fallen_leaf",
|
"icon": "fallen_leaf",
|
||||||
|
"image_url": "/season/ginkgo.jpg",
|
||||||
|
"image_credit": "ⓒKorea.net · CC BY-SA 2.0",
|
||||||
"show_from": "2026-10-10",
|
"show_from": "2026-10-10",
|
||||||
"show_until": "2026-11-15",
|
"show_until": "2026-11-15",
|
||||||
"body": [
|
"body": [
|
||||||
@@ -296,6 +307,8 @@
|
|||||||
"title": "군고구마가 생각나는 첫 추위",
|
"title": "군고구마가 생각나는 첫 추위",
|
||||||
"read_minutes": 2,
|
"read_minutes": 2,
|
||||||
"icon": "sweet_potato",
|
"icon": "sweet_potato",
|
||||||
|
"image_url": "/season/sweet_potato.jpg",
|
||||||
|
"image_credit": "ⓒ국립국어원 · CC BY-SA 2.0 KR",
|
||||||
"show_from": "2026-10-15",
|
"show_from": "2026-10-15",
|
||||||
"show_until": "2026-12-31",
|
"show_until": "2026-12-31",
|
||||||
"body": [
|
"body": [
|
||||||
@@ -311,6 +324,7 @@
|
|||||||
"title": "노지 귤이 나오기 시작해요",
|
"title": "노지 귤이 나오기 시작해요",
|
||||||
"read_minutes": 2,
|
"read_minutes": 2,
|
||||||
"icon": "tangerine",
|
"icon": "tangerine",
|
||||||
|
"image_url": "/season/tangerine.jpg",
|
||||||
"show_from": "2026-10-20",
|
"show_from": "2026-10-20",
|
||||||
"show_until": "2026-12-31",
|
"show_until": "2026-12-31",
|
||||||
"body": [
|
"body": [
|
||||||
@@ -326,6 +340,8 @@
|
|||||||
"title": "부사 사과가 나오는 때",
|
"title": "부사 사과가 나오는 때",
|
||||||
"read_minutes": 2,
|
"read_minutes": 2,
|
||||||
"icon": "apple",
|
"icon": "apple",
|
||||||
|
"image_url": "/season/apple_fuji.jpg",
|
||||||
|
"image_credit": "ⓒAomorikuma · CC BY-SA 4.0",
|
||||||
"show_from": "2026-10-20",
|
"show_from": "2026-10-20",
|
||||||
"show_until": "2026-11-30",
|
"show_until": "2026-11-30",
|
||||||
"body": [
|
"body": [
|
||||||
@@ -341,6 +357,7 @@
|
|||||||
"title": "김장, 언제 하면 좋을까?",
|
"title": "김장, 언제 하면 좋을까?",
|
||||||
"read_minutes": 2,
|
"read_minutes": 2,
|
||||||
"icon": "kimchi",
|
"icon": "kimchi",
|
||||||
|
"image_url": "/season/kimjang.jpg",
|
||||||
"show_from": "2026-11-01",
|
"show_from": "2026-11-01",
|
||||||
"show_until": "2026-12-15",
|
"show_until": "2026-12-15",
|
||||||
"body": [
|
"body": [
|
||||||
|
|||||||
@@ -70,7 +70,8 @@
|
|||||||
"60": "꽤 괜찮은 저녁! 바람만 살랑 불어 주면 딱이에요.",
|
"60": "꽤 괜찮은 저녁! 바람만 살랑 불어 주면 딱이에요.",
|
||||||
"80": "18~24°에 바람 살랑, 비 걱정 없음! 오늘은 무조건 바깥 자리 🍻"
|
"80": "18~24°에 바람 살랑, 비 걱정 없음! 오늘은 무조건 바깥 자리 🍻"
|
||||||
},
|
},
|
||||||
"sort_order": 1
|
"sort_order": 1,
|
||||||
|
"priority": 2
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"code": "picnic",
|
"code": "picnic",
|
||||||
@@ -87,13 +88,13 @@
|
|||||||
"to": 16
|
"to": 16
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"weight_temp": 25,
|
"weight_temp": 20,
|
||||||
"weight_rain": 25,
|
"weight_rain": 20,
|
||||||
"weight_wind": 15,
|
"weight_wind": 15,
|
||||||
"weight_humidity": 5,
|
"weight_humidity": 5,
|
||||||
"weight_air": 10,
|
"weight_air": 10,
|
||||||
"weight_uv": 10,
|
"weight_uv": 10,
|
||||||
"weight_sun": 0,
|
"weight_sun": 10,
|
||||||
"weight_view": 0,
|
"weight_view": 0,
|
||||||
"weight_time": 10,
|
"weight_time": 10,
|
||||||
"factor_rules": {
|
"factor_rules": {
|
||||||
@@ -126,6 +127,10 @@
|
|||||||
"uv": {
|
"uv": {
|
||||||
"zero": 8,
|
"zero": 8,
|
||||||
"full": 2
|
"full": 2
|
||||||
|
},
|
||||||
|
"sun": {
|
||||||
|
"zero": 0.2,
|
||||||
|
"full": 0.8
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"zero_rules": [
|
"zero_rules": [
|
||||||
@@ -142,7 +147,8 @@
|
|||||||
"60": "돗자리 펴기 괜찮은 날! 바람막이 하나면 완벽해요.",
|
"60": "돗자리 펴기 괜찮은 날! 바람막이 하나면 완벽해요.",
|
||||||
"80": "20~26°에 바람 잔잔, 김밥 싸서 당장 출발! 🧺"
|
"80": "20~26°에 바람 잔잔, 김밥 싸서 당장 출발! 🧺"
|
||||||
},
|
},
|
||||||
"sort_order": 2
|
"sort_order": 2,
|
||||||
|
"priority": 1
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"code": "chimaek",
|
"code": "chimaek",
|
||||||
@@ -214,7 +220,8 @@
|
|||||||
"60": "바깥 테이블 괜찮아요! 얇은 겉옷 하나만 챙겨요.",
|
"60": "바깥 테이블 괜찮아요! 얇은 겉옷 하나만 챙겨요.",
|
||||||
"80": "20~27°의 선선한 저녁, 치킨에 맥주 부르는 날 🍗"
|
"80": "20~27°의 선선한 저녁, 치킨에 맥주 부르는 날 🍗"
|
||||||
},
|
},
|
||||||
"sort_order": 3
|
"sort_order": 3,
|
||||||
|
"priority": 2
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"code": "walk",
|
"code": "walk",
|
||||||
@@ -284,7 +291,8 @@
|
|||||||
"60": "한 바퀴 돌기 좋은 저녁! 이어폰 챙겨서 가볍게 나가요.",
|
"60": "한 바퀴 돌기 좋은 저녁! 이어폰 챙겨서 가볍게 나가요.",
|
||||||
"80": "15~23°에 공기 맑고 바람 살랑, 동네 한 바퀴 무조건 🚶"
|
"80": "15~23°에 공기 맑고 바람 살랑, 동네 한 바퀴 무조건 🚶"
|
||||||
},
|
},
|
||||||
"sort_order": 4
|
"sort_order": 4,
|
||||||
|
"priority": 1
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"code": "vent",
|
"code": "vent",
|
||||||
@@ -359,7 +367,8 @@
|
|||||||
"60": "열어도 괜찮아요. 맞바람 나게 10분이면 충분!",
|
"60": "열어도 괜찮아요. 맞바람 나게 10분이면 충분!",
|
||||||
"80": "공기 맑고 바람도 적당, 창문 활짝 열 시간 🌬️"
|
"80": "공기 맑고 바람도 적당, 창문 활짝 열 시간 🌬️"
|
||||||
},
|
},
|
||||||
"sort_order": 5
|
"sort_order": 5,
|
||||||
|
"priority": 3
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"code": "hiking",
|
"code": "hiking",
|
||||||
@@ -376,13 +385,13 @@
|
|||||||
"to": 12
|
"to": 12
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"weight_temp": 25,
|
"weight_temp": 20,
|
||||||
"weight_rain": 25,
|
"weight_rain": 20,
|
||||||
"weight_wind": 20,
|
"weight_wind": 15,
|
||||||
"weight_humidity": 5,
|
"weight_humidity": 5,
|
||||||
"weight_air": 10,
|
"weight_air": 10,
|
||||||
"weight_uv": 5,
|
"weight_uv": 10,
|
||||||
"weight_sun": 0,
|
"weight_sun": 10,
|
||||||
"weight_view": 5,
|
"weight_view": 5,
|
||||||
"weight_time": 5,
|
"weight_time": 5,
|
||||||
"factor_rules": {
|
"factor_rules": {
|
||||||
@@ -420,6 +429,10 @@
|
|||||||
"view": {
|
"view": {
|
||||||
"zero": 5,
|
"zero": 5,
|
||||||
"full": 20
|
"full": 20
|
||||||
|
},
|
||||||
|
"sun": {
|
||||||
|
"zero": 0.2,
|
||||||
|
"full": 0.8
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"zero_rules": [
|
"zero_rules": [
|
||||||
@@ -441,7 +454,8 @@
|
|||||||
"60": "오를 만해요! 바람막이 챙기고 일찍 출발해요.",
|
"60": "오를 만해요! 바람막이 챙기고 일찍 출발해요.",
|
||||||
"80": "산 위도 선선하고 바람 잔잔, 정상 인증각 ⛰️"
|
"80": "산 위도 선선하고 바람 잔잔, 정상 인증각 ⛰️"
|
||||||
},
|
},
|
||||||
"sort_order": 6
|
"sort_order": 6,
|
||||||
|
"priority": 1
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"code": "carwash",
|
"code": "carwash",
|
||||||
@@ -460,12 +474,12 @@
|
|||||||
}
|
}
|
||||||
],
|
],
|
||||||
"weight_temp": 5,
|
"weight_temp": 5,
|
||||||
"weight_rain": 60,
|
"weight_rain": 40,
|
||||||
"weight_wind": 10,
|
"weight_wind": 10,
|
||||||
"weight_humidity": 10,
|
"weight_humidity": 10,
|
||||||
"weight_air": 10,
|
"weight_air": 10,
|
||||||
"weight_uv": 0,
|
"weight_uv": 10,
|
||||||
"weight_sun": 0,
|
"weight_sun": 10,
|
||||||
"weight_view": 0,
|
"weight_view": 0,
|
||||||
"weight_time": 5,
|
"weight_time": 5,
|
||||||
"factor_rules": {
|
"factor_rules": {
|
||||||
@@ -488,6 +502,14 @@
|
|||||||
"time": {
|
"time": {
|
||||||
"type": "fixed",
|
"type": "fixed",
|
||||||
"value": 100
|
"value": 100
|
||||||
|
},
|
||||||
|
"uv": {
|
||||||
|
"zero": 8,
|
||||||
|
"full": 2
|
||||||
|
},
|
||||||
|
"sun": {
|
||||||
|
"zero": 0.2,
|
||||||
|
"full": 0.8
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"zero_rules": [
|
"zero_rules": [
|
||||||
@@ -505,7 +527,8 @@
|
|||||||
"60": "세차해도 괜찮아요. 먼지는 좀 붙을 수 있어요.",
|
"60": "세차해도 괜찮아요. 먼지는 좀 붙을 수 있어요.",
|
||||||
"80": "비 걱정 없고 공기도 맑아요. 반짝반짝 오래가는 날 ✨"
|
"80": "비 걱정 없고 공기도 맑아요. 반짝반짝 오래가는 날 ✨"
|
||||||
},
|
},
|
||||||
"sort_order": 7
|
"sort_order": 7,
|
||||||
|
"priority": 3
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"code": "camping",
|
"code": "camping",
|
||||||
@@ -579,7 +602,8 @@
|
|||||||
"60": "하룻밤 괜찮아요. 새벽엔 쌀쌀하니 담요 챙기기!",
|
"60": "하룻밤 괜찮아요. 새벽엔 쌀쌀하니 담요 챙기기!",
|
||||||
"80": "밤새 12~22°에 바람 잔잔, 불멍하기 딱 좋은 밤 🔥"
|
"80": "밤새 12~22°에 바람 잔잔, 불멍하기 딱 좋은 밤 🔥"
|
||||||
},
|
},
|
||||||
"sort_order": 8
|
"sort_order": 8,
|
||||||
|
"priority": 1
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"code": "running",
|
"code": "running",
|
||||||
@@ -604,8 +628,8 @@
|
|||||||
"weight_rain": 20,
|
"weight_rain": 20,
|
||||||
"weight_wind": 10,
|
"weight_wind": 10,
|
||||||
"weight_humidity": 15,
|
"weight_humidity": 15,
|
||||||
"weight_air": 10,
|
"weight_air": 15,
|
||||||
"weight_uv": 5,
|
"weight_uv": 0,
|
||||||
"weight_sun": 0,
|
"weight_sun": 0,
|
||||||
"weight_view": 0,
|
"weight_view": 0,
|
||||||
"weight_time": 5,
|
"weight_time": 5,
|
||||||
@@ -629,10 +653,6 @@
|
|||||||
"time": {
|
"time": {
|
||||||
"type": "fixed",
|
"type": "fixed",
|
||||||
"value": 100
|
"value": 100
|
||||||
},
|
|
||||||
"uv": {
|
|
||||||
"zero": 8,
|
|
||||||
"full": 2
|
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"zero_rules": [
|
"zero_rules": [
|
||||||
@@ -654,7 +674,8 @@
|
|||||||
"60": "뛸 만해요! 아침·저녁 중 시원한 쪽 고르기.",
|
"60": "뛸 만해요! 아침·저녁 중 시원한 쪽 고르기.",
|
||||||
"80": "8~18°에 공기 보송, 기록 갱신각 🏃"
|
"80": "8~18°에 공기 보송, 기록 갱신각 🏃"
|
||||||
},
|
},
|
||||||
"sort_order": 9
|
"sort_order": 9,
|
||||||
|
"priority": 1
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"code": "stars",
|
"code": "stars",
|
||||||
@@ -719,7 +740,8 @@
|
|||||||
"60": "꽤 보여요! 불빛 적은 곳으로 조금만 나가요.",
|
"60": "꽤 보여요! 불빛 적은 곳으로 조금만 나가요.",
|
||||||
"80": "달은 어둡고 공기는 맑아요. 은하수 노려볼 만한 밤 ✨"
|
"80": "달은 어둡고 공기는 맑아요. 은하수 노려볼 만한 밤 ✨"
|
||||||
},
|
},
|
||||||
"sort_order": 10
|
"sort_order": 10,
|
||||||
|
"priority": 2
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"code": "jjamppong",
|
"code": "jjamppong",
|
||||||
@@ -777,7 +799,8 @@
|
|||||||
"60": "쌀쌀하거나 비 와서 국물 각 잡혀요!",
|
"60": "쌀쌀하거나 비 와서 국물 각 잡혀요!",
|
||||||
"80": "춥고 비까지! 얼큰한 짬뽕 한 그릇 무조건 🍜"
|
"80": "춥고 비까지! 얼큰한 짬뽕 한 그릇 무조건 🍜"
|
||||||
},
|
},
|
||||||
"sort_order": 11
|
"sort_order": 11,
|
||||||
|
"priority": 3
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"code": "makgeolli",
|
"code": "makgeolli",
|
||||||
@@ -833,7 +856,8 @@
|
|||||||
"60": "비 기운이 있어요. 파전 반죽 준비각!",
|
"60": "비 기운이 있어요. 파전 반죽 준비각!",
|
||||||
"80": "비 오고 선선한 저녁, 파전에 막걸리 확정 🍶"
|
"80": "비 오고 선선한 저녁, 파전에 막걸리 확정 🍶"
|
||||||
},
|
},
|
||||||
"sort_order": 12
|
"sort_order": 12,
|
||||||
|
"priority": 3
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"code": "iced_hot",
|
"code": "iced_hot",
|
||||||
@@ -887,7 +911,8 @@
|
|||||||
"60": "아침 공기가 차요. 오늘은 뜨아로 갈아탈 때!",
|
"60": "아침 공기가 차요. 오늘은 뜨아로 갈아탈 때!",
|
||||||
"80": "아침이 한 자릿수, 따뜻한 커피 없인 못 버텨요 ☕"
|
"80": "아침이 한 자릿수, 따뜻한 커피 없인 못 버텨요 ☕"
|
||||||
},
|
},
|
||||||
"sort_order": 13
|
"sort_order": 13,
|
||||||
|
"priority": 3
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"code": "laundry",
|
"code": "laundry",
|
||||||
@@ -951,7 +976,8 @@
|
|||||||
"60": "잘 마르는 편이에요. 두꺼운 건 오후까지 두기!",
|
"60": "잘 마르는 편이에요. 두꺼운 건 오후까지 두기!",
|
||||||
"80": "따뜻하고 보송한데 바람까지 솔솔, 이불 빨래 가능한 날 ☀️"
|
"80": "따뜻하고 보송한데 바람까지 솔솔, 이불 빨래 가능한 날 ☀️"
|
||||||
},
|
},
|
||||||
"sort_order": 14
|
"sort_order": 14,
|
||||||
|
"priority": 1
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"code": "bike",
|
"code": "bike",
|
||||||
@@ -968,13 +994,13 @@
|
|||||||
"to": 19
|
"to": 19
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"weight_temp": 25,
|
"weight_temp": 20,
|
||||||
"weight_rain": 25,
|
"weight_rain": 20,
|
||||||
"weight_wind": 25,
|
"weight_wind": 20,
|
||||||
"weight_humidity": 5,
|
"weight_humidity": 5,
|
||||||
"weight_air": 10,
|
"weight_air": 10,
|
||||||
"weight_uv": 5,
|
"weight_uv": 10,
|
||||||
"weight_sun": 0,
|
"weight_sun": 10,
|
||||||
"weight_view": 0,
|
"weight_view": 0,
|
||||||
"weight_time": 5,
|
"weight_time": 5,
|
||||||
"factor_rules": {
|
"factor_rules": {
|
||||||
@@ -1007,6 +1033,10 @@
|
|||||||
"uv": {
|
"uv": {
|
||||||
"zero": 8,
|
"zero": 8,
|
||||||
"full": 2
|
"full": 2
|
||||||
|
},
|
||||||
|
"sun": {
|
||||||
|
"zero": 0.2,
|
||||||
|
"full": 0.8
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"zero_rules": [
|
"zero_rules": [
|
||||||
@@ -1033,7 +1063,8 @@
|
|||||||
"60": "탈 만해요! 강변은 바람 좀 부니 바람막이 챙기기.",
|
"60": "탈 만해요! 강변은 바람 좀 부니 바람막이 챙기기.",
|
||||||
"80": "15~24°에 바람 잔잔, 멀리 달려도 좋은 날 🚲"
|
"80": "15~24°에 바람 잔잔, 멀리 달려도 좋은 날 🚲"
|
||||||
},
|
},
|
||||||
"sort_order": 15
|
"sort_order": 15,
|
||||||
|
"priority": 1
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"code": "dog",
|
"code": "dog",
|
||||||
@@ -1054,12 +1085,12 @@
|
|||||||
"to": 20
|
"to": 20
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"weight_temp": 35,
|
"weight_temp": 40,
|
||||||
"weight_rain": 25,
|
"weight_rain": 25,
|
||||||
"weight_wind": 10,
|
"weight_wind": 10,
|
||||||
"weight_humidity": 5,
|
"weight_humidity": 5,
|
||||||
"weight_air": 15,
|
"weight_air": 15,
|
||||||
"weight_uv": 5,
|
"weight_uv": 0,
|
||||||
"weight_sun": 0,
|
"weight_sun": 0,
|
||||||
"weight_view": 0,
|
"weight_view": 0,
|
||||||
"weight_time": 5,
|
"weight_time": 5,
|
||||||
@@ -1086,10 +1117,6 @@
|
|||||||
"time": {
|
"time": {
|
||||||
"type": "fixed",
|
"type": "fixed",
|
||||||
"value": 100
|
"value": 100
|
||||||
},
|
|
||||||
"uv": {
|
|
||||||
"zero": 8,
|
|
||||||
"full": 2
|
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"zero_rules": [
|
"zero_rules": [
|
||||||
@@ -1116,7 +1143,8 @@
|
|||||||
"60": "산책 괜찮아요! 그늘 많은 길로 가요.",
|
"60": "산책 괜찮아요! 그늘 많은 길로 가요.",
|
||||||
"80": "5~22°에 공기 맑음, 멍멍이 신나는 날 🐶"
|
"80": "5~22°에 공기 맑음, 멍멍이 신나는 날 🐶"
|
||||||
},
|
},
|
||||||
"sort_order": 16
|
"sort_order": 16,
|
||||||
|
"priority": 2
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"code": "glasses",
|
"code": "glasses",
|
||||||
@@ -1170,7 +1198,8 @@
|
|||||||
"60": "출근길 안경에 김 서려요. 닦을 천 챙기기!",
|
"60": "출근길 안경에 김 서려요. 닦을 천 챙기기!",
|
||||||
"80": "영하권 아침에 습하기까지, 문 열자마자 앞이 하얘져요 👓"
|
"80": "영하권 아침에 습하기까지, 문 열자마자 앞이 하얘져요 👓"
|
||||||
},
|
},
|
||||||
"sort_order": 17
|
"sort_order": 17,
|
||||||
|
"priority": 2
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"code": "makeup",
|
"code": "makeup",
|
||||||
@@ -1224,7 +1253,8 @@
|
|||||||
"60": "덥고 습해서 무너지기 쉬워요. 픽서 챙기기!",
|
"60": "덥고 습해서 무너지기 쉬워요. 픽서 챙기기!",
|
||||||
"80": "30° 넘는 찜통에 습도까지, 기름종이 필수 🫠"
|
"80": "30° 넘는 찜통에 습도까지, 기름종이 필수 🫠"
|
||||||
},
|
},
|
||||||
"sort_order": 18
|
"sort_order": 18,
|
||||||
|
"priority": 2
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"code": "naengmyeon",
|
"code": "naengmyeon",
|
||||||
@@ -1280,7 +1310,8 @@
|
|||||||
"60": "점심에 덥네요. 냉면 한 그릇 생각나요!",
|
"60": "점심에 덥네요. 냉면 한 그릇 생각나요!",
|
||||||
"80": "30° 넘는 한낮, 살얼음 동동 냉면 확정 🥶"
|
"80": "30° 넘는 한낮, 살얼음 동동 냉면 확정 🥶"
|
||||||
},
|
},
|
||||||
"sort_order": 19
|
"sort_order": 19,
|
||||||
|
"priority": 3
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"code": "taxi",
|
"code": "taxi",
|
||||||
@@ -1336,7 +1367,8 @@
|
|||||||
"60": "비나 추위로 택시 잡기 힘들어요. 막차 시간 확인!",
|
"60": "비나 추위로 택시 잡기 힘들어요. 막차 시간 확인!",
|
||||||
"80": "비 오는 추운 밤, 택시 전쟁이에요. 막차 타세요 🚕"
|
"80": "비 오는 추운 밤, 택시 전쟁이에요. 막차 타세요 🚕"
|
||||||
},
|
},
|
||||||
"sort_order": 20
|
"sort_order": 20,
|
||||||
|
"priority": 2
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"code": "delivery",
|
"code": "delivery",
|
||||||
@@ -1393,7 +1425,8 @@
|
|||||||
"60": "비나 추위로 주문이 몰려요. 일찍 시키기!",
|
"60": "비나 추위로 주문이 몰려요. 일찍 시키기!",
|
||||||
"80": "비 오는 추운 저녁, 배달 한참 걸려요. 지금 바로 주문! 🛵"
|
"80": "비 오는 추운 저녁, 배달 한참 걸려요. 지금 바로 주문! 🛵"
|
||||||
},
|
},
|
||||||
"sort_order": 21
|
"sort_order": 21,
|
||||||
|
"priority": 2
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"code": "garden",
|
"code": "garden",
|
||||||
@@ -1410,13 +1443,13 @@
|
|||||||
"to": 10
|
"to": 10
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"weight_temp": 25,
|
"weight_temp": 20,
|
||||||
"weight_rain": 30,
|
"weight_rain": 25,
|
||||||
"weight_wind": 10,
|
"weight_wind": 10,
|
||||||
"weight_humidity": 15,
|
"weight_humidity": 10,
|
||||||
"weight_air": 10,
|
"weight_air": 10,
|
||||||
"weight_uv": 5,
|
"weight_uv": 10,
|
||||||
"weight_sun": 0,
|
"weight_sun": 10,
|
||||||
"weight_view": 0,
|
"weight_view": 0,
|
||||||
"weight_time": 5,
|
"weight_time": 5,
|
||||||
"factor_rules": {
|
"factor_rules": {
|
||||||
@@ -1446,6 +1479,10 @@
|
|||||||
"uv": {
|
"uv": {
|
||||||
"zero": 8,
|
"zero": 8,
|
||||||
"full": 2
|
"full": 2
|
||||||
|
},
|
||||||
|
"sun": {
|
||||||
|
"zero": 0.2,
|
||||||
|
"full": 0.8
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"zero_rules": [
|
"zero_rules": [
|
||||||
@@ -1462,7 +1499,8 @@
|
|||||||
"60": "화분 돌보기 괜찮아요. 아침에 물 듬뿍!",
|
"60": "화분 돌보기 괜찮아요. 아침에 물 듬뿍!",
|
||||||
"80": "12~25°의 보송한 아침, 분갈이까지 해도 되는 날 🌱"
|
"80": "12~25°의 보송한 아침, 분갈이까지 해도 되는 날 🌱"
|
||||||
},
|
},
|
||||||
"sort_order": 22
|
"sort_order": 22,
|
||||||
|
"priority": 3
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"code": "photo",
|
"code": "photo",
|
||||||
@@ -1530,7 +1568,8 @@
|
|||||||
"60": "노을이 꽤 기대돼요. 해 지기 30분 전에 나가요.",
|
"60": "노을이 꽤 기대돼요. 해 지기 30분 전에 나가요.",
|
||||||
"80": "노을 점수 높고 공기 맑음, 인생샷 각 📸"
|
"80": "노을 점수 높고 공기 맑음, 인생샷 각 📸"
|
||||||
},
|
},
|
||||||
"sort_order": 23
|
"sort_order": 23,
|
||||||
|
"priority": 2
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"code": "baseball",
|
"code": "baseball",
|
||||||
@@ -1596,7 +1635,8 @@
|
|||||||
"60": "직관 괜찮아요! 밤엔 선선하니 겉옷 하나.",
|
"60": "직관 괜찮아요! 밤엔 선선하니 겉옷 하나.",
|
||||||
"80": "15~25°에 비 걱정 없음, 응원가 목청껏 부르는 날 ⚾"
|
"80": "15~25°에 비 걱정 없음, 응원가 목청껏 부르는 날 ⚾"
|
||||||
},
|
},
|
||||||
"sort_order": 24
|
"sort_order": 24,
|
||||||
|
"priority": 3
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"code": "study",
|
"code": "study",
|
||||||
@@ -1653,7 +1693,8 @@
|
|||||||
"60": "밖이 애매해서 책상에 앉을 만해요.",
|
"60": "밖이 애매해서 책상에 앉을 만해요.",
|
||||||
"80": "비 오고 춥거나 더워서 나갈 맛이 안 나요. 집중각 📚"
|
"80": "비 오고 춥거나 더워서 나갈 맛이 안 나요. 집중각 📚"
|
||||||
},
|
},
|
||||||
"sort_order": 25
|
"sort_order": 25,
|
||||||
|
"priority": 3
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"code": "netflix",
|
"code": "netflix",
|
||||||
@@ -1709,7 +1750,8 @@
|
|||||||
"60": "비 오거나 쌀쌀한 밤, 이불 속이 최고!",
|
"60": "비 오거나 쌀쌀한 밤, 이불 속이 최고!",
|
||||||
"80": "비 오는 주말 앞 밤, 정주행 시작각 🍿"
|
"80": "비 오는 주말 앞 밤, 정주행 시작각 🍿"
|
||||||
},
|
},
|
||||||
"sort_order": 26
|
"sort_order": 26,
|
||||||
|
"priority": 3
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"code": "chestnut",
|
"code": "chestnut",
|
||||||
@@ -1763,6 +1805,524 @@
|
|||||||
"60": "손이 시려요. 따끈한 군밤 한 봉지!",
|
"60": "손이 시려요. 따끈한 군밤 한 봉지!",
|
||||||
"80": "영하 가까운 저녁, 군밤 품고 걷는 날 🌰"
|
"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
|
region_name,area,name,is_outdoor,icon,reason,best_time,sort_order,lat,lon,source
|
||||||
서울 성동구,성수,서울숲,1,picnic,돗자리 펴고 낮 피크닉,낮 12시~4시,1
|
서울 성동구,성수,서울숲,1,picnic,돗자리 펴고 낮 피크닉,낮 12시~4시,1,37.54307,127.04180,tourapi:128611
|
||||||
서울 성동구,성수,성수 갤러리 골목,0,photo,작은 전시와 팝업을 걸어서,비 오는 오후,2
|
서울 성동구,성수,성수 갤러리 골목,0,photo,작은 전시와 팝업을 걸어서,비 오는 오후,2,37.54320,127.05660,tourapi:2930901
|
||||||
서울 마포구,연남·망원,경의선숲길,1,walk,해 질 녘 산책 데이트,저녁 6시 이후,3
|
서울 마포구,연남·망원,경의선숲길,1,walk,해 질 녘 산책 데이트,저녁 6시 이후,3,37.56170,126.92306,tourapi:2553819
|
||||||
서울 마포구,연남·망원,망원한강공원,1,sunset,노을 명소 1위 강 건너 서쪽,노을 무렵,4
|
서울 마포구,연남·망원,망원한강공원,1,sunset,노을 명소 1위 강 건너 서쪽,노을 무렵,4,37.55140,126.90050,tourapi:1059638
|
||||||
서울 영등포구,여의도,여의도한강공원,1,chimaek,한강 치맥,저녁 7시,5
|
서울 영등포구,여의도,여의도한강공원,1,chimaek,한강 치맥,저녁 7시,5,37.52640,126.93361,tourapi:1059479
|
||||||
서울 영등포구,여의도,더현대 서울,0,calendar,비 와도 하루 종일 실내,비 오는 날,6
|
서울 영등포구,여의도,더현대 서울,0,calendar,비 와도 하루 종일 실내,비 오는 날,6,37.52710,126.92730,tourapi:2708109
|
||||||
서울 송파구,잠실,석촌호수,1,walk,호수 한 바퀴 2.5km,선선한 저녁,7
|
서울 송파구,잠실,석촌호수,1,walk,호수 한 바퀴 2.5km,선선한 저녁,7,37.50792,127.09894,tourapi:754052
|
||||||
서울 송파구,잠실,롯데월드 아쿠아리움,0,rain,비 오는 날 실내 데이트,비 오는 오후,8
|
서울 송파구,잠실,롯데월드 아쿠아리움,0,rain,비 오는 날 실내 데이트,비 오는 오후,8,37.51417,127.10407,tourapi:2476731
|
||||||
서울 종로구,북촌·익선,북촌한옥마을,1,photo,맑은 날 한옥 골목 사진,오전 10시~,9
|
서울 종로구,북촌·익선,북촌한옥마을,1,photo,맑은 날 한옥 골목 사진,오전 10시~,9,37.57905,126.98671,tourapi:126537
|
||||||
서울 종로구,북촌·익선,국립현대미술관 서울관,0,bulb,비 오면 미술관으로,비 오는 날,10
|
서울 종로구,북촌·익선,국립현대미술관 서울관,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.58845,126.45721,1,tourapi:1937784
|
||||||
충남 홍성군,남당노을전망대,바다 너머 서쪽이 트임 · 충남 홍성군,36.54428,126.4656,1,tourapi:3065226
|
충남 홍성군,남당노을전망대,바다 너머 서쪽이 트임 · 충남 홍성군,36.54428,126.4656,1,tourapi:3065226
|
||||||
충남 홍성군,어사리 노을공원,바다 너머 서쪽이 트임 · 충남 홍성군,36.55615,126.46837,1,tourapi:2678991
|
충남 홍성군,어사리 노을공원,바다 너머 서쪽이 트임 · 충남 홍성군,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)
|
# 편한 범위 안에서 최적값 ±이만큼은 100점 (기온 °, 습도 %p)
|
||||||
_TEMP_PLATEAU = 2
|
_TEMP_PLATEAU = 2
|
||||||
_HUMIDITY_PLATEAU = 5
|
_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)
|
@dataclass(frozen=True)
|
||||||
@@ -47,6 +54,7 @@ class Context:
|
|||||||
sunset_score: Optional[int]
|
sunset_score: Optional[int]
|
||||||
wind_warning: bool
|
wind_warning: bool
|
||||||
lookahead_rain_prob: int
|
lookahead_rain_prob: int
|
||||||
|
moon_note: str = "" # 별보기각 근거 문구: 그날 밤 달 모양·보이는 시간
|
||||||
|
|
||||||
|
|
||||||
@dataclass(frozen=True)
|
@dataclass(frozen=True)
|
||||||
@@ -108,7 +116,7 @@ def temp_score(rule: dict, feels: float) -> tuple[int, str]:
|
|||||||
shown = f"산 정상 기준 {round(t)}°" if rule.get("offset") else f"체감 {round(t)}°"
|
shown = f"산 정상 기준 {round(t)}°" if rule.get("offset") else f"체감 {round(t)}°"
|
||||||
if rule["type"] == "range":
|
if rule["type"] == "range":
|
||||||
lo, hi = rule["lo"], rule["hi"]
|
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":
|
if rule["type"] == "away":
|
||||||
lo, hi = rule["lo"], rule["hi"]
|
lo, hi = rule["lo"], rule["hi"]
|
||||||
dist = 0 if lo <= t <= hi else min(abs(t - lo), abs(t - hi))
|
dist = 0 if lo <= t <= hi else min(abs(t - lo), abs(t - hi))
|
||||||
@@ -154,10 +162,15 @@ def humidity_score(rule: dict, humidity: float) -> tuple[int, str]:
|
|||||||
return 50, f"{note}, 이 각엔 상관없어 50점으로 둬요"
|
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:
|
if pm25 is None:
|
||||||
return _UNKNOWN, f"미세먼지 정보가 없어 {_UNKNOWN}점으로 둬요"
|
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]:
|
def uv_score(rule: dict, uv: Optional[float]) -> tuple[int, str]:
|
||||||
@@ -185,7 +198,7 @@ def time_score(rule: dict, ctx: Context) -> tuple[int, str]:
|
|||||||
v = rule.get(key, rule.get("default", 100))
|
v = rule.get(key, rule.get("default", 100))
|
||||||
return _clamp(v), f"{_WEEKDAY_KO[ctx.day.weekday()]}요일{' 공휴일' if ctx.is_holiday else ''}"
|
return _clamp(v), f"{_WEEKDAY_KO[ctx.day.weekday()]}요일{' 공휴일' if ctx.is_holiday else ''}"
|
||||||
if kind == "moon":
|
if kind == "moon":
|
||||||
return _clamp(20 + 80 * (1 - ctx.moon)), f"달 밝기 {round(ctx.moon * 100)}%"
|
return _clamp(20 + 80 * (1 - ctx.moon)), ctx.moon_note or f"달이 비추는 정도 {round(ctx.moon * 100)}%"
|
||||||
if kind == "sunset_score":
|
if kind == "sunset_score":
|
||||||
return (ctx.sunset_score if ctx.sunset_score is not None else _UNKNOWN), (
|
return (ctx.sunset_score if ctx.sunset_score is not None else _UNKNOWN), (
|
||||||
f"노을 점수 {ctx.sunset_score}" if ctx.sunset_score is not None else f"노을 점수 계산 전이라 {_UNKNOWN}점으로 둬요"
|
f"노을 점수 {ctx.sunset_score}" if ctx.sunset_score is not None else f"노을 점수 계산 전이라 {_UNKNOWN}점으로 둬요"
|
||||||
@@ -208,7 +221,8 @@ def axis_label(axis: str, rules: dict) -> str:
|
|||||||
if axis == "rain":
|
if axis == "rain":
|
||||||
return "비 옴" if rules["rain"]["dir"] == "wet" else "비 안 옴"
|
return "비 옴" if rules["rain"]["dir"] == "wet" else "비 안 옴"
|
||||||
if axis == "air":
|
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]
|
table = {"temp": _TEMP_LABEL, "wind": _WIND_LABEL, "humidity": _HUMIDITY_LABEL, "time": _TIME_LABEL}[axis]
|
||||||
return table[rules[axis]["type"]]
|
return table[rules[axis]["type"]]
|
||||||
|
|
||||||
@@ -304,7 +318,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 ""),
|
"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),
|
"wind": wind_score(rules["wind"], max(winds) if winds else None),
|
||||||
"humidity": humidity_score(rules["humidity"], mean(h.humidity for h in hours)),
|
"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, ""),
|
"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, ""),
|
"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, ""),
|
"view": view_score(rules["view"], min(views, default=None)) if weights["view"] else (0, ""),
|
||||||
|
|||||||
@@ -1,5 +1,9 @@
|
|||||||
import math
|
import math
|
||||||
from datetime import datetime, timedelta, timezone
|
from dataclasses import dataclass
|
||||||
|
from datetime import date, datetime, time, timedelta, timezone
|
||||||
|
from typing import Optional
|
||||||
|
|
||||||
|
from common.utils.kma_time import KST
|
||||||
|
|
||||||
_SYNODIC_DAYS = 29.530588
|
_SYNODIC_DAYS = 29.530588
|
||||||
_KNOWN_NEW_MOON = datetime(2000, 1, 6, 18, 14, tzinfo=timezone.utc)
|
_KNOWN_NEW_MOON = datetime(2000, 1, 6, 18, 14, tzinfo=timezone.utc)
|
||||||
@@ -11,10 +15,12 @@ def illumination(at: datetime) -> float:
|
|||||||
|
|
||||||
|
|
||||||
def _fraction(at: datetime) -> float:
|
def _fraction(at: datetime) -> float:
|
||||||
"""직전 삭에서 다음 삭까지 얼마나 지났는지 0~1. 앞뒤 삭은 실제 시각(nearest)으로 잡는다."""
|
"""달이 해보다 황경으로 얼마나 앞섰는지 0~1 (0 삭, 0.5 보름). 실제 위치로 보므로 보름·삭 시각과 맞는다."""
|
||||||
near = nearest(at, False)
|
d = _days(at)
|
||||||
prev, nxt = (near, nearest(near + timedelta(days=_SYNODIC_DAYS), False)) if near <= at else (nearest(near - timedelta(days=_SYNODIC_DAYS), False), near)
|
t = d / 36525
|
||||||
return (at - prev) / (nxt - prev)
|
m = math.radians(357.52911 + 35999.05029 * t)
|
||||||
|
sun = 280.46646 + 36000.76983 * t + 1.914602 * math.sin(m) + 0.019993 * math.sin(2 * m)
|
||||||
|
return ((math.degrees(_ecliptic(d)[0]) - sun) % 360) / 360
|
||||||
|
|
||||||
|
|
||||||
# 달 모양 이름. 차오르는 비율(0 삭 → 0.5 보름 → 1 삭) 구간마다
|
# 달 모양 이름. 차오르는 비율(0 삭 → 0.5 보름 → 1 삭) 구간마다
|
||||||
@@ -51,3 +57,99 @@ def nearest(at: datetime, full: bool) -> datetime:
|
|||||||
offset = 0.5 if full else 0.0
|
offset = 0.5 if full else 0.0
|
||||||
k = round((at - _KNOWN_NEW_MOON).total_seconds() / 86400 / _SYNODIC_DAYS - offset) + offset
|
k = round((at - _KNOWN_NEW_MOON).total_seconds() / 86400 / _SYNODIC_DAYS - offset) + offset
|
||||||
return min((_true_phase(k + dk, full) for dk in (-1, 0, 1)), key=lambda x: abs(x - at))
|
return min((_true_phase(k + dk, full) for dk in (-1, 0, 1)), key=lambda x: abs(x - at))
|
||||||
|
|
||||||
|
|
||||||
|
_HORIZON = -0.83 # 달 윗면이 지평선에 닿는 고도 (대기 굴절·반지름 포함, 지표에서 본 고도 기준)
|
||||||
|
_NIGHT = (19, 29) # '오늘 밤': 19시~다음 날 5시
|
||||||
|
_STEP = timedelta(minutes=10)
|
||||||
|
|
||||||
|
|
||||||
|
def _days(at: datetime) -> float:
|
||||||
|
return (at - datetime(2000, 1, 1, 12, tzinfo=timezone.utc)).total_seconds() / 86400
|
||||||
|
|
||||||
|
|
||||||
|
def _ecliptic(d: float) -> tuple[float, float, float]:
|
||||||
|
"""2000-01-01 12시(UTC)부터 d 일 뒤 달의 황경·황위(라디안)와 거리(km). Meeus 47장 주요 항만 쓴 간이식, 오차 0.5° 안팎."""
|
||||||
|
t = d / 36525
|
||||||
|
r, s, c = math.radians, math.sin, math.cos
|
||||||
|
lp = 218.3164477 + 481267.88123421 * t
|
||||||
|
dd = r(297.8501921 + 445267.1114034 * t)
|
||||||
|
m = r(357.5291092 + 35999.0502909 * t)
|
||||||
|
mp = r(134.9633964 + 477198.8675055 * t)
|
||||||
|
f = r(93.2720950 + 483202.0175233 * t)
|
||||||
|
lam = r(lp + 6.289 * s(mp) + 1.274 * s(2 * dd - mp) + 0.658 * s(2 * dd) + 0.214 * s(2 * mp) - 0.186 * s(m) - 0.114 * s(2 * f))
|
||||||
|
beta = r(5.128 * s(f) + 0.281 * s(mp + f) + 0.278 * s(mp - f) + 0.173 * s(2 * dd - f))
|
||||||
|
dist_km = 385001 - 20905 * c(mp) - 3699 * c(2 * dd - mp) - 2956 * c(2 * dd)
|
||||||
|
return lam, beta, dist_km
|
||||||
|
|
||||||
|
|
||||||
|
def altitude(at: datetime, lat: float, lon: float) -> float:
|
||||||
|
"""그 시각 그 자리에서 본 달 고도(도). 뜨고 지는 시각은 몇 분 차이."""
|
||||||
|
d = _days(at)
|
||||||
|
r, s, c = math.radians, math.sin, math.cos
|
||||||
|
lam, beta, dist_km = _ecliptic(d)
|
||||||
|
eps = r(23.439 - 0.0000004 * d)
|
||||||
|
ra = math.atan2(s(lam) * c(eps) - math.tan(beta) * s(eps), c(lam))
|
||||||
|
dec = math.asin(s(beta) * c(eps) + c(beta) * s(eps) * s(lam))
|
||||||
|
ha = r(280.46061837 + 360.98564736629 * d + lon) - ra
|
||||||
|
phi = r(lat)
|
||||||
|
alt = math.asin(s(phi) * s(dec) + c(phi) * c(dec) * c(ha))
|
||||||
|
return math.degrees(alt - math.asin(6378.14 / dist_km) * c(alt))
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class MoonNight:
|
||||||
|
"""그날 밤(19시~다음 날 5시) 달. lit 는 빛나는 면의 비율(모양), 밝기가 아니다."""
|
||||||
|
name: str
|
||||||
|
lit: float
|
||||||
|
waxing: bool # 삭 → 보름 사이 (해 진 뒤 서쪽 하늘에 있다가 지는 쪽)
|
||||||
|
rise_at: Optional[datetime] # 밤 사이에 뜨면 그 시각 (저녁부터 떠 있으면 None)
|
||||||
|
set_at: Optional[datetime] # 밤 사이에 지면 그 시각 (새벽까지 떠 있으면 None)
|
||||||
|
up_hours: tuple[int, ...] # 달이 떠 있는 시각 (19~28, 24 이상은 다음 날)
|
||||||
|
|
||||||
|
|
||||||
|
def night(day: date, lat: float, lon: float) -> MoonNight:
|
||||||
|
start = datetime.combine(day, time(0), tzinfo=KST)
|
||||||
|
mid = start + timedelta(hours=23)
|
||||||
|
at, end = start + timedelta(hours=_NIGHT[0]), start + timedelta(hours=_NIGHT[1])
|
||||||
|
prev = altitude(at, lat, lon) > _HORIZON
|
||||||
|
rise_at = set_at = None
|
||||||
|
ups: set[int] = set()
|
||||||
|
while at < end:
|
||||||
|
up = altitude(at, lat, lon) > _HORIZON
|
||||||
|
if up and not prev and rise_at is None:
|
||||||
|
rise_at = at
|
||||||
|
if prev and not up and set_at is None:
|
||||||
|
set_at = at
|
||||||
|
if up:
|
||||||
|
ups.add(int((at - start).total_seconds() // 3600))
|
||||||
|
prev = up
|
||||||
|
at += _STEP
|
||||||
|
return MoonNight(name=phase_name(mid), lit=illumination(mid), waxing=_fraction(mid) < 0.5, rise_at=rise_at, set_at=set_at, up_hours=tuple(sorted(ups)))
|
||||||
|
|
||||||
|
|
||||||
|
def up_ratio(m: MoonNight, hours: range) -> float:
|
||||||
|
"""hours(19~28 기준 시각) 중 달이 떠 있는 비율."""
|
||||||
|
return sum(h in m.up_hours for h in hours) / len(hours)
|
||||||
|
|
||||||
|
|
||||||
|
def view_line(m: MoonNight, cloudy: Optional[float]) -> str:
|
||||||
|
"""오늘 밤 달이 잘 보이는지 한 마디. 안 보이면 왜인지까지. cloudy 는 달이 떠 있는 동안 흐린 정도 0~1 (모르면 None)."""
|
||||||
|
if m.lit < 0.03:
|
||||||
|
return "해와 같은 쪽에 있어 안 보여요"
|
||||||
|
if not m.up_hours:
|
||||||
|
return "해 진 뒤 곧 져서 밤엔 안 보여요" if m.waxing else "새벽 늦게 떠서 밤엔 안 보여요"
|
||||||
|
if m.rise_at is not None and m.rise_at.hour not in range(19, 22):
|
||||||
|
return f"{_clock(m.rise_at)}에 떠요"
|
||||||
|
if cloudy is not None and cloudy >= 0.6:
|
||||||
|
return "흐려서 구름에 가려요"
|
||||||
|
if cloudy is not None and cloudy >= 0.3:
|
||||||
|
return "구름 사이로 보여요"
|
||||||
|
if m.set_at is not None:
|
||||||
|
return f"{_clock(m.set_at)}까지 보여요"
|
||||||
|
return "밤새 잘 보여요"
|
||||||
|
|
||||||
|
|
||||||
|
def _clock(at: datetime) -> str:
|
||||||
|
h = at.astimezone(KST).hour
|
||||||
|
return f"{'새벽' if h < 6 else '밤' if h >= 21 or h == 0 else '저녁'} {h % 12 or 12}시"
|
||||||
@@ -1,14 +1,17 @@
|
|||||||
import statistics
|
import statistics
|
||||||
from dataclasses import dataclass
|
from dataclasses import dataclass
|
||||||
from datetime import datetime, timedelta
|
from datetime import datetime, timedelta
|
||||||
|
from typing import Optional
|
||||||
|
|
||||||
from common.enums import Confidence, SkyGrade, SkySituation, SkyType
|
from common.enums import Confidence, SkyGrade, SkySituation, SkyType
|
||||||
|
|
||||||
DISTANCES_KM = (20, 100)
|
DISTANCES_KM = (20, 100)
|
||||||
# 물들 구름이 하나도 없을 때의 canvas 값. 50% 까지 곧게 올라가 맑은 날도 구름 몇 % 차이로 점수가 갈린다 (맑은 하늘 40점 = 은은함).
|
# 물들 구름이 하나도 없을 때의 canvas 값. 50% 까지 곧게 올라가 맑은 날도 구름 몇 % 차이로 점수가 갈린다 (맑은 하늘 55점 = 은은함).
|
||||||
_CLEAR_CANVAS = 0.2
|
_CLEAR_CANVAS = 0.4
|
||||||
# 해 지기(뜨기) 이만큼 전 사이에 비가 왔다가 그 시각엔 개면 공기가 맑고 구름이 남아 더 붉다.
|
# 해 지기(뜨기) 이만큼 전 사이에 비가 왔다가 그 시각엔 개면 공기가 맑고 구름이 남아 더 붉다.
|
||||||
RAIN_BEFORE_HOURS = (2, 6)
|
RAIN_BEFORE_HOURS = (2, 6)
|
||||||
|
# 서쪽이 바다·강·전망대로 트여 해가 지평선까지 보이는 곳은 산·건물에 가리지 않아 노을이 더 잘 보인다.
|
||||||
|
OPEN_WEST_BONUS = 1.1
|
||||||
|
|
||||||
|
|
||||||
@dataclass(frozen=True)
|
@dataclass(frozen=True)
|
||||||
@@ -25,6 +28,7 @@ class Air:
|
|||||||
humidity: float | None = None
|
humidity: float | None = None
|
||||||
rain_before: int | None = None # RAIN_BEFORE_HOURS 사이 가장 높은 비 확률
|
rain_before: int | None = None # RAIN_BEFORE_HOURS 사이 가장 높은 비 확률
|
||||||
rain_now: int | None = None
|
rain_now: int | None = None
|
||||||
|
open_west: bool = False # 가까이 서쪽이 트인 노을 명소가 있음 (노을만)
|
||||||
|
|
||||||
|
|
||||||
def score(near20: Layers, far100: Layers) -> int:
|
def score(near20: Layers, far100: Layers) -> int:
|
||||||
@@ -36,24 +40,94 @@ def score(near20: Layers, far100: Layers) -> int:
|
|||||||
return round(100 * (0.75 * f_canvas + 0.25 * f_near) * (0.25 + 0.75 * light))
|
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:
|
# 공기 보정 기준점 (값, 배수). 평소 공기(가시거리 20km, 습도 60%)가 ×1.0 이고 좋으면 올리고 나쁘면 내린다. 양 끝 밖은 끝 값 그대로.
|
||||||
"""good 쪽은 1.0, bad 쪽은 low, 사이는 직선."""
|
_VISIBILITY_FACTOR = ((5, 0.8), (20, 1.0), (40, 1.12))
|
||||||
t = max(0.0, min(1.0, (v - bad) / (good - bad)))
|
_HUMIDITY_FACTOR = ((40, 1.06), (60, 1.0), (90, 0.85))
|
||||||
return low + (1 - low) * t
|
|
||||||
|
|
||||||
|
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:
|
def air_factor(air: Air) -> float:
|
||||||
"""공기로 구름 점수를 보정하는 배수. 뿌연 공기·높은 습도는 색을 흐리게 하고, 비 갠 뒤는 더 붉다."""
|
"""공기로 구름 점수를 보정하는 배수. 맑고 건조하면 올리고 뿌옇거나 습하면 내린다. 비 갠 뒤는 더 붉다."""
|
||||||
f = 1.0
|
f = 1.0
|
||||||
if air.visibility_km is not None:
|
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:
|
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:
|
if air.rain_before is not None and air.rain_before >= 60 and (air.rain_now or 0) < 40:
|
||||||
f *= 1.15
|
f *= 1.15
|
||||||
|
if air.open_west:
|
||||||
|
f *= OPEN_WEST_BONUS
|
||||||
return f
|
return f
|
||||||
|
|
||||||
|
|
||||||
|
HAZY = 0.7 # 공기 보정이 이보다 작으면 결론을 한 단계 낮추고 이유에 공기를 말한다
|
||||||
|
|
||||||
|
|
||||||
|
def air_note(air: Optional[dict]) -> Optional[str]:
|
||||||
|
"""공기 보정이 크게 깎였으면 그 이유를 눈에 보이는 말로 (숫자 없이). 아니면 None.
|
||||||
|
가시거리 20km 미만 = 먼 건물이 흐릿하게 보이는 정도, 습도 70% 이상 = 습한 공기."""
|
||||||
|
if not air or air.get("factor") is None or air["factor"] >= HAZY:
|
||||||
|
return None
|
||||||
|
hazy = air.get("visibility_km") is not None and air["visibility_km"] < 20
|
||||||
|
humid = air.get("humidity") is not None and air["humidity"] >= 70
|
||||||
|
if hazy and humid:
|
||||||
|
return "먼 건물이 흐릿할 만큼 공기가 뿌옇고 습해서 노을 색이 바래 보일 거예요"
|
||||||
|
if hazy:
|
||||||
|
return "먼 건물이 흐릿할 만큼 공기가 뿌예서 노을 색이 바래 보일 거예요"
|
||||||
|
return "공기가 습해서 노을 색이 바래 보일 거예요"
|
||||||
|
|
||||||
|
|
||||||
|
def topic(word: str) -> str:
|
||||||
|
"""받침 있으면 '은', 없으면 '는'. 오늘은 · 모레는"""
|
||||||
|
last = ord(word[-1]) - 0xAC00
|
||||||
|
return f"{word}{'은' if 0 <= last < 11172 and last % 28 else '는'}"
|
||||||
|
|
||||||
|
|
||||||
|
GRADE_RANK = {SkyGrade.GRAY: 0, SkyGrade.SOFT: 1, SkyGrade.GLOW: 2, SkyGrade.RED: 3}
|
||||||
|
|
||||||
|
|
||||||
|
def sky_title(
|
||||||
|
grade_: SkyGrade, kind: SkyType = SkyType.SUNSET, when: Optional[str] = None, peak_at: Optional[datetime] = None,
|
||||||
|
) -> str:
|
||||||
|
"""히어로·피드 카드 큰 글씨. 점수 등급으로: 잿빛이면 거의 안 보인다고, 아니면 노을 피크 시각과 어떻게 물드는지.
|
||||||
|
when 이 없으면 날 없이(피드 카드)."""
|
||||||
|
w = "아침 노을" if kind is SkyType.SUNRISE else "노을"
|
||||||
|
if grade_ is SkyGrade.GRAY:
|
||||||
|
return f"{topic(when) + ' ' if when else ''}{w}이 거의 안 보여요"
|
||||||
|
pre = f"{peak_at:%H:%M}, " if peak_at is not None else ""
|
||||||
|
day = f"{when} " if when else ""
|
||||||
|
if grade_ is SkyGrade.RED:
|
||||||
|
sky = "아침 하늘" if kind is SkyType.SUNRISE else "하늘"
|
||||||
|
return f"{pre}{day}{sky}이 온통 붉게 물들어요"
|
||||||
|
how = "곱게" if grade_ is SkyGrade.GLOW else "은은하게"
|
||||||
|
return f"{pre}{day}{w}이 {how} 물들어요"
|
||||||
|
|
||||||
|
|
||||||
|
def plain_line(grade_: SkyGrade, situation: SkySituation | None, air: Optional[dict], kind: SkyType = SkyType.SUNSET) -> Optional[str]:
|
||||||
|
"""잿빛 날만, 큰 글씨 아래 왜 안 보이는지 한 줄. 다른 날은 없음."""
|
||||||
|
if grade_ is not SkyGrade.GRAY:
|
||||||
|
return None
|
||||||
|
side = "해 뜨는 쪽" if kind is SkyType.SUNRISE else "해 지는 쪽"
|
||||||
|
by_situation = {
|
||||||
|
SkySituation.COVERED: f"{side} 하늘이 구름에 가려요",
|
||||||
|
SkySituation.LOW_CLOUD: "구름이 낮게 깔려 있어요",
|
||||||
|
SkySituation.THICK: "구름이 너무 두꺼워요",
|
||||||
|
SkySituation.FEW: "구름이 거의 없어요",
|
||||||
|
}
|
||||||
|
if situation in by_situation:
|
||||||
|
return by_situation[situation]
|
||||||
|
return "하늘이 뿌예서 색이 바래요" if air_note(air) else None
|
||||||
|
|
||||||
|
|
||||||
def grade(value: int) -> SkyGrade:
|
def grade(value: int) -> SkyGrade:
|
||||||
if value >= 80:
|
if value >= 80:
|
||||||
return SkyGrade.RED
|
return SkyGrade.RED
|
||||||
@@ -131,23 +205,42 @@ SITUATION_VERDICT = {
|
|||||||
VERDICT_RANK = {"rest": 0, "maybe": 1, "go": 2}
|
VERDICT_RANK = {"rest": 0, "maybe": 1, "go": 2}
|
||||||
|
|
||||||
|
|
||||||
def reason(near20: Layers, far100: Layers) -> str:
|
def reason(near20: Layers, far100: Layers, kind: SkyType = SkyType.SUNSET) -> str:
|
||||||
"""score() 가 깎는 순서대로 본다: 먼 쪽 빛이 막혔나 → 머리 위 낮은 구름 → 물들 중·높은 구름의 양."""
|
"""score() 가 깎는 순서대로 본다: 먼 쪽 빛이 막혔나 → 머리 위 낮은 구름 → 물들 중·높은 구름의 양."""
|
||||||
|
side = "해 뜨는 쪽" if kind is SkyType.SUNRISE else "해 지는 쪽"
|
||||||
if far100.low + 0.5 * far100.mid >= 60:
|
if far100.low + 0.5 * far100.mid >= 60:
|
||||||
return "해 지는 쪽 먼 하늘이 구름에 막혀 빛이 못 들어와요"
|
return f"{side} 멀리까지 구름이 끼어 햇빛이 하늘을 물들이지 못해요"
|
||||||
if near20.low >= 60:
|
if near20.low >= 60:
|
||||||
return "낮은 구름이 머리 위를 덮어 붉은빛을 가려요"
|
return "낮게 깔린 구름이 하늘을 덮어 붉은빛을 가려요"
|
||||||
canvas = round(max(near20.mid, near20.high))
|
canvas = round(max(near20.mid, near20.high))
|
||||||
if canvas < 10:
|
if canvas < 10:
|
||||||
return "물들 구름이 거의 없어 하늘이 은은하게 끝나요"
|
return "하늘에 구름이 거의 없어요. 노을은 구름에 햇빛이 비쳐야 붉어져서 은은하게 끝나요"
|
||||||
if canvas > 85:
|
if canvas > 85:
|
||||||
return f"중·높은 구름이 {canvas}%로 두꺼워 빛이 덜 비쳐요"
|
return "구름이 너무 두껍게 덮여 햇빛이 잘 안 비쳐요"
|
||||||
if 25 <= canvas <= 75:
|
if 25 <= canvas <= 75:
|
||||||
return f"중·높은 구름이 {canvas}% 알맞게 깔리고 해 지는 쪽이 트였어요"
|
return f"{side} 하늘에 구름이 적당히 있어 햇빛을 받아 물들기 좋아요"
|
||||||
return f"물들 중·높은 구름이 {canvas}%로 {'적은' if canvas < 25 else '많은'} 편이에요"
|
return f"구름이 {'적은' if canvas < 25 else '많은'} 편이라 물드는 색이 약할 수 있어요"
|
||||||
|
|
||||||
|
|
||||||
def sunset_timeline(golden_at: datetime, sun_at: datetime, peak_at: datetime | None, blue_at: datetime) -> list[dict]:
|
def _row(kind: str, label: str, at: datetime | None, end: datetime | None = None) -> dict | None:
|
||||||
"""일몰 전 골든아워 → 해 짐 → 가장 붉을 때 → 블루아워. 분 아래는 버린다."""
|
if at is None:
|
||||||
rows = [("golden", "골든아워", golden_at), ("sun", "해 져요", sun_at), ("peak", "가장 붉을 때", peak_at), ("blue", "블루아워", blue_at)]
|
return None
|
||||||
return [{"at": at.replace(second=0, microsecond=0).isoformat(), "kind": kind, "label": label} for kind, label, at in rows if at is not None]
|
row = {"at": at.replace(second=0, microsecond=0).isoformat(), "kind": kind, "label": label}
|
||||||
|
if end is not None:
|
||||||
|
row["end"] = end.replace(second=0, microsecond=0).isoformat()
|
||||||
|
return row
|
||||||
|
|
||||||
|
|
||||||
|
def sunrise_timeline(blue_at: datetime, blue_end_at: datetime, peak_at: datetime | None, sun_at: datetime, golden_end_at: datetime) -> list[dict]:
|
||||||
|
"""블루아워(범위) → 노을 피크 → 해 뜸 → 골든아워(범위). 분 아래는 버린다."""
|
||||||
|
rows = [_row("blue", "블루아워", blue_at, blue_end_at), _row("peak", "노을 피크", peak_at), _row("sun", "해 떠요", sun_at),
|
||||||
|
_row("golden", "골든아워", sun_at, golden_end_at)]
|
||||||
|
return [r for r in rows if r]
|
||||||
|
|
||||||
|
|
||||||
|
def sunset_timeline(golden_at: datetime, sun_at: datetime, peak_at: datetime | None, blue_at: datetime, blue_end_at: datetime) -> list[dict]:
|
||||||
|
"""골든아워 시작 → 해 짐(골든아워 끝) → 노을 피크 → 블루아워(범위). 분 아래는 버린다."""
|
||||||
|
rows = [_row("golden", "골든아워", golden_at), _row("sun", "해 져요", sun_at), _row("peak", "노을 피크", peak_at),
|
||||||
|
_row("blue", "블루아워", blue_at, blue_end_at)]
|
||||||
|
return [r for r in rows if r]
|
||||||
|
|
||||||
@@ -4,6 +4,7 @@ from datetime import date, datetime, timedelta, timezone
|
|||||||
|
|
||||||
_SUN_ALTITUDE = -0.833
|
_SUN_ALTITUDE = -0.833
|
||||||
_CIVIL_ALTITUDE = -6.0
|
_CIVIL_ALTITUDE = -6.0
|
||||||
|
_BLUE_ALTITUDE = -4.0 # 블루아워: 해 고도 -4° ~ -6°
|
||||||
_GOLDEN_ALTITUDE = 6.0
|
_GOLDEN_ALTITUDE = 6.0
|
||||||
|
|
||||||
|
|
||||||
@@ -16,6 +17,9 @@ class SunTimes:
|
|||||||
dawn_start_at: datetime
|
dawn_start_at: datetime
|
||||||
sunrise_azimuth: int
|
sunrise_azimuth: int
|
||||||
golden_start_at: datetime
|
golden_start_at: datetime
|
||||||
|
golden_end_at: datetime # 아침에 해 고도가 골든아워 높이까지 올라오는 때
|
||||||
|
blue_start_at: datetime # 저녁 블루아워 시작 (해 고도 -4°)
|
||||||
|
blue_end_morning_at: datetime # 아침 블루아워 끝 (해 고도 -4°)
|
||||||
|
|
||||||
|
|
||||||
def _solar(d: date, lon: float) -> tuple[float, float]:
|
def _solar(d: date, lon: float) -> tuple[float, float]:
|
||||||
@@ -44,6 +48,7 @@ def sun_times(d: date, lat: float, lon: float) -> SunTimes:
|
|||||||
h_sun = _hour_angle(lat, decl, _SUN_ALTITUDE) * 4
|
h_sun = _hour_angle(lat, decl, _SUN_ALTITUDE) * 4
|
||||||
h_civil = _hour_angle(lat, decl, _CIVIL_ALTITUDE) * 4
|
h_civil = _hour_angle(lat, decl, _CIVIL_ALTITUDE) * 4
|
||||||
h_golden = _hour_angle(lat, decl, _GOLDEN_ALTITUDE) * 4
|
h_golden = _hour_angle(lat, decl, _GOLDEN_ALTITUDE) * 4
|
||||||
|
h_blue = _hour_angle(lat, decl, _BLUE_ALTITUDE) * 4
|
||||||
phi, dl = math.radians(lat), math.radians(decl)
|
phi, dl = math.radians(lat), math.radians(decl)
|
||||||
azimuth = math.degrees(math.acos(max(-1.0, min(1.0, math.sin(dl) / math.cos(phi)))))
|
azimuth = math.degrees(math.acos(max(-1.0, min(1.0, math.sin(dl) / math.cos(phi)))))
|
||||||
return SunTimes(
|
return SunTimes(
|
||||||
@@ -54,4 +59,7 @@ def sun_times(d: date, lat: float, lon: float) -> SunTimes:
|
|||||||
dawn_start_at=at(noon_min - h_civil),
|
dawn_start_at=at(noon_min - h_civil),
|
||||||
sunrise_azimuth=round(azimuth),
|
sunrise_azimuth=round(azimuth),
|
||||||
golden_start_at=at(noon_min + h_golden),
|
golden_start_at=at(noon_min + h_golden),
|
||||||
|
golden_end_at=at(noon_min - h_golden),
|
||||||
|
blue_start_at=at(noon_min + h_blue),
|
||||||
|
blue_end_morning_at=at(noon_min - h_blue),
|
||||||
)
|
)
|
||||||
+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"
|
REALTIME_URL = "https://apis.data.go.kr/B552584/ArpltnInforInqireSvc/getCtprvnRltmMesureDnsty"
|
||||||
STATION_URL = "https://apis.data.go.kr/B552584/MsrstnInfoInqireSvc/getMsrstnList"
|
STATION_URL = "https://apis.data.go.kr/B552584/MsrstnInfoInqireSvc/getMsrstnList"
|
||||||
|
# 전국 조회는 한 번에 15~20초 걸린다. 갱신은 피드 응답과 따로 돌아 기다리게 하지 않는다.
|
||||||
|
BUDGET_SEC = 45.0
|
||||||
|
|
||||||
|
|
||||||
def _int(v) -> Optional[int]:
|
def _int(v) -> Optional[int]:
|
||||||
@@ -26,11 +28,11 @@ def _measured_at(text: str) -> datetime:
|
|||||||
|
|
||||||
|
|
||||||
async def fetch_realtime(client: httpx.AsyncClient) -> list[dict]:
|
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]:
|
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]:
|
def parse_realtime(items: list[dict]) -> list[dict]:
|
||||||
|
|||||||
+5
-4
@@ -1,4 +1,5 @@
|
|||||||
import asyncio
|
import asyncio
|
||||||
|
from typing import Optional
|
||||||
|
|
||||||
import httpx
|
import httpx
|
||||||
|
|
||||||
@@ -17,12 +18,12 @@ class DataGoKrRequestFailed(RuntimeError):
|
|||||||
pass
|
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 를 쉰다. 로그·예외에 키를 남기지 않는다."""
|
"""data.go.kr 공통 호출. 가끔 오는 504(SERVICETIMEOUT)는 다시 시도하고, 응답이 없으면 잠시 그 API 를 쉰다. 로그·예외에 키를 남기지 않는다."""
|
||||||
if not settings.data_go_kr_service_key:
|
if not settings.data_go_kr_service_key:
|
||||||
raise DataGoKrNotConfigured("DATA_GO_KR_SERVICE_KEY is empty")
|
raise DataGoKrNotConfigured("DATA_GO_KR_SERVICE_KEY is empty")
|
||||||
op = url.rsplit("/", 1)[-1]
|
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:
|
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'}")
|
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] = []
|
items: list[dict] = []
|
||||||
page = 1
|
page = 1
|
||||||
while True:
|
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 []
|
raw = body.get("items") or []
|
||||||
chunk = raw.get("item", []) if isinstance(raw, dict) else raw
|
chunk = raw.get("item", []) if isinstance(raw, dict) else raw
|
||||||
chunk = [chunk] if isinstance(chunk, dict) else chunk
|
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"
|
SITEMAP_URL = "https://popga.co.kr/sitemap.xml"
|
||||||
POPUP_URL = "https://popga.co.kr/popup/{id}"
|
POPUP_URL = "https://popga.co.kr/popup/{id}"
|
||||||
SOURCE_PREFIX = "popga:"
|
SOURCE_PREFIX = "popga:"
|
||||||
STORE = "STORE" # 팝가 분류: STORE=팝업스토어, PERFORMANCE=공연, FESTIVAL=축제
|
# 팝가 분류(STORE=팝업스토어, PERFORMANCE=공연, FESTIVAL=축제) 중 받는 것. 공연은 문화정보원에서 따로 받는다
|
||||||
|
_KINDS = {"STORE": EventKind.POPUP, "FESTIVAL": EventKind.FESTIVAL}
|
||||||
REQUEST_GAP_SEC = 0.3
|
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>")
|
_LOC = re.compile(r"<loc>\s*([^<\s]+)\s*</loc>")
|
||||||
_URL = re.compile(r"<url>(.*?)</url>", re.S)
|
_URL = re.compile(r"<url>(.*?)</url>", re.S)
|
||||||
_LASTMOD = re.compile(r"<lastmod>\s*([^<\s]+)\s*</lastmod>")
|
_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]:
|
def parse_popup(page: str, popup_id: int, since: date) -> Optional[dict]:
|
||||||
"""팝업스토어이고 since 이후에 끝나면 event 행, 아니면 None."""
|
"""팝업스토어·축제이고 since 이후에 끝나면 event 행, 아니면 None."""
|
||||||
kind = re.search(rf'\\?"id\\?":{popup_id},\\?"type\\?":\\?"([A-Z_]+)', page)
|
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)
|
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
|
return None
|
||||||
start, end = _date(ld.get("startDate")), _date(ld.get("endDate"))
|
start, end = _date(ld.get("startDate")), _date(ld.get("endDate"))
|
||||||
if start is None or end is None or end < since:
|
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:
|
if sido is None:
|
||||||
return None
|
return None
|
||||||
geo = loc.get("geo") or {}
|
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 {
|
return {
|
||||||
"source_id": f"{SOURCE_PREFIX}{popup_id}", "sido_code": sido, "name": html.unescape(ld.get("name") or "")[:60],
|
"source_id": f"{SOURCE_PREFIX}{popup_id}", "sido_code": sido, "name": name[:60],
|
||||||
"place_name": html.unescape(loc.get("name") or "")[:60], "start_date": start, "end_date": end, "is_confirmed": True,
|
"place_name": place[:60], "start_date": start, "end_date": end, "is_confirmed": True,
|
||||||
"source_url": POPUP_URL.format(id=popup_id), "image_url": None,
|
"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
|
||||||
@@ -11,7 +11,7 @@ from common.cache.lock import redis_lock
|
|||||||
from common.cache.redis_client import REDIS
|
from common.cache.redis_client import REDIS
|
||||||
from common.database.db_session_manager import DB_SESSION_MNG
|
from common.database.db_session_manager import DB_SESSION_MNG
|
||||||
from common.database.model.models import Article, OpenMeteoHourly, Post, Region, WeatherHourly
|
from common.database.model.models import Article, OpenMeteoHourly, Post, Region, WeatherHourly
|
||||||
from common.enums import AirGrade, ArticleCategory, ErrorType, PostType, RainType, RefType, Sky, SkyGrade, SkySituation, WarningType
|
from common.enums import AirGrade, ArticleCategory, ErrorType, PostType, RainType, RefType, Sky, SkyGrade, SkySituation, SkyType, WarningType
|
||||||
from common.logger import LOG
|
from common.logger import LOG
|
||||||
from common.utils.kma_time import KST, kst_midnight, next_vilage_available, now_kst
|
from common.utils.kma_time import KST, kst_midnight, next_vilage_available, now_kst
|
||||||
from common.utils.text import compass, day_range, hour_label, short_day
|
from common.utils.text import compass, day_range, hour_label, short_day
|
||||||
@@ -21,19 +21,20 @@ from crud.season_crud import SeasonCRUD
|
|||||||
from crud.weather_crud import WeatherCRUD
|
from crud.weather_crud import WeatherCRUD
|
||||||
from router.v1.feed.protocol import (
|
from router.v1.feed.protocol import (
|
||||||
BandArticle, BandEvent, Bands, Cut, GakSlide, Hero, HeroStat, HourCell, HoursSlide, PostData, Res_Feed, Row, RowsSlide, SunsetSlide,
|
BandArticle, BandEvent, Bands, Cut, GakSlide, Hero, HeroStat, HourCell, HoursSlide, PostData, Res_Feed, Row, RowsSlide, SunsetSlide,
|
||||||
PlanSlide, PlanStep, TopIndex, WeekDay, WeekSlide,
|
PlanSlide, PlanStep, TopIndex, WeekDay, WeekGak, WeekSlide,
|
||||||
)
|
)
|
||||||
from services.air_service import GRADE_LABEL as AIR_GRADE_LABEL
|
from services.air_service import GRADE_LABEL as AIR_GRADE_LABEL
|
||||||
from services.air_service import pm10_grade, pm25_grade
|
from services.air_service import pm10_grade, pm25_grade
|
||||||
from services.calc.moon import illumination, nearest, phase_name
|
from services.calc.day_slot import NIGHT_AFTER_SUNSET, slot_of
|
||||||
from services.calc.sky_score import GRADE_LABEL, SITUATION_LINE
|
from services.calc.index_calc import rank_score
|
||||||
|
from services.calc.moon import MoonNight, nearest, night, view_line
|
||||||
|
from services.calc.sky_score import GRADE_LABEL, sky_title
|
||||||
from services.calc.sun import sun_times
|
from services.calc.sun import sun_times
|
||||||
from services.hero_stats import UV_HIGH, HeroInput, hero_stats, uv_label
|
from services.hero_stats import UV_HIGH, HeroInput, discomfort_label, hero_stats, hero_status, uv_label, uv_level
|
||||||
from services.index_service import IndexBoard, IndexItem, IndexService
|
from services.index_service import IndexBoard, IndexItem, IndexService
|
||||||
from services.now_service import NowService, NowWeather
|
from services.now_service import NowService, NowWeather
|
||||||
from services.season_service import SeasonService
|
from services.season_service import SeasonService
|
||||||
from services.sky_service import SkyService, SkyView, day_verdict
|
from services.sky_service import SkyService, SkyView, day_verdict
|
||||||
from services.sky_service import outlook as sky_outlook
|
|
||||||
from services.weather_service import TodayWeather, WeatherService
|
from services.weather_service import TodayWeather, WeatherService
|
||||||
from services.week_service import DayPlan, EventItem, WeekService, image_credit, mix_kinds
|
from services.week_service import DayPlan, EventItem, WeekService, image_credit, mix_kinds
|
||||||
from services.weekend_plan import day_plan, forecast, pick_events
|
from services.weekend_plan import day_plan, forecast, pick_events
|
||||||
@@ -62,12 +63,25 @@ LINEUP = [
|
|||||||
(19, PostType.MOON, RefType.NONE, None),
|
(19, PostType.MOON, RefType.NONE, None),
|
||||||
(20, PostType.UV, 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 = {
|
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],
|
"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],
|
"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],
|
"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.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],
|
"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"}
|
_SKY_MODE = {"morning": "morning", "day": "day", "evening": "sunset", "night": "night"}
|
||||||
_CATEGORY_META = {ArticleCategory.SEASON.value: "계절 소식", ArticleCategory.TIP.value: "날씨 상식", ArticleCategory.GAK.value: "각 원리", ArticleCategory.QUOTE.value: "한 문장"}
|
_CATEGORY_META = {ArticleCategory.SEASON.value: "계절 소식", ArticleCategory.TIP.value: "날씨 상식", ArticleCategory.GAK.value: "각 원리", ArticleCategory.QUOTE.value: "한 문장"}
|
||||||
@@ -116,11 +130,9 @@ def _pick(articles: list[Article], day: date) -> Optional[Article]:
|
|||||||
return articles[day.toordinal() % len(articles)] if articles else None
|
return articles[day.toordinal() % len(articles)] if articles else None
|
||||||
|
|
||||||
|
|
||||||
def _discomfort_label(v: int) -> str:
|
def _hero_input(
|
||||||
return "쾌적" if v < 68 else "보통" if v < 75 else "불쾌" if v < 80 else "매우 불쾌"
|
now: datetime, slot: str, cur: Optional[WeatherHourly], now_w: Optional[NowWeather], today: Optional[TodayWeather], uv: Optional[float], moon: Optional[str],
|
||||||
|
) -> HeroInput:
|
||||||
|
|
||||||
def _hero_input(now: datetime, slot: str, cur: Optional[WeatherHourly], now_w: Optional[NowWeather], today: Optional[TodayWeather], uv: Optional[float]) -> HeroInput:
|
|
||||||
temps = [float(x.row.temp_c) for x in today.slots if x.row] if today else []
|
temps = [float(x.row.temp_c) for x in today.slots if x.row] if today else []
|
||||||
rainy = [h for h in now_w.rain_hours if h.rain_type is not RainType.NONE] if now_w else []
|
rainy = [h for h in now_w.rain_hours if h.rain_type is not RainType.NONE] if now_w else []
|
||||||
ahead = [x for x in today.slots if x.row and x.at > now] if today else []
|
ahead = [x for x in today.slots if x.row and x.at > now] if today else []
|
||||||
@@ -130,8 +142,8 @@ def _hero_input(now: datetime, slot: str, cur: Optional[WeatherHourly], now_w: O
|
|||||||
rain_later_at=later, today_known=bool(ahead),
|
rain_later_at=later, today_known=bool(ahead),
|
||||||
air=AirGrade(now_w.air.grade) if now_w and now_w.air and now_w.air.grade is not None else None, uv=uv,
|
air=AirGrade(now_w.air.grade) if now_w and now_w.air and now_w.air.grade is not None else None, uv=uv,
|
||||||
temp_min=min(temps, default=None), temp_max=max(temps, default=None),
|
temp_min=min(temps, default=None), temp_max=max(temps, default=None),
|
||||||
temp=float(cur.temp_c) if cur else None, feels=float(cur.feels_c) if cur else None, discomfort=cur.discomfort_index if cur else None,
|
temp=float(cur.temp_c) if cur else None, feels=float(cur.feels_c) if cur else None,
|
||||||
moon=phase_name(_tonight(now)),
|
moon=moon, humidity=cur.humidity if cur else None, discomfort=cur.discomfort_index if cur else None,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@@ -139,22 +151,12 @@ def feed_day(now: datetime) -> date:
|
|||||||
return (now - timedelta(hours=_FEED_DAY_START)).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:
|
def feed_ttl_sec(now: datetime, sunset_at: datetime) -> int:
|
||||||
"""다음에 피드가 달라지는 시각까지. 시간대 경계·일몰(노을 카드가 내일 것으로)·03:00·예보·미세먼지 갱신 중 가장 빠른 쪽."""
|
"""다음에 피드가 달라지는 시각까지. 시간대 경계·일몰(노을 카드가 내일 것으로)·03:00·예보·미세먼지 갱신 중 가장 빠른 쪽."""
|
||||||
day = now.date()
|
day = now.date()
|
||||||
at = lambda d, h: datetime.combine(d, time(h), tzinfo=KST) # noqa: E731
|
at = lambda d, h: datetime.combine(d, time(h), tzinfo=KST) # noqa: E731
|
||||||
sunset = sunset_at.astimezone(KST)
|
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)]
|
at(day + timedelta(days=1), _FEED_DAY_START), next_vilage_available(now)]
|
||||||
air = now.replace(minute=20, second=0, microsecond=0)
|
air = now.replace(minute=20, second=0, microsecond=0)
|
||||||
changes.append(air if air > now else air + timedelta(hours=1))
|
changes.append(air if air > now else air + timedelta(hours=1))
|
||||||
@@ -222,17 +224,34 @@ def arrange(cards: list[PostData], slot: str, now: datetime, sunset_at: datetime
|
|||||||
return head + rest
|
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:
|
def _top(i: IndexItem) -> TopIndex:
|
||||||
d = i.definition
|
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,
|
||||||
|
slots=i.slots, slot_ranks=i.slot_ranks)
|
||||||
|
|
||||||
|
|
||||||
async def build_feed_day(day: date, crud: FeedCRUD, season_crud: SeasonCRUD) -> ErrorType:
|
async def build_feed_day(day: date, crud: FeedCRUD, season_crud: SeasonCRUD, regions: RegionCRUD) -> ErrorType:
|
||||||
"""그날 피드 카드를 넣는다. 이미 있는 번호는 그대로 두고, 새로 생긴 종류만 더한다. 모든 카드는 03:00 부터 다음 날 03:00 까지 유효하다."""
|
"""그날 피드 카드를 전국 1벌·시도마다 1벌 넣는다. 이미 있는 (scope, 번호)는 그대로 두고, 빠진 것만 더한다.
|
||||||
|
전국 행이 있는 번호는 모든 시도가 그 행을 쓰므로 시도 행을 만들지 않는다. 모든 카드는 03:00 부터 다음 날 03:00 까지 유효하다."""
|
||||||
err, made = await DB_SESSION_MNG.execute_lambda(lambda s: crud.positions(s, day))
|
err, made = await DB_SESSION_MNG.execute_lambda(lambda s: crud.positions(s, day))
|
||||||
if err is not ErrorType.SUCCESS:
|
if err is not ErrorType.SUCCESS:
|
||||||
return err
|
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:
|
if not lineup:
|
||||||
return err
|
return err
|
||||||
_, season = await DB_SESSION_MNG.execute_lambda(lambda s: season_crud.articles(s, day, ArticleCategory.SEASON.value))
|
_, season = await DB_SESSION_MNG.execute_lambda(lambda s: season_crud.articles(s, day, ArticleCategory.SEASON.value))
|
||||||
@@ -241,12 +260,12 @@ async def build_feed_day(day: date, crud: FeedCRUD, season_crud: SeasonCRUD) ->
|
|||||||
start = kst_midnight(day) + timedelta(hours=_FEED_DAY_START)
|
start = kst_midnight(day) + timedelta(hours=_FEED_DAY_START)
|
||||||
end = start + timedelta(days=1)
|
end = start + timedelta(days=1)
|
||||||
rows = []
|
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)
|
ref = refs.get(post_type)
|
||||||
if ref_type is RefType.ARTICLE and ref is None:
|
if ref_type is RefType.ARTICLE and ref is None:
|
||||||
continue
|
continue
|
||||||
rows.append({
|
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,
|
"ref_id": ref.article_id if ref is not None else None, "index_rank": rank,
|
||||||
"published_at": start, "end_at": end,
|
"published_at": start, "end_at": end,
|
||||||
})
|
})
|
||||||
@@ -300,7 +319,7 @@ class FeedService:
|
|||||||
|
|
||||||
day = feed_day(now)
|
day = feed_day(now)
|
||||||
async with redis_lock("lock:feed:build", ttl_sec=20):
|
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)
|
res, partial = await self._assemble(region, now, day, slot, sunset_at)
|
||||||
try:
|
try:
|
||||||
await REDIS.conn.set(key, res.model_dump_json(), ex=_PARTIAL_TTL if partial else feed_ttl_sec(now, sunset_at))
|
await REDIS.conn.set(key, res.model_dump_json(), ex=_PARTIAL_TTL if partial else feed_ttl_sec(now, sunset_at))
|
||||||
@@ -331,7 +350,8 @@ class FeedService:
|
|||||||
_, hourly = await DB_SESSION_MNG.execute_lambda(
|
_, 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)))
|
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))
|
_, 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 []}
|
by_article = {a.article_id: a for a in articles or []}
|
||||||
quotes = [a for a in articles or [] if a.category == ArticleCategory.QUOTE.value]
|
quotes = [a for a in articles or [] if a.category == ArticleCategory.QUOTE.value]
|
||||||
@@ -339,7 +359,7 @@ class FeedService:
|
|||||||
days=days, events=events, sunsets=sunsets, hourly=hourly or [], articles=by_article, quotes=quotes, trip=trip,
|
days=days, events=events, sunsets=sunsets, hourly=hourly or [], articles=by_article, quotes=quotes, trip=trip,
|
||||||
uv=await self._uv_today(region.code, now))
|
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 = []
|
cards = []
|
||||||
for p in posts or []:
|
for p in posts or []:
|
||||||
if PostType(p.post_type) is PostType.GAK:
|
if PostType(p.post_type) is PostType.GAK:
|
||||||
@@ -354,14 +374,15 @@ class FeedService:
|
|||||||
items = board.items if board else []
|
items = board.items if board else []
|
||||||
feed = Res_Feed(
|
feed = Res_Feed(
|
||||||
region_code=region.code, region_name=region.name, slot=slot,
|
region_code=region.code, region_name=region.name, slot=slot,
|
||||||
hero=self._hero(now, slot, hourly[0] if hourly else None, now_w, board, today, await self._uv(region.code, hour)),
|
hero=self._hero(now, slot, hourly[0] if hourly else None, now_w, board, today, await self._uv(region.code, hour), _moon_view(region, now, hourly or [])),
|
||||||
stories=[_top(i) for i in items], posts=arrange(cards, slot, now, sunset_at, has_warning, f"{day}:{region.code}"),
|
stories=[_top(i) for i in items], posts=arrange(cards, slot, now, sunset_at, has_warning, f"{day}:{region.code}"),
|
||||||
bands=Bands(
|
bands=Bands(
|
||||||
events=[BandEvent(event_id=e.event.event_id, name=e.event.name, status_label=e.status_label, icon=e.event.icon,
|
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]],
|
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=[
|
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
|
for a in articles or [] if a.category == ArticleCategory.SEASON.value
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
@@ -394,25 +415,29 @@ class FeedService:
|
|||||||
return [r for r in rows or [] if r.uv_index is not None] if err is ErrorType.SUCCESS else []
|
return [r for r in rows or [] if r.uv_index is not None] if err is ErrorType.SUCCESS else []
|
||||||
|
|
||||||
async def _uv(self, region_code: str, hour: datetime) -> Optional[float]:
|
async def _uv(self, region_code: str, hour: datetime) -> Optional[float]:
|
||||||
err, rows = await DB_SESSION_MNG.execute_lambda(lambda s: self.weather_crud.openmeteo_between(s, region_code, hour, hour))
|
"""지금 칸의 자외선. Open-Meteo 는 3시간 칸이라 지금 시각을 넘지 않는 마지막 칸을 쓴다."""
|
||||||
if err is not ErrorType.SUCCESS or not rows or rows[0].uv_index is None:
|
err, rows = await DB_SESSION_MNG.execute_lambda(lambda s: self.weather_crud.openmeteo_between(s, region_code, hour - timedelta(hours=2), hour))
|
||||||
return None
|
rows = [r for r in rows or [] if r.uv_index is not None] if err is ErrorType.SUCCESS else []
|
||||||
return float(rows[0].uv_index)
|
return float(max(rows, key=lambda r: r.forecast_at).uv_index) if rows else None
|
||||||
|
|
||||||
def _hero(self, now: datetime, slot: str, cur: Optional[WeatherHourly], now_w: Optional[NowWeather], board: Optional[IndexBoard],
|
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:
|
today: Optional[TodayWeather] = None, uv: Optional[float] = None, moon: Optional[tuple[MoonNight, str]] = 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
|
bubble = None
|
||||||
if top is not None:
|
if top is not None:
|
||||||
bubble = f"오늘은 {top.definition.name}!" if top.score.score >= 70 else "오늘은 쉬어 가요"
|
bubble = f"오늘은 {top.definition.name}!" if top.score.score >= 70 else "오늘은 쉬어 가요"
|
||||||
|
x_in = _hero_input(now, slot, cur, now_w, today, uv, f"{moon[0].name}, {moon[1]}" if moon else None)
|
||||||
return Hero(
|
return Hero(
|
||||||
now_at=now, sky_mode=_SKY_MODE[slot],
|
now_at=now, sky_mode=_SKY_MODE[slot],
|
||||||
temp_c=float(cur.temp_c) if cur else None, feels_c=float(cur.feels_c) if cur else None,
|
temp_c=float(cur.temp_c) if cur else None, feels_c=float(cur.feels_c) if cur else None,
|
||||||
discomfort=cur.discomfort_index if cur else None, discomfort_label=_discomfort_label(cur.discomfort_index) if cur else None,
|
humidity=cur.humidity if cur else None,
|
||||||
|
discomfort=cur.discomfort_index if cur else None, discomfort_label=discomfort_label(cur.discomfort_index) if cur else None,
|
||||||
rain_2h_text=now_w.rain_2h_text if now_w else None, will_rain_2h=now_w.will_rain_2h if now_w else None,
|
rain_2h_text=now_w.rain_2h_text if now_w else None, will_rain_2h=now_w.will_rain_2h if now_w else None,
|
||||||
weather_score=board.weather_score if board else None, top1=_top(top) if top else None, bubble=bubble,
|
weather_score=board.weather_score if board else None, weather_slots=board.weather_slots if board else {},
|
||||||
moon_name=phase_name(_tonight(now)), moon_pct=round(illumination(_tonight(now)) * 100),
|
top1=_top(top) if top else None, bubble=bubble,
|
||||||
stats=[HeroStat(icon=x.icon, label=x.label, value=x.value, tone=x.tone) for x in hero_stats(_hero_input(now, slot, cur, now_w, today, uv))],
|
moon_name=moon[0].name if moon else None, moon_pct=round(moon[0].lit * 100) if moon else None,
|
||||||
|
stats=[HeroStat(icon=x.icon, label=x.label, value=x.value, tone=x.tone) for x in hero_stats(x_in)],
|
||||||
|
status=[HeroStat(icon=x.icon, label=x.label, value=x.value, tone=x.tone) for x in hero_status(x_in)],
|
||||||
)
|
)
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
@@ -449,7 +474,8 @@ class FeedService:
|
|||||||
if t in (PostType.SEASON, PostType.TIP) and p.ref_id in c.articles:
|
if t in (PostType.SEASON, PostType.TIP) and p.ref_id in c.articles:
|
||||||
a = c.articles[p.ref_id]
|
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],
|
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:
|
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()])
|
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
|
rank = p.index_rank or 1
|
||||||
@@ -469,7 +495,8 @@ class FeedService:
|
|||||||
for label, w in zip(("이번 주말", "다음 주말"), weekends):
|
for label, w in zip(("이번 주말", "다음 주말"), weekends):
|
||||||
f = forecast(w)
|
f = forecast(w)
|
||||||
slides.append(WeekSlide(kind="week", eyebrow=f"{label} · {day_range(w[0].day, w[-1].day)}", line=f.line, tip=f.tip, days=[
|
slides.append(WeekSlide(kind="week", eyebrow=f"{label} · {day_range(w[0].day, w[-1].day)}", line=f.line, tip=f.tip, days=[
|
||||||
WeekDay(day=d.day, weekday=d.weekday, icon=d.icon, text=d.headline, temp_min_c=d.temp_min_c, temp_max_c=d.temp_max_c, rain_prob=d.rain_prob)
|
WeekDay(day=d.day, weekday=d.weekday, icon=d.icon, text=d.headline, temp_min_c=d.temp_min_c, temp_max_c=d.temp_max_c, rain_prob=d.rain_prob,
|
||||||
|
gaks=_day_gaks(c.board, d.day))
|
||||||
for d in w
|
for d in w
|
||||||
]))
|
]))
|
||||||
first = forecast(weekends[0])
|
first = forecast(weekends[0])
|
||||||
@@ -487,39 +514,42 @@ class FeedService:
|
|||||||
return None
|
return None
|
||||||
|
|
||||||
def _moon(self, base: dict, c: "_Ctx") -> PostData:
|
def _moon(self, base: dict, c: "_Ctx") -> PostData:
|
||||||
"""오늘 밤(정오~다음 날 정오)에 보름이나 삭이 있으면 그 이야기를, 아니면 달 모양·밝기와 다음 보름. 피드 아래쪽에 둔다."""
|
"""오늘 밤(정오~다음 날 정오)에 보름이나 삭이 있으면 그 이야기를, 아니면 달 모양·잘 보이는지와 다음 보름. 피드 아래쪽에 둔다."""
|
||||||
tonight = _tonight(c.now)
|
tonight = _tonight(c.now)
|
||||||
|
m, view = _moon_view(c.region, c.now, c.hourly)
|
||||||
start = tonight.replace(hour=12)
|
start = tonight.replace(hour=12)
|
||||||
full, new = nearest(tonight, True).astimezone(KST), nearest(tonight, False).astimezone(KST)
|
full, new = nearest(tonight, True).astimezone(KST), nearest(tonight, False).astimezone(KST)
|
||||||
at, is_full = (full, True) if start <= full < start + timedelta(days=1) else (new, False) if start <= new < start + timedelta(days=1) else (None, False)
|
at, is_full = (full, True) if start <= full < start + timedelta(days=1) else (new, False) if start <= new < start + timedelta(days=1) else (None, False)
|
||||||
row = next((h for h in c.hourly if h.forecast_at.astimezone(KST) == tonight), None)
|
row = next((h for h in c.hourly if h.forecast_at.astimezone(KST) == tonight), None)
|
||||||
sky = Sky(row.sky) if row is not None else None
|
sky = Sky(row.sky) if row is not None else None
|
||||||
rows = [Row(label="밤 하늘", value=_MOON_SKY[sky])] if sky is not None else []
|
rows = [Row(label=label, value=_clock_word(t)) for label, t in (("달 뜸", m.rise_at), ("달 짐", m.set_at)) if t is not None]
|
||||||
eyebrow = f"오늘 밤 달 · {c.region.short_name}"
|
eyebrow = f"오늘 밤 달 · {c.region.short_name}"
|
||||||
if at is None:
|
if at is None:
|
||||||
name, pct = phase_name(tonight), round(illumination(tonight) * 100)
|
name = m.name
|
||||||
nxt = nearest(tonight + timedelta(days=15), True) if full < tonight else full
|
nxt = nearest(tonight + timedelta(days=15), True) if full < tonight else full
|
||||||
nxt = nxt.astimezone(KST)
|
nxt = nxt.astimezone(KST)
|
||||||
waxing = name in ("초승달", "상현달", "차오르는 달")
|
waxing = name in ("초승달", "상현달", "차오르는 달")
|
||||||
caption = ("구름이 많아 달은 숨바꼭질해요." if sky is Sky.CLOUDY
|
# 본문(잘 보이는지)과 어긋나지 않게: 안 보이는 밤·흐린 밤은 그 이유에 맞춰서
|
||||||
|
caption = ("달이 없는 만큼 별은 더 잘 보여요 ✨" if "안 보여요" in view
|
||||||
|
else "구름 사이로 잠깐씩 보일 수도 있어요." if view.startswith("흐려서")
|
||||||
else "하루하루 차오르는 중이에요. 보름까지 같이 세어 봐요 🌙" if waxing else "조금씩 기우는 중이에요. 그만큼 별은 더 잘 보여요 ✨")
|
else "하루하루 차오르는 중이에요. 보름까지 같이 세어 봐요 🌙" if waxing else "조금씩 기우는 중이에요. 그만큼 별은 더 잘 보여요 ✨")
|
||||||
return PostData(**base, title=f"오늘 밤 {name}", icon="moon", caption=caption,
|
return PostData(**base, title=f"오늘 밤 {name}", icon="moon", caption=caption,
|
||||||
slides=[RowsSlide(kind="rows", eyebrow=eyebrow, line=f"오늘 밤은 {name},\n밝기 {pct}%", icon="moon",
|
slides=[RowsSlide(kind="rows", eyebrow=eyebrow, line=f"오늘 밤은 {name},\n{view}", icon="moon",
|
||||||
rows=[*rows, Row(label="다음 보름", value=f"{nxt.month}.{nxt.day:02d} ({_WEEKDAY_KO[nxt.weekday()]})")])],
|
rows=[*rows, Row(label="다음 보름", value=f"{nxt.month}.{nxt.day:02d} ({_WEEKDAY_KO[nxt.weekday()]})")])],
|
||||||
share_messages=[f"오늘 밤은 {name}이래 🌙"])
|
share_messages=[f"오늘 밤은 {name}이래 🌙"])
|
||||||
when = f"{'내일 ' if at.date() > tonight.date() else ''}{at:%H:%M}"
|
when = f"{'내일 ' if at.date() > tonight.date() else ''}{at:%H:%M}"
|
||||||
if is_full:
|
if is_full:
|
||||||
line = f"오늘 밤 보름달,\n{when}에 가장 둥글어요"
|
line = f"오늘 밤 보름달,\n{when}에 가장 둥글어요"
|
||||||
caption = "구름 사이로 잠깐씩 보일 수 있어요." if sky is Sky.CLOUDY else "소원 빌기 딱 좋은 밤이에요 🌕"
|
caption = "구름 사이로 잠깐씩 보일 수 있어요." if view.startswith("흐려서") else "소원 빌기 딱 좋은 밤이에요 🌕"
|
||||||
return PostData(**base, title="오늘 밤 보름달", icon="moon", caption=caption,
|
return PostData(**base, title="오늘 밤 보름달", icon="moon", caption=caption,
|
||||||
slides=[RowsSlide(kind="rows", eyebrow=eyebrow, line=line, icon="moon", rows=[Row(label="달 밝기", value="100%"), *rows])],
|
slides=[RowsSlide(kind="rows", eyebrow=eyebrow, line=line, icon="moon", rows=[Row(label="보이는지", value=view), *rows])],
|
||||||
share_messages=["오늘 밤 보름달이래 🌕 같이 볼래?"])
|
share_messages=["오늘 밤 보름달이래 🌕 같이 볼래?"])
|
||||||
stars = next((i for i in (c.board.items if c.board else []) if i.definition.code == "stars"), None)
|
stars = next((i for i in (c.board.items if c.board else []) if i.definition.code == "stars"), None)
|
||||||
if stars is not None:
|
if stars is not None:
|
||||||
rows.append(Row(label="별보기각", value=f"{stars.score.score}점"))
|
rows.append(Row(label="별보기각", value=f"{stars.score.score}점"))
|
||||||
caption = "구름이 많아 별은 아쉬워요." if sky is Sky.CLOUDY else "불빛 적은 곳으로 조금만 나가 봐요 ✨"
|
caption = "구름이 많아 별은 아쉬워요." if sky is Sky.CLOUDY else "불빛 적은 곳으로 조금만 나가 봐요 ✨"
|
||||||
return PostData(**base, title="오늘 밤 달 없는 밤", icon="moon", caption=caption,
|
return PostData(**base, title="오늘 밤 달 없는 밤", icon="moon", caption=caption,
|
||||||
slides=[RowsSlide(kind="rows", eyebrow=eyebrow, line="달이 숨는 밤,\n별이 제일 잘 보여요", icon="moon", rows=[Row(label="달 밝기", value="0%"), *rows])],
|
slides=[RowsSlide(kind="rows", eyebrow=eyebrow, line="달이 숨는 밤,\n별이 제일 잘 보여요", icon="moon", rows=rows)],
|
||||||
share_messages=["오늘 밤 달이 없어서 별 보기 좋대 ✨"])
|
share_messages=["오늘 밤 달이 없어서 별 보기 좋대 ✨"])
|
||||||
|
|
||||||
def _day_trip(self, base: dict, pick: TripPick, events: list[EventItem]) -> PostData:
|
def _day_trip(self, base: dict, pick: TripPick, events: list[EventItem]) -> PostData:
|
||||||
@@ -596,14 +626,13 @@ class FeedService:
|
|||||||
return None
|
return None
|
||||||
label = uv_label(top)
|
label = uv_label(top)
|
||||||
at = peak.forecast_at.astimezone(KST)
|
at = peak.forecast_at.astimezone(KST)
|
||||||
rows = [Row(label=f"{r.forecast_at.astimezone(KST).hour}시", value=f"{round(float(r.uv_index))} · {uv_label(float(r.uv_index))}") for r in c.uv]
|
rows = [Row(label=f"{r.forecast_at.astimezone(KST).hour}시", value=uv_label(float(r.uv_index)), level=uv_level(float(r.uv_index))) for r in c.uv]
|
||||||
high = top >= UV_HIGH
|
when = "점심때" if at.hour == 12 else f"{hour_label(at.hour)} 무렵"
|
||||||
if high:
|
todo = "선크림·모자·선글라스 챙기고 그늘로 다녀요" if top >= UV_HIGH else "선크림·모자 챙겨요"
|
||||||
rows.append(Row(label="이렇게 해요", value="선크림 바르고, 모자·선글라스 챙겨요"))
|
line = f"오늘 자외선 지수 {label}\n{when} 나가면 {todo}"
|
||||||
line = f"{hour_label(at.hour)} 무렵 자외선 {label},\n" + ("선크림 꼭 챙겨요" if high else "오래 밖에 있으면 선크림")
|
return PostData(**base, title=f"자외선 지수 {label}", icon="glasses", caption=f"가장 셀 때 {hour_label(at.hour)}",
|
||||||
return PostData(**base, title=f"자외선 {label}", icon="glasses", caption=f"가장 셀 때 {hour_label(at.hour)} · {round(top)}",
|
|
||||||
slides=[RowsSlide(kind="rows", eyebrow=f"오늘 자외선 · {c.region.short_name}", line=line, icon="glasses", rows=rows)],
|
slides=[RowsSlide(kind="rows", eyebrow=f"오늘 자외선 · {c.region.short_name}", line=line, icon="glasses", rows=rows)],
|
||||||
share_messages=[f"오늘 자외선 {label}, 선크림 챙겨!"])
|
share_messages=[f"오늘 자외선 지수 {label}, 선크림 챙겨!"])
|
||||||
|
|
||||||
def _air(self, base: dict, c: "_Ctx") -> Optional[PostData]:
|
def _air(self, base: dict, c: "_Ctx") -> Optional[PostData]:
|
||||||
"""가까운 측정소의 지금 초미세먼지·미세먼지. 측정값이 없거나 3시간 넘게 지났으면 끈다."""
|
"""가까운 측정소의 지금 초미세먼지·미세먼지. 측정값이 없거나 3시간 넘게 지났으면 끈다."""
|
||||||
@@ -625,29 +654,28 @@ class FeedService:
|
|||||||
share_messages=[f"{c.region.short_name} 지금 미세먼지 {label} {tail}"])
|
share_messages=[f"{c.region.short_name} 지금 미세먼지 {label} {tail}"])
|
||||||
|
|
||||||
def _sunset(self, base: dict, c: "_Ctx") -> Optional[PostData]:
|
def _sunset(self, base: dict, c: "_Ctx") -> Optional[PostData]:
|
||||||
"""해 지기 전엔 오늘, 진 뒤엔 내일 노을. 하늘 상황으로 말하고, '쉬어요'면 한 줄 카드."""
|
"""노을 탭 결론과 같은 것: 해 뜨기 전·밤엔 일출, 그 사이엔 노을. 노을 탭 히어로와 같은 문장, 안 볼 만한 날은 한 줄 카드."""
|
||||||
after = c.now >= c.sunset_at
|
plan = c.sky.plan
|
||||||
target = next((x for x in c.sky.days if x.score_date > c.now.date()), None) if after else c.sky.sunset
|
if plan is None:
|
||||||
if target is None:
|
|
||||||
return None
|
return None
|
||||||
when = "내일" if after else "오늘"
|
target, when, rise = plan.target, plan.when, plan.kind is SkyType.SUNRISE
|
||||||
|
word, icon = ("일출", "sun") if rise else ("노을", "sunset")
|
||||||
sit = SkySituation(target.situation) if target.situation else None
|
sit = SkySituation(target.situation) if target.situation else None
|
||||||
line = SITUATION_LINE[sit] if sit else GRADE_LABEL[SkyGrade(target.grade)]
|
line = plan.situation_label or "" # 보이는 날만 그날 하늘 한 줄
|
||||||
better = sky_outlook(target, c.sky.days, c.now.date())
|
better = plan.outlook
|
||||||
sun = next((b for b in target.best_times if b["kind"] == "sun"), target.best_times[0])
|
if day_verdict(target) == "rest" or SkyGrade(target.grade) is SkyGrade.GRAY: # 거의 안 보이는 날은 한 줄 카드
|
||||||
sun_at = datetime.fromisoformat(sun["at"]).astimezone(KST)
|
return PostData(**base, size="line", title=plan.title, icon=icon, caption=" ".join(filter(None, [line and f"{line}.", better])),
|
||||||
if day_verdict(target) == "rest":
|
slides=[], share_messages=[plan.title])
|
||||||
return PostData(**base, size="line", title=f"{when} 노을은 쉬어요", icon="sunset", caption=f"{line}." + (f" {better}" if better else ""),
|
|
||||||
slides=[], share_messages=[f"{when} 노을은 쉬어요, {line}"])
|
|
||||||
cuts = [Cut(**b) for b in target.best_times if b["kind"] != "peak"]
|
cuts = [Cut(**b) for b in target.best_times if b["kind"] != "peak"]
|
||||||
slides = [SunsetSlide(kind="sunset", eyebrow=f"{when} 노을 · {c.region.name}", line=line, score=target.score,
|
slides = [SunsetSlide(kind="sunset", eyebrow=f"{when} {word} · {c.region.name}", line=line, score=target.score,
|
||||||
grade_label=line, cuts=cuts, situation=sit)]
|
grade_label=GRADE_LABEL[SkyGrade(target.grade)], cuts=cuts, situation=sit,
|
||||||
if c.sky.spots:
|
headline=sky_title(SkyGrade(target.grade), plan.kind, None, plan.best_at), peak_at=plan.best_at)]
|
||||||
|
if c.sky.spots and not rise:
|
||||||
slides.append(RowsSlide(kind="rows", eyebrow="가까운 노을 명소", line=f"해 지는 {compass(c.sky.sunset_azimuth)}쪽", icon="sunset",
|
slides.append(RowsSlide(kind="rows", eyebrow="가까운 노을 명소", line=f"해 지는 {compass(c.sky.sunset_azimuth)}쪽", icon="sunset",
|
||||||
rows=[Row(label=f"{n + 1} {x.spot.name}", value=f"{compass(x.direction)} {x.distance_km}km", place=x.spot.name) for n, x in enumerate(c.sky.spots)]))
|
rows=[Row(label=f"{n + 1} {x.spot.name}", value=f"{compass(x.direction)} {x.distance_km}km", place=x.spot.name) for n, x in enumerate(c.sky.spots)]))
|
||||||
caption = better or "보통 해 진 뒤 10~20분이 가장 붉어요."
|
caption = better or ("보통 해 뜨기 10~20분 전이 가장 붉어요." if rise else "보통 해 진 뒤 10~20분이 가장 붉어요.")
|
||||||
return PostData(**base, title=f"{when} 노을 · {line}", icon="sunset", caption=caption,
|
share = f"{plan.title} {'🌅' if rise else '🌇'}"
|
||||||
slides=slides, share_messages=[f"{when} 노을, {line} 🌇 {sun_at:%H:%M}에 해 져요"])
|
return PostData(**base, title=plan.title, icon=icon, caption=caption, slides=slides, share_messages=[share])
|
||||||
|
|
||||||
def _tomorrow(self, base: dict, c: "_Ctx") -> PostData:
|
def _tomorrow(self, base: dict, c: "_Ctx") -> PostData:
|
||||||
tomorrow = c.now.date() + timedelta(days=1)
|
tomorrow = c.now.date() + timedelta(days=1)
|
||||||
@@ -655,7 +683,7 @@ class FeedService:
|
|||||||
best = None
|
best = None
|
||||||
for i in c.board.items if c.board else []:
|
for i in c.board.items if c.board else []:
|
||||||
s = next((x for x in i.trend if x.score_date == tomorrow), None)
|
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)
|
best = (i, s)
|
||||||
if best is not None:
|
if best is not None:
|
||||||
rows.append(Row(label="내일 1위 각", value=f"{best[0].definition.name} {best[1].score}점"))
|
rows.append(Row(label="내일 1위 각", value=f"{best[0].definition.name} {best[1].score}점"))
|
||||||
@@ -723,7 +751,29 @@ def _event_caption(e: EventItem) -> str:
|
|||||||
return "일정이 확정됐어요." if e.event.is_confirmed else "올해 정확한 일정은 공식 안내로 확인해 주세요."
|
return "일정이 확정됐어요." if e.event.is_confirmed else "올해 정확한 일정은 공식 안내로 확인해 주세요."
|
||||||
|
|
||||||
|
|
||||||
_MOON_SKY = {Sky.CLEAR: "맑음, 잘 보여요", Sky.PARTLY: "구름 조금, 사이사이 보여요", Sky.CLOUDY: "흐림, 가려질 수 있어요"}
|
_CLOUDY = {Sky.CLEAR: 0.0, Sky.PARTLY: 0.5, Sky.CLOUDY: 1.0}
|
||||||
|
|
||||||
|
|
||||||
|
def _day_gaks(board: Optional[IndexBoard], day: date, n: int = 3) -> list[WeekGak]:
|
||||||
|
"""그날 대표 각: 각 상세의 날짜별 점수(하루 중 가장 좋은 시간대)를 점수 × 중요도 순으로."""
|
||||||
|
scored = [(i.definition, s) for i in (board.items if board else []) for s in i.trend if s.score_date == day]
|
||||||
|
scored.sort(key=lambda x: rank_score(x[1].score, x[0].priority), reverse=True)
|
||||||
|
return [WeekGak(index_id=d.index_id, name=d.name, icon=d.icon, score=s.score) for d, s in scored[:n]]
|
||||||
|
|
||||||
|
|
||||||
|
def _moon_view(region: Region, now: datetime, hourly: list[WeatherHourly]) -> tuple[MoonNight, str]:
|
||||||
|
"""오늘 밤 달과 잘 보이는지 한 마디. 구름은 달이 떠 있는 시각의 시간별 예보 하늘로 본다."""
|
||||||
|
day = feed_day(now.astimezone(KST))
|
||||||
|
m = night(day, float(region.lat), float(region.lon))
|
||||||
|
start = kst_midnight(day)
|
||||||
|
by_at = {h.forecast_at: h for h in hourly}
|
||||||
|
skies = [_CLOUDY[Sky(r.sky)] for h in m.up_hours if (r := by_at.get(start + timedelta(hours=h))) is not None]
|
||||||
|
return m, view_line(m, sum(skies) / len(skies) if skies else None)
|
||||||
|
|
||||||
|
|
||||||
|
def _clock_word(at: datetime) -> str:
|
||||||
|
h = at.astimezone(KST).hour
|
||||||
|
return f"{'새벽' if h < 6 else '밤' if h >= 21 or h == 0 else '저녁'} {h % 12 or 12}시 {at.astimezone(KST).minute:02d}분"
|
||||||
|
|
||||||
|
|
||||||
def _tonight(now: datetime) -> datetime:
|
def _tonight(now: datetime) -> datetime:
|
||||||
|
|||||||
@@ -10,10 +10,11 @@ from services.air_service import GRADE_LABEL
|
|||||||
Tone = Literal["normal", "warn", "rain"]
|
Tone = Literal["normal", "warn", "rain"]
|
||||||
|
|
||||||
UV_HIGH = 6.0
|
UV_HIGH = 6.0
|
||||||
|
MUGGY_DI = 75 # 불쾌지수 '불쾌'가 시작되는 값
|
||||||
|
HUMID_DRY, HUMID_WET = 30, 60 # 습도 % : 이 아래 건조, 이 위 습함
|
||||||
TEMP_SWING_C = 10.0
|
TEMP_SWING_C = 10.0
|
||||||
WIND_CHILL_C = 3.0
|
WIND_CHILL_C = 3.0
|
||||||
MUGGY = 75
|
SHOWN = 1
|
||||||
SHOWN = 2
|
|
||||||
|
|
||||||
|
|
||||||
@dataclass(frozen=True)
|
@dataclass(frozen=True)
|
||||||
@@ -38,16 +39,43 @@ class HeroInput:
|
|||||||
temp_max: Optional[float] = None
|
temp_max: Optional[float] = None
|
||||||
temp: Optional[float] = None
|
temp: Optional[float] = None
|
||||||
feels: Optional[float] = None
|
feels: Optional[float] = None
|
||||||
discomfort: Optional[int] = None
|
|
||||||
moon: Optional[str] = None
|
moon: Optional[str] = None
|
||||||
|
humidity: Optional[int] = None
|
||||||
|
discomfort: Optional[int] = None
|
||||||
|
|
||||||
|
|
||||||
|
_UV_LABELS = ("낮음", "보통", "높음", "매우 높음", "위험")
|
||||||
|
|
||||||
|
|
||||||
|
def uv_level(uv: float) -> int:
|
||||||
|
"""기상청 자외선 단계 1 낮음 ~ 5 위험."""
|
||||||
|
return 1 if uv < 3 else 2 if uv < 6 else 3 if uv < 8 else 4 if uv < 11 else 5
|
||||||
|
|
||||||
|
|
||||||
def uv_label(uv: float) -> str:
|
def uv_label(uv: float) -> str:
|
||||||
return "낮음" if uv < 3 else "보통" if uv < 6 else "높음" if uv < 8 else "매우 높음" if uv < 11 else "위험"
|
return _UV_LABELS[uv_level(uv) - 1]
|
||||||
|
|
||||||
|
|
||||||
def _discomfort_label(v: int) -> str:
|
def discomfort_label(v: int) -> str:
|
||||||
return "보통" if v < 75 else "높음" if v < 80 else "매우 높음"
|
return "쾌적" if v < 68 else "보통" if v < MUGGY_DI else "불쾌" if v < 80 else "매우 불쾌"
|
||||||
|
|
||||||
|
|
||||||
|
def humidity_label(h: int) -> str:
|
||||||
|
return "건조" if h < HUMID_DRY else "보통" if h <= HUMID_WET else "습함"
|
||||||
|
|
||||||
|
|
||||||
|
def hero_status(x: HeroInput) -> list[HeroStatItem]:
|
||||||
|
"""히어로 상태 한 줄: 습도·불쾌지수·자외선(낮에만)·미세먼지를 단계 이름으로. 값이 없는 칸은 뺀다. 조심할 것만 warn."""
|
||||||
|
out: list[HeroStatItem] = []
|
||||||
|
if x.humidity is not None:
|
||||||
|
out.append(HeroStatItem("humidity", "muggy", "습도", humidity_label(x.humidity)))
|
||||||
|
if x.discomfort is not None:
|
||||||
|
out.append(HeroStatItem("discomfort", "muggy", "불쾌지수", discomfort_label(x.discomfort), "warn" if x.discomfort >= MUGGY_DI else "normal"))
|
||||||
|
if not x.night and x.uv is not None:
|
||||||
|
out.append(HeroStatItem("uv", "glasses", "자외선", uv_label(x.uv), "warn" if x.uv >= UV_HIGH else "normal"))
|
||||||
|
if x.air is not None:
|
||||||
|
out.append(HeroStatItem("air", "mask", "미세먼지", GRADE_LABEL[x.air], "warn" if x.air in (AirGrade.BAD, AirGrade.VERY_BAD) else "normal"))
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
def _rain_value(now: datetime, at: datetime) -> str:
|
def _rain_value(now: datetime, at: datetime) -> str:
|
||||||
@@ -55,7 +83,7 @@ def _rain_value(now: datetime, at: datetime) -> str:
|
|||||||
|
|
||||||
|
|
||||||
def hero_stats(x: HeroInput) -> list[HeroStatItem]:
|
def hero_stats(x: HeroInput) -> list[HeroStatItem]:
|
||||||
"""히어로 두 칸. 지금 챙겨야 할 것(경고)을 먼저, 모자라면 기본값으로 채운다."""
|
"""히어로 상황 칸 (습도·불쾌지수는 늘 따로 보인다). 지금 챙겨야 할 것(경고)을 먼저, 모자라면 기본값으로 채운다."""
|
||||||
alerts: list[HeroStatItem] = []
|
alerts: list[HeroStatItem] = []
|
||||||
if x.rain_at is not None:
|
if x.rain_at is not None:
|
||||||
alerts.append(HeroStatItem("rain", "umbrella", "지금 비", _rain_value(x.now, x.rain_at), "rain"))
|
alerts.append(HeroStatItem("rain", "umbrella", "지금 비", _rain_value(x.now, x.rain_at), "rain"))
|
||||||
@@ -69,8 +97,6 @@ def hero_stats(x: HeroInput) -> list[HeroStatItem]:
|
|||||||
alerts.append(HeroStatItem("swing", "coldwind", f"일교차 {round(x.temp_max - x.temp_min)}°", "아침엔 겉옷"))
|
alerts.append(HeroStatItem("swing", "coldwind", f"일교차 {round(x.temp_max - x.temp_min)}°", "아침엔 겉옷"))
|
||||||
if x.temp is not None and x.feels is not None and x.temp - x.feels >= WIND_CHILL_C:
|
if x.temp is not None and x.feels is not None and x.temp - x.feels >= WIND_CHILL_C:
|
||||||
alerts.append(HeroStatItem("chill", "coldwind", f"체감 {round(x.feels)}°", "바람 쌀쌀"))
|
alerts.append(HeroStatItem("chill", "coldwind", f"체감 {round(x.feels)}°", "바람 쌀쌀"))
|
||||||
if x.discomfort is not None and x.discomfort >= MUGGY:
|
|
||||||
alerts.append(HeroStatItem("muggy", "muggy", "불쾌지수", f"{x.discomfort} · {_discomfort_label(x.discomfort)}", "warn"))
|
|
||||||
|
|
||||||
# 챙길 게 없을 땐 하루 기준 비 소식과 밤의 달만. '미세먼지 좋음'·'자외선 낮음' 같은 값으로 칸을 채우지 않는다
|
# 챙길 게 없을 땐 하루 기준 비 소식과 밤의 달만. '미세먼지 좋음'·'자외선 낮음' 같은 값으로 칸을 채우지 않는다
|
||||||
fills: list[HeroStatItem] = []
|
fills: list[HeroStatItem] = []
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import asyncio
|
import asyncio
|
||||||
from dataclasses import dataclass, replace
|
from dataclasses import dataclass, field, replace
|
||||||
from datetime import date, datetime, time, timedelta
|
from datetime import date, datetime, time, timedelta
|
||||||
from types import SimpleNamespace
|
from types import SimpleNamespace
|
||||||
from typing import Optional
|
from typing import Optional
|
||||||
@@ -16,8 +16,9 @@ from crud.sky_crud import SkyCRUD
|
|||||||
from crud.weather_crud import WeatherCRUD
|
from crud.weather_crud import WeatherCRUD
|
||||||
from crud.week_crud import WeekCRUD
|
from crud.week_crud import WeekCRUD
|
||||||
from services.air_service import GRADE_LABEL, AirService
|
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.moon import illumination
|
from services.calc.index_calc import AXES, Context, DayForecast, Hour, Result, estimate, evaluate, rank_score
|
||||||
|
from services.calc.moon import night, up_ratio, view_line
|
||||||
from services.calc.sun import sun_times
|
from services.calc.sun import sun_times
|
||||||
from services.external.open_meteo import is_dark_slot
|
from services.external.open_meteo import is_dark_slot
|
||||||
from services.warning_service import WarningService
|
from services.warning_service import WarningService
|
||||||
@@ -26,16 +27,18 @@ from services.weather_service import WeatherService
|
|||||||
# 시간별 예보로 늘 계산하는 날 수 (오늘~모레). 이번 주말은 시간별 예보가 없으면 중기예보로 예상 점수를 낸다.
|
# 시간별 예보로 늘 계산하는 날 수 (오늘~모레). 이번 주말은 시간별 예보가 없으면 중기예보로 예상 점수를 낸다.
|
||||||
DAYS = 3
|
DAYS = 3
|
||||||
_LOOKAHEAD_HOURS = (9, 18)
|
_LOOKAHEAD_HOURS = (9, 18)
|
||||||
|
_STARS_HOURS = range(21, 26) # 달빛이 별보기를 가리는지 보는 시각 (별보기각 시간대)
|
||||||
_WEEKDAY_KO = ("월", "화", "수", "목", "금", "토", "일")
|
_WEEKDAY_KO = ("월", "화", "수", "목", "금", "토", "일")
|
||||||
|
|
||||||
# 메인 하늘 영역의 '오늘 날씨 점수': 낮 9~21시 밖에 나가기 좋은 정도.
|
# 메인 하늘 영역의 '지금 날씨 점수': 지금 구간(아침·낮·저녁·밤) 밖에 나가기 좋은 정도.
|
||||||
WEATHER_SCORE_DEF = SimpleNamespace(
|
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={
|
factor_rules={
|
||||||
"temp": {"type": "range", "lo": 18, "hi": 24}, "rain": {"dir": "dry"}, "wind": {"type": "calm", "ok": 4, "limit": 12},
|
"temp": {"type": "range", "lo": 18, "hi": 24, "best": 21, "plateau": 0.5}, "rain": {"dir": "dry"},
|
||||||
"humidity": {"type": "ignore"}, "time": {"type": "fixed", "value": 100},
|
"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 +48,10 @@ class IndexItem:
|
|||||||
score: IndexScore
|
score: IndexScore
|
||||||
rank: int
|
rank: int
|
||||||
trend: list[IndexScore]
|
trend: list[IndexScore]
|
||||||
|
slot: Optional[str] = None
|
||||||
|
slots: dict[str, int] = field(default_factory=dict)
|
||||||
|
slot_ranks: dict[str, int] = field(default_factory=dict) # 구간별 순위. 그 구간과 안 겹치는 각은 없음
|
||||||
|
active: bool = True # 지금 구간이 이 각의 시간대와 겹치는지. 아니면 순위·피드에서 빼고 목록 끝에 하루 점수로 둔다
|
||||||
|
|
||||||
|
|
||||||
@dataclass
|
@dataclass
|
||||||
@@ -53,6 +60,12 @@ class IndexBoard:
|
|||||||
day: date
|
day: date
|
||||||
weather_score: Optional[int]
|
weather_score: Optional[int]
|
||||||
items: list[IndexItem]
|
items: list[IndexItem]
|
||||||
|
weather_slots: dict[str, int] = field(default_factory=dict)
|
||||||
|
|
||||||
|
@property
|
||||||
|
def ranked(self) -> list[IndexItem]:
|
||||||
|
"""지금 구간에 해당하는 각만 (순위·피드용)."""
|
||||||
|
return [i for i in self.items if i.active]
|
||||||
|
|
||||||
|
|
||||||
def _hour(r: WeatherHourly) -> Hour:
|
def _hour(r: WeatherHourly) -> Hour:
|
||||||
@@ -118,13 +131,17 @@ def _om_fields(instant: Optional[OpenMeteoHourly], covering: Optional[OpenMeteoH
|
|||||||
|
|
||||||
|
|
||||||
def windows_for(
|
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]]:
|
) -> list[list[Hour]]:
|
||||||
"""시간대 정의를 그날의 시간별 날씨 목록으로 바꾼다. 24시 이후는 다음 날로 넘어간다. 시간마다 Open-Meteo 3시간 구간 값을 붙인다 (순간값은 가장 가까운 구간, 일조는 덮는 구간)."""
|
"""시간대 정의를 그날의 시간별 날씨 목록으로 바꾼다. 24시 이후는 다음 날로 넘어간다. 시간마다 Open-Meteo 3시간 구간 값을 붙인다 (순간값은 가장 가까운 구간, 일조는 덮는 구간).
|
||||||
|
only 가 있으면 그 시각만 남긴다."""
|
||||||
by_om = by_om or {}
|
by_om = by_om or {}
|
||||||
start = kst_midnight(day)
|
start = kst_midnight(day)
|
||||||
out = []
|
out = []
|
||||||
for hours in window_hours(defn, day, region):
|
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]
|
rows = [by_at.get(start + timedelta(hours=h)) for h in hours]
|
||||||
out.append([
|
out.append([
|
||||||
replace(_hour(r), hour=h, **_om_fields(
|
replace(_hour(r), hour=h, **_om_fields(
|
||||||
@@ -135,6 +152,50 @@ def windows_for(
|
|||||||
return out
|
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 _shown_parts(parts: dict[str, int], cur: str) -> dict[str, int]:
|
||||||
|
"""구간 점수를 아침·낮·저녁·밤 순으로. 0~5시면 밤은 전날 밤 구간을 쓴다."""
|
||||||
|
shown = {shown_slot(k): v for k, v in parts.items() if k != ("night" if cur == EARLY else EARLY)}
|
||||||
|
return {k: shown[k] for k in SLOTS if k in shown}
|
||||||
|
|
||||||
|
|
||||||
|
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:
|
def day_forecast(d: WeatherDaily) -> DayForecast:
|
||||||
return DayForecast(
|
return DayForecast(
|
||||||
temp_min_c=float(d.temp_min_c) if d.temp_min_c is not None else None,
|
temp_min_c=float(d.temp_min_c) if d.temp_min_c is not None else None,
|
||||||
@@ -200,28 +261,58 @@ class IndexService:
|
|||||||
if region is None:
|
if region is None:
|
||||||
return ErrorType.NOT_FOUND, None
|
return ErrorType.NOT_FOUND, None
|
||||||
now = now_kst()
|
now = now_kst()
|
||||||
err, weather_score = await self.ensure(region, now)
|
err, weather_parts = await self.ensure(region, now)
|
||||||
if err is not ErrorType.SUCCESS:
|
if err is not ErrorType.SUCCESS:
|
||||||
return err, None
|
return err, None
|
||||||
today = now.date()
|
today = now.date()
|
||||||
|
cur = current_slot(now, sun_times(today, float(region.lat), float(region.lon)).sunset_at)
|
||||||
slots = slot_days(today)
|
slots = slot_days(today)
|
||||||
err, defs = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.definitions(s))
|
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]))
|
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):
|
if ErrorType.DB_ERROR in (err, err2):
|
||||||
return ErrorType.DB_ERROR, None
|
return ErrorType.DB_ERROR, None
|
||||||
by_key = {(x.index_id, x.score_date): x for x in scores}
|
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 = [
|
now_score: dict[int, IndexScore] = {}
|
||||||
IndexItem(
|
for d in defs:
|
||||||
definition=d, score=by_key[(d.index_id, today)], rank=i + 1,
|
row = by_key.get((d.index_id, today))
|
||||||
trend=[by_key[k] for k in ((d.index_id, day) for day in slots) if k in by_key],
|
if row is None:
|
||||||
)
|
continue
|
||||||
for i, d in enumerate(ranked)
|
if not row.slots:
|
||||||
]
|
now_score[d.index_id] = row
|
||||||
return ErrorType.SUCCESS, IndexBoard(region=region, day=today, weather_score=weather_score, items=items)
|
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_parts({k: v["score"] for k, v in row.slots.items()}, cur)
|
||||||
|
items.append(IndexItem(
|
||||||
|
definition=d, score=now_score[d.index_id], rank=i + 1,
|
||||||
|
trend=[now_score[d.index_id] if day == today else by_key[(d.index_id, day)] for day in slots if (d.index_id, day) in by_key],
|
||||||
|
slot=shown_slot(cur), slots=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_parts({k: v["score"] for k, v in row.slots.items()}, cur), active=False,
|
||||||
|
))
|
||||||
|
for k in SLOTS:
|
||||||
|
in_slot = sorted((i for i in items if k in i.slots), key=lambda i: rank_score(i.slots[k], i.definition.priority), reverse=True)
|
||||||
|
for n, i in enumerate(in_slot):
|
||||||
|
i.slot_ranks[k] = n + 1
|
||||||
|
return ErrorType.SUCCESS, IndexBoard(
|
||||||
|
region=region, day=today, weather_score=weather_parts.get(cur), items=items, weather_slots=_shown_parts(weather_parts, cur),
|
||||||
|
)
|
||||||
|
|
||||||
async def ensure(self, region: Region, now: datetime) -> tuple[ErrorType, Optional[int]]:
|
async def ensure(self, region: Region, now: datetime) -> tuple[ErrorType, Optional[dict[str, int]]]:
|
||||||
"""재료(예보·미세먼지)가 지수 계산 뒤에 바뀌었으면 오늘~모레와 이번 주말을 다시 계산한다. 오늘 날씨 점수도 같이 낸다."""
|
"""재료(예보·미세먼지)가 지수 계산 뒤에 바뀌었으면 오늘~모레와 이번 주말을 다시 계산한다. 오늘 구간별 날씨 점수도 같이 낸다."""
|
||||||
_, _, _, warnings = await asyncio.gather(
|
_, _, _, warnings = await asyncio.gather(
|
||||||
self.weather_service.ensure_vilage(region, now), self.weather_service.ensure_mid(region, now), self.air_service.ensure(now),
|
self.weather_service.ensure_vilage(region, now), self.weather_service.ensure_mid(region, now), self.air_service.ensure(now),
|
||||||
self.warning_service.for_region(region, now),
|
self.warning_service.for_region(region, now),
|
||||||
@@ -250,7 +341,8 @@ class IndexService:
|
|||||||
wind_warning=any(w.warning_type is WarningType.WIND for w in warnings or []),
|
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)
|
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_parts = {k: r.score for k, r in slot_results(WEATHER_SCORE_DEF, today, region, by_at, by_om, today_ctx, sunset_at).items()}
|
||||||
|
|
||||||
issued = max([r.issued_at for r in rows] + [d.issued_at for d in daily_rows or []])
|
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
|
inputs_at = max(issued, air.measured_at) if air else issued
|
||||||
@@ -258,9 +350,10 @@ class IndexService:
|
|||||||
inputs_at = max(inputs_at, max(r.fetched_at for r in by_om.values()))
|
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))
|
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]))
|
_, 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)}
|
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
|
return ErrorType.SUCCESS, weather_parts
|
||||||
|
|
||||||
err, defs = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.definitions(s))
|
err, defs = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.definitions(s))
|
||||||
_, holidays = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.holidays(s, today, days[-1]))
|
_, holidays = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.holidays(s, today, days[-1]))
|
||||||
@@ -270,18 +363,21 @@ class IndexService:
|
|||||||
return err, None
|
return err, None
|
||||||
out = []
|
out = []
|
||||||
for day in days:
|
for day in days:
|
||||||
|
m = night(day, float(region.lat), float(region.lon))
|
||||||
ctx = Context(
|
ctx = Context(
|
||||||
day=day, is_holiday=day in (holidays or set()), moon=illumination(datetime.combine(day, time(23), tzinfo=KST)),
|
day=day, is_holiday=day in (holidays or set()), moon=m.lit * up_ratio(m, _STARS_HOURS), moon_note=f"{m.name}, {view_line(m, None)}",
|
||||||
sunset_score=sunset.get(day), lookahead_rain_prob=0, **base_ctx,
|
sunset_score=sunset.get(day), lookahead_rain_prob=0, **base_ctx,
|
||||||
)
|
)
|
||||||
for d in defs:
|
for d in defs:
|
||||||
result = day_result(d, day, region, by_at, daily, ctx, short=day < today + timedelta(days=DAYS), by_om=by_om)
|
result = day_result(d, day, region, by_at, daily, ctx, short=day < today + timedelta(days=DAYS), by_om=by_om)
|
||||||
if result is None:
|
if result is None:
|
||||||
continue
|
continue
|
||||||
|
parts = slot_results(d, day, region, by_at, by_om, ctx, sunset_at) if day == today else {}
|
||||||
out.append({
|
out.append({
|
||||||
"region_code": region.code, "score_date": day, "index_id": d.index_id, "score": result.score, "summary": result.summary,
|
"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,
|
**{f"{a}_score": result.factors[a] for a in AXES}, "zero_reason": result.zero_reason, "notes": result.notes,
|
||||||
"estimated": result.estimated, "computed_at": now,
|
"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)])
|
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
|
return err, weather_parts
|
||||||
+110
-43
@@ -1,7 +1,7 @@
|
|||||||
import asyncio
|
import asyncio
|
||||||
import math
|
import math
|
||||||
import statistics
|
import statistics
|
||||||
from dataclasses import dataclass
|
from dataclasses import dataclass, field, replace
|
||||||
from datetime import date, datetime, timedelta, timezone
|
from datetime import date, datetime, timedelta, timezone
|
||||||
from typing import Optional
|
from typing import Optional
|
||||||
|
|
||||||
@@ -20,8 +20,8 @@ from common.utils.kma_time import KST, kst_midnight, now_kst
|
|||||||
from crud.region_crud import RegionCRUD
|
from crud.region_crud import RegionCRUD
|
||||||
from crud.sky_crud import SkyCRUD
|
from crud.sky_crud import SkyCRUD
|
||||||
from services.calc.sky_score import (
|
from services.calc.sky_score import (
|
||||||
DISTANCES_KM, GRADE_LABEL, RAIN_BEFORE_HOURS, SITUATION_LINE, SITUATION_VERDICT, VERDICT_LINE, VERDICT_RANK, Air, Layers, air_factor, best_times,
|
DISTANCES_KM, GRADE_LABEL, RAIN_BEFORE_HOURS, SITUATION_VERDICT, VERDICT_LINE, VERDICT_RANK, Air, Layers, air_factor, best_times,
|
||||||
confidence, grade, mean_layers, reason, score, situation, sunset_timeline, verdict,
|
GRADE_RANK, air_note, confidence, grade, mean_layers, plain_line, reason, sky_title, score, situation, sunrise_timeline, sunset_timeline, verdict,
|
||||||
)
|
)
|
||||||
from services.calc.sun import SunTimes, sun_times
|
from services.calc.sun import SunTimes, sun_times
|
||||||
from services.external.open_meteo import OpenMeteoRequestFailed, fetch_clouds, parse_clouds
|
from services.external.open_meteo import OpenMeteoRequestFailed, fetch_clouds, parse_clouds
|
||||||
@@ -31,6 +31,7 @@ DAYS = 3
|
|||||||
SPOT_RADIUS_KM = EVENT_RADIUS_KM
|
SPOT_RADIUS_KM = EVENT_RADIUS_KM
|
||||||
SPOT_LIMIT = 3
|
SPOT_LIMIT = 3
|
||||||
_MARKER_TTL = 24 * 3600
|
_MARKER_TTL = 24 * 3600
|
||||||
|
OPEN_WEST_KM = 20 # 이 안에 서쪽이 트인 명소가 있으면 노을 가산 (부안 채석강·진도 세방낙조가 구 중심에서 10km 넘게 떨어져 있어 20km)
|
||||||
_background: set[asyncio.Task] = set()
|
_background: set[asyncio.Task] = set()
|
||||||
|
|
||||||
|
|
||||||
@@ -43,7 +44,10 @@ class Spot:
|
|||||||
|
|
||||||
@dataclass
|
@dataclass
|
||||||
class SkyPlan:
|
class SkyPlan:
|
||||||
"""노을 탭 맨 위 결론: 나가 볼 만한지, 왜, 몇 시에 어디로."""
|
"""노을 탭 맨 위 결론: 나가 볼 만한지, 왜, 몇 시에 어디로. 다음에 오는 일출 또는 노을."""
|
||||||
|
kind: SkyType
|
||||||
|
title: str # 하늘이 어떻게 보일지 한 문장 (히어로 제목)
|
||||||
|
target: SkyScore
|
||||||
day: date
|
day: date
|
||||||
when: str
|
when: str
|
||||||
verdict: str
|
verdict: str
|
||||||
@@ -69,6 +73,7 @@ class SkyView:
|
|||||||
days: list[SkyScore]
|
days: list[SkyScore]
|
||||||
spots: list[Spot]
|
spots: list[Spot]
|
||||||
plan: Optional[SkyPlan] = None
|
plan: Optional[SkyPlan] = None
|
||||||
|
plans: list[SkyPlan] = field(default_factory=list) # plan 과 같은 종류(노을·일출)로 아직 안 끝난 날 최대 3일. 날짜 타일용
|
||||||
|
|
||||||
|
|
||||||
@dataclass
|
@dataclass
|
||||||
@@ -79,10 +84,12 @@ class RankItem:
|
|||||||
|
|
||||||
|
|
||||||
def nearest_spots(lat: float, lon: float, spots: list[SunsetSpot]) -> list[Spot]:
|
def nearest_spots(lat: float, lon: float, spots: list[SunsetSpot]) -> list[Spot]:
|
||||||
"""반경 안에서 해 지는 쪽이 트인 곳(sort_order 0)을 먼저, 그 안에서는 가까운 순."""
|
"""반경 안에서 해 지는 쪽이 트인 곳(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)))
|
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]
|
for p in spots]
|
||||||
near = [x for x in near if x.distance_km <= SPOT_RADIUS_KM]
|
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]
|
return sorted(near, key=lambda x: (x.spot.sort_order, x.distance_km))[:SPOT_LIMIT]
|
||||||
|
|
||||||
|
|
||||||
@@ -96,44 +103,89 @@ def _word(d: date, today: date) -> str:
|
|||||||
return _DAY_WORD[i] if 0 <= i < len(_DAY_WORD) else f"{d.month}.{d.day}"
|
return _DAY_WORD[i] if 0 <= i < len(_DAY_WORD) else f"{d.month}.{d.day}"
|
||||||
|
|
||||||
|
|
||||||
def _subject(word: str) -> str:
|
|
||||||
"""받침 있으면 '이', 없으면 '가'. 오늘이 · 모레가"""
|
|
||||||
last = ord(word[-1]) - 0xAC00
|
|
||||||
return f"{word}{'이' if 0 <= last < 11172 and last % 28 else '가'}"
|
|
||||||
|
|
||||||
|
|
||||||
def day_verdict(x: SkyScore) -> str:
|
def day_verdict(x: SkyScore) -> str:
|
||||||
"""하늘 상황이 있으면 그걸로, 없으면(예전 계산분) 점수로."""
|
"""하늘 상황이 있으면 그걸로, 없으면(예전 계산분) 점수로. 공기가 뿌예 점수가 크게 깎였으면 한 단계 낮춘다."""
|
||||||
return SITUATION_VERDICT[SkySituation(x.situation)] if x.situation else verdict(x.score)
|
v = SITUATION_VERDICT[SkySituation(x.situation)] if x.situation else verdict(x.score)
|
||||||
|
if air_note(getattr(x, "air", None)) is not None and VERDICT_RANK[v] > 0:
|
||||||
|
v = next(k for k, r in VERDICT_RANK.items() if r == VERDICT_RANK[v] - 1)
|
||||||
|
return v
|
||||||
|
|
||||||
|
|
||||||
|
def peak_of(x: SkyScore) -> Optional[datetime]:
|
||||||
|
peak = next((b for b in x.best_times or [] if b["kind"] == "peak"), None)
|
||||||
|
return datetime.fromisoformat(peak["at"]) if peak else None
|
||||||
|
|
||||||
|
|
||||||
def outlook(target: SkyScore, days: list[SkyScore], today: date) -> str:
|
def outlook(target: SkyScore, days: list[SkyScore], today: date) -> str:
|
||||||
"""뒤의 날 중 결론이 더 좋은 날이 있을 때만 한 줄. 없으면 빈 문자열."""
|
"""뒤의 날 중 점수 등급이 더 높은 날이 있을 때만 그날 문장 (18:07, 모레 노을이 은은하게 물들어요). 없으면 빈 문자열."""
|
||||||
later = [x for x in days if x.score_date > target.score_date and VERDICT_RANK[day_verdict(x)] > VERDICT_RANK[day_verdict(target)]]
|
rank = lambda x: GRADE_RANK[SkyGrade(x.grade)] # noqa: E731
|
||||||
|
later = [x for x in days if x.score_date > target.score_date and x.grade is not None and rank(x) > rank(target)]
|
||||||
if not later:
|
if not later:
|
||||||
return ""
|
return ""
|
||||||
best = max(later, key=lambda x: (VERDICT_RANK[day_verdict(x)], x.score))
|
best = max(later, key=lambda x: (rank(x), x.score))
|
||||||
line = SITUATION_LINE[SkySituation(best.situation)] if best.situation else VERDICT_LINE[day_verdict(best)]
|
kind = SkyType.SUNRISE if best.sky_type == SkyType.SUNRISE.value else SkyType.SUNSET
|
||||||
return f"{_subject(_word(best.score_date, today))} 더 나아요 · {line}"
|
return sky_title(SkyGrade(best.grade), kind, _word(best.score_date, today), peak_of(best))
|
||||||
|
|
||||||
|
|
||||||
def build_plan(target: SkyScore, st: SunTimes, layers: Optional[list[Layers]], spots: list[Spot], days: list[SkyScore], today: date) -> SkyPlan:
|
def build_plan(
|
||||||
|
target: SkyScore, st: SunTimes, layers: Optional[list[Layers]], spots: list[Spot], days: list[SkyScore], today: date, kind: SkyType = SkyType.SUNSET,
|
||||||
|
) -> SkyPlan:
|
||||||
|
"""days 는 target 과 같은 종류(일출·노을)만."""
|
||||||
v = day_verdict(target)
|
v = day_verdict(target)
|
||||||
|
rise = kind is SkyType.SUNRISE
|
||||||
when = _word(target.score_date, today)
|
when = _word(target.score_date, today)
|
||||||
peak = next((b for b in target.best_times if b["kind"] == "peak"), None)
|
peak = next((b for b in target.best_times if b["kind"] == "peak"), None)
|
||||||
peak_at = datetime.fromisoformat(peak["at"]) if peak else None
|
peak_at = datetime.fromisoformat(peak["at"]) if peak else None
|
||||||
return SkyPlan(
|
return SkyPlan(
|
||||||
|
kind=kind, target=target,
|
||||||
|
title=sky_title(SkyGrade(target.grade), kind, when, peak_at),
|
||||||
day=target.score_date, when=when, verdict=v, headline=VERDICT_LINE[v],
|
day=target.score_date, when=when, verdict=v, headline=VERDICT_LINE[v],
|
||||||
reason=reason(*layers) if layers else _FALLBACK_REASON[v],
|
reason=". ".join(filter(None, [reason(*layers, kind) if layers else _FALLBACK_REASON[v], air_note(target.air)])),
|
||||||
score=target.score, grade_label=GRADE_LABEL[SkyGrade(target.grade)],
|
score=target.score, grade_label=GRADE_LABEL[SkyGrade(target.grade)],
|
||||||
situation_label=SITUATION_LINE[SkySituation(target.situation)] if target.situation else None,
|
situation_label=plain_line(SkyGrade(target.grade), SkySituation(target.situation) if target.situation else None, target.air, kind),
|
||||||
models_total=target.models_total, models_agree=target.models_agree,
|
models_total=target.models_total, models_agree=target.models_agree,
|
||||||
best_at=peak_at, spot=spots[0] if spots and v != "rest" else None,
|
best_at=peak_at, spot=spots[0] if spots and v != "rest" and not rise else None,
|
||||||
timeline=sunset_timeline(st.golden_start_at.astimezone(KST), st.sunset_at.astimezone(KST), None, st.dusk_end_at.astimezone(KST)),
|
timeline=(
|
||||||
|
sunrise_timeline(st.dawn_start_at.astimezone(KST), st.blue_end_morning_at.astimezone(KST), peak_at, st.sunrise_at.astimezone(KST), st.golden_end_at.astimezone(KST))
|
||||||
|
if rise
|
||||||
|
else sunset_timeline(st.golden_start_at.astimezone(KST), st.sunset_at.astimezone(KST), peak_at, st.blue_start_at.astimezone(KST), st.dusk_end_at.astimezone(KST))
|
||||||
|
),
|
||||||
outlook=outlook(target, days, today),
|
outlook=outlook(target, days, today),
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def next_event(sunsets: list[SkyScore], sunrises: list[SkyScore], lat: float, lon: float, now: datetime) -> Optional[tuple[SkyType, SkyScore, SunTimes]]:
|
||||||
|
"""가장 먼저 끝나지 않은 일출(해 뜰 때까지) 또는 노을(블루아워 끝까지)."""
|
||||||
|
upcoming = []
|
||||||
|
for kind, days in ((SkyType.SUNRISE, sunrises), (SkyType.SUNSET, sunsets)):
|
||||||
|
for x in days:
|
||||||
|
st = sun_times(x.score_date, lat, lon)
|
||||||
|
end = st.sunrise_at if kind is SkyType.SUNRISE else st.dusk_end_at
|
||||||
|
if end > now:
|
||||||
|
upcoming.append((end, kind, x, st))
|
||||||
|
if not upcoming:
|
||||||
|
return None
|
||||||
|
_, kind, target, st = min(upcoming, key=lambda e: e[0])
|
||||||
|
return kind, target, st
|
||||||
|
|
||||||
|
|
||||||
|
def day_plans(
|
||||||
|
plan: Optional[SkyPlan], sunsets: list[SkyScore], sunrises: list[SkyScore], spots: list[Spot], lat: float, lon: float, now: datetime,
|
||||||
|
) -> list[SkyPlan]:
|
||||||
|
"""plan 과 같은 종류로 아직 끝나지 않은 날들의 결론. plan 의 날은 plan 그대로."""
|
||||||
|
if plan is None:
|
||||||
|
return []
|
||||||
|
rise = plan.kind is SkyType.SUNRISE
|
||||||
|
same = sunrises if rise else sunsets
|
||||||
|
out = []
|
||||||
|
for x in same:
|
||||||
|
st = sun_times(x.score_date, lat, lon)
|
||||||
|
if (st.sunrise_at if rise else st.dusk_end_at) <= now:
|
||||||
|
continue
|
||||||
|
out.append(plan if x.score_date == plan.day else build_plan(x, st, None, spots, same, now.date(), plan.kind))
|
||||||
|
return out[:DAYS]
|
||||||
|
|
||||||
|
|
||||||
def _slot(now: datetime) -> str:
|
def _slot(now: datetime) -> str:
|
||||||
"""노을은 13시, 일출은 21시 이후 예보로 다시 계산한다."""
|
"""노을은 13시, 일출은 21시 이후 예보로 다시 계산한다."""
|
||||||
return "am" if now.hour < 13 else "pm" if now.hour < 21 else "night"
|
return "am" if now.hour < 13 else "pm" if now.hour < 21 else "night"
|
||||||
@@ -171,11 +223,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(
|
def _score_rows(
|
||||||
region: Region, today: date, clouds: dict, now: datetime,
|
region: Region, today: date, clouds: dict, now: datetime,
|
||||||
hourly: Optional[dict[tuple[str, datetime], WeatherHourly]] = None, om: Optional[dict[tuple[str, datetime], OpenMeteoHourly]] = None,
|
hourly: Optional[dict[tuple[str, datetime], WeatherHourly]] = None, om: Optional[dict[tuple[str, datetime], OpenMeteoHourly]] = None,
|
||||||
|
open_west: bool = False,
|
||||||
) -> list[dict]:
|
) -> list[dict]:
|
||||||
"""구름 점수(모델 평균)에 공기 보정(가시거리·습도·비 갠 뒤)을 곱한다. 공기 값이 없으면 구름 점수 그대로."""
|
"""구름 점수(모델 평균)에 공기 보정(가시거리·습도·비 갠 뒤)을 곱한다. 공기 값이 없으면 구름 점수 그대로.
|
||||||
|
open_west 면 노을에만 서쪽이 트인 곳 가산을 더한다."""
|
||||||
rows = []
|
rows = []
|
||||||
for kind in (SkyType.SUNSET, SkyType.SUNRISE):
|
for kind in (SkyType.SUNSET, SkyType.SUNRISE):
|
||||||
for i in range(DAYS):
|
for i in range(DAYS):
|
||||||
@@ -193,7 +253,9 @@ def _score_rows(
|
|||||||
model_layers.append(layers)
|
model_layers.append(layers)
|
||||||
if not per_model:
|
if not per_model:
|
||||||
continue
|
continue
|
||||||
value = min(100, round(statistics.mean(per_model) * air_factor(_air(region.code, sun_at, hourly or {}, om or {}))))
|
air = replace(_air(region.code, sun_at, hourly or {}, om or {}), open_west=open_west and kind is SkyType.SUNSET)
|
||||||
|
factor = air_factor(air)
|
||||||
|
value = min(100, round(statistics.mean(per_model) * factor))
|
||||||
sit = situation(*(mean_layers([m[k] for m in model_layers]) for k in range(len(DISTANCES_KM))))
|
sit = situation(*(mean_layers([m[k] for m in model_layers]) for k in range(len(DISTANCES_KM))))
|
||||||
rows.append({
|
rows.append({
|
||||||
"region_code": region.code, "score_date": d, "sky_type": kind.value, "score": value, "grade": grade(value).value,
|
"region_code": region.code, "score_date": d, "sky_type": kind.value, "score": value, "grade": grade(value).value,
|
||||||
@@ -201,6 +263,8 @@ def _score_rows(
|
|||||||
"best_times": best_times(kind, sun_at.astimezone(KST), twilight_at.astimezone(KST), statistics.mean(highs)),
|
"best_times": best_times(kind, sun_at.astimezone(KST), twilight_at.astimezone(KST), statistics.mean(highs)),
|
||||||
"computed_at": now,
|
"computed_at": now,
|
||||||
"situation": sit.value, "models_total": len(model_layers), "models_agree": sum(situation(*m) is sit for m in model_layers),
|
"situation": sit.value, "models_total": len(model_layers), "models_agree": sum(situation(*m) is sit for m in model_layers),
|
||||||
|
"air": {"factor": round(factor, 2), "visibility_km": round(air.visibility_km, 1) if air.visibility_km is not None else None,
|
||||||
|
"humidity": air.humidity},
|
||||||
})
|
})
|
||||||
return rows
|
return rows
|
||||||
|
|
||||||
@@ -246,8 +310,10 @@ class SkyService:
|
|||||||
LOG.error(f"[sky] spots {region.code}: {err.name}")
|
LOG.error(f"[sky] spots {region.code}: {err.name}")
|
||||||
near = nearest_spots(lat, lon, spots or [])
|
near = nearest_spots(lat, lon, spots or [])
|
||||||
first = sun_times(now.date(), lat, lon)
|
first = sun_times(now.date(), lat, lon)
|
||||||
plan = await self._plan(region, sunsets, near, now)
|
sunrises = [x for x in scores if x.sky_type == SkyType.SUNRISE.value][:DAYS]
|
||||||
|
plan = await self._plan(region, sunsets, sunrises, near, now)
|
||||||
return ErrorType.SUCCESS, SkyView(
|
return ErrorType.SUCCESS, SkyView(
|
||||||
|
plans=day_plans(plan, sunsets, sunrises, near, lat, lon, now),
|
||||||
region=region,
|
region=region,
|
||||||
sunset_azimuth=first.sunset_azimuth,
|
sunset_azimuth=first.sunset_azimuth,
|
||||||
sunset=next((x for x in sunsets if x.score_date == now.date()), None),
|
sunset=next((x for x in sunsets if x.score_date == now.date()), None),
|
||||||
@@ -257,26 +323,24 @@ class SkyService:
|
|||||||
plan=plan,
|
plan=plan,
|
||||||
)
|
)
|
||||||
|
|
||||||
async def _plan(self, region: Region, sunsets: list[SkyScore], spots: list[Spot], now: datetime) -> Optional[SkyPlan]:
|
async def _plan(self, region: Region, sunsets: list[SkyScore], sunrises: list[SkyScore], spots: list[Spot], now: datetime) -> Optional[SkyPlan]:
|
||||||
"""블루아워가 끝나기 전엔 오늘, 지나면 내일 노을로 결론을 낸다. 구름 층은 점수 계산 때 받은 값을 다시 읽는다."""
|
"""다음에 오는 것으로 결론을 낸다: 오늘 해 뜨기 전엔 오늘 일출, 블루아워가 끝나기 전엔 오늘 노을, 그 뒤엔 내일 일출.
|
||||||
lat, lon = float(region.lat), float(region.lon)
|
구름 층은 점수 계산 때 받은 값을 다시 읽는다."""
|
||||||
target, st = None, None
|
picked = next_event(sunsets, sunrises, float(region.lat), float(region.lon), now)
|
||||||
for x in sunsets:
|
if picked is None:
|
||||||
st = sun_times(x.score_date, lat, lon)
|
|
||||||
if st.dusk_end_at > now:
|
|
||||||
target = x
|
|
||||||
break
|
|
||||||
if target is None or st is None:
|
|
||||||
return None
|
return None
|
||||||
err, rows = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.clouds_at(s, region.code, _nearest_hour(st.sunset_at)))
|
kind, target, st = picked
|
||||||
|
sun_at = st.sunrise_at if kind is SkyType.SUNRISE else st.sunset_at
|
||||||
|
err, rows = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.clouds_at(s, region.code, _nearest_hour(sun_at)))
|
||||||
if err is not ErrorType.SUCCESS:
|
if err is not ErrorType.SUCCESS:
|
||||||
LOG.error(f"[sky] plan clouds {region.code}: {err.name}")
|
LOG.error(f"[sky] plan clouds {region.code}: {err.name}")
|
||||||
by_km: dict[int, list[Layers]] = {}
|
by_km: dict[int, list[Layers]] = {}
|
||||||
for r in rows or []:
|
for r in rows or []:
|
||||||
if r.kind == SkyType.SUNSET.value:
|
if r.kind == kind.value:
|
||||||
by_km.setdefault(r.distance_km, []).append(Layers(r.cloud_low, r.cloud_mid, r.cloud_high))
|
by_km.setdefault(r.distance_km, []).append(Layers(r.cloud_low, r.cloud_mid, r.cloud_high))
|
||||||
layers = [mean_layers(by_km[km]) for km in DISTANCES_KM if km in by_km]
|
layers = [mean_layers(by_km[km]) for km in DISTANCES_KM if km in by_km]
|
||||||
return build_plan(target, st, layers if len(layers) == len(DISTANCES_KM) else None, spots, sunsets, now.date())
|
same = sunrises if kind is SkyType.SUNRISE else sunsets
|
||||||
|
return build_plan(target, st, layers if len(layers) == len(DISTANCES_KM) else None, spots, same, now.date(), kind)
|
||||||
|
|
||||||
async def ranking(self) -> tuple[ErrorType, list[RankItem]]:
|
async def ranking(self) -> tuple[ErrorType, list[RankItem]]:
|
||||||
err, regions = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.ranking_regions(s))
|
err, regions = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.ranking_regions(s))
|
||||||
@@ -362,7 +426,10 @@ class SkyService:
|
|||||||
LOG.error(f"[sky] air openmeteo: {err.name}")
|
LOG.error(f"[sky] air openmeteo: {err.name}")
|
||||||
hourly = {(w.region_code, w.forecast_at): w for w in hourly_rows or []}
|
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 []}
|
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([
|
err = await DB_SESSION_MNG.execute_lambda_run([
|
||||||
lambda s: self.crud.upsert_clouds(s, cloud_rows),
|
lambda s: self.crud.upsert_clouds(s, cloud_rows),
|
||||||
lambda s: self.crud.upsert_scores(s, score_rows),
|
lambda s: self.crud.upsert_scores(s, score_rows),
|
||||||
|
|||||||
@@ -170,19 +170,33 @@ class WeatherService:
|
|||||||
"""예보가 지났으면 새로 받는다. 이미 있으면 뒤에서 갱신하고, background=False 면 받을 때까지 기다린다."""
|
"""예보가 지났으면 새로 받는다. 이미 있으면 뒤에서 갱신하고, background=False 면 받을 때까지 기다린다."""
|
||||||
latest = latest_vilage_base(now)
|
latest = latest_vilage_base(now)
|
||||||
err, issued = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.latest_issued(s, region.code))
|
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
|
return
|
||||||
if issued is None or not background:
|
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
|
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)
|
_background.add(task)
|
||||||
task.add_done_callback(_background.discard)
|
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:
|
async with redis_lock(f"lock:vilage:{region.code}") as acquired:
|
||||||
if 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)))
|
await self._fetch_and_store(region, sorted(set(bases)))
|
||||||
return
|
return
|
||||||
if wait:
|
if wait:
|
||||||
|
|||||||
@@ -1,4 +1,6 @@
|
|||||||
import asyncio
|
import asyncio
|
||||||
|
import math
|
||||||
|
import re
|
||||||
from dataclasses import dataclass
|
from dataclasses import dataclass
|
||||||
from datetime import date, timedelta
|
from datetime import date, timedelta
|
||||||
from typing import Optional
|
from typing import Optional
|
||||||
@@ -20,11 +22,16 @@ from crud.index_crud import IndexCRUD
|
|||||||
from crud.region_crud import RegionCRUD
|
from crud.region_crud import RegionCRUD
|
||||||
from crud.weather_crud import WeatherCRUD
|
from crud.weather_crud import WeatherCRUD
|
||||||
from crud.week_crud import WeekCRUD
|
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 IMAGE_CREDIT as CULTURE_CREDIT
|
||||||
from services.external.culture_api import SOURCE_PREFIX as CULTURE_PREFIX
|
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.culture_api import CONCERT, EXHIBITION, fetch_exhibitions, parse_exhibitions
|
||||||
from services.external.data_go_kr import DataGoKrNotConfigured, DataGoKrRequestFailed
|
from services.external.data_go_kr import DataGoKrNotConfigured, DataGoKrRequestFailed
|
||||||
from services.external.kasi import fetch_holidays
|
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 IMAGE_CREDIT as TOUR_CREDIT
|
||||||
from services.external.tour_api import fetch_festivals, parse_festivals
|
from services.external.tour_api import fetch_festivals, parse_festivals
|
||||||
from services.index_service import IndexService
|
from services.index_service import IndexService
|
||||||
@@ -36,6 +43,12 @@ MAX_EVENT_DAYS = 60
|
|||||||
EVENT_RADIUS_KM = 30
|
EVENT_RADIUS_KM = 30
|
||||||
# 행사는 시도 단위로 받는다. 구 중심이 이 거리 안에 있는 시도는 경계가 반경에 걸칠 수 있어 같이 받는다.
|
# 행사는 시도 단위로 받는다. 구 중심이 이 거리 안에 있는 시도는 경계가 반경에 걸칠 수 있어 같이 받는다.
|
||||||
_SIDO_REACH_KM = EVENT_RADIUS_KM + 20
|
_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)
|
_ERRORS = (DataGoKrNotConfigured, DataGoKrRequestFailed, RedisError)
|
||||||
_WEEKDAY_KO = ("월", "화", "수", "목", "금", "토", "일")
|
_WEEKDAY_KO = ("월", "화", "수", "목", "금", "토", "일")
|
||||||
_SKY_WORD = {Sky.CLEAR: "맑음", Sky.PARTLY: "구름 많음", Sky.CLOUDY: "흐림"}
|
_SKY_WORD = {Sky.CLEAR: "맑음", Sky.PARTLY: "구름 많음", Sky.CLOUDY: "흐림"}
|
||||||
@@ -62,6 +75,7 @@ class DayPlan:
|
|||||||
class PlaceItem:
|
class PlaceItem:
|
||||||
place: Place
|
place: Place
|
||||||
is_good: bool
|
is_good: bool
|
||||||
|
distance_km: float
|
||||||
|
|
||||||
|
|
||||||
@dataclass
|
@dataclass
|
||||||
@@ -97,6 +111,8 @@ def image_credit(e: Event) -> Optional[str]:
|
|||||||
"""사진 출처 표기. 직접 넣은 행사(source_id 없음)는 출처를 모르니 None."""
|
"""사진 출처 표기. 직접 넣은 행사(source_id 없음)는 출처를 모르니 None."""
|
||||||
if not e.image_url or e.source_id is None:
|
if not e.image_url or e.source_id is None:
|
||||||
return 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
|
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
|
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]:
|
def nearby_sidos(region: Region, regions: list[Region]) -> list[str]:
|
||||||
"""반경 안에 걸칠 수 있는 시도들. 자기 시도는 항상 앞에."""
|
"""반경 안에 걸칠 수 있는 시도들(행사 시도 코드). 자기 시도는 항상 앞에."""
|
||||||
lat, lon = float(region.lat), float(region.lon)
|
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}
|
own = event_sidos(region.code)
|
||||||
return [region.code[:2]] + sorted(near - {region.code[:2]})
|
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]:
|
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
|
return distance_km <= EVENT_RADIUS_KM
|
||||||
if e.region_code is not None:
|
if e.region_code is not None:
|
||||||
return e.region_code == region.code
|
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]:
|
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 []
|
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]]:
|
async def collect_events(sido: str, today: date) -> tuple[ErrorType, dict[str, int]]:
|
||||||
"""시도 하나의 축제·전시·콘서트를 받아 event 에 넣는다. 종류별 건수를 돌려준다."""
|
"""시도 하나의 축제·전시·콘서트를 받아 event 에 넣는다. 종류별 건수를 돌려준다."""
|
||||||
try:
|
try:
|
||||||
async with httpx.AsyncClient(timeout=30) as client:
|
async with httpx.AsyncClient(timeout=30) as client:
|
||||||
festivals = parse_festivals(await fetch_festivals(client, sido, today), sido)
|
festivals = parse_festivals(await fetch_festivals(client, sido, today), sido)
|
||||||
|
festivals += await _seoul(client, sido, today, festivals)
|
||||||
exhibitions = await _culture(client, sido, today, EXHIBITION)
|
exhibitions = await _culture(client, sido, today, EXHIBITION)
|
||||||
concerts = await _culture(client, sido, today, CONCERT)
|
concerts = await _culture(client, sido, today, CONCERT)
|
||||||
except (DataGoKrNotConfigured, DataGoKrRequestFailed) as e:
|
except (DataGoKrNotConfigured, DataGoKrRequestFailed) as e:
|
||||||
LOG.error(f"[week] events {sido}: {e}")
|
LOG.error(f"[week] events {sido}: {e}")
|
||||||
return ErrorType.EXTERNAL_API_ERROR, {}
|
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)])
|
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}")
|
LOG.info(f"[week] events {sido} {len(rows)}: {err.name}")
|
||||||
return err, {"festival": len(festivals), "exhibition": len(exhibitions), "concert": len(concerts)}
|
return err, {"festival": len(festivals), "exhibition": len(exhibitions), "concert": len(concerts)}
|
||||||
@@ -205,11 +286,12 @@ class WeekService:
|
|||||||
if err is not ErrorType.SUCCESS:
|
if err is not ErrorType.SUCCESS:
|
||||||
return err, []
|
return err, []
|
||||||
names = {d.index_id: d.name for d in defs or []}
|
names = {d.index_id: d.name for d in defs or []}
|
||||||
|
priority = {d.index_id: d.priority for d in defs or []}
|
||||||
plans = []
|
plans = []
|
||||||
for d in daily:
|
for d in daily:
|
||||||
rows = [r for r in hourly or [] if r.forecast_at.astimezone(KST).date() == d.forecast_date]
|
rows = [r for r in hourly or [] if r.forecast_at.astimezone(KST).date() == d.forecast_date]
|
||||||
rain_hours = _rain_hours(rows)
|
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)
|
holiday = (holidays or {}).get(d.forecast_date)
|
||||||
weekday = _WEEKDAY_KO[d.forecast_date.weekday()]
|
weekday = _WEEKDAY_KO[d.forecast_date.weekday()]
|
||||||
word = _weather_word(d, rain_hours)
|
word = _weather_word(d, rain_hours)
|
||||||
@@ -229,19 +311,21 @@ class WeekService:
|
|||||||
))
|
))
|
||||||
return ErrorType.SUCCESS, plans
|
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)
|
err, region = await self._region(region_code)
|
||||||
if err is not ErrorType.SUCCESS:
|
if err is not ErrorType.SUCCESS:
|
||||||
return err, [], []
|
return err, [], [], False
|
||||||
err, places = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.places(s, region.code[:2]))
|
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))
|
_, daily = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.daily(s, region.code, day, day))
|
||||||
if err is not ErrorType.SUCCESS:
|
if err is not ErrorType.SUCCESS:
|
||||||
return err, [], []
|
return err, [], [], False
|
||||||
rainy = bool(daily) and daily[0].rain_type != RainType.NONE.value
|
rainy = bool(daily) and daily[0].rain_type != RainType.NONE.value
|
||||||
areas = list(dict.fromkeys(p.area for p in places))
|
items, areas = pick_places(region, places, rainy, area)
|
||||||
picked = [p for p in places if area is None or p.area == area]
|
return ErrorType.SUCCESS, items, areas, rainy
|
||||||
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
|
|
||||||
|
|
||||||
async def events(self, region_code: str, area: Optional[str]) -> tuple[ErrorType, list[EventItem]]:
|
async def events(self, region_code: str, area: Optional[str]) -> tuple[ErrorType, list[EventItem]]:
|
||||||
err, region = await self._region(region_code)
|
err, region = await self._region(region_code)
|
||||||
|
|||||||
@@ -1,7 +1,9 @@
|
|||||||
|
import re
|
||||||
from dataclasses import dataclass
|
from dataclasses import dataclass
|
||||||
from datetime import date, datetime
|
from datetime import date, datetime
|
||||||
from typing import Optional
|
from typing import Optional
|
||||||
|
|
||||||
|
from common.enums import EventKind
|
||||||
from common.utils.kma_time import KST
|
from common.utils.kma_time import KST
|
||||||
from common.utils.text import day_range, short_day
|
from common.utils.text import day_range, short_day
|
||||||
from services.week_service import DayPlan, EventItem, image_credit
|
from services.week_service import DayPlan, EventItem, image_credit
|
||||||
@@ -10,6 +12,8 @@ _HOT = 28
|
|||||||
_COLD = 10
|
_COLD = 10
|
||||||
_BIG_GAP = 10
|
_BIG_GAP = 10
|
||||||
_MAX_EVENTS = 2
|
_MAX_EVENTS = 2
|
||||||
|
# 주말 동선은 축제를 먼저, 전시는 마지막. 가깝다고 미술관만 이어지지 않게
|
||||||
|
_KIND_RANK = {EventKind.FESTIVAL: 0, EventKind.CONCERT: 1, EventKind.POPUP: 2, EventKind.EXHIBITION: 3}
|
||||||
|
|
||||||
|
|
||||||
@dataclass
|
@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]:
|
def pick_events(d: date, events: list[EventItem], exclude: frozenset[int] = frozenset()) -> list[EventItem]:
|
||||||
"""그날 열리는 행사 중 가까운 순. 일요일은 그날 끝나는 것을 먼저 (마지막 날 찬스)."""
|
"""그날 열리는 행사를 축제→공연→팝업→전시 순으로 종류마다 하나씩, 같은 종류는 가까운 순. 일요일은 같은 종류 안에서 그날 끝나는 것을 먼저 (마지막 날 찬스)."""
|
||||||
sunday = d.weekday() == 6
|
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_ = [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))
|
open_.sort(key=lambda e: (_KIND_RANK.get(e.event.kind, len(_KIND_RANK)), sunday and e.event.end_date != d,
|
||||||
return open_[:_MAX_EVENTS]
|
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:
|
def _place(e: EventItem) -> str:
|
||||||
@@ -150,7 +159,7 @@ def _sort(steps: list[Step]) -> list[Step]:
|
|||||||
def key(s: Step) -> float:
|
def key(s: Step) -> float:
|
||||||
t = s.time
|
t = s.time
|
||||||
if t[0].isdigit():
|
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
|
return 5.5 if h >= 17 else 1.5 if h < 12 else 3
|
||||||
if t.startswith("~"):
|
if t.startswith("~"):
|
||||||
return 0
|
return 0
|
||||||
|
|||||||
@@ -65,6 +65,14 @@ async def _async(v):
|
|||||||
return 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
|
@pytest.fixture
|
||||||
def offline(monkeypatch):
|
def offline(monkeypatch):
|
||||||
"""외부 API 를 모두 맑고 잔잔한 가짜 값으로 바꾼다."""
|
"""외부 API 를 모두 맑고 잔잔한 가짜 값으로 바꾼다."""
|
||||||
|
|||||||
@@ -5,7 +5,8 @@ import httpx
|
|||||||
import pytest
|
import pytest
|
||||||
|
|
||||||
from config.settings import settings
|
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.data_go_kr import DataGoKrRequestFailed, get_body
|
||||||
from services.external.open_meteo import OpenMeteoRequestFailed, fetch_clouds
|
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):
|
with pytest.raises(OpenMeteoRequestFailed):
|
||||||
await fetch_clouds(client, [(37.5, 127.0)])
|
await fetch_clouds(client, [(37.5, 127.0)])
|
||||||
assert len(calls) == 1
|
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,69 @@
|
|||||||
|
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, _shown_parts, 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}
|
||||||
|
|
||||||
|
|
||||||
|
def test_shown_parts_uses_last_night_before_five():
|
||||||
|
parts = {"morning": 1, "day": 2, "evening": 3, "night": 4, EARLY: 5}
|
||||||
|
assert _shown_parts(parts, "day") == {"morning": 1, "day": 2, "evening": 3, "night": 4}
|
||||||
|
assert _shown_parts(parts, EARLY) == {"morning": 1, "day": 2, "evening": 3, "night": 5}
|
||||||
+23
-12
@@ -8,6 +8,7 @@ from common.database.db_session_manager import DB_SESSION_MNG
|
|||||||
from common.enums import PostType
|
from common.enums import PostType
|
||||||
from common.utils.kma_time import now_kst
|
from common.utils.kma_time import now_kst
|
||||||
from crud.feed_crud import FeedCRUD
|
from crud.feed_crud import FeedCRUD
|
||||||
|
from crud.region_crud import RegionCRUD
|
||||||
from crud.season_crud import SeasonCRUD
|
from crud.season_crud import SeasonCRUD
|
||||||
from router.router import app
|
from router.router import app
|
||||||
from services.feed_service import build_feed_day
|
from services.feed_service import build_feed_day
|
||||||
@@ -16,17 +17,19 @@ from services.week_service import collect_events
|
|||||||
REGION = "1114000000"
|
REGION = "1114000000"
|
||||||
|
|
||||||
|
|
||||||
async def _posts(day: date):
|
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}' ORDER BY position")))
|
"""한 시도가 보는 그날 카드 (전국 + 그 시도)."""
|
||||||
|
_, 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]
|
return [r[0] for r in rows]
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.anyio
|
@pytest.mark.anyio
|
||||||
async def test_build_day_adds_weekend_post_every_day():
|
async def test_build_day_adds_weekend_post_every_day():
|
||||||
monday, thursday = date(2026, 10, 12), date(2026, 10, 15)
|
monday, thursday = date(2026, 10, 12), date(2026, 10, 15)
|
||||||
await build_feed_day(monday, FeedCRUD(), SeasonCRUD())
|
await build_feed_day(monday, FeedCRUD(), SeasonCRUD(), RegionCRUD())
|
||||||
await build_feed_day(thursday, FeedCRUD(), SeasonCRUD())
|
await build_feed_day(thursday, FeedCRUD(), SeasonCRUD(), RegionCRUD())
|
||||||
await build_feed_day(thursday, FeedCRUD(), SeasonCRUD())
|
await build_feed_day(thursday, FeedCRUD(), SeasonCRUD(), RegionCRUD())
|
||||||
assert (await _posts(monday)).count(PostType.WEEK.value) == 1
|
assert (await _posts(monday)).count(PostType.WEEK.value) == 1
|
||||||
assert (await _posts(thursday)).count(PostType.WEEK.value) == 1
|
assert (await _posts(thursday)).count(PostType.WEEK.value) == 1
|
||||||
assert (await _posts(thursday))[0] == PostType.WEATHER.value
|
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():
|
async def test_build_day_adds_new_card_types_to_existing_day():
|
||||||
"""이미 만든 날에 새 종류(미세먼지)가 생기면 빠진 카드만 더한다."""
|
"""이미 만든 날에 새 종류(미세먼지)가 생기면 빠진 카드만 더한다."""
|
||||||
thursday = date(2026, 10, 15)
|
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}"))])
|
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))
|
before = len(await _posts(thursday))
|
||||||
await build_feed_day(thursday, FeedCRUD(), SeasonCRUD())
|
await build_feed_day(thursday, FeedCRUD(), SeasonCRUD(), RegionCRUD())
|
||||||
after = await _posts(thursday)
|
after = await _posts(thursday)
|
||||||
assert len(after) == before + 1 and after.count(PostType.AIR.value) == 1
|
assert len(after) == before + 1 and after.count(PostType.AIR.value) == 1
|
||||||
|
|
||||||
@@ -58,7 +61,9 @@ async def test_feed_assembles_hero_stories_posts_and_bands(offline):
|
|||||||
body = (await client.get("/v1/feed", params={"region": REGION})).json()
|
body = (await client.get("/v1/feed", params={"region": REGION})).json()
|
||||||
assert body["result"]["success"] is True
|
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 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
|
||||||
|
assert body["hero"]["weather_score"] == body["hero"]["weather_slots"][body["slot"]]
|
||||||
|
assert all(g["slots"][body["slot"]] == g["score"] and g["slot_ranks"][body["slot"]] == g["rank"] for g in body["stories"] if g["active"])
|
||||||
weather = next(p for p in body["posts"] if p["post_type"] == PostType.WEATHER.value)
|
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 [s["kind"] for s in weather["slides"]] == ["hours", "hours"]
|
||||||
assert len(weather["slides"][0]["hours"]) == 8
|
assert len(weather["slides"][0]["hours"]) == 8
|
||||||
@@ -100,8 +105,11 @@ def test_slot_follows_sunset():
|
|||||||
|
|
||||||
sunset = datetime(2026, 10, 2, 18, 10, tzinfo=KST)
|
sunset = datetime(2026, 10, 2, 18, 10, tzinfo=KST)
|
||||||
at = lambda h, m=0: datetime(2026, 10, 2, h, m, tzinfo=KST) # noqa: E731
|
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))] == [
|
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", "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():
|
def test_arrange_orders_by_slot_and_keeps_same_types_apart():
|
||||||
@@ -152,7 +160,7 @@ def test_arrange_scatters_up_to_three_events_same_spot_all_day():
|
|||||||
@pytest.mark.anyio
|
@pytest.mark.anyio
|
||||||
async def test_build_day_makes_every_card_at_three():
|
async def test_build_day_makes_every_card_at_three():
|
||||||
thursday = date(2026, 10, 15)
|
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 = 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)
|
rows = list(rows)
|
||||||
assert {PostType.ALERT.value, PostType.TOMORROW.value, PostType.QUOTE.value} <= {r[0] for r in rows}
|
assert {PostType.ALERT.value, PostType.TOMORROW.value, PostType.QUOTE.value} <= {r[0] for r in rows}
|
||||||
@@ -361,6 +369,9 @@ def test_uv_post_only_when_moderate_or_higher():
|
|||||||
base = dict(post_id=1, post_type=PostType.UV, like_count=0, comment_count=0, published_at=at(9))
|
base = dict(post_id=1, post_type=PostType.UV, like_count=0, comment_count=0, published_at=at(9))
|
||||||
ctx = lambda vals: SimpleNamespace(region=SimpleNamespace(short_name="분당구"), uv=[SimpleNamespace(forecast_at=at(h), uv_index=v) for h, v in vals]) # noqa: E731
|
ctx = lambda vals: SimpleNamespace(region=SimpleNamespace(short_name="분당구"), uv=[SimpleNamespace(forecast_at=at(h), uv_index=v) for h, v in vals]) # noqa: E731
|
||||||
post = FeedService._uv_post(None, base, ctx([(9, 2.0), (12, 6.4), (15, 4.0)]))
|
post = FeedService._uv_post(None, base, ctx([(9, 2.0), (12, 6.4), (15, 4.0)]))
|
||||||
assert post.title == "자외선 높음" and post.caption == "가장 셀 때 낮 12시 · 6" and post.slides[0].rows[-1].label == "이렇게 해요"
|
assert post.title == "자외선 지수 높음" and post.caption == "가장 셀 때 낮 12시"
|
||||||
|
assert post.slides[0].line == "오늘 자외선 지수 높음\n점심때 나가면 선크림·모자·선글라스 챙기고 그늘로 다녀요"
|
||||||
|
assert [(r.label, r.value, r.level) for r in post.slides[0].rows] == [("9시", "낮음", 1), ("12시", "높음", 3), ("15시", "보통", 2)]
|
||||||
|
assert FeedService._uv_post(None, base, ctx([(12, 2.0), (15, 3.4)])).slides[0].line == "오늘 자외선 지수 보통\n오후 3시 무렵 나가면 선크림·모자 챙겨요"
|
||||||
assert FeedService._uv_post(None, base, ctx([(9, 1.0), (12, 2.5)])) is None
|
assert FeedService._uv_post(None, base, ctx([(9, 1.0), (12, 2.5)])) is None
|
||||||
assert FeedService._uv_post(None, base, ctx([])) is None
|
assert FeedService._uv_post(None, base, ctx([])) is None
|
||||||
@@ -2,7 +2,7 @@ from datetime import datetime, timedelta
|
|||||||
|
|
||||||
from common.enums import AirGrade
|
from common.enums import AirGrade
|
||||||
from common.utils.kma_time import KST
|
from common.utils.kma_time import KST
|
||||||
from services.hero_stats import HeroInput, hero_stats
|
from services.hero_stats import HeroInput, hero_stats, hero_status
|
||||||
|
|
||||||
NOW = datetime(2026, 10, 7, 14, 20, tzinfo=KST)
|
NOW = datetime(2026, 10, 7, 14, 20, tzinfo=KST)
|
||||||
|
|
||||||
@@ -12,8 +12,9 @@ def _view(x: HeroInput) -> list[tuple[str, str, str, str]]:
|
|||||||
|
|
||||||
|
|
||||||
def test_clear_day_shows_uv_warning_and_temp_swing():
|
def test_clear_day_shows_uv_warning_and_temp_swing():
|
||||||
x = HeroInput(now=NOW, night=False, air=AirGrade.GOOD, uv=6.1, temp_min=13, temp_max=23, temp=23, feels=23, discomfort=68)
|
x = HeroInput(now=NOW, night=False, air=AirGrade.GOOD, uv=6.1, temp_min=13, temp_max=23, temp=23, feels=23)
|
||||||
assert _view(x) == [("glasses", "자외선", "6 · 높음", "warn"), ("coldwind", "일교차 10°", "아침엔 겉옷", "normal")]
|
assert _view(x) == [("glasses", "자외선", "6 · 높음", "warn")]
|
||||||
|
assert _view(HeroInput(now=NOW, night=False, air=AirGrade.GOOD, uv=2.0, temp_min=13, temp_max=23)) == [("coldwind", "일교차 10°", "아침엔 겉옷", "normal")]
|
||||||
|
|
||||||
|
|
||||||
def test_rain_comes_first():
|
def test_rain_comes_first():
|
||||||
@@ -30,12 +31,12 @@ def test_rain_later_today_and_no_rain_today():
|
|||||||
|
|
||||||
def test_bad_air_beats_uv_and_wears_mask():
|
def test_bad_air_beats_uv_and_wears_mask():
|
||||||
x = HeroInput(now=NOW, night=False, air=AirGrade.VERY_BAD, uv=7.2)
|
x = HeroInput(now=NOW, night=False, air=AirGrade.VERY_BAD, uv=7.2)
|
||||||
assert _view(x) == [("mask", "미세먼지", "매우나쁨", "warn"), ("glasses", "자외선", "7 · 높음", "warn")]
|
assert _view(x) == [("mask", "미세먼지", "매우나쁨", "warn")]
|
||||||
|
|
||||||
|
|
||||||
def test_summer_night_muggy_then_moon_and_no_card_for_no_rain():
|
def test_night_without_alert_shows_moon_and_no_card_for_no_rain():
|
||||||
x = HeroInput(now=NOW.replace(hour=21), night=True, uv=0.0, temp=28, feels=31, discomfort=80, moon="보름달")
|
x = HeroInput(now=NOW.replace(hour=21), night=True, uv=0.0, temp=28, feels=31, moon="보름달")
|
||||||
assert _view(x) == [("muggy", "불쾌지수", "80 · 매우 높음", "warn"), ("moon", "오늘 밤 달", "보름달", "normal")]
|
assert _view(x) == [("moon", "오늘 밤 달", "보름달", "normal")]
|
||||||
|
|
||||||
|
|
||||||
def test_one_coldwind_card_only():
|
def test_one_coldwind_card_only():
|
||||||
@@ -45,3 +46,19 @@ def test_one_coldwind_card_only():
|
|||||||
|
|
||||||
def test_nothing_known_gives_nothing():
|
def test_nothing_known_gives_nothing():
|
||||||
assert hero_stats(HeroInput(now=NOW, night=False)) == []
|
assert hero_stats(HeroInput(now=NOW, night=False)) == []
|
||||||
|
|
||||||
|
|
||||||
|
def _status(x: HeroInput) -> list[tuple[str, str, str]]:
|
||||||
|
return [(s.label, s.value, s.tone) for s in hero_status(x)]
|
||||||
|
|
||||||
|
|
||||||
|
def test_status_line_has_four_by_day_and_warns_only_caution():
|
||||||
|
x = HeroInput(now=NOW, night=False, humidity=55, discomfort=75, uv=4.2, air=AirGrade.GOOD)
|
||||||
|
assert _status(x) == [("습도", "보통", "normal"), ("불쾌지수", "불쾌", "warn"), ("자외선", "보통", "normal"), ("미세먼지", "좋음", "normal")]
|
||||||
|
x = HeroInput(now=NOW, night=False, humidity=72, discomfort=60, uv=6.0, air=AirGrade.BAD)
|
||||||
|
assert _status(x) == [("습도", "습함", "normal"), ("불쾌지수", "쾌적", "normal"), ("자외선", "높음", "warn"), ("미세먼지", "나쁨", "warn")]
|
||||||
|
|
||||||
|
|
||||||
|
def test_status_line_drops_uv_at_night_and_missing_values():
|
||||||
|
assert _status(HeroInput(now=NOW, night=True, humidity=25, uv=3.0, air=AirGrade.NORMAL)) == [("습도", "건조", "normal"), ("미세먼지", "보통", "normal")]
|
||||||
|
assert _status(HeroInput(now=NOW, night=False)) == []
|
||||||
@@ -9,10 +9,13 @@ import services.warning_service as warning_service
|
|||||||
import services.weather_service as weather_service
|
import services.weather_service as weather_service
|
||||||
from common.database.db_session_manager import DB_SESSION_MNG
|
from common.database.db_session_manager import DB_SESSION_MNG
|
||||||
from common.database.model.models import OpenMeteoHourly, WeatherHourly
|
from common.database.model.models import OpenMeteoHourly, WeatherHourly
|
||||||
|
from common.enums import ErrorType
|
||||||
from common.utils.kma_time import kst_midnight, now_kst
|
from common.utils.kma_time import kst_midnight, now_kst
|
||||||
|
from crud.region_crud import RegionCRUD
|
||||||
from crud.weather_crud import WeatherCRUD
|
from crud.weather_crud import WeatherCRUD
|
||||||
from router.router import app
|
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"
|
REGION = "1141000000"
|
||||||
|
|
||||||
@@ -51,13 +54,18 @@ def fakes(monkeypatch):
|
|||||||
|
|
||||||
|
|
||||||
@pytest.mark.anyio
|
@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:
|
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
|
||||||
body = (await client.get("/v1/index/list", params={"region": REGION})).json()
|
body = (await client.get("/v1/index/list", params={"region": REGION})).json()
|
||||||
assert body["result"]["success"] is True
|
assert body["result"]["success"] is True
|
||||||
assert len(body["items"]) == 27 and len(body["top3"]) == 3
|
assert len(body["items"]) == 34 and len(body["top3"]) == 3
|
||||||
scores = [i["score"] for i in body["items"]]
|
priority = {d["code"]: d["priority"] for d in _seed()}
|
||||||
assert scores == sorted(scores, reverse=True)
|
# 지금 구간에 해당하는 각이 먼저(순위), 해당 없는 각은 그 뒤. 각 묶음 안에서는 점수 × 중요도 순
|
||||||
|
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()
|
today = now_kst().date()
|
||||||
for i in body["items"]:
|
for i in body["items"]:
|
||||||
assert [t["label"] for t in i["trend"]] == [slot_label(d, today) for d in slot_days(today)]
|
assert [t["label"] for t in i["trend"]] == [slot_label(d, today) for d in slot_days(today)]
|
||||||
@@ -95,13 +103,60 @@ 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"]
|
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 json
|
||||||
import os
|
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)
|
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, {"morning": 50, "day": 50, "evening": 50, "night": 50, "early": 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)]
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.anyio
|
||||||
|
async def test_board_ranks_each_slot_with_priority_weight(monkeypatch):
|
||||||
|
today = now_kst().date()
|
||||||
|
defs = [SimpleNamespace(index_id=1, code="low", priority=3), SimpleNamespace(index_id=2, code="high", priority=1)]
|
||||||
|
every = ("morning", "day", "evening", "night", "early")
|
||||||
|
slots = {1: {k: {"score": 90, "summary": "", "factors": {}, "zero_reason": None, "notes": []} for k in every},
|
||||||
|
2: {k: {"score": 20 if k == "morning" else 70, "summary": "", "factors": {}, "zero_reason": None, "notes": []} for k in every if k not in ("night", "early")}}
|
||||||
|
scores = [SimpleNamespace(index_id=x, score_date=today, score=80, slots=slots[x]) for x in (1, 2)]
|
||||||
|
crud = SimpleNamespace(definitions=lambda s: _async(defs), scores=lambda s, *a: _async(scores))
|
||||||
|
service = IndexService(RegionCRUD(), crud, None, None, None, None, None, None)
|
||||||
|
monkeypatch.setattr(service, "ensure", lambda *a: _async((ErrorType.SUCCESS, {k: 50 for k in every})))
|
||||||
|
monkeypatch.setattr("services.index_service._with_slot", lambda row, data: SimpleNamespace(score=data["score"]))
|
||||||
|
_, board = await service.board(REGION)
|
||||||
|
ranks = {i.definition.code: i.slot_ranks for i in board.items}
|
||||||
|
# 아침: 하 90(63) > 상 20(20). 낮: 상 70(70) > 하 90(63). 상은 밤 구간이 없어 밤 순위도 없다
|
||||||
|
assert ranks["low"]["morning"] == 1 and ranks["high"]["morning"] == 2
|
||||||
|
assert ranks["high"]["day"] == 1 and ranks["low"]["day"] == 2
|
||||||
|
assert "night" not in ranks["high"]
|
||||||
|
|
||||||
|
|
||||||
def _om_row(at, **over):
|
def _om_row(at, **over):
|
||||||
row = {
|
row = {
|
||||||
"region_code": REGION, "forecast_at": at, "fetched_at": now_kst(), "uv_index": 2.0, "uv_index_clear_sky": 2.0,
|
"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 dataclasses import replace
|
||||||
from datetime import date, datetime, timezone
|
from datetime import date, datetime, timezone
|
||||||
|
from pathlib import Path
|
||||||
from types import SimpleNamespace
|
from types import SimpleNamespace
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
from common.enums import RainType, Sky
|
from common.enums import RainType, Sky
|
||||||
from services.calc.index_calc import (
|
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,
|
uv_score, view_score, zero_rules_text,
|
||||||
)
|
)
|
||||||
from services.calc.moon import illumination
|
from services.calc.moon import illumination
|
||||||
@@ -222,3 +226,51 @@ def test_outing_estimate_from_mid_forecast():
|
|||||||
assert r.reason.startswith("비 20% · 낮 ")
|
assert r.reason.startswith("비 20% · 낮 ")
|
||||||
assert outing_estimate(_fc(pm=60)).score <= 30
|
assert outing_estimate(_fc(pm=60)).score <= 30
|
||||||
assert outing_estimate(_fc(lo=None, hi=None)) is None
|
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
|
||||||
@@ -1,9 +1,10 @@
|
|||||||
from datetime import datetime, timezone
|
from dataclasses import replace
|
||||||
|
from datetime import datetime, timedelta, timezone
|
||||||
from types import SimpleNamespace
|
from types import SimpleNamespace
|
||||||
|
|
||||||
from common.enums import PostType
|
from common.enums import PostType
|
||||||
from common.utils.kma_time import KST
|
from common.utils.kma_time import KST
|
||||||
from services.calc.moon import nearest, phase_name
|
from services.calc.moon import MoonNight, altitude, nearest, night, phase_name, view_line
|
||||||
from services.feed_service import FeedService, _tonight
|
from services.feed_service import FeedService, _tonight
|
||||||
|
|
||||||
|
|
||||||
@@ -27,7 +28,7 @@ def test_tonight_follows_feed_day_starting_at_3am():
|
|||||||
|
|
||||||
def _moon_post(now: datetime):
|
def _moon_post(now: datetime):
|
||||||
base = dict(post_id=1, post_type=PostType.MOON, like_count=0, comment_count=0, published_at=now)
|
base = dict(post_id=1, post_type=PostType.MOON, like_count=0, comment_count=0, published_at=now)
|
||||||
c = SimpleNamespace(now=now, region=SimpleNamespace(short_name="분당구"), hourly=[], board=None)
|
c = SimpleNamespace(now=now, region=SimpleNamespace(short_name="분당구", lat=37.38, lon=127.12), hourly=[], board=None)
|
||||||
return FeedService._moon(None, base, c)
|
return FeedService._moon(None, base, c)
|
||||||
|
|
||||||
|
|
||||||
@@ -38,3 +39,41 @@ def test_moon_post_every_night_with_full_and_new_moon_stories():
|
|||||||
assert new.title == "오늘 밤 달 없는 밤"
|
assert new.title == "오늘 밤 달 없는 밤"
|
||||||
plain = _moon_post(datetime(2025, 10, 4, 20, 0, tzinfo=KST)) # 보름 사흘 전
|
plain = _moon_post(datetime(2025, 10, 4, 20, 0, tzinfo=KST)) # 보름 사흘 전
|
||||||
assert plain.title == "오늘 밤 차오르는 달" and plain.slides[0].rows[-1].label == "다음 보름" and plain.slides[0].rows[-1].value.startswith("10.07")
|
assert plain.title == "오늘 밤 차오르는 달" and plain.slides[0].rows[-1].label == "다음 보름" and plain.slides[0].rows[-1].value.startswith("10.07")
|
||||||
|
|
||||||
|
|
||||||
|
SEOUL = (37.57, 126.98)
|
||||||
|
|
||||||
|
|
||||||
|
def _night_of(at):
|
||||||
|
"""그 시각과 23시가 가장 가까운 밤."""
|
||||||
|
return (at.astimezone(KST) - timedelta(hours=11)).date()
|
||||||
|
|
||||||
|
|
||||||
|
def test_full_moon_is_up_all_night_and_highest_near_solar_midnight():
|
||||||
|
full = nearest(datetime(2026, 10, 25, tzinfo=KST), True)
|
||||||
|
day = _night_of(full)
|
||||||
|
m = night(day, *SEOUL)
|
||||||
|
assert m.name == "보름달" and set(range(20, 29)) <= set(m.up_hours)
|
||||||
|
start = datetime.combine(day, datetime.min.time(), tzinfo=KST)
|
||||||
|
peak = max((start + timedelta(hours=22, minutes=10 * i) for i in range(24)), key=lambda t: altitude(t, *SEOUL))
|
||||||
|
assert 23 <= (peak.hour if peak.hour >= 12 else peak.hour + 24) <= 25
|
||||||
|
assert view_line(m, 0.0) == "밤새 잘 보여요"
|
||||||
|
assert view_line(m, 0.8) == "흐려서 구름에 가려요"
|
||||||
|
|
||||||
|
|
||||||
|
def test_first_quarter_sets_around_midnight_and_new_moon_is_not_seen():
|
||||||
|
new = nearest(datetime(2026, 10, 12, tzinfo=KST), False)
|
||||||
|
quarter = night(_night_of(new + timedelta(days=7.4)), *SEOUL)
|
||||||
|
assert quarter.set_at is not None and quarter.set_at.astimezone(KST).hour in (21, 22, 23, 0, 1, 2)
|
||||||
|
assert view_line(quarter, 0.0).endswith("까지 보여요")
|
||||||
|
assert view_line(night(_night_of(new), *SEOUL), 0.0) == "해와 같은 쪽에 있어 안 보여요"
|
||||||
|
hidden = MoonNight(name="초승달", lit=0.05, waxing=True, rise_at=None, set_at=None, up_hours=())
|
||||||
|
assert view_line(hidden, 0.0) == "해 진 뒤 곧 져서 밤엔 안 보여요"
|
||||||
|
assert view_line(replace(hidden, name="그믐달", waxing=False), 0.0) == "새벽 늦게 떠서 밤엔 안 보여요"
|
||||||
|
|
||||||
|
|
||||||
|
def test_waning_moon_rises_late():
|
||||||
|
full = nearest(datetime(2026, 10, 25, tzinfo=KST), True)
|
||||||
|
m = night(_night_of(full + timedelta(days=7.4)), *SEOUL)
|
||||||
|
assert m.rise_at is not None and m.rise_at.astimezone(KST).hour in (21, 22, 23, 0, 1, 2)
|
||||||
|
assert view_line(m, 0.0).endswith("에 떠요")
|
||||||
@@ -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", [
|
@pytest.mark.parametrize("kind,end,address", [
|
||||||
("PERFORMANCE", "2026-10-11", "서울 성동구 테스트로 1"),
|
("PERFORMANCE", "2026-10-11", "서울 성동구 테스트로 1"),
|
||||||
("STORE", "2026-09-30", "서울 성동구 테스트로 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
|
import pytest
|
||||||
from httpx import ASGITransport, AsyncClient
|
from httpx import ASGITransport, AsyncClient
|
||||||
|
from sqlalchemy import text
|
||||||
|
|
||||||
import services.season_service as season_service
|
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 common.utils.kma_time import now_kst
|
||||||
from router.router import app
|
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()
|
missing = (await client.get("/v1/season/article/9999")).json()
|
||||||
assert first["body"] and first["article"]["title"] == listed[0]["title"]
|
assert first["body"] and first["article"]["title"] == listed[0]["title"]
|
||||||
assert missing["result"]["desc"] == "NOT_FOUND"
|
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"]
|
||||||
@@ -52,10 +52,10 @@ async def test_sky_view_scores_three_days_with_spots(monkeypatch, clean):
|
|||||||
assert 255 <= body["sunset_azimuth"] <= 280
|
assert 255 <= body["sunset_azimuth"] <= 280
|
||||||
plan = body["plan"]
|
plan = body["plan"]
|
||||||
assert plan["verdict"] == "go" and plan["headline"] == "나가 볼 만해요" and plan["when"] in ("오늘", "내일")
|
assert plan["verdict"] == "go" and plan["headline"] == "나가 볼 만해요" and plan["when"] in ("오늘", "내일")
|
||||||
assert "알맞게" in plan["reason"]
|
assert "적당히" in plan["reason"]
|
||||||
assert plan["spot"]["name"] == "망원한강공원" and plan["best_at"]
|
assert plan["spot"]["name"] == "망원한강공원" and plan["best_at"]
|
||||||
assert [t["kind"] for t in plan["timeline"]] == ["golden", "sun", "blue"]
|
assert [t["kind"] for t in plan["timeline"]] == ["golden", "sun", "peak", "blue"]
|
||||||
assert plan["situation_label"] == "하늘이 넓게 물들 수 있어요" and plan["models_agree"] == plan["models_total"] == 2
|
assert plan["title"].startswith(plan["timeline"][2]["at"][11:16]) and plan["title"].endswith("물들어요") and plan["models_agree"] == plan["models_total"] == 2
|
||||||
assert plan["outlook"] == ""
|
assert plan["outlook"] == ""
|
||||||
assert body["sunset"]["verdict"] == "go" and body["spots"][0]["direction"]
|
assert body["sunset"]["verdict"] == "go" and body["spots"][0]["direction"]
|
||||||
|
|
||||||
@@ -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)
|
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 decimal import Decimal
|
||||||
|
|
||||||
from common.database.model.models import SunsetSpot
|
from common.database.model.models import SunsetSpot
|
||||||
@@ -103,25 +103,21 @@ def test_nearest_spots_west_first_and_empty_outside_radius():
|
|||||||
|
|
||||||
spots = [spot("가까운 동쪽", 37.01, False), spot("먼 서쪽", 37.1, True), spot("반경 밖", 37.5, True)]
|
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 [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():
|
def test_outlook_only_when_a_later_day_has_a_higher_grade():
|
||||||
from datetime import date, timedelta
|
from datetime import date, timedelta
|
||||||
|
|
||||||
from common.database.model.models import SkyScore
|
from common.database.model.models import SkyScore
|
||||||
from common.enums import SkySituation
|
from services.calc.sky_score import grade
|
||||||
|
|
||||||
today = date(2026, 10, 6)
|
today = date(2026, 10, 6)
|
||||||
day = lambda i, v: SkyScore(score_date=today + timedelta(days=i), score=v) # noqa: E731
|
day = lambda i, v: SkyScore(score_date=today + timedelta(days=i), score=v, grade=grade(v).value, sky_type=1) # noqa: E731
|
||||||
sit = lambda i, s: SkyScore(score_date=today + timedelta(days=i), score=48, situation=s.value) # noqa: E731
|
assert sky_service.outlook(day(0, 30), [day(0, 30), day(1, 35), day(2, 72)], today) == "모레 노을이 곱게 물들어요"
|
||||||
assert sky_service.outlook(day(0, 30), [day(0, 30), day(1, 35), day(2, 72)], today) == "모레가 더 나아요 · 나가 볼 만해요"
|
assert sky_service.outlook(day(0, 29), [day(0, 29), day(1, 30)], today) == ""
|
||||||
assert sky_service.outlook(day(0, 80), [day(0, 80), day(1, 50), day(2, 40)], today) == ""
|
assert sky_service.outlook(day(0, 80), [day(0, 80), day(1, 50), day(2, 40)], today) == ""
|
||||||
assert sky_service.outlook(day(0, 50), [day(0, 50), day(1, 55), day(2, 45)], today) == ""
|
|
||||||
assert sky_service.outlook(day(2, 50), [day(2, 50)], today) == ""
|
assert sky_service.outlook(day(2, 50), [day(2, 50)], today) == ""
|
||||||
few, glow = SkySituation.FEW, SkySituation.GLOW
|
|
||||||
assert sky_service.outlook(sit(0, few), [sit(0, few), sit(1, few), sit(2, glow)], today) == "모레가 더 나아요 · 하늘이 넓게 물들 수 있어요"
|
|
||||||
assert sky_service.outlook(sit(0, few), [sit(0, few), sit(1, few)], today) == ""
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.anyio
|
@pytest.mark.anyio
|
||||||
@@ -160,8 +156,8 @@ def test_score_rows_apply_air_at_sunset_and_keep_cloud_score_without_air():
|
|||||||
hourly = {("R", hour): SimpleNamespace(humidity=90, rain_prob=0)}
|
hourly = {("R", hour): SimpleNamespace(humidity=90, rain_prob=0)}
|
||||||
om = {("R", sky_service._nearest_slot(hour)): SimpleNamespace(visibility_m=5000)}
|
om = {("R", sky_service._nearest_slot(hour)): SimpleNamespace(visibility_m=5000)}
|
||||||
hazy = sky_service._score_rows(region, today, clouds, now, hourly, om)[0]["score"]
|
hazy = sky_service._score_rows(region, today, clouds, now, hourly, om)[0]["score"]
|
||||||
assert hazy == round(plain * 0.6 * 0.75)
|
assert hazy == round(plain * 0.8 * 0.85)
|
||||||
rain = {("R", hour - timedelta(hours=3)): SimpleNamespace(humidity=50, rain_prob=80), ("R", hour): SimpleNamespace(humidity=50, rain_prob=10)}
|
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))
|
assert sky_service._score_rows(region, today, clouds, now, rain, {})[0]["score"] == min(100, round(plain * 1.15))
|
||||||
|
|
||||||
|
|
||||||
@@ -169,3 +165,30 @@ def test_nearest_slot_is_closest_three_hour_end():
|
|||||||
from datetime import datetime, timezone
|
from datetime import datetime, timezone
|
||||||
at = lambda h, m=0: datetime(2026, 10, 7, h, m, tzinfo=timezone.utc) # noqa: E731
|
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]
|
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, [])
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
from datetime import date, datetime, timedelta, timezone
|
from datetime import date, datetime, timedelta, timezone
|
||||||
|
|
||||||
from common.enums import Confidence, SkyGrade, SkyType
|
from common.enums import Confidence, SkyGrade, SkySituation, SkyType
|
||||||
from common.utils.geo import destination, haversine_km
|
from common.utils.geo import destination, haversine_km
|
||||||
from services.calc.sky_score import (
|
from services.calc.sky_score import (
|
||||||
GRADE_LABEL, Air, Layers, air_factor, best_times, confidence, grade, reason, score, situation, sunset_timeline, verdict,
|
GRADE_LABEL, Air, Layers, air_factor, best_times, confidence, grade, reason, score, situation, sunset_timeline, verdict,
|
||||||
@@ -24,15 +24,21 @@ def test_score_rises_steadily_with_a_few_clouds():
|
|||||||
assert scores == sorted(scores) and len(set(scores)) == len(scores) # 맑은 날도 구름 몇 %로 갈리고 10%에서 꺾이지 않는다
|
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()) == 1.0
|
||||||
assert air_factor(Air(visibility_km=40, humidity=50)) == 1.0
|
assert air_factor(Air(visibility_km=20, humidity=60)) == 1.0 # 평소 공기
|
||||||
assert air_factor(Air(visibility_km=5)) == 0.6 and air_factor(Air(humidity=90)) == 0.75
|
assert air_factor(Air(visibility_km=5)) == 0.8 and air_factor(Air(humidity=90)) == 0.85
|
||||||
assert 0.6 < air_factor(Air(visibility_km=30)) < 1.0
|
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=10)) == 1.15
|
||||||
assert air_factor(Air(rain_before=70, rain_now=60)) == 1.0 # 아직 비 오는 중이면 가산 없음
|
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():
|
def test_low_clouds_toward_sun_block_the_light():
|
||||||
canvas = Layers(low=0, mid=20, high=50)
|
canvas = Layers(low=0, mid=20, high=50)
|
||||||
assert grade(score(canvas, Layers(low=90, mid=50, high=0))) is SkyGrade.GRAY
|
assert grade(score(canvas, Layers(low=90, mid=50, high=0))) is SkyGrade.GRAY
|
||||||
@@ -64,9 +70,9 @@ def test_sunset_best_times_order():
|
|||||||
|
|
||||||
def test_reason_names_what_decided_the_score():
|
def test_reason_names_what_decided_the_score():
|
||||||
canvas = Layers(low=0, mid=20, high=50)
|
canvas = Layers(low=0, mid=20, high=50)
|
||||||
assert "알맞게" in reason(canvas, CLEAR)
|
assert "적당히" in reason(canvas, CLEAR)
|
||||||
assert "먼 하늘" in reason(canvas, Layers(low=90, mid=50, high=0))
|
assert "멀리까지 구름이 끼어" in reason(canvas, Layers(low=90, mid=50, high=0))
|
||||||
assert "낮은 구름" in reason(Layers(100, 0, 0), CLEAR)
|
assert "낮게 깔린 구름" in reason(Layers(100, 0, 0), CLEAR)
|
||||||
assert "거의 없어" in reason(CLEAR, CLEAR)
|
assert "거의 없어" in reason(CLEAR, CLEAR)
|
||||||
|
|
||||||
|
|
||||||
@@ -77,7 +83,7 @@ def test_verdict_bands_and_gray_label_is_not_weather_word():
|
|||||||
|
|
||||||
def test_sunset_timeline_runs_golden_to_blue():
|
def test_sunset_timeline_runs_golden_to_blue():
|
||||||
sun = sun_times(date(2026, 10, 6), 37.56, 126.91)
|
sun = sun_times(date(2026, 10, 6), 37.56, 126.91)
|
||||||
rows = sunset_timeline(sun.golden_start_at, sun.sunset_at, sun.sunset_at + timedelta(minutes=15), sun.dusk_end_at)
|
rows = sunset_timeline(sun.golden_start_at, sun.sunset_at, sun.sunset_at + timedelta(minutes=15), sun.blue_start_at, sun.dusk_end_at)
|
||||||
assert [r["kind"] for r in rows] == ["golden", "sun", "peak", "blue"]
|
assert [r["kind"] for r in rows] == ["golden", "sun", "peak", "blue"]
|
||||||
ats = [datetime.fromisoformat(r["at"]) for r in rows]
|
ats = [datetime.fromisoformat(r["at"]) for r in rows]
|
||||||
assert ats == sorted(ats) and 15 <= (ats[1] - ats[0]).total_seconds() / 60 <= 60
|
assert ats == sorted(ats) and 15 <= (ats[1] - ats[0]).total_seconds() / 60 <= 60
|
||||||
@@ -101,3 +107,66 @@ def test_ranking_summary_only_when_most_spots_share_a_situation():
|
|||||||
item = lambda s: SimpleNamespace(score=SimpleNamespace(situation=s.value)) # noqa: E731
|
item = lambda s: SimpleNamespace(score=SimpleNamespace(situation=s.value)) # noqa: E731
|
||||||
assert ranking_summary([item(SkySituation.FEW)] * 8 + [item(SkySituation.GLOW)] * 2) == "오늘은 전국이 맑아 대부분 짧게 끝나요"
|
assert ranking_summary([item(SkySituation.FEW)] * 8 + [item(SkySituation.GLOW)] * 2) == "오늘은 전국이 맑아 대부분 짧게 끝나요"
|
||||||
assert ranking_summary([item(SkySituation.FEW)] * 5 + [item(SkySituation.GLOW)] * 5) is None
|
assert ranking_summary([item(SkySituation.FEW)] * 5 + [item(SkySituation.GLOW)] * 5) is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_next_event_sunrise_then_sunset_then_tomorrow_sunrise():
|
||||||
|
from types import SimpleNamespace
|
||||||
|
|
||||||
|
from common.utils.kma_time import KST
|
||||||
|
from services.sky_service import next_event
|
||||||
|
|
||||||
|
day = date(2026, 10, 8)
|
||||||
|
rows = lambda kind: [SimpleNamespace(score_date=day + timedelta(days=i), sky_type=kind.value) for i in range(3)] # noqa: E731
|
||||||
|
sunsets, sunrises = rows(SkyType.SUNSET), rows(SkyType.SUNRISE)
|
||||||
|
pick = lambda h, m=0: next_event(sunsets, sunrises, 37.5, 127.0, datetime(2026, 10, 8, h, m, tzinfo=KST)) # noqa: E731
|
||||||
|
assert (pick(5)[0], pick(5)[1].score_date) == (SkyType.SUNRISE, day)
|
||||||
|
assert (pick(9)[0], pick(9)[1].score_date) == (SkyType.SUNSET, day)
|
||||||
|
assert (pick(18, 10)[0], pick(18, 10)[1].score_date) == (SkyType.SUNSET, day)
|
||||||
|
assert (pick(21)[0], pick(21)[1].score_date) == (SkyType.SUNRISE, day + timedelta(days=1))
|
||||||
|
|
||||||
|
|
||||||
|
def test_sunrise_reason_and_timeline():
|
||||||
|
from services.calc.sky_score import sunrise_timeline
|
||||||
|
|
||||||
|
assert "해 뜨는 쪽" in reason(Layers(0, 0, 0), Layers(90, 50, 0), SkyType.SUNRISE)
|
||||||
|
sun = sun_times(date(2026, 10, 8), 37.5, 127.0)
|
||||||
|
rows = sunrise_timeline(sun.dawn_start_at, sun.blue_end_morning_at, sun.sunrise_at - timedelta(minutes=12), sun.sunrise_at, sun.golden_end_at)
|
||||||
|
assert [r["kind"] for r in rows] == ["blue", "peak", "sun", "golden"]
|
||||||
|
assert sun.dawn_start_at < sun.sunrise_at < sun.golden_end_at
|
||||||
|
|
||||||
|
|
||||||
|
def test_hazy_air_lowers_verdict_and_says_why():
|
||||||
|
from types import SimpleNamespace
|
||||||
|
|
||||||
|
from services.calc.sky_score import air_note
|
||||||
|
from services.sky_service import day_verdict
|
||||||
|
|
||||||
|
hazy = {"factor": 0.5, "visibility_km": 6.5, "humidity": 80}
|
||||||
|
assert air_note(hazy) == "먼 건물이 흐릿할 만큼 공기가 뿌옇고 습해서 노을 색이 바래 보일 거예요"
|
||||||
|
assert air_note({"factor": 0.9, "visibility_km": 30.0, "humidity": 60}) is None
|
||||||
|
glow = SimpleNamespace(situation=SkySituation.GLOW.value, score=29, air=hazy)
|
||||||
|
assert day_verdict(glow) == "maybe"
|
||||||
|
assert day_verdict(SimpleNamespace(situation=SkySituation.GLOW.value, score=60, air=None)) == "go"
|
||||||
|
assert day_verdict(SimpleNamespace(situation=SkySituation.COVERED.value, score=10, air=hazy)) == "rest"
|
||||||
|
|
||||||
|
|
||||||
|
def test_plain_line_says_why_only_on_gray_days():
|
||||||
|
from services.calc.sky_score import plain_line
|
||||||
|
|
||||||
|
hazy = {"factor": 0.5, "visibility_km": 6.5, "humidity": 80}
|
||||||
|
assert plain_line(SkyGrade.GRAY, SkySituation.GLOW, hazy) == "하늘이 뿌예서 색이 바래요"
|
||||||
|
assert plain_line(SkyGrade.GRAY, SkySituation.COVERED, hazy, SkyType.SUNRISE) == "해 뜨는 쪽 하늘이 구름에 가려요"
|
||||||
|
assert plain_line(SkyGrade.GRAY, SkySituation.FEW, None) == "구름이 거의 없어요"
|
||||||
|
assert plain_line(SkyGrade.GLOW, SkySituation.GLOW, None) is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_sky_title_follows_grade():
|
||||||
|
from services.calc.sky_score import sky_title
|
||||||
|
|
||||||
|
peak = datetime(2026, 10, 12, 18, 10, tzinfo=timezone(timedelta(hours=9)))
|
||||||
|
assert sky_title(SkyGrade.GRAY, SkyType.SUNSET, "오늘", peak) == "오늘은 노을이 거의 안 보여요"
|
||||||
|
assert sky_title(SkyGrade.SOFT, SkyType.SUNSET, "모레", peak) == "18:10, 모레 노을이 은은하게 물들어요"
|
||||||
|
assert sky_title(SkyGrade.GLOW, SkyType.SUNSET, "오늘", peak) == "18:10, 오늘 노을이 곱게 물들어요"
|
||||||
|
assert sky_title(SkyGrade.RED, SkyType.SUNSET, None, peak) == "18:10, 하늘이 온통 붉게 물들어요"
|
||||||
|
assert sky_title(SkyGrade.GLOW, SkyType.SUNRISE, "내일", peak) == "18:10, 내일 아침 노을이 곱게 물들어요"
|
||||||
|
assert sky_title(SkyGrade.GRAY, SkyType.SUNRISE, None) == "아침 노을이 거의 안 보여요"
|
||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import asyncio
|
||||||
from datetime import timedelta
|
from datetime import timedelta
|
||||||
|
|
||||||
import pytest
|
import pytest
|
||||||
@@ -5,8 +6,10 @@ from httpx import ASGITransport, AsyncClient
|
|||||||
from sqlalchemy import text
|
from sqlalchemy import text
|
||||||
|
|
||||||
import services.weather_service as weather_service
|
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.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
|
from router.router import app
|
||||||
|
|
||||||
REGION = "1144000000"
|
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 weather_daily WHERE region_code='{REGION}'")),
|
||||||
lambda s: s.execute(text(f"DELETE FROM sun_time 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()
|
await wipe()
|
||||||
yield
|
yield
|
||||||
await wipe()
|
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.CLEAR), sun)[0::2] == ("sunset", "노을")
|
||||||
assert _slot_view(at, row(Sky.CLOUDY), sun)[0::2] == ("cloud", "흐림")
|
assert _slot_view(at, row(Sky.CLOUDY), sun)[0::2] == ("cloud", "흐림")
|
||||||
assert _slot_view(at, row(Sky.PARTLY), 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.warning_service as warning_service
|
||||||
import services.weather_service as weather_service
|
import services.weather_service as weather_service
|
||||||
import services.week_service as week_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.enums import EventKind, RainType, Sky
|
||||||
from common.utils.kma_time import KST, kst_midnight, now_kst
|
from common.utils.kma_time import KST, kst_midnight, now_kst
|
||||||
from router.router import app
|
from router.router import app
|
||||||
from services.external.kma import latest_mid_base, mid_word, parse_mid
|
from services.external.kma import latest_mid_base, mid_word, parse_mid
|
||||||
from services.external.data_go_kr import DataGoKrRequestFailed
|
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"
|
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"]} == {"잠실 축제", "좌표 없는 경기 축제"}
|
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
|
@pytest.mark.anyio
|
||||||
async def test_places_put_indoor_first_on_rainy_day(fakes):
|
async def test_places_put_indoor_first_on_rainy_day(fakes):
|
||||||
rainy_day = (now_kst().date() + timedelta(days=2)).isoformat()
|
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
|
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
|
@pytest.mark.anyio
|
||||||
async def test_weekend_ranking_scores_30_spots_and_caches(fakes, monkeypatch):
|
async def test_weekend_ranking_scores_30_spots_and_caches(fakes, monkeypatch):
|
||||||
from services.weekend_rank import weekend_days
|
from services.weekend_rank import weekend_days
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
from datetime import date, datetime
|
from datetime import date, datetime
|
||||||
from types import SimpleNamespace
|
from types import SimpleNamespace
|
||||||
|
|
||||||
|
from common.enums import EventKind
|
||||||
from common.utils.kma_time import KST
|
from common.utils.kma_time import KST
|
||||||
from services.week_service import DayPlan, EventItem
|
from services.week_service import DayPlan, EventItem
|
||||||
from services.weekend_plan import day_plan, forecast, pick_events
|
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)
|
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:
|
def _event(name, start, end, dist, image="https://img/x.jpg", kind=EventKind.FESTIVAL) -> 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")
|
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)
|
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("비 오는 토요일")
|
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():
|
def test_saturday_ignores_ending_hook_and_sunday_skips_saturday_events():
|
||||||
near = _event("가까운 축제", SAT, SUN, 3.0)
|
near = _event("가까운 축제", SAT, SUN, 3.0)
|
||||||
ends_sat = _event("토요일 끝", SAT, SAT, 50.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)) == []
|
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():
|
def test_cloudy_weekend_is_not_called_clear():
|
||||||
cloudy = [_day(SAT), _day(SUN)]
|
cloudy = [_day(SAT), _day(SUN)]
|
||||||
for d in cloudy:
|
for d in cloudy:
|
||||||
|
|||||||
@@ -0,0 +1,157 @@
|
|||||||
|
# 기능 QA 체크리스트 (휴대폰)
|
||||||
|
|
||||||
|
아이폰 Safari와 안드로이드 Chrome에서 http://<킹서버>:30040 에 들어가 위에서부터 따라 하며 체크합니다. 기대 결과는 `frontend/src/b/` 코드 기준이고, 확실하지 않은 동작은 "(확인)"을 붙였습니다.
|
||||||
|
|
||||||
|
## 0. 처음 들어가기
|
||||||
|
|
||||||
|
- [ ] 사이트 데이터를 지우고 접속 → 위치 권한을 묻고, 상단 지역 버튼 자리에 스켈레톤 막대
|
||||||
|
- [ ] 위치 허용 → 가장 가까운 구로 바뀐다 / 거부 → 기본 "서울 마포구"
|
||||||
|
- [ ] 새로고침 → 위치를 다시 묻지 않고 마지막 지역 그대로
|
||||||
|
|
||||||
|
## 1. 공통: 상단 바·하단 탭
|
||||||
|
|
||||||
|
- [ ] 하단 탭이 노을 · 각 · 오늘(가운데 큰 주황 동그라미) · 주말·행사 · 계절·상식 순
|
||||||
|
- [ ] 탭을 옮길 때마다 맨 위에서 시작하고, 제목이 오늘은 주황 "날씨각", 나머지는 노을 / 오늘의 각 / 주말·행사 / 계절·상식
|
||||||
|
- [ ] 로그아웃 상태는 오른쪽 위 "로그인" 버튼, 로그인 상태는 내 캐릭터 동그라미(기분 이모지 포함)
|
||||||
|
- [ ] 스크롤해도 상단 바·하단 탭이 고정되고 뒤 내용이 흐리게 비친다
|
||||||
|
|
||||||
|
## 2. 오늘 탭: 히어로
|
||||||
|
|
||||||
|
- [ ] 시간대 버튼 지금 · 아침 · 낮 · 저녁 · 밤, 처음엔 "지금", 날짜 줄은 "M월 D일 요일 · HH:MM"
|
||||||
|
- [ ] 해 안에 "지금 날씨 점수"와 큰 숫자, 아래 한 줄 네 칸: "지금 + 기온·하늘" · "습도 N%" · "불쾌지수 N 쾌적"(75 이상이면 경고 색) · 챙길 것 한 칸(비·미세먼지 등). 폰 너비에서 넘치지 않는다
|
||||||
|
- [ ] "아침" → 시계 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°") + 검은 팁 줄
|
||||||
|
- [ ] 오늘 밤 달: "오늘 밤은 (모양), (잘 보이는지)"(예: 흐려서 구름에 가려요 · 새벽 2시에 떠요 · 밤 11시까지 보여요 · 해와 같은 쪽에 있어 안 보여요), 안 보일 땐 늘 이유가 붙는다, 달 뜸·짐 시각 줄, "밝기 %"는 어디에도 없다
|
||||||
|
- [ ] 주말 플랜: 시간·아이콘·제목·설명 줄, 사진이 있으면 작은 사진과 맨 아래 "사진 출처"
|
||||||
|
- [ ] 행사·당일치기 사진 슬라이드: 사진 위 글자, 오른쪽 위 출처
|
||||||
|
- [ ] 점선 밑줄 장소 이름 → 네이버 지도 검색이 새 탭으로
|
||||||
|
- [ ] 한 줄 카드(흐린 날 노을 등)는 아이콘·제목·설명만, 버튼 없음
|
||||||
|
- [ ] 카드 아래 "좋아요 N개", 본문, "댓글 N개 모두 보기"(0개면 "첫 댓글 남기기")
|
||||||
|
|
||||||
|
## 6. 좋아요·댓글
|
||||||
|
|
||||||
|
- [ ] 로그아웃 상태에서 하트 또는 사진 두 번 탭 → 로그인 시트
|
||||||
|
- [ ] 로그인 후 사진 두 번 탭 → 큰 하트 + 튀는 하트 + "좋아요했어요!", 하트 빨강, 숫자 +1
|
||||||
|
- [ ] 이미 좋아요한 사진 두 번 탭 → 효과만 다시, 숫자 그대로 / 하트 버튼 → 취소, -1
|
||||||
|
- [ ] 다른 탭에 다녀와도 하트·숫자 유지
|
||||||
|
- [ ] (비행기 모드) 좋아요 → 원래대로 돌아가고 아래에 "좋아요를 반영하지 못했어요. 다시 해 주세요." 2.5초
|
||||||
|
- [ ] 댓글 아이콘·"댓글 … 보기" → 댓글 시트, 없으면 "아직 댓글이 없어요. 첫 댓글을 남겨 보세요."
|
||||||
|
- [ ] 빠른 이모지(☀️🌂🍻🌇😍👍) → 입력칸 끝에 붙고 포커스, 입력은 60자까지
|
||||||
|
- [ ] 로그인 후 "게시" → "올리는 중…" 뒤 목록에 뜨고 입력칸이 비며, 피드 댓글 수도 늘어난다
|
||||||
|
- [ ] 로그아웃 상태에서 "게시" → 로그인 시트로 바뀐다
|
||||||
|
- [ ] 내 댓글에만 "지우기" → 흐려졌다 사라진다 / 댓글 작은 하트 → 좋아요 수 변경
|
||||||
|
- [ ] 댓글이 많으면 "댓글 더 보기"로 더 불러온다 (확인: 한 번에 몇 개인지)
|
||||||
|
|
||||||
|
## 7. 로그인·내 정보
|
||||||
|
|
||||||
|
- [ ] 로그인 시트 "로그인 / 처음이에요" 전환, 처음이에요는 닉네임 칸 + "가입하고 시작하기"
|
||||||
|
- [ ] 틀린 비밀번호 → "아이디나 비밀번호가 맞지 않아요." / 있는 아이디로 가입 → "이미 쓰고 있는 아이디예요."
|
||||||
|
- [ ] 로그인 성공 → 시트가 닫히고 오른쪽 위가 내 캐릭터 / "나중에 할게요" → 닫힘
|
||||||
|
- [ ] 캐릭터 누름 → "내 정보" 시트, "아이디(으)로 로그인했어요"
|
||||||
|
- [ ] 캐릭터 6종·배경색 6개 누름 → 주황 테두리, 큰 캐릭터·상단 바 캐릭터가 바뀐다
|
||||||
|
- [ ] 오늘 기분 8개 → 캐릭터 오른쪽 위 이모지, 같은 기분 다시 누르면 지워진다
|
||||||
|
- [ ] 닉네임이 지금과 같으면 "바꾸기"가 막혀 있고, 바꾸면 "저장 중…" 뒤 저장, 댓글 목록에도 반영
|
||||||
|
- [ ] "로그아웃" → 시트 닫힘, 오른쪽 위 "로그인", 좋아요 표시가 풀린다
|
||||||
|
|
||||||
|
## 8. 지역 바꾸기
|
||||||
|
|
||||||
|
- [ ] 지역 버튼 → "지역 바꾸기" 시트, 지금 지역은 주황 글자 + "지금 보는 곳"
|
||||||
|
- [ ] "마포" 입력 → 목록이 걸러짐, 없는 이름 → "찾는 구가 없어요."
|
||||||
|
- [ ] 다른 구 누름 → 시트가 닫히고 지역 이름·모든 탭 데이터가 바뀐다
|
||||||
|
- [ ] "지금 위치로 찾기" → "위치를 찾는 중이에요…", 성공하면 지역이 바뀌고 시트는 열린 채 (확인)
|
||||||
|
- [ ] 위치 권한 끈 상태 → "위치 권한이 꺼져 있어요. 아래 목록에서 골라 주세요."
|
||||||
|
|
||||||
|
## 9. 노을 탭
|
||||||
|
|
||||||
|
- [ ] 히어로 "오늘 노을 · 지역"(해 뜨기 전·블루아워 뒤엔 "… 일출"), 큰 점수 + "점 · 등급", 그 아래 "HH:MM 해 져요(떠요) · 하늘 상황", 상황에 따라 색이 다르고 아래 동네 실루엣
|
||||||
|
- [ ] 흰 카드: 결론 + 이유, "예보 모델 N개 중 M개가 같은 예보"
|
||||||
|
- [ ] "언제 보면 좋을까" 세 시각(해 짐·뜸 점만 주황) + 아래 골든아워·블루아워 뜻 두 줄(일출이면 일출 기준 설명), 더 나은 날이 있을 때만 분홍 안내 상자
|
||||||
|
- [ ] 일출일 땐 가까운 노을 명소가 안 나온다
|
||||||
|
- [ ] 가까운 노을 명소 최대 3곳("방향쪽" · "Nkm", 이름 → 네이버 지도), 전국 노을 순위 8곳(내 지역 흰 바탕 + "내 지역")
|
||||||
|
|
||||||
|
## 10. 각 탭
|
||||||
|
|
||||||
|
- [ ] "오늘 1~3위"(지금 구간 기준, 안 맞는 각 제외) 부제 "M월 D일 기준 · 지역", 받침대 2위 · 1위(가장 크고 노란 바탕) · 3위, 누르면 계산 근거
|
||||||
|
- [ ] 분야 칩 전체 · 밖에서 놀기 · 먹고 마시기 · 집안일 · 생활 고민 · 가을 각 → 3열 목록이 바뀐다
|
||||||
|
- [ ] 목록 칸: 왼쪽 위 순위, 가을 핵심 각은 초록 "가을", 50점 미만 점수 회색, 지금 구간에 안 맞는 각은 맨 뒤 흐리게 "지금 아님"(순위 없음)
|
||||||
|
- [ ] 맨 아래 "각 점수는 어떻게 매길까?" → 읽을거리 시트
|
||||||
|
- [ ] 계산 근거 시트: 제목 "N위 이름", 지금 구간 설명, 레이더(요소 3개 이상), 오늘 아침·낮·저녁·밤 4칸(지금 칸 강조, 안 겹치는 구간 '–'), 날짜별 추이("예상" 표시), 구간 목록, 요소별 막대·비중, 계산 방법
|
||||||
|
|
||||||
|
## 11. 주말·행사 탭
|
||||||
|
|
||||||
|
- [ ] "열흘 날씨" 한 화면 7칸, 밀면 10일까지, 처음엔 이번 토요일 선택
|
||||||
|
- [ ] 토·일·공휴일은 분홍 글자, 공휴일은 날짜 대신 이름
|
||||||
|
- [ ] 날짜 누름 → 초록 추천 카드가 그날 것으로 바뀐다
|
||||||
|
- [ ] 서울: 동네 고르기로 명소가 바뀌고, 부제가 날씨에 맞게("비가 와서 실내 명소를 먼저" / "맑아서 야외 명소를 먼저")
|
||||||
|
- [ ] 명소 배지 "오늘 딱"(야외) / "비 와도 OK"(실내), 이름 → 네이버 지도
|
||||||
|
- [ ] 서울이 아닌 지역 → 데이트 명소 칸이 통째로 숨는다, 지역을 바꾸면 동네 고르기가 "전체"로
|
||||||
|
- [ ] 전국 날씨 순위: 토/일 칩 전환, 10위까지, 내 지역 표시, 추정은 "· 예상"
|
||||||
|
- [ ] 축제·행사: 진행 중(초록)/곧 시작(주황) 배지, 기간·장소, 미확정 "· 일정 확인 필요", 날씨 줄(비면 분홍)
|
||||||
|
- [ ] "이번 주말 일정 보내기" → 공유 시트(고른 날 추천 카드 이미지)
|
||||||
|
|
||||||
|
## 12. 계절·상식 탭
|
||||||
|
|
||||||
|
- [ ] 특집 상자: "이번 주 특집 · 기간", 제목, 시, 절기 막대
|
||||||
|
- [ ] 특집 상자 → "이번 주 특집" 시트, 그 안 글 목록 → 읽을거리 시트로 바뀐다
|
||||||
|
- [ ] 분류 칩 전체 · 계절 소식 · 날씨 상식 · 각 원리로 걸러지고, 줄 누름 → 읽을거리(제목이 분류 이름, "분류 · N분")
|
||||||
|
|
||||||
|
## 13. 공유하기
|
||||||
|
|
||||||
|
- [ ] 포스트 종이비행기 → "보내기" 시트, 9:16 선택된 채 "이미지 만드는 중" 뒤 미리보기
|
||||||
|
- [ ] 4:5, 1:1로 바꾸면 비율이 바뀌고, 다시 돌아가면 바로 뜬다
|
||||||
|
- [ ] 이미지: 위 "날씨각" + "지역 · 오늘 날짜", 슬라이드 최대 2장(2장이면 1·2 번호), 아래 "오늘 내 동네 각 보기 + 주소"
|
||||||
|
- [ ] 이미지에 버튼("계산 근거 보기")·"1/N"·화살표가 빠져 있고, 밤 테마면 배경도 어두운 하늘
|
||||||
|
- [ ] "공유하기" → 휴대폰 공유창에 이미지와 "제목 · 날씨각 주소" 글이 같이 넘어가고, 보내면 "보냈어요"(그냥 닫으면 안내 없음)
|
||||||
|
- [ ] 카카오톡·인스타 스토리·사진 저장으로 실제 보내 본다 (확인: 앱마다 글이 빠질 수 있음)
|
||||||
|
|
||||||
|
## 14. 시트 공통
|
||||||
|
|
||||||
|
- [ ] 아래에서 올라오고 ×·바깥 어두운 곳 누름으로 닫힌다
|
||||||
|
- [ ] 열린 동안 뒤 페이지가 스크롤되지 않고, 긴 내용은 시트 안에서만 스크롤된다
|
||||||
|
- [ ] 안드로이드 뒤로 가기 → 시트만 닫힌다 (확인: 페이지가 뒤로 갈 수 있음)
|
||||||
|
|
||||||
|
## 15. 스켈레톤 · '?' · 실패
|
||||||
|
|
||||||
|
- [ ] 처음 열 때 각 화면·시트에 같은 틀의 회색 막대가 먼저 보이고, 데이터가 와도 덜컹이지 않는다
|
||||||
|
- [ ] 값이 없는 칸은 흐린 '?'(히어로 점수·기온, 날짜 칸 기온, 시간별 "?°", 주말 "비 ?%")
|
||||||
|
- [ ] 비행기 모드로 새로고침 → "정보를 불러오지 못했어요." + "다시 시도", 히어로 "앗, 날씨를 못 불러왔어요" / "점수를 못 불러왔어요"
|
||||||
|
- [ ] 비행기 모드 해제 후 "다시 시도" → "다시 불러오는 중…" 뒤 정상 표시
|
||||||
|
|
||||||
|
## 16. 모바일에서 특히 볼 것
|
||||||
|
|
||||||
|
- [ ] 글자를 길게 눌러도 선택·돋보기·복사 메뉴가 안 뜬다, 사진·링크 길게 눌러도 미리보기 메뉴 없음(아이폰)
|
||||||
|
- [ ] 입력칸(댓글·로그인·지역 검색·닉네임)은 글자 선택·붙여넣기가 되고, 눌러도 화면이 확대되지 않는다
|
||||||
|
- [ ] 두 번 탭해도 확대되지 않는다, 두 손가락 확대 (확인: iOS는 막히지 않을 수 있음)
|
||||||
|
- [ ] 아이폰 홈 막대가 하단 탭·댓글 입력줄을 가리지 않고, 좋아요 실패 알림은 하단 탭 위에 뜬다
|
||||||
|
- [ ] 가로 모드에서 노치가 상단 바·카드 왼쪽 끝을 가리는지 (확인)
|
||||||
|
- [ ] 어느 탭에서도 화면 전체가 옆으로 밀리지 않는다, 옆으로 미는 건 줄·슬라이드만
|
||||||
|
- [ ] 슬라이드를 밀 때 페이지 위아래 스크롤이 같이 튀지 않는다
|
||||||
|
- [ ] 작은 버튼이 잘 눌리는지: 포스트 하트·댓글·보내기, 댓글 하트, 시트 ×
|
||||||
|
- [ ] 댓글 입력칸을 누르면 키보드 위로 입력칸·게시 버튼이 보인다 (확인)
|
||||||
|
- [ ] 로그인 시트 비밀번호 칸·버튼, 지역 검색 목록이 키보드에 가려지지 않는다 (확인)
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
# 2026-10-08(목) 회의 — 날씨각
|
||||||
|
|
||||||
|
## 수정
|
||||||
|
- 전체 날씨 점수 기준 강화. 100점은 '1년에 하루 있을까' 수준으로만 (결정) — 각 점수만 낮췄고 총점은 그대로라 100점이 계속 나옴. 총점과 각 점수의 흐름도 맞아야 함 (`backend/services/index_service.py:203`)
|
||||||
|
- 각 점수를 아침·낮·저녁·밤 시간대별로 바뀌게 (결정) — 지금은 하루 중 가장 좋은 시간대 점수로 하루 고정이라 비가 와도 안 바뀜 (`backend/services/calc/index_calc.py:297`)
|
||||||
|
- 노을 순위 분포 넓히기 — 10위까지 4점 차로 몰림 (김성경 선임 진행 중)
|
||||||
|
- 히어로에 습도·불쾌지수 항상 표시 (결정) — 지금은 상황별로 두 칸을 골라 불쾌지수는 일정 수치 이상일 때만 나옴 (`frontend/src/b/TodayPage.tsx`, `HeroStat`)
|
||||||
|
- 달 '밝기 5%'가 밝기인지 보이는 면적인지 정의하고, 구름·달 모양을 반영한 산정 로직으로 (`backend/services/calc/moon.py`)
|
||||||
|
- 노을은 하늘 상황 문구 대신 점수 강조 + 골든아워·블루아워 설명 추가 — 10/7 다시 기획(점수 대신 상황 5가지)을 되돌림 (사용자 결정) (`frontend/src/b/SkyPage.tsx`)
|
||||||
|
- 주말 예보 UI 개선 (구체 내용 없음) (`frontend/src/b/WeekPage.tsx`)
|
||||||
|
|
||||||
|
## 검색 등록 (우선)
|
||||||
|
- 도메인은 지금처럼 별도 도메인 유지 (결정, Web4Ai 하위 경로 통합 안 함)
|
||||||
|
- AEO·SEO 메타데이터를 넣고 구글·네이버 검색 등록부터 진행 (결정, 금일 핵심 업무) — 지금은 발행만 되고 등록 안 됨
|
||||||
|
- 넣은 태그·키워드는 정의서로 정리 → 대표 보고
|
||||||
|
- 콘텐츠가 매시간 바뀌는 데 맞는 재발행·노출 방식 정리 → 대표 보고 (TODO의 SEO 빌드 방식 [결정 필요] 행과 이어짐)
|
||||||
|
- 사내 용어: '인덱싱' 대신 '검색 등록' (결정)
|
||||||
|
|
||||||
|
## 워치 앱 (양 팀장)
|
||||||
|
- 축제: 메인 1건을 크게, 주변 축제는 넘겨 보기
|
||||||
|
- 날씨각 데이터 연동용 앱 등록에 구글 개발자 본인 인증 필요 (대표 또는 소장)
|
||||||
|
|
||||||
|
## 담당·기한
|
||||||
|
| 할 일 | 담당 | 기한 | 보고 |
|
||||||
|
|---|---|---|---|
|
||||||
|
| 날씨 점수 기준 강화, 시간대별 각 점수 | 김성경·최미나 | 미정 | 대표 보고 |
|
||||||
|
| 히어로 습도·불쾌지수, 달 밝기 로직, 노을 점수·골든아워 설명 | 최미나 | 미정 | 대표 공유 |
|
||||||
|
| 메타데이터 정의서, 구글·네이버 검색 등록 | 최미나 | 미정 | 대표 보고 |
|
||||||
|
| 매시간 갱신 콘텐츠 검색 노출 방식 | 최미나 | 미정 | 대표 보고 |
|
||||||
|
|
||||||
|
## 날씨각 외 (이 저장소 밖)
|
||||||
|
- 스테이머뭄 중복 사이트 내리고 하나로 (최미나, 금일 핵심 업무)
|
||||||
|
- 에드오트 신버전 정식 배포·봇/사람 분리 통계 (김성경, 10/14), 일반 키워드 메타데이터·FAQ
|
||||||
|
- 동적 목표가 상승 편향 시뮬레이션 (양 팀장, 다음 주)
|
||||||
|
- 챗봇 품질 검증 에이전트 기획 (양 팀장·소장)
|
||||||
|
- Claude 크레딧 1만 달러 사용 계획 (6개월, 담당 미정)
|
||||||
+207
-57
@@ -8,47 +8,55 @@
|
|||||||
- 최종 점수 = 비중대로 섞은 점수 × (0.75 + 0.25 × 가장 낮은 요소 점수 ÷ 100). 비중 0%인 요소는 '가장 낮은 요소'에서 뺍니다. 가장 낮은 요소가 0점이면 25%가 깎입니다.
|
- 최종 점수 = 비중대로 섞은 점수 × (0.75 + 0.25 × 가장 낮은 요소 점수 ÷ 100). 비중 0%인 요소는 '가장 낮은 요소'에서 뺍니다. 가장 낮은 요소가 0점이면 25%가 깎입니다.
|
||||||
- '0점 조건'에 걸리면 0점, '최대 N점' 조건에 걸리면 N점을 넘지 못합니다.
|
- '0점 조건'에 걸리면 0점, '최대 N점' 조건에 걸리면 N점을 넘지 못합니다.
|
||||||
- 시간대가 여러 개면 그중 가장 좋은 시간대 점수를 씁니다.
|
- 시간대가 여러 개면 그중 가장 좋은 시간대 점수를 씁니다.
|
||||||
- 미세먼지는 모든 각이 같은 규칙입니다: 초미세먼지 15㎍/㎥ 이하 100점 → 75㎍/㎥ 이상 0점.
|
- 미세먼지는 초미세먼지 15㎍/㎥ 이하 100점 → 75㎍/㎥ 이상 0점입니다. 집콕각처럼 규칙을 따로 적은 각만 거꾸로(탁할수록 좋음) 셉니다.
|
||||||
- 바람·미세먼지·노을 정보가 없으면 70점으로 둡니다.
|
- 바람·미세먼지·노을 정보가 없으면 70점으로 둡니다.
|
||||||
|
- 순위는 점수 × 중요도 가중치(상 1.0 · 중 0.85 · 하 0.7)로 정합니다. 화면에 보이는 점수는 그대로입니다.
|
||||||
|
|
||||||
## 한눈에 보기
|
## 한눈에 보기
|
||||||
|
|
||||||
| 순서 | 각 | 코드 | 분류 | 시간대 | 기온 | 비 | 바람 | 습도 | 미세먼지 | 시간 | 재미 각 | 계절 핵심 |
|
| 순서 | 각 | 코드 | 분류 | 중요도 | 시간대 | 기온 | 비 | 바람 | 습도 | 미세먼지 | 시간 | 재미 각 | 계절 핵심 |
|
||||||
|---:|---|---|---|---|---:|---:|---:|---:|---:|---:|:---:|:---:|
|
|---:|---|---|---|:---:|---|---:|---:|---:|---:|---:|---:|:---:|:---:|
|
||||||
| 1 | 야장각 | `yajang` | 먹고 마시기 | 18~24시 | 30% | 25% | 15% | 10% | 10% | 10% | ○ | |
|
| 1 | 야장각 | `yajang` | 먹고 마시기 | 중 | 18~24시 | 30% | 25% | 15% | 10% | 10% | 10% | ○ | |
|
||||||
| 2 | 피크닉각 | `picnic` | 밖에서 놀기 | 11~16시 | 25% | 25% | 15% | 5% | 10% | 10% | | ○ |
|
| 2 | 피크닉각 | `picnic` | 밖에서 놀기 | 상 | 11~16시 | 25% | 25% | 15% | 5% | 10% | 10% | | ○ |
|
||||||
| 3 | 치맥각 | `chimaek` | 먹고 마시기 | 18~23시 | 30% | 20% | 15% | 15% | 10% | 10% | ○ | |
|
| 3 | 치맥각 | `chimaek` | 먹고 마시기 | 중 | 18~23시 | 30% | 20% | 15% | 15% | 10% | 10% | ○ | |
|
||||||
| 4 | 산책각 | `walk` | 밖에서 놀기 | 18~22시 | 30% | 25% | 15% | 10% | 15% | 5% | | |
|
| 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% | | |
|
| 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% | | ○ |
|
| 6 | 등산각 | `hiking` | 밖에서 놀기 | 상 | 7~12시 | 25% | 25% | 20% | 5% | 10% | 5% | | ○ |
|
||||||
| 7 | 세차각 | `carwash` | 집안일 | 9~18시 (비는 2일 뒤까지 봄) | 5% | 60% | 10% | 10% | 10% | 5% | | |
|
| 7 | 세차각 | `carwash` | 집안일 | 하 | 9~18시 (비는 2일 뒤까지 봄) | 5% | 60% | 10% | 10% | 10% | 5% | | |
|
||||||
| 8 | 캠핑각 | `camping` | 밖에서 놀기 | 18~다음 날 8시 | 30% | 25% | 15% | 15% | 10% | 5% | | ○ |
|
| 8 | 캠핑각 | `camping` | 밖에서 놀기 | 상 | 18~다음 날 8시 | 30% | 25% | 15% | 15% | 10% | 5% | | ○ |
|
||||||
| 9 | 러닝각 | `running` | 밖에서 놀기 | 6~8시 / 19~22시 | 35% | 20% | 10% | 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% | | ○ |
|
| 10 | 별보기각 | `stars` | 밖에서 놀기 | 중 | 21~다음 날 2시 | 5% | 10% | 5% | 5% | 15% | 45% | | ○ |
|
||||||
| 11 | 짬뽕각 | `jjamppong` | 먹고 마시기 | 11~14시 / 17~20시 | 40% | 25% | 15% | 10% | 5% | 5% | ○ | |
|
| 11 | 짬뽕각 | `jjamppong` | 먹고 마시기 | 하 | 11~14시 / 17~20시 | 40% | 25% | 15% | 10% | 5% | 5% | ○ | |
|
||||||
| 12 | 막걸리각 | `makgeolli` | 먹고 마시기 | 17~22시 | 15% | 50% | 10% | 15% | 5% | 5% | ○ | |
|
| 12 | 막걸리각 | `makgeolli` | 먹고 마시기 | 하 | 17~22시 | 15% | 50% | 10% | 15% | 5% | 5% | ○ | |
|
||||||
| 13 | 뜨아각 | `iced_hot` | 먹고 마시기 | 7~10시 | 50% | 10% | 15% | 10% | 5% | 10% | ○ | |
|
| 13 | 뜨아각 | `iced_hot` | 먹고 마시기 | 하 | 7~10시 | 50% | 10% | 15% | 10% | 5% | 10% | ○ | |
|
||||||
| 14 | 빨래각 | `laundry` | 집안일 | 9~16시 | 15% | 30% | 15% | 10% | 0% | 5% | | |
|
| 14 | 빨래각 | `laundry` | 집안일 | 상 | 9~16시 | 15% | 30% | 15% | 10% | 0% | 5% | | |
|
||||||
| 15 | 자전거각 | `bike` | 밖에서 놀기 | 9~19시 | 25% | 25% | 25% | 5% | 10% | 5% | | |
|
| 15 | 자전거각 | `bike` | 밖에서 놀기 | 상 | 9~19시 | 25% | 25% | 25% | 5% | 10% | 5% | | |
|
||||||
| 16 | 멍뭉산책각 | `dog` | 밖에서 놀기 | 7~9시 / 17~20시 | 35% | 25% | 10% | 5% | 15% | 5% | | |
|
| 16 | 멍뭉산책각 | `dog` | 밖에서 놀기 | 중 | 7~9시 / 17~20시 | 35% | 25% | 10% | 5% | 15% | 5% | | |
|
||||||
| 17 | 김서림각 | `glasses` | 생활 고민 | 7~9시 | 50% | 10% | 5% | 30% | 0% | 5% | | |
|
| 17 | 김서림각 | `glasses` | 생활 고민 | 중 | 7~9시 | 50% | 10% | 5% | 30% | 0% | 5% | | |
|
||||||
| 18 | 화장붕괴각 | `makeup` | 생활 고민 | 10~18시 | 40% | 10% | 10% | 35% | 0% | 5% | | |
|
| 18 | 화장붕괴각 | `makeup` | 생활 고민 | 중 | 10~18시 | 40% | 10% | 10% | 35% | 0% | 5% | | |
|
||||||
| 19 | 냉면각 | `naengmyeon` | 먹고 마시기 | 11~14시 | 55% | 15% | 5% | 15% | 5% | 5% | ○ | |
|
| 19 | 냉면각 | `naengmyeon` | 먹고 마시기 | 하 | 11~14시 | 55% | 15% | 5% | 15% | 5% | 5% | ○ | |
|
||||||
| 20 | 택시대란각 | `taxi` | 생활 고민 | 22~다음 날 2시 | 15% | 55% | 10% | 5% | 0% | 15% | | |
|
| 20 | 택시대란각 | `taxi` | 생활 고민 | 중 | 22~다음 날 2시 | 15% | 55% | 10% | 5% | 0% | 15% | | |
|
||||||
| 21 | 배달폭주각 | `delivery` | 생활 고민 | 17~21시 | 20% | 50% | 10% | 5% | 5% | 10% | | |
|
| 21 | 배달폭주각 | `delivery` | 생활 고민 | 중 | 17~21시 | 20% | 50% | 10% | 5% | 5% | 10% | | |
|
||||||
| 22 | 가드닝각 | `garden` | 집안일 | 7~10시 | 25% | 30% | 10% | 15% | 10% | 5% | | |
|
| 22 | 가드닝각 | `garden` | 집안일 | 하 | 7~10시 | 25% | 30% | 10% | 15% | 10% | 5% | | |
|
||||||
| 23 | 사진산책각 | `photo` | 밖에서 놀기 | 일몰 앞뒤 1시간 | 10% | 25% | 10% | 5% | 10% | 30% | | |
|
| 23 | 사진산책각 | `photo` | 밖에서 놀기 | 중 | 일몰 앞뒤 1시간 | 10% | 25% | 10% | 5% | 10% | 30% | | |
|
||||||
| 24 | 야구각 | `baseball` | 밖에서 놀기 | 18~22시 | 25% | 40% | 10% | 5% | 10% | 10% | ○ | |
|
| 24 | 야구각 | `baseball` | 밖에서 놀기 | 하 | 18~22시 | 25% | 40% | 10% | 5% | 10% | 10% | ○ | |
|
||||||
| 25 | 공부각 | `study` | 집안일 | 13~18시 | 35% | 35% | 10% | 5% | 5% | 10% | ○ | |
|
| 25 | 공부각 | `study` | 집안일 | 하 | 13~18시 | 35% | 35% | 10% | 5% | 5% | 10% | ○ | |
|
||||||
| 26 | 넷플릭스각 | `netflix` | 집안일 | 20~24시 | 30% | 35% | 15% | 5% | 0% | 15% | ○ | |
|
| 26 | 넷플릭스각 | `netflix` | 집안일 | 하 | 20~24시 | 30% | 35% | 15% | 5% | 0% | 15% | ○ | |
|
||||||
| 27 | 군밤각 | `chestnut` | 먹고 마시기 | 17~21시 | 55% | 25% | 10% | 0% | 5% | 5% | ○ | |
|
| 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`)
|
### 야장각 (`yajang`)
|
||||||
|
|
||||||
- 설명: 저녁 6시~자정, 바깥 자리에 앉기 좋은 정도
|
- 설명: 저녁 6시~자정, 바깥 자리에 앉기 좋은 정도
|
||||||
- 분류: 먹고 마시기 · 아이콘 `yajang` · 재미 각 예 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
- 분류: 먹고 마시기 · 중요도 중 · 아이콘 `yajang` · 재미 각 예 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
||||||
- 시간대: 18~24시
|
- 시간대: 18~24시
|
||||||
- 요소별 규칙 (비중):
|
- 요소별 규칙 (비중):
|
||||||
- 기온 30%: 체감 18~24°가 좋음
|
- 기온 30%: 체감 18~24°가 좋음
|
||||||
@@ -68,7 +76,7 @@
|
|||||||
### 피크닉각 (`picnic`)
|
### 피크닉각 (`picnic`)
|
||||||
|
|
||||||
- 설명: 낮 동안 돗자리 펴고 쉬기 좋은 정도
|
- 설명: 낮 동안 돗자리 펴고 쉬기 좋은 정도
|
||||||
- 분류: 밖에서 놀기 · 아이콘 `picnic` · 재미 각 아니오 · 계절 핵심 예 · 계산 근거 화면 있음
|
- 분류: 밖에서 놀기 · 중요도 상 · 아이콘 `picnic` · 재미 각 아니오 · 계절 핵심 예 · 계산 근거 화면 있음
|
||||||
- 시간대: 11~16시
|
- 시간대: 11~16시
|
||||||
- 요소별 규칙 (비중):
|
- 요소별 규칙 (비중):
|
||||||
- 기온 25%: 체감 20~26°가 좋음
|
- 기온 25%: 체감 20~26°가 좋음
|
||||||
@@ -89,7 +97,7 @@
|
|||||||
### 치맥각 (`chimaek`)
|
### 치맥각 (`chimaek`)
|
||||||
|
|
||||||
- 설명: 저녁에 바깥에서 치킨과 맥주가 당기는 정도
|
- 설명: 저녁에 바깥에서 치킨과 맥주가 당기는 정도
|
||||||
- 분류: 먹고 마시기 · 아이콘 `chimaek` · 재미 각 예 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
- 분류: 먹고 마시기 · 중요도 중 · 아이콘 `chimaek` · 재미 각 예 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
||||||
- 시간대: 18~23시
|
- 시간대: 18~23시
|
||||||
- 요소별 규칙 (비중):
|
- 요소별 규칙 (비중):
|
||||||
- 기온 30%: 체감 20~27°가 좋음
|
- 기온 30%: 체감 20~27°가 좋음
|
||||||
@@ -109,7 +117,7 @@
|
|||||||
### 산책각 (`walk`)
|
### 산책각 (`walk`)
|
||||||
|
|
||||||
- 설명: 걷기 좋은 정도 (해 진 뒤 기준)
|
- 설명: 걷기 좋은 정도 (해 진 뒤 기준)
|
||||||
- 분류: 밖에서 놀기 · 아이콘 `walk` · 재미 각 아니오 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
- 분류: 밖에서 놀기 · 중요도 상 · 아이콘 `walk` · 재미 각 아니오 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
||||||
- 시간대: 18~22시
|
- 시간대: 18~22시
|
||||||
- 요소별 규칙 (비중):
|
- 요소별 규칙 (비중):
|
||||||
- 기온 30%: 체감 15~23°가 좋음
|
- 기온 30%: 체감 15~23°가 좋음
|
||||||
@@ -129,7 +137,7 @@
|
|||||||
### 환기각 (`vent`)
|
### 환기각 (`vent`)
|
||||||
|
|
||||||
- 설명: 창문 열어 공기 바꾸기 좋은 정도
|
- 설명: 창문 열어 공기 바꾸기 좋은 정도
|
||||||
- 분류: 집안일 · 아이콘 `vent` · 재미 각 아니오 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
- 분류: 집안일 · 중요도 하 · 아이콘 `vent` · 재미 각 아니오 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
||||||
- 시간대: 10~12시 / 12~14시 / 14~16시 / 16~18시
|
- 시간대: 10~12시 / 12~14시 / 14~16시 / 16~18시
|
||||||
- 요소별 규칙 (비중):
|
- 요소별 규칙 (비중):
|
||||||
- 기온 10%: 체감 15~26°가 좋음
|
- 기온 10%: 체감 15~26°가 좋음
|
||||||
@@ -149,7 +157,7 @@
|
|||||||
### 등산각 (`hiking`)
|
### 등산각 (`hiking`)
|
||||||
|
|
||||||
- 설명: 산에 오르기 좋은 정도 (오전 기준)
|
- 설명: 산에 오르기 좋은 정도 (오전 기준)
|
||||||
- 분류: 밖에서 놀기 · 아이콘 `hiking` · 재미 각 아니오 · 계절 핵심 예 · 계산 근거 화면 있음
|
- 분류: 밖에서 놀기 · 중요도 상 · 아이콘 `hiking` · 재미 각 아니오 · 계절 핵심 예 · 계산 근거 화면 있음
|
||||||
- 시간대: 7~12시
|
- 시간대: 7~12시
|
||||||
- 요소별 규칙 (비중):
|
- 요소별 규칙 (비중):
|
||||||
- 기온 25%: 체감 10~20°가 좋음, 산 정상 보정 -6°
|
- 기온 25%: 체감 10~20°가 좋음, 산 정상 보정 -6°
|
||||||
@@ -171,7 +179,7 @@
|
|||||||
### 세차각 (`carwash`)
|
### 세차각 (`carwash`)
|
||||||
|
|
||||||
- 설명: 세차한 뒤 깨끗함이 오래가는 정도
|
- 설명: 세차한 뒤 깨끗함이 오래가는 정도
|
||||||
- 분류: 집안일 · 아이콘 `carwash` · 재미 각 아니오 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
- 분류: 집안일 · 중요도 하 · 아이콘 `carwash` · 재미 각 아니오 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
||||||
- 시간대: 9~18시 (비는 2일 뒤까지 봄)
|
- 시간대: 9~18시 (비는 2일 뒤까지 봄)
|
||||||
- 요소별 규칙 (비중):
|
- 요소별 규칙 (비중):
|
||||||
- 기온 5%: 체감 5~28°가 좋음
|
- 기온 5%: 체감 5~28°가 좋음
|
||||||
@@ -191,7 +199,7 @@
|
|||||||
### 캠핑각 (`camping`)
|
### 캠핑각 (`camping`)
|
||||||
|
|
||||||
- 설명: 하룻밤 캠핑하기 좋은 정도
|
- 설명: 하룻밤 캠핑하기 좋은 정도
|
||||||
- 분류: 밖에서 놀기 · 아이콘 `camping` · 재미 각 아니오 · 계절 핵심 예 · 계산 근거 화면 있음
|
- 분류: 밖에서 놀기 · 중요도 상 · 아이콘 `camping` · 재미 각 아니오 · 계절 핵심 예 · 계산 근거 화면 있음
|
||||||
- 시간대: 18~다음 날 8시
|
- 시간대: 18~다음 날 8시
|
||||||
- 요소별 규칙 (비중):
|
- 요소별 규칙 (비중):
|
||||||
- 기온 30%: 체감 12~22°가 좋음
|
- 기온 30%: 체감 12~22°가 좋음
|
||||||
@@ -211,7 +219,7 @@
|
|||||||
### 러닝각 (`running`)
|
### 러닝각 (`running`)
|
||||||
|
|
||||||
- 설명: 뛰기 좋은 정도 (아침·저녁 중 좋은 쪽)
|
- 설명: 뛰기 좋은 정도 (아침·저녁 중 좋은 쪽)
|
||||||
- 분류: 밖에서 놀기 · 아이콘 `running` · 재미 각 아니오 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
- 분류: 밖에서 놀기 · 중요도 상 · 아이콘 `running` · 재미 각 아니오 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
||||||
- 시간대: 6~8시 / 19~22시
|
- 시간대: 6~8시 / 19~22시
|
||||||
- 요소별 규칙 (비중):
|
- 요소별 규칙 (비중):
|
||||||
- 기온 35%: 체감 8~18°가 좋음
|
- 기온 35%: 체감 8~18°가 좋음
|
||||||
@@ -232,7 +240,7 @@
|
|||||||
### 별보기각 (`stars`)
|
### 별보기각 (`stars`)
|
||||||
|
|
||||||
- 설명: 밤하늘 별이 잘 보이는 정도
|
- 설명: 밤하늘 별이 잘 보이는 정도
|
||||||
- 분류: 밖에서 놀기 · 아이콘 `stars` · 재미 각 아니오 · 계절 핵심 예 · 계산 근거 화면 있음
|
- 분류: 밖에서 놀기 · 중요도 중 · 아이콘 `stars` · 재미 각 아니오 · 계절 핵심 예 · 계산 근거 화면 있음
|
||||||
- 시간대: 21~다음 날 2시
|
- 시간대: 21~다음 날 2시
|
||||||
- 요소별 규칙 (비중):
|
- 요소별 규칙 (비중):
|
||||||
- 기온 5%: 체감 5~25°가 좋음
|
- 기온 5%: 체감 5~25°가 좋음
|
||||||
@@ -253,7 +261,7 @@
|
|||||||
### 짬뽕각 (`jjamppong`)
|
### 짬뽕각 (`jjamppong`)
|
||||||
|
|
||||||
- 설명: 뜨끈한 국물이 당기는 정도
|
- 설명: 뜨끈한 국물이 당기는 정도
|
||||||
- 분류: 먹고 마시기 · 아이콘 `jjamppong` · 재미 각 예 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
- 분류: 먹고 마시기 · 중요도 하 · 아이콘 `jjamppong` · 재미 각 예 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
||||||
- 시간대: 11~14시 / 17~20시
|
- 시간대: 11~14시 / 17~20시
|
||||||
- 요소별 규칙 (비중):
|
- 요소별 규칙 (비중):
|
||||||
- 기온 40%: 추울수록 좋음 (25°=0점 → 5°=100점)
|
- 기온 40%: 추울수록 좋음 (25°=0점 → 5°=100점)
|
||||||
@@ -273,7 +281,7 @@
|
|||||||
### 막걸리각 (`makgeolli`)
|
### 막걸리각 (`makgeolli`)
|
||||||
|
|
||||||
- 설명: 비 오는 날 파전에 막걸리가 당기는 정도
|
- 설명: 비 오는 날 파전에 막걸리가 당기는 정도
|
||||||
- 분류: 먹고 마시기 · 아이콘 `makgeolli` · 재미 각 예 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
- 분류: 먹고 마시기 · 중요도 하 · 아이콘 `makgeolli` · 재미 각 예 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
||||||
- 시간대: 17~22시
|
- 시간대: 17~22시
|
||||||
- 요소별 규칙 (비중):
|
- 요소별 규칙 (비중):
|
||||||
- 기온 15%: 추울수록 좋음 (28°=0점 → 10°=100점)
|
- 기온 15%: 추울수록 좋음 (28°=0점 → 10°=100점)
|
||||||
@@ -293,7 +301,7 @@
|
|||||||
### 뜨아각 (`iced_hot`)
|
### 뜨아각 (`iced_hot`)
|
||||||
|
|
||||||
- 설명: 아이스 대신 따뜻한 커피로 바꿀 때가 된 정도
|
- 설명: 아이스 대신 따뜻한 커피로 바꿀 때가 된 정도
|
||||||
- 분류: 먹고 마시기 · 아이콘 `iced_hot` · 재미 각 예 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
- 분류: 먹고 마시기 · 중요도 하 · 아이콘 `iced_hot` · 재미 각 예 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
||||||
- 시간대: 7~10시
|
- 시간대: 7~10시
|
||||||
- 요소별 규칙 (비중):
|
- 요소별 규칙 (비중):
|
||||||
- 기온 50%: 추울수록 좋음 (22°=0점 → 8°=100점)
|
- 기온 50%: 추울수록 좋음 (22°=0점 → 8°=100점)
|
||||||
@@ -313,7 +321,7 @@
|
|||||||
### 빨래각 (`laundry`)
|
### 빨래각 (`laundry`)
|
||||||
|
|
||||||
- 설명: 빨래가 잘 마르는 정도
|
- 설명: 빨래가 잘 마르는 정도
|
||||||
- 분류: 집안일 · 아이콘 `laundry` · 재미 각 아니오 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
- 분류: 집안일 · 중요도 상 · 아이콘 `laundry` · 재미 각 아니오 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
||||||
- 시간대: 9~16시
|
- 시간대: 9~16시
|
||||||
- 요소별 규칙 (비중):
|
- 요소별 규칙 (비중):
|
||||||
- 기온 15%: 더울수록 좋음 (10°=0점 → 25°=100점)
|
- 기온 15%: 더울수록 좋음 (10°=0점 → 25°=100점)
|
||||||
@@ -334,7 +342,7 @@
|
|||||||
### 자전거각 (`bike`)
|
### 자전거각 (`bike`)
|
||||||
|
|
||||||
- 설명: 자전거 타기 좋은 정도
|
- 설명: 자전거 타기 좋은 정도
|
||||||
- 분류: 밖에서 놀기 · 아이콘 `bike` · 재미 각 아니오 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
- 분류: 밖에서 놀기 · 중요도 상 · 아이콘 `bike` · 재미 각 아니오 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
||||||
- 시간대: 9~19시
|
- 시간대: 9~19시
|
||||||
- 요소별 규칙 (비중):
|
- 요소별 규칙 (비중):
|
||||||
- 기온 25%: 체감 15~24°가 좋음
|
- 기온 25%: 체감 15~24°가 좋음
|
||||||
@@ -355,7 +363,7 @@
|
|||||||
### 멍뭉산책각 (`dog`)
|
### 멍뭉산책각 (`dog`)
|
||||||
|
|
||||||
- 설명: 반려견과 산책하기 좋은 정도
|
- 설명: 반려견과 산책하기 좋은 정도
|
||||||
- 분류: 밖에서 놀기 · 아이콘 `dog` · 재미 각 아니오 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
- 분류: 밖에서 놀기 · 중요도 중 · 아이콘 `dog` · 재미 각 아니오 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
||||||
- 시간대: 7~9시 / 17~20시
|
- 시간대: 7~9시 / 17~20시
|
||||||
- 요소별 규칙 (비중):
|
- 요소별 규칙 (비중):
|
||||||
- 기온 35%: 체감 5~22°가 좋음
|
- 기온 35%: 체감 5~22°가 좋음
|
||||||
@@ -376,7 +384,7 @@
|
|||||||
### 김서림각 (`glasses`)
|
### 김서림각 (`glasses`)
|
||||||
|
|
||||||
- 설명: 안경에 김이 서리기 쉬운 정도
|
- 설명: 안경에 김이 서리기 쉬운 정도
|
||||||
- 분류: 생활 고민 · 아이콘 `glasses` · 재미 각 아니오 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
- 분류: 생활 고민 · 중요도 중 · 아이콘 `glasses` · 재미 각 아니오 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
||||||
- 시간대: 7~9시
|
- 시간대: 7~9시
|
||||||
- 요소별 규칙 (비중):
|
- 요소별 규칙 (비중):
|
||||||
- 기온 50%: 추울수록 좋음 (15°=0점 → -5°=100점)
|
- 기온 50%: 추울수록 좋음 (15°=0점 → -5°=100점)
|
||||||
@@ -396,7 +404,7 @@
|
|||||||
### 화장붕괴각 (`makeup`)
|
### 화장붕괴각 (`makeup`)
|
||||||
|
|
||||||
- 설명: 화장이 무너지기 쉬운 정도
|
- 설명: 화장이 무너지기 쉬운 정도
|
||||||
- 분류: 생활 고민 · 아이콘 `makeup` · 재미 각 아니오 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
- 분류: 생활 고민 · 중요도 중 · 아이콘 `makeup` · 재미 각 아니오 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
||||||
- 시간대: 10~18시
|
- 시간대: 10~18시
|
||||||
- 요소별 규칙 (비중):
|
- 요소별 규칙 (비중):
|
||||||
- 기온 40%: 더울수록 좋음 (20°=0점 → 32°=100점)
|
- 기온 40%: 더울수록 좋음 (20°=0점 → 32°=100점)
|
||||||
@@ -416,7 +424,7 @@
|
|||||||
### 냉면각 (`naengmyeon`)
|
### 냉면각 (`naengmyeon`)
|
||||||
|
|
||||||
- 설명: 시원한 냉면이 당기는 정도
|
- 설명: 시원한 냉면이 당기는 정도
|
||||||
- 분류: 먹고 마시기 · 아이콘 `naengmyeon` · 재미 각 예 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
- 분류: 먹고 마시기 · 중요도 하 · 아이콘 `naengmyeon` · 재미 각 예 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
||||||
- 시간대: 11~14시
|
- 시간대: 11~14시
|
||||||
- 요소별 규칙 (비중):
|
- 요소별 규칙 (비중):
|
||||||
- 기온 55%: 더울수록 좋음 (18°=0점 → 32°=100점)
|
- 기온 55%: 더울수록 좋음 (18°=0점 → 32°=100점)
|
||||||
@@ -436,7 +444,7 @@
|
|||||||
### 택시대란각 (`taxi`)
|
### 택시대란각 (`taxi`)
|
||||||
|
|
||||||
- 설명: 밤늦게 택시 잡기 어려운 정도
|
- 설명: 밤늦게 택시 잡기 어려운 정도
|
||||||
- 분류: 생활 고민 · 아이콘 `taxi` · 재미 각 아니오 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
- 분류: 생활 고민 · 중요도 중 · 아이콘 `taxi` · 재미 각 아니오 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
||||||
- 시간대: 22~다음 날 2시
|
- 시간대: 22~다음 날 2시
|
||||||
- 요소별 규칙 (비중):
|
- 요소별 규칙 (비중):
|
||||||
- 기온 15%: 추울수록 좋음 (15°=0점 → -5°=100점)
|
- 기온 15%: 추울수록 좋음 (15°=0점 → -5°=100점)
|
||||||
@@ -456,7 +464,7 @@
|
|||||||
### 배달폭주각 (`delivery`)
|
### 배달폭주각 (`delivery`)
|
||||||
|
|
||||||
- 설명: 배달 주문이 몰리는 정도
|
- 설명: 배달 주문이 몰리는 정도
|
||||||
- 분류: 생활 고민 · 아이콘 `delivery` · 재미 각 아니오 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
- 분류: 생활 고민 · 중요도 중 · 아이콘 `delivery` · 재미 각 아니오 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
||||||
- 시간대: 17~21시
|
- 시간대: 17~21시
|
||||||
- 요소별 규칙 (비중):
|
- 요소별 규칙 (비중):
|
||||||
- 기온 20%: 추울수록 좋음 (22°=0점 → 0°=100점)
|
- 기온 20%: 추울수록 좋음 (22°=0점 → 0°=100점)
|
||||||
@@ -476,7 +484,7 @@
|
|||||||
### 가드닝각 (`garden`)
|
### 가드닝각 (`garden`)
|
||||||
|
|
||||||
- 설명: 화분 돌보고 물 주기 좋은 정도
|
- 설명: 화분 돌보고 물 주기 좋은 정도
|
||||||
- 분류: 집안일 · 아이콘 `garden` · 재미 각 아니오 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
- 분류: 집안일 · 중요도 하 · 아이콘 `garden` · 재미 각 아니오 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
||||||
- 시간대: 7~10시
|
- 시간대: 7~10시
|
||||||
- 요소별 규칙 (비중):
|
- 요소별 규칙 (비중):
|
||||||
- 기온 25%: 체감 12~25°가 좋음
|
- 기온 25%: 체감 12~25°가 좋음
|
||||||
@@ -497,7 +505,7 @@
|
|||||||
### 사진산책각 (`photo`)
|
### 사진산책각 (`photo`)
|
||||||
|
|
||||||
- 설명: 노을 무렵 사진 찍으며 걷기 좋은 정도
|
- 설명: 노을 무렵 사진 찍으며 걷기 좋은 정도
|
||||||
- 분류: 밖에서 놀기 · 아이콘 `photo` · 재미 각 아니오 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
- 분류: 밖에서 놀기 · 중요도 중 · 아이콘 `photo` · 재미 각 아니오 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
||||||
- 시간대: 일몰 앞뒤 1시간
|
- 시간대: 일몰 앞뒤 1시간
|
||||||
- 요소별 규칙 (비중):
|
- 요소별 규칙 (비중):
|
||||||
- 기온 10%: 체감 10~26°가 좋음
|
- 기온 10%: 체감 10~26°가 좋음
|
||||||
@@ -518,7 +526,7 @@
|
|||||||
### 야구각 (`baseball`)
|
### 야구각 (`baseball`)
|
||||||
|
|
||||||
- 설명: 저녁 6~10시, 야구장 직관하기 좋은 정도
|
- 설명: 저녁 6~10시, 야구장 직관하기 좋은 정도
|
||||||
- 분류: 밖에서 놀기 · 아이콘 `baseball` · 재미 각 예 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
- 분류: 밖에서 놀기 · 중요도 하 · 아이콘 `baseball` · 재미 각 예 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
||||||
- 시간대: 18~22시
|
- 시간대: 18~22시
|
||||||
- 요소별 규칙 (비중):
|
- 요소별 규칙 (비중):
|
||||||
- 기온 25%: 체감 15~25°가 좋음
|
- 기온 25%: 체감 15~25°가 좋음
|
||||||
@@ -538,7 +546,7 @@
|
|||||||
### 공부각 (`study`)
|
### 공부각 (`study`)
|
||||||
|
|
||||||
- 설명: 오후 1~6시, 밖에 나가기 싫어서 공부가 잘되는 정도
|
- 설명: 오후 1~6시, 밖에 나가기 싫어서 공부가 잘되는 정도
|
||||||
- 분류: 집안일 · 아이콘 `study` · 재미 각 예 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
- 분류: 집안일 · 중요도 하 · 아이콘 `study` · 재미 각 예 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
||||||
- 시간대: 13~18시
|
- 시간대: 13~18시
|
||||||
- 요소별 규칙 (비중):
|
- 요소별 규칙 (비중):
|
||||||
- 기온 35%: 체감이 15~24°에서 멀수록(덥거나 추울수록) 좋음
|
- 기온 35%: 체감이 15~24°에서 멀수록(덥거나 추울수록) 좋음
|
||||||
@@ -558,7 +566,7 @@
|
|||||||
### 넷플릭스각 (`netflix`)
|
### 넷플릭스각 (`netflix`)
|
||||||
|
|
||||||
- 설명: 밤 8시~자정, 집에서 영화 보기 좋은 정도
|
- 설명: 밤 8시~자정, 집에서 영화 보기 좋은 정도
|
||||||
- 분류: 집안일 · 아이콘 `netflix` · 재미 각 예 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
- 분류: 집안일 · 중요도 하 · 아이콘 `netflix` · 재미 각 예 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
||||||
- 시간대: 20~24시
|
- 시간대: 20~24시
|
||||||
- 요소별 규칙 (비중):
|
- 요소별 규칙 (비중):
|
||||||
- 기온 30%: 추울수록 좋음 (22°=0점 → 0°=100점)
|
- 기온 30%: 추울수록 좋음 (22°=0점 → 0°=100점)
|
||||||
@@ -578,7 +586,7 @@
|
|||||||
### 군밤각 (`chestnut`)
|
### 군밤각 (`chestnut`)
|
||||||
|
|
||||||
- 설명: 저녁 5~9시, 길거리 군밤이 당기는 정도
|
- 설명: 저녁 5~9시, 길거리 군밤이 당기는 정도
|
||||||
- 분류: 먹고 마시기 · 아이콘 `chestnut` · 재미 각 예 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
- 분류: 먹고 마시기 · 중요도 하 · 아이콘 `chestnut` · 재미 각 예 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
||||||
- 시간대: 17~21시
|
- 시간대: 17~21시
|
||||||
- 요소별 규칙 (비중):
|
- 요소별 규칙 (비중):
|
||||||
- 기온 55%: 추울수록 좋음 (18°=0점 → 0°=100점)
|
- 기온 55%: 추울수록 좋음 (18°=0점 → 0°=100점)
|
||||||
@@ -595,3 +603,145 @@
|
|||||||
- 60~79점: 손이 시려요. 따끈한 군밤 한 봉지!
|
- 60~79점: 손이 시려요. 따끈한 군밤 한 봉지!
|
||||||
- 80~100점: 영하 가까운 저녁, 군밤 품고 걷는 날 🌰
|
- 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,424 @@
|
|||||||
|
# 날씨각 서비스 동작 안내
|
||||||
|
|
||||||
|
날씨 정보를 언제 가져오는지, 점수를 어떻게 매기는지, 피드가 어떻게 만들어지는지 정리한 문서입니다. 개발자가 아닌 분이 확인하실 수 있도록 썼습니다.
|
||||||
|
|
||||||
|
- 기준: 2026년 10월 12일 코드 (10/8 회의 반영분 포함, 아직 배포 전)
|
||||||
|
- 개발자용 원본: 점수 계산식은 `docs/점수_계산식.md`, 각별 설정은 `docs/각_계산기준.md`, 피드는 `docs/피드_동작방식.md`
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. 날씨 정보는 언제 가져오나
|
||||||
|
|
||||||
|
정보는 두 가지 방식으로 가져옵니다.
|
||||||
|
|
||||||
|
- **정해진 시각에 미리 받기:** 서버가 시계를 보고 전국 정보를 한꺼번에 받습니다.
|
||||||
|
- **누가 열 때 받기:** 사용자가 어떤 구를 열었는데 가진 정보가 오래됐으면 그때 받습니다. 아무도 열지 않는 구는 받지 않습니다.
|
||||||
|
|
||||||
|
### 1-1. 정해진 시각에 미리 받는 것
|
||||||
|
|
||||||
|
| 시각 | 하는 일 |
|
||||||
|
|---|---|
|
||||||
|
| 매일 03:00 | 그날 피드의 틀(칸 19개)을 만들고 저장해 둔 피드를 모두 비웁니다. 7일 지난 날씨 기록도 지우고, 미세먼지 측정소 목록을 새로 받습니다. |
|
||||||
|
| 매일 03:10 · 09:10 · 15:10 · 21:10 | 해외 날씨 서비스(Open-Meteo)에서 전국의 자외선, 가시거리(얼마나 멀리 보이는지), 돌풍, 햇빛 든 시간을 받습니다. |
|
||||||
|
| 매일 06:40 · 18:40 | 주말 나들이 점수(주말 전국 순위, 당일치기)를 미리 계산합니다. 기상청 단기·중기예보가 모두 나온 뒤입니다. |
|
||||||
|
| 매주 월요일 04:00 | 전국 축제·전시·콘서트·팝업 정보를 받고, 끝나면 Teams로 알립니다. |
|
||||||
|
|
||||||
|
### 1-2. 누가 열 때 받는 것
|
||||||
|
|
||||||
|
| 정보 | 어디서 | 새 정보가 나오는 때 | 받는 때 |
|
||||||
|
|---|---|---|---|
|
||||||
|
| 단기예보 (오늘~모레, 시간별 기온·비·바람·습도·하늘) | 기상청 | 하루 8번: 02·05·08·11·14·17·20·23시 발표, 10분 뒤부터 받을 수 있음 | 가진 예보보다 새 발표가 있으면 |
|
||||||
|
| 중기예보 (3~10일 뒤, 하루 단위) | 기상청 | 하루 2번: 06·18시 발표 | 발표 30분 뒤부터, 아직 안 받았으면 |
|
||||||
|
| 초단기예보 (앞으로 6시간 비) | 기상청 | 매시 30분 발표, 45분부터 받을 수 있음 | 새 발표가 있으면 |
|
||||||
|
| 미세먼지 | 에어코리아 | 매시 측정, 20분쯤 뒤에 나옴 | 이번 시각 측정값이 없으면 전국을 한 번에 |
|
||||||
|
| 기상특보 | 기상청 | 수시 | 1시간에 한 번 |
|
||||||
|
| 노을·일출 구름 | Open-Meteo | 수시 | 하루 3번: 오전, 13시 이후, 21시 이후 |
|
||||||
|
| 해·달 뜨고 지는 시각 | 받지 않고 서버가 계산 | 날짜와 위치로 정해짐 | 처음 필요할 때 한 번 |
|
||||||
|
|
||||||
|
- 외부 서비스가 응답하지 않으면 8초까지만 기다린 뒤, 가지고 있던 정보로 화면을 보여 줍니다.
|
||||||
|
- 예보와 점수 기록은 7일, 구름 기록은 2일, 끝난 행사는 30일 뒤에 지웁니다.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. 점수는 어떻게 매기나
|
||||||
|
|
||||||
|
이 장은 점수를 내는 식을 모두 적습니다. 식 옆에 쉬운 설명과 실제 숫자 예시를 붙였습니다.
|
||||||
|
|
||||||
|
### 2-1. 재료: 어떤 값을 쓰나
|
||||||
|
|
||||||
|
| 값 | 어디서 | 단위 |
|
||||||
|
|---|---|---|
|
||||||
|
| 기온, 습도, 바람, 비 올 확률, 비 형태(없음·비·눈), 하늘(맑음·구름많음·흐림) | 기상청 단기예보 | 1시간마다 |
|
||||||
|
| 체감온도 | 위 기온·습도·바람으로 서버가 계산 (2-11) | 1시간마다 |
|
||||||
|
| 초미세먼지 | 에어코리아, 구에서 가장 가까운 측정소의 **지금 측정값** | 하나 |
|
||||||
|
| 햇빛 든 비율 | Open-Meteo, 3시간 동안 해가 난 시간 ÷ 3시간. **해가 진 구간은 0** | 3시간마다 |
|
||||||
|
| 자외선, 가시거리, 돌풍, 땅 표면 온도 | Open-Meteo | 3시간마다 |
|
||||||
|
| 노을 점수, 달 모양 | 서버가 계산 (2-9, 2-10) | 하루에 하나 |
|
||||||
|
|
||||||
|
### 2-2. 계산 순서 (지금 날씨 점수, 각 점수, 나들이 점수 공통)
|
||||||
|
|
||||||
|
1. **시간 고르기:** 점수를 낼 시간들을 고릅니다. 예: 저녁 구간이면 16~19시.
|
||||||
|
2. **대표값 하나로 묶기:** 고른 시간들의 값을 요소마다 하나로 묶습니다. 묶는 법은 아래 표와 같습니다.
|
||||||
|
3. **요소 점수 매기기:** 대표값마다 0~100점을 매깁니다 (2-3).
|
||||||
|
4. **섞고 깎기:** 비중대로 섞은 뒤 가장 나쁜 요소만큼 깎습니다 (2-4).
|
||||||
|
5. **조건 적용:** "비 확률 70% 이상이면 0점" 같은 조건이 있으면 적용합니다 (2-4).
|
||||||
|
6. **시간대가 여러 개면** (예: 러닝각 6~8시와 19~22시) 각각 계산해 더 높은 쪽을 씁니다.
|
||||||
|
|
||||||
|
| 요소 | 묶는 법 | 이유 |
|
||||||
|
|---|---|---|
|
||||||
|
| 체감온도, 습도, 햇빛 든 비율 | 평균 | 그 시간 동안 대체로 어떤지 |
|
||||||
|
| 비 올 확률 | 가장 높은 값 | 한 번이라도 비 올 수 있으면 곤란 |
|
||||||
|
| 비 소식 | 한 시간이라도 있으면 "비 옴" | |
|
||||||
|
| 바람, 자외선, 돌풍 | 가장 센 값 | 가장 나쁜 순간 기준 |
|
||||||
|
| 가시거리 | 가장 짧은 값 | |
|
||||||
|
| 초미세먼지 | 지금 측정값 그대로 | 예보가 없음 |
|
||||||
|
|
||||||
|
### 2-3. 요소 점수 식
|
||||||
|
|
||||||
|
**내려가는 곡선.** 거의 모든 요소가 이 곡선 하나로 점수를 깎습니다. 만점 근처에서는 천천히, 멀어질수록 빠르게 내려갑니다.
|
||||||
|
|
||||||
|
> 곡선(t) = (e^(−t²/2) − e^(−1/2)) ÷ (1 − e^(−1/2))
|
||||||
|
> t는 "만점 지점에서 0점 지점까지 얼마나 갔나"(0~1)입니다.
|
||||||
|
|
||||||
|
| t | 0 | 0.25 | 0.5 | 0.75 | 1 |
|
||||||
|
|---|---:|---:|---:|---:|---:|
|
||||||
|
| 곡선(t) | 1.00 | 0.92 | 0.70 | 0.38 | 0 |
|
||||||
|
|
||||||
|
**요소 점수를 매기는 방식은 아래 다섯 가지입니다.**
|
||||||
|
|
||||||
|
| 방식 | 식 | 쓰는 곳 |
|
||||||
|
|---|---|---|
|
||||||
|
| ① 편한 범위 | 범위 안: 최적값 ± 만점폭은 100점. 그 밖은 범위 끝으로 갈수록 85점까지 곡선으로 내려감. 범위 밖: 85점에서 곡선으로 0점까지 | 기온, 습도 |
|
||||||
|
| ② 한쪽으로 | 100 × 곡선((값 − 만점 지점) ÷ (0점 지점 − 만점 지점)) | 비 확률, 미세먼지, 햇빛, 자외선, 가시거리, 덥거나 추울수록 좋은 기온 |
|
||||||
|
| ③ 잔잔할수록 | '괜찮은 바람'의 절반 이하는 100점, 괜찮은 바람까지 85점으로 곧게, 그 뒤 '한계 바람'에서 0점까지 곡선 | 바람 |
|
||||||
|
| ④ 고정값 | 정해진 점수 | 상관없는 요소(50점), 정보 없음(70점) |
|
||||||
|
| ⑤ 각 전용 | 요일, 달, 노을 점수 | 각의 '시간' 요소 (2-7) |
|
||||||
|
|
||||||
|
① 편한 범위의 자세한 식:
|
||||||
|
- 만점폭 = min(정해진 만점폭, 최적값에서 범위 끝까지 거리 ÷ 3). 범위가 좁아도 끝에서 갑자기 떨어지지 않게 하려는 것입니다.
|
||||||
|
- 범위 안에서 만점폭 밖이면: 85 + 15 × 곡선(최적값에서 벗어난 만큼 ÷ 범위 끝까지 남은 거리)
|
||||||
|
- 범위 밖이면: 85 × 곡선(범위에서 벗어난 만큼 × 기울기 ÷ 85). 기울기는 기온 8, 습도 2입니다. 그래서 **기온은 범위 밖으로 약 10.6°, 습도는 약 42.5% 벗어나면 0점**입니다.
|
||||||
|
|
||||||
|
**요소별 기준과 실제 점수 (지금 날씨 점수 기준)**
|
||||||
|
|
||||||
|
| 요소 | 기준 | 값 → 점수 |
|
||||||
|
|---|---|---|
|
||||||
|
| 체감온도 | ① 편한 범위 18~24°, 최적 21°, 만점폭 0.5° | 21°→100 · 22°→99 · 23°→94 · 24°→85 · 25°→84 · 27°→77 · 30°→53 · 34°→8 |
|
||||||
|
| 비 | 비 소식이 있으면 0점. 없으면 ② 확률 0%가 100점, 100%가 0점 | 0%→100 · 20%→95 · 30%→89 · 50%→70 · 70%→45 · 100%→0 |
|
||||||
|
| 바람 | ③ 괜찮은 바람 초속 2m, 한계 10m | 1m→100 · 1.5m→92 · 2m→85 · 3m→83 · 4m→78 · 6m→60 · 8m→32 · 10m→0 |
|
||||||
|
| 습도 | ① 편한 범위 40~60%, 최적 50%, 만점폭 5% | 50%→100 · 55%→99 · 58%→92 · 60%→85 · 70%→79 · 80%→62 · 90%→37 |
|
||||||
|
| 초미세먼지 | ② 10㎍/㎥가 100점, 75가 0점 | 10→100 · 15→99 · 25→93 · 35→82 · 50→56 · 75→0 |
|
||||||
|
| 햇빛 든 비율 | ② 90%가 100점, 20%가 0점 | 90%→100 · 70%→90 · 50%→62 · 30%→22 · 20% 이하→0 |
|
||||||
|
|
||||||
|
**각마다 다르게 쓰는 방식**
|
||||||
|
|
||||||
|
| 요소 | 방식 | 식 |
|
||||||
|
|---|---|---|
|
||||||
|
| 기온 | 편한 범위 (21개) | 위 ① |
|
||||||
|
| 기온 | 추울수록 (짬뽕각·군밤각 등 8개) | ② 각마다 정한 0점 지점과 만점 지점. 예: 군밤각은 18°에서 0점, 0°에서 100점 |
|
||||||
|
| 기온 | 더울수록 (빨래각·화장붕괴각·냉면각) | ② 예: 냉면각은 18°에서 0점, 32°에서 100점 |
|
||||||
|
| 기온 | 범위에서 멀수록 (공부각·집콕각) | 30 + 7 × 범위에서 벗어난 도(°) |
|
||||||
|
| 비 | 비 안 와야 좋음 (24개) | 위 표의 '비' |
|
||||||
|
| 비 | 비 와야 좋음 (10개) | 비 소식이 있으면 100점. 없으면 ② 확률 0%가 0점, 100%가 100점 |
|
||||||
|
| 바람 | 잔잔할수록 (20개) | ③ 각마다 괜찮은 바람·한계 바람이 다름 |
|
||||||
|
| 바람 | 적당히 (환기각·빨래각·연날리기각) | 초속 2~5m는 100점. 2m 미만은 60 + 20 × 바람, 5m 넘으면 12m에서 0점까지 곡선 |
|
||||||
|
| 바람 | 셀수록 (짬뽕각 등 10개) | ② 0m가 0점, 8m가 100점 |
|
||||||
|
| 바람 | 상관없음 (김서림각) | 50점 |
|
||||||
|
| 습도 | 편한 범위 (13개) | 위 ① |
|
||||||
|
| 습도 | 높을수록 (8개) | ② 40%가 0점, 90%가 100점 |
|
||||||
|
| 습도 | 낮을수록 (5개) | ② 90%가 0점, 40%가 100점 |
|
||||||
|
| 습도 | 상관없음 (8개) | 50점 |
|
||||||
|
| 미세먼지 | 맑을수록 (기본) | ② 15㎍/㎥가 100점, 75가 0점 |
|
||||||
|
| 미세먼지 | 탁할수록 (집콕각) | ② 75가 100점, 15가 0점 |
|
||||||
|
|
||||||
|
### 2-4. 섞고 깎는 식
|
||||||
|
|
||||||
|
> **섞은 점수** = (요소1 점수 × 비중1 + 요소2 점수 × 비중2 + …) ÷ 100
|
||||||
|
> **최종 점수** = 섞은 점수 × (0.75 + 0.25 × 가장 낮은 요소 점수 ÷ 100), 반올림
|
||||||
|
|
||||||
|
- 비중이 0%인 요소는 '가장 낮은 요소'를 고를 때 뺍니다.
|
||||||
|
- 가장 낮은 요소가 0점이면 25%, 50점이면 12.5%가 깎입니다. 100점은 비중이 있는 요소가 모두 100점일 때만 나옵니다.
|
||||||
|
|
||||||
|
**예시: 저녁 구간 지금 날씨 점수**
|
||||||
|
- 재료: 체감 23°, 비 확률 20%(비 소식 없음), 바람 초속 3m, 습도 65%, 초미세먼지 20, 햇빛 든 비율 60%
|
||||||
|
- 요소 점수: 체감 94, 비 95, 바람 83, 습도 84, 미세먼지 97, 햇빛 78
|
||||||
|
- 섞은 점수 = (94×30 + 95×25 + 83×10 + 84×10 + 97×10 + 78×15) ÷ 100 = 90.05
|
||||||
|
- 가장 낮은 요소 = 햇빛 78 → 최종 = 90.05 × (0.75 + 0.25 × 0.78) = 90.05 × 0.945 = **85점**
|
||||||
|
|
||||||
|
**조건 (0점·최대 N점)**
|
||||||
|
- 각마다 "이 조건이면 0점" 또는 "이 조건이면 최대 N점"이 있습니다. 위 식으로 낸 점수와 상한 중 작은 값을 씁니다.
|
||||||
|
- 조건에 쓰는 값과 쓰는 각 수: 비 올 확률 18, 바람 6, 체감온도 5(구간 안 최저 또는 최고), 초미세먼지 3, 강풍 특보 3, 돌풍 3, 흐린 하늘 비율 1, 땅 표면 온도 1. 조건이 있는 각은 34개 중 22개입니다.
|
||||||
|
- 각별 조건은 `docs/각_계산기준.md`에 있습니다.
|
||||||
|
|
||||||
|
### 2-5. 하루를 네 구간으로 나눕니다
|
||||||
|
|
||||||
|
점수와 피드 순서는 모두 아래 네 구간을 기준으로 합니다. 해 지는 시각은 지역과 날짜마다 다르기 때문에 구간 경계도 매일 달라집니다.
|
||||||
|
|
||||||
|
| 구간 | 시각 | 예: 분당구 10/12 (해 짐 18:00) |
|
||||||
|
|---|---|---|
|
||||||
|
| 아침 | 05~11시 | 05:00~11:00 |
|
||||||
|
| 낮 | 11시 ~ 해 지기 2시간 전 | 11:00~16:00 |
|
||||||
|
| 저녁 | 해 지기 2시간 전 ~ 해 지고 1시간 뒤 | 16:00~19:00 |
|
||||||
|
| 밤 | 해 지고 1시간 뒤 ~ 다음 날 05시 | 19:00~05:00 |
|
||||||
|
|
||||||
|
- 한 시간은 그 시간의 한가운데(30분)가 속한 구간에 넣습니다. 예: 해 짐이 18:20이면 16시대(16:30)는 저녁입니다.
|
||||||
|
- 0~5시는 전날 밤 구간으로 봅니다.
|
||||||
|
|
||||||
|
### 2-6. 지금 날씨 점수 (오늘 탭 맨 위 큰 숫자)
|
||||||
|
|
||||||
|
- **지금 구간의 시간들**만으로 2-2~2-4 순서대로 계산합니다. 아침·낮·저녁·밤 모두 같은 식이고, 들어가는 시간만 다릅니다.
|
||||||
|
- 요소와 비중: 체감온도 30%, 비 25%, 햇빛 든 비율 15%, 바람 10%, 습도 10%, 초미세먼지 10%. 조건(0점·최대 N점)은 없습니다.
|
||||||
|
- **밤에는 최대 64점입니다.** 해가 진 구간은 햇빛 든 비율이 0이라 햇빛 점수가 0점입니다. 다른 다섯 요소가 모두 100점이어도 85 × 0.75 = 64점입니다. 저녁 구간도 해 진 뒤 시간이 섞여 낮보다 낮게 나옵니다.
|
||||||
|
- 초미세먼지는 지금 측정값이라, 어느 구간이든 지금 공기 상태가 들어갑니다.
|
||||||
|
- 기준값은 경험으로 잡은 것이고, 1년에 100점이 며칠 나오는지는 아직 확인하지 않았습니다.
|
||||||
|
|
||||||
|
### 2-7. 각 점수 (오늘의 각 34개)
|
||||||
|
|
||||||
|
- **식은 2-2~2-4와 같습니다.** 각마다 요소별 비중, 방식(2-3), 조건, 하기 좋은 시간대가 다릅니다. 34개 각의 시간대와 주요 비중은 [부록](#부록-각-34개-한눈에-보기)에 있습니다.
|
||||||
|
- **오늘 점수 = 지금 구간 점수.** 각의 시간대 중 지금 구간에 드는 시간만 골라 계산합니다. 예: 오후 5시(저녁 구간)의 야장각(18~24시)은 18시대만 봅니다.
|
||||||
|
- 각의 시간대가 지금 구간과 겹치지 않으면(예: 아침의 야장각) 순위, 피드 카드, 맨 위 1위에서 빠집니다. 각 탭 전체 목록에는 맨 뒤에 '지금 아님'으로, 하루 점수와 함께 남습니다.
|
||||||
|
- **하루 점수**(내일·토·일 칸, '지금 아님' 각): 각의 시간대 전체로 계산한 점수입니다.
|
||||||
|
- **햇빛·자외선·가시거리:** 10개 각(피크닉, 등산, 세차, 별보기, 빨래, 자전거, 가드닝, 사진산책, 드라이브, 물놀이)은 이 요소도 봅니다. 모두 2-3의 ② 방식입니다.
|
||||||
|
- **'시간' 요소**는 날씨가 아닌 것을 넣는 칸입니다.
|
||||||
|
|
||||||
|
| 종류 | 식 | 쓰는 각 |
|
||||||
|
|---|---|---|
|
||||||
|
| 요일 | 요일·공휴일마다 정한 점수 | 19개 |
|
||||||
|
| 고정 | 정한 점수 하나 | 13개 |
|
||||||
|
| 달 | 20 + 80 × (1 − 달이 비추는 정도). 달이 비추는 정도 = 달의 빛나는 면 × 21~26시 중 달이 떠 있는 비율 | 별보기각 |
|
||||||
|
| 노을 | 그날 노을 점수 (2-9) | 사진산책각 |
|
||||||
|
|
||||||
|
- **며칠 뒤 비까지 보는 각:** 세차각은 비 올 확률을 2일 뒤까지 보고, 그중 가장 높은 값을 씁니다.
|
||||||
|
- **순위** = 점수 × 중요도(상 1.0 · 중 0.85 · 하 0.7). 화면에 보이는 숫자는 곱하기 전 점수입니다.
|
||||||
|
- **먼 날의 예상 점수:** 단기예보가 닿지 않는 날(주말 등)은 중기예보의 최저·최고 기온으로 시간별 기온을 어림합니다(새벽 6시 최저, 오후 3시 최고, 그 사이는 코사인 곡선). 비 확률은 오전·오후 값을 쓰고, 바람·습도·미세먼지·햇빛은 정보 없음(70점)입니다. 조건은 비 확률만 봅니다.
|
||||||
|
|
||||||
|
### 2-8. 나들이 점수 (주말 전국 순위, 당일치기)
|
||||||
|
|
||||||
|
- 토·일 **10~17시**를 2-2~2-4 순서대로 계산합니다. 시간별 예보가 8시간 모두 있어야 계산합니다.
|
||||||
|
|
||||||
|
| 요소 | 비중 | 식 |
|
||||||
|
|---|---:|---|
|
||||||
|
| 비 | 40% | 비 안 와야 좋음 (2-3 '비') |
|
||||||
|
| 체감온도 | 35% | ① 편한 범위 17~24°, 최적 21°, 만점폭 2° |
|
||||||
|
| 하늘 | 15% | 시간마다 맑음 100 · 구름많음 80 · 흐림 50 점의 평균 |
|
||||||
|
| 바람 | 10% | ③ 괜찮은 바람 초속 4m, 한계 12m |
|
||||||
|
|
||||||
|
- 비 소식이 있거나 비 확률이 60% 이상이면 **최대 30점**입니다.
|
||||||
|
- 중기예보뿐인 날은 기온을 어림하고(2-7), 하늘은 그날 하늘 하나, 바람은 70점입니다.
|
||||||
|
- **전국 순위:** 대표 30곳을 점수 순으로 줄 세웁니다.
|
||||||
|
- **당일치기:** 내 지역에서 직선 20~200km 안 후보 도시 중 토·일 가운데 더 좋은 날의 점수가 가장 높은 곳입니다. 동점이면 비 확률이 낮은 곳, 이른 날, 가까운 곳 순입니다. 1위가 50점 미만이면 카드를 보여 주지 않습니다.
|
||||||
|
|
||||||
|
### 2-9. 노을 점수 (노을 탭, 피드 노을 카드)
|
||||||
|
|
||||||
|
노을은 **해 지는(뜨는) 시각에 가장 가까운 정시의 구름**으로 정합니다. 해 지는 방향으로 **20km 앞(머리 위)**과 **100km 앞(먼 하늘)** 두 지점의 구름을 봅니다. 구름은 높이에 따라 낮은 구름, 중간 구름, 높은 구름(각 0~100%)으로 나뉩니다.
|
||||||
|
|
||||||
|
**① 구름 점수**
|
||||||
|
|
||||||
|
| 항목 | 식 | 뜻 |
|
||||||
|
|---|---|---|
|
||||||
|
| 물들 구름 | 20km 지점의 중간 구름과 높은 구름 중 큰 값 | 햇빛을 받아 붉게 물드는 구름 |
|
||||||
|
| 물들 정도 | 물들 구름 0%면 0.4 → 50%에서 1.0까지 곧게 → 100%에서 0까지 곧게 | 반쯤 덮였을 때 가장 좋음. 구름 없는 맑은 하늘은 55점 안팎(은은함) |
|
||||||
|
| 머리 위 막힘 | 1 − 0.8 × 20km 낮은 구름 ÷ 100 | 낮은 구름은 하늘을 가림 |
|
||||||
|
| 빛 들어옴 | 1 − min(100km 낮은 구름 + 0.5 × 100km 중간 구름, 100) ÷ 100 | 먼 하늘이 막히면 햇빛이 못 들어옴 |
|
||||||
|
|
||||||
|
> **구름 점수** = 100 × (0.75 × 물들 정도 + 0.25 × 머리 위 막힘) × (0.25 + 0.75 × 빛 들어옴)
|
||||||
|
|
||||||
|
예보 모델 2개(일본 JMA, 독일 ICON)로 각각 계산해 평균을 냅니다.
|
||||||
|
|
||||||
|
**② 공기·장소 보정 (곱하는 값)**
|
||||||
|
|
||||||
|
평소 공기(가시거리 20km, 습도 60%)를 1.0으로 두고, 맑으면 올리고 뿌옇거나 습하면 내립니다. 기준점 사이는 곧게 잇고, 양 끝 밖은 끝 값 그대로입니다.
|
||||||
|
|
||||||
|
| 조건 | 기준점 |
|
||||||
|
|---|---|
|
||||||
|
| 가시거리 | 5km 0.8 · 20km 1.0 · 40km 1.12 |
|
||||||
|
| 습도 | 40% 1.06 · 60% 1.0 · 90% 0.85 |
|
||||||
|
| 비 갠 직후 | 해 지기 2~6시간 전 비 확률이 60% 이상이었고 그 시각 40% 미만이면 × 1.15 |
|
||||||
|
| 서쪽이 트인 명소 | 구 중심 20km 안에 서쪽이 바다·강·전망대로 트인 노을 명소가 있으면 × 1.1 (노을만) |
|
||||||
|
|
||||||
|
값이 없는 조건은 건너뜁니다.
|
||||||
|
|
||||||
|
> **노을 점수** = min(100, 구름 점수 모델 평균 × 공기·장소 보정)
|
||||||
|
|
||||||
|
**예시**
|
||||||
|
- 구름 점수 57 (구름은 알맞음), 가시거리 6.5km, 습도 80%, 근처에 서쪽 트인 명소 없음
|
||||||
|
- 보정 = 가시거리 0.82 × 습도 0.90 = 0.74
|
||||||
|
- 노을 점수 = 57 × 0.74 = **42점 → 은은함**
|
||||||
|
|
||||||
|
**③ 등급과 화면 문구**
|
||||||
|
|
||||||
|
| 점수 | 등급 | 노을 탭 큰 글씨 (예) |
|
||||||
|
|---|---|---|
|
||||||
|
| 80 이상 | 붉음 | 18:10, 오늘 하늘이 온통 붉게 물들어요 |
|
||||||
|
| 60~79 | 고움 | 18:10, 오늘 노을이 곱게 물들어요 |
|
||||||
|
| 40~59 | 은은함 | 18:10, 오늘 노을이 은은하게 물들어요 |
|
||||||
|
| 40 미만 | 잿빛 | 오늘 노을이 거의 안 보여요 |
|
||||||
|
|
||||||
|
잿빛인 날은 시각을 말하지 않고, 왜 안 보이는지 한 줄을 붙입니다. 위에서부터 먼저 걸리는 것 하나입니다.
|
||||||
|
|
||||||
|
| 조건 (두 모델 평균 구름) | 문구 |
|
||||||
|
|---|---|
|
||||||
|
| 100km 낮은 구름 + 0.5 × 중간 구름 ≥ 60 | 해 지는 쪽 하늘이 구름에 가려요 |
|
||||||
|
| 20km 낮은 구름 ≥ 60 | 구름이 낮게 깔려 있어요 |
|
||||||
|
| 물들 구름 < 25 | 구름이 거의 없어요 |
|
||||||
|
| 물들 구름 > 75 | 구름이 너무 두꺼워요 |
|
||||||
|
| 공기·장소 보정 < 0.7 (아주 뿌옇고 습한 날) | 하늘이 뿌예서 색이 바래요 |
|
||||||
|
|
||||||
|
- 큰 글씨 아래에는 오늘·내일·모레 세 칸을 그날 등급 색으로 칠해 보여 주고, 칸을 누르면 그날로 바뀝니다.
|
||||||
|
- **무엇을 보여 주나:** 다음에 올 것입니다. 해 뜨기 전엔 오늘 일출, 블루아워가 끝나기 전엔 오늘 노을, 그 뒤엔 내일 일출. 일출도 같은 식이고 구름은 해 뜨는 쪽을 봅니다.
|
||||||
|
- 점수는 지금 하늘이 아니라 **해 질 무렵 예보**로 낸 값입니다.
|
||||||
|
|
||||||
|
**④ 노을 시간표**
|
||||||
|
|
||||||
|
| 항목 | 식 |
|
||||||
|
|---|---|
|
||||||
|
| 골든아워 | 해가 지평선 위 6°로 내려온 때부터 해 질 때까지 |
|
||||||
|
| 해 져요 | 해 고도 −0.833° (해 윗부분이 지평선에 닿는 때) |
|
||||||
|
| 노을 피크 | 해 진 시각 + 10분 + (20km 높은 구름 % ÷ 10)분. 높은 구름이 많을수록 늦게까지 물듦 |
|
||||||
|
| 블루아워 | 해 고도 −4°부터 −6°까지 |
|
||||||
|
|
||||||
|
일출은 순서가 반대이고, 노을 피크는 해 뜨기 같은 시간 전입니다. 해의 위치는 날짜와 구 중심 좌표로 계산합니다(NOAA 근사식).
|
||||||
|
|
||||||
|
### 2-10. 달 (오늘 밤 달 칸, 달 포스트, 별보기각)
|
||||||
|
|
||||||
|
- **모양:** 달과 해가 하늘에서 벌어진 각도(0° 삭 → 180° 보름)로 정합니다. 빛나는 면 = (1 − cos 각도) ÷ 2. 이 각도 구간으로 삭·초승달·상현달·차오르는 달·보름달·기우는 달·하현달·그믐달을 정합니다.
|
||||||
|
- '달 밝기 N%'는 쓰지 않습니다. 초승달도 달 자체는 밝게 보여서, 퍼센트는 밝기가 아니라 모양일 뿐이기 때문입니다.
|
||||||
|
- **뜨고 지는 시각:** 19시~다음 날 5시를 10분 간격으로 달 높이를 계산해(Meeus 간이식) 지평선을 넘는 때를 찾습니다.
|
||||||
|
- **잘 보이는지:** 위에서부터 먼저 걸리는 것 하나입니다.
|
||||||
|
|
||||||
|
| 조건 | 문구 |
|
||||||
|
|---|---|
|
||||||
|
| 빛나는 면 3% 미만 (삭 무렵) | 해와 같은 쪽에 있어 안 보여요 |
|
||||||
|
| 19~5시에 한 번도 안 뜸, 차오르는 달 | 해 진 뒤 곧 져서 밤엔 안 보여요 |
|
||||||
|
| 19~5시에 한 번도 안 뜸, 기우는 달 | 새벽 늦게 떠서 밤엔 안 보여요 |
|
||||||
|
| 밤늦게 뜸 | 새벽 2시에 떠요 (뜨는 시각) |
|
||||||
|
| 달이 떠 있는 시간의 하늘 평균(맑음 0 · 구름많음 0.5 · 흐림 1)이 0.6 이상 | 흐려서 구름에 가려요 |
|
||||||
|
| 같은 평균 0.3 이상 | 구름 사이로 보여요 |
|
||||||
|
| 밤사이 짐 | 밤 11시까지 보여요 (지는 시각) |
|
||||||
|
| 그 밖 | 밤새 잘 보여요 |
|
||||||
|
|
||||||
|
### 2-11. 체감온도, 불쾌지수
|
||||||
|
|
||||||
|
- **체감온도, 5~9월 (기상청 여름식):** 습구온도 Tw를 기온·습도로 구한 뒤, −0.2442 + 0.55399 × Tw + 0.45535 × 기온 − 0.0022 × Tw² + 0.00278 × Tw × 기온 + 3.0
|
||||||
|
- **체감온도, 10~4월 (기상청 겨울식):** 기온 10° 이하이고 바람 4.8km/h 이상일 때만 13.12 + 0.6215 × 기온 − 11.37 × V^0.16 + 0.3965 × 기온 × V^0.16 (V는 km/h 바람). 그 밖엔 기온 그대로
|
||||||
|
- **불쾌지수** = 0.81 × 기온 + 0.01 × 습도 × (0.99 × 기온 − 14.3) + 46.3
|
||||||
|
- 불쾌지수 기준: 68 미만 쾌적, 68~74 보통, 75~79 불쾌, 80 이상 매우 불쾌
|
||||||
|
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. 피드는 어떻게 만들어지나
|
||||||
|
|
||||||
|
### 3-1. 하루 한 번 틀을 만듭니다 (03:00)
|
||||||
|
|
||||||
|
- 매일 03:00에 그날 피드의 **칸 19개**를 정해 둡니다. 피드의 하루는 03:00에 시작해 다음 날 03:00에 끝납니다.
|
||||||
|
- 틀에는 내용(점수, 문장)이 없고 "몇 번째 칸에 무엇이 들어간다"만 있습니다. 내용은 구마다 다르기 때문에 열 때 채웁니다.
|
||||||
|
- 계절 소식, 날씨 상식, 한 문장, 달 칸은 전국이 같은 글입니다. 나머지 칸은 시도마다 따로입니다. 그래서 좋아요·댓글은 같은 시도끼리 같은 글에 쌓입니다.
|
||||||
|
- 03:00 작업이 실패해도, 누가 피드를 열 때 빠진 칸을 다시 만듭니다.
|
||||||
|
|
||||||
|
### 3-2. 누가 열 때 내용을 채웁니다
|
||||||
|
|
||||||
|
1. 그 구의 날씨, 미세먼지, 특보, 노을, 각 점수, 열흘 날씨, 행사를 한꺼번에 모읍니다. 오래된 정보는 이때 새로 받습니다(1-2 참고).
|
||||||
|
2. 칸마다 내용을 채웁니다. **채울 내용이 없거나 조건이 안 맞는 칸은 빠집니다.** 예를 들어 특보가 없으면 특보 칸이, 아침에는 내일 미리보기 칸이 빠집니다.
|
||||||
|
3. 지금 구간에 맞는 순서로 놓고 저장해 둡니다.
|
||||||
|
|
||||||
|
| 칸 | 내용 | 나오는 조건 |
|
||||||
|
|---|---|---|
|
||||||
|
| 오늘·내일 날씨 | 시간별 날씨 | 예보가 있으면 |
|
||||||
|
| 생활 알림 | 기상특보 | 그 구에 특보가 있을 때 |
|
||||||
|
| 오늘의 각 1·2·3위 | 지금 구간 점수 상위 3개 | 점수가 있으면 |
|
||||||
|
| 노을 | 노을 탭과 같은 문장 | 늘 (시간에 따라 노을 또는 일출) |
|
||||||
|
| 내일 미리보기 | 내일 날씨 | 저녁·밤에만 |
|
||||||
|
| 주말 예보, 주말 플랜(토·일) | 주말 날씨와 할 거리 | 주말 예보가 있으면 |
|
||||||
|
| 가까운 행사 (최대 3장) | 7일 안에 열리는 행사 | 있는 만큼 |
|
||||||
|
| 계절 소식, 날씨 상식 | 그날 고른 글 | 늘 |
|
||||||
|
| 한 문장 | 그날 날씨에 맞는 글 | 늘 |
|
||||||
|
| 미세먼지 | 지금 공기 | 측정값이 3시간 안이면 |
|
||||||
|
| 당일치기 | 1~2시간 거리 추천 도시 | 50점 넘는 곳이 있으면 |
|
||||||
|
| 오늘 밤 달 | 달 모양, 잘 보이는지 | 늘 |
|
||||||
|
|
||||||
|
### 3-3. 순서는 시간대마다 다릅니다
|
||||||
|
|
||||||
|
| 구간 | 앞쪽에 오는 것 | 이유 |
|
||||||
|
|---|---|---|
|
||||||
|
| 아침 | 특보 → 미세먼지 → 오늘의 각 | 나가기 전에 볼 것 |
|
||||||
|
| 낮 | 오늘의 각 | 지금 할 거리 |
|
||||||
|
| 저녁 | 노을 → 각 → 달 | 하늘을 볼 시간 |
|
||||||
|
| 밤 | 내일 미리보기 → 달 → 주말 예보 | 내일과 주말 준비 |
|
||||||
|
|
||||||
|
순서에 덧붙는 규칙은 다음과 같습니다.
|
||||||
|
|
||||||
|
- 특보가 있으면 무조건 맨 위에 둡니다.
|
||||||
|
- 금요일 저녁엔 주말 예보를 두 번째로 올립니다.
|
||||||
|
- 해가 진 뒤엔 노을 카드가 세 번째로 내려가고, 블루아워가 끝나면 내일 일출 카드로 바뀝니다.
|
||||||
|
- 같은 종류(각·각·각)가 연달아 나오지 않게 사이에 다른 카드를 끼웁니다.
|
||||||
|
- 행사 카드는 날짜와 구로 정한 자리에 들어가서, 같은 날 같은 구는 늘 같은 자리에 있습니다.
|
||||||
|
- 각 카드 세 장은 지금 시각에 가장 가까운 시간대의 각이 먼저 옵니다.
|
||||||
|
|
||||||
|
### 3-4. 피드는 언제 새로 바뀌나
|
||||||
|
|
||||||
|
만든 피드는 잠깐 저장해 두고 다시 씁니다. 저장은 다음에 내용이 바뀔 시각까지, 최대 1시간입니다.
|
||||||
|
|
||||||
|
| 바뀌는 때 | 무엇이 바뀌나 |
|
||||||
|
|---|---|
|
||||||
|
| 03:00 | 새 날 틀로 바뀝니다 |
|
||||||
|
| 구간이 바뀔 때 (05시, 11시, 해 지기 2시간 전, 해 짐, 해 지고 1시간 뒤) | 순서가 바뀝니다 |
|
||||||
|
| 새 단기예보가 나올 때 (하루 8번) | 각 점수, 순위, 문장이 바뀔 수 있습니다 |
|
||||||
|
| 매시 20분 (미세먼지) | 미세먼지와 관련 점수가 바뀔 수 있습니다 |
|
||||||
|
| 정보 하나라도 못 받았을 때 | 1분 뒤 다시 만듭니다 |
|
||||||
|
|
||||||
|
좋아요·댓글 수는 저장본을 쓰지 않고 매번 새로 읽기 때문에 누르는 즉시 반영됩니다.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. 알아 두실 점
|
||||||
|
|
||||||
|
- **공유 링크:** 지금 그 구의 피드에서 글을 찾기 때문에, 어제 글이나 지금 꺼진 칸의 글은 '없는 글'로 나옵니다.
|
||||||
|
- **예보 기준:** 모든 점수는 그 시점에 받은 예보로 계산합니다. 예보가 바뀌면 점수도 바뀝니다.
|
||||||
|
- **노을 피크 시각:** 해 지는 시각에 10~20분을 더한 어림값이라 실제와 다를 수 있습니다.
|
||||||
|
- **밤 날씨 점수:** 해가 진 뒤엔 햇빛이 0점이라 날씨가 완벽해도 최대 64점입니다 (2-6).
|
||||||
|
- **점수 기준값:** 대부분 경험으로 잡은 값입니다. 실제 분포(예: 노을 점수가 1년에 며칠 붉음인지)는 아직 확인 중입니다.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 부록: 각 34개 한눈에 보기
|
||||||
|
|
||||||
|
| 각 | 분류 | 하기 좋은 시간대 | 가장 크게 보는 요소 |
|
||||||
|
|---|---|---|---|
|
||||||
|
| 야장각 | 먹고 마시기 | 18~24시 | 기온 30% · 비 25% |
|
||||||
|
| 피크닉각 | 밖에서 놀기 | 11~16시 | 비 20% · 기온 20% |
|
||||||
|
| 치맥각 | 먹고 마시기 | 18~23시 | 기온 30% · 비 20% |
|
||||||
|
| 산책각 | 밖에서 놀기 | 18~22시 | 기온 30% · 비 25% |
|
||||||
|
| 환기각 | 집안일 | 10~18시 (2시간씩) | 미세먼지 45% · 비 15% |
|
||||||
|
| 등산각 | 밖에서 놀기 | 7~12시 | 비 20% · 기온 20% |
|
||||||
|
| 세차각 | 집안일 | 9~18시 (비는 2일 뒤까지 봄) | 비 40% · 햇빛 10% |
|
||||||
|
| 캠핑각 | 밖에서 놀기 | 18시~다음 날 8시 | 기온 30% · 비 25% |
|
||||||
|
| 러닝각 | 밖에서 놀기 | 6~8시 / 19~22시 | 기온 35% · 비 20% |
|
||||||
|
| 별보기각 | 밖에서 놀기 | 21시~다음 날 2시 | 달·시간 45% · 미세먼지 15% |
|
||||||
|
| 짬뽕각 | 먹고 마시기 | 11~14시 / 17~20시 | 기온 40% · 비 25% |
|
||||||
|
| 막걸리각 | 먹고 마시기 | 17~22시 | 비 50% · 습도 15% |
|
||||||
|
| 뜨아각 | 먹고 마시기 | 7~10시 | 기온 50% · 바람 15% |
|
||||||
|
| 빨래각 | 집안일 | 9~16시 | 비 30% · 햇빛 25% |
|
||||||
|
| 자전거각 | 밖에서 놀기 | 9~19시 | 비 20% · 바람 20% |
|
||||||
|
| 멍뭉산책각 | 밖에서 놀기 | 7~9시 / 17~20시 | 기온 40% · 비 25% |
|
||||||
|
| 김서림각 | 생활 고민 | 7~9시 | 기온 50% · 습도 30% |
|
||||||
|
| 화장붕괴각 | 생활 고민 | 10~18시 | 기온 40% · 습도 35% |
|
||||||
|
| 냉면각 | 먹고 마시기 | 11~14시 | 기온 55% · 습도 15% |
|
||||||
|
| 택시대란각 | 생활 고민 | 22시~다음 날 2시 | 비 55% · 시간 15% |
|
||||||
|
| 배달폭주각 | 생활 고민 | 17~21시 | 비 50% · 기온 20% |
|
||||||
|
| 가드닝각 | 집안일 | 7~10시 | 비 25% · 기온 20% |
|
||||||
|
| 사진산책각 | 밖에서 놀기 | 해 지기 앞뒤 1시간 | 시간 30% · 비 25% |
|
||||||
|
| 야구각 | 밖에서 놀기 | 18~22시 | 비 40% · 기온 25% |
|
||||||
|
| 공부각 | 집안일 | 13~18시 | 비 35% · 기온 35% |
|
||||||
|
| 넷플릭스각 | 집안일 | 20~24시 | 비 35% · 기온 30% |
|
||||||
|
| 군밤각 | 먹고 마시기 | 17~21시 | 기온 55% · 비 25% |
|
||||||
|
| 골프각 | 밖에서 놀기 | 7~12시 / 12~17시 | 비 30% · 기온 30% |
|
||||||
|
| 집콕각 | 집안일 | 10~18시 | 비 30% · 기온 30% |
|
||||||
|
| 낚시각 | 밖에서 놀기 | 5~9시 / 16~19시 | 바람 35% · 비 25% |
|
||||||
|
| 드라이브각 | 밖에서 놀기 | 10~17시 | 비 30% · 기온 20% |
|
||||||
|
| 연날리기각 | 밖에서 놀기 | 11~16시 | 바람 45% · 비 25% |
|
||||||
|
| 물놀이각 | 밖에서 놀기 | 11~17시 | 기온 40% · 비 25% |
|
||||||
|
| 김장각 | 집안일 | 9~16시 | 기온 50% · 비 25% |
|
||||||
|
|
||||||
|
- 비 요소는 34개 중 24개가 "비가 안 와야 좋음"입니다. 나머지 10개(짬뽕각, 막걸리각, 뜨아각, 김서림각, 화장붕괴각, 택시대란각, 배달폭주각, 공부각, 넷플릭스각, 집콕각)는 비가 와야 점수가 오릅니다.
|
||||||
|
- 각별 0점 조건과 자세한 기준은 `docs/각_계산기준.md`에 있습니다.
|
||||||
@@ -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)나 운영 사이트에서 눌러 본다.
|
||||||
+180
@@ -0,0 +1,180 @@
|
|||||||
|
# 점수 계산식
|
||||||
|
|
||||||
|
화면에 나오는 점수·판정의 계산식을 한곳에 모은 문서입니다. 각별 비중·시간대는 [각_계산기준.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. 시간대 구간
|
||||||
|
|
||||||
|
| 구간 | 시각 |
|
||||||
|
|---|---|
|
||||||
|
| 아침 | 5~11시 |
|
||||||
|
| 낮 | 11시 ~ 일몰 2시간 전 |
|
||||||
|
| 저녁 | 일몰 2시간 전 ~ 일몰 1시간 뒤 |
|
||||||
|
| 밤 | 일몰 1시간 뒤 ~ 다음 날 5시 (0~5시는 전날 밤 구간) |
|
||||||
|
|
||||||
|
한 시간은 그 시각 30분이 속한 구간에 넣습니다. 피드 카드 순서도 같은 구간을 씁니다 (`backend/services/calc/day_slot.py`).
|
||||||
|
|
||||||
|
## 3. 지금 날씨 점수
|
||||||
|
|
||||||
|
**지금 구간**의 모든 시각이 밖에 나가기 좋은 정도. 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점 미만.
|
||||||
|
|
||||||
|
## 4. 각 점수
|
||||||
|
|
||||||
|
- 1의 방식. 요소·비중·시간대·0점 조건은 각마다 다르며 [각_계산기준.md](각_계산기준.md)에 있습니다.
|
||||||
|
- **오늘 점수 = 지금 구간 점수.** 각의 시간대 중 지금 구간에 드는 시각만으로 계산합니다(시간대가 여러 개면 그중 가장 좋은 쪽). 비가 오면 그 뒤 구간 점수가 내려갑니다.
|
||||||
|
- 각의 시간대가 지금 구간과 겹치지 않으면(예: 아침의 야장각) **순위·피드 카드·히어로 1위에서 빠집니다.** 스토리·각 탭 '전체'에는 맨 뒤에 '지금 아님'으로 남고, 점수는 하루 점수(가장 좋은 시간대)입니다.
|
||||||
|
- 각 상세 창에 오늘 아침·낮·저녁·밤 점수를 보여 줍니다. 안 겹치는 구간은 '–'.
|
||||||
|
- 내일·토·일 칸은 하루 점수(가장 좋은 시간대)입니다.
|
||||||
|
- 순위는 점수 × 중요도(상 1.0 · 중 0.85 · 하 0.7). 화면 숫자는 점수 그대로입니다.
|
||||||
|
- 단기예보가 닿지 않는 날(토·일 등)은 중기예보의 최저·최고 기온으로 시각별 기온을 어림하고(새벽 6시 최저, 오후 3시 최고, 코사인 곡선), 바람·습도·미세먼지는 정보 없음으로 둔 '예상 점수'입니다.
|
||||||
|
|
||||||
|
## 5. 나들이 점수 (주말 순위·당일치기)
|
||||||
|
|
||||||
|
토·일 **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점 미만이면 카드를 보이지 않습니다.
|
||||||
|
|
||||||
|
## 6. 노을 점수
|
||||||
|
|
||||||
|
해 지는(뜨는) 시각에 가장 가까운 정시의 구름을, 해 지는 방향 **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) | 나가 볼 만해요 |
|
||||||
|
|
||||||
|
- **무엇을 보여 주나**: 다음에 오는 것. 오늘 해 뜨기 전엔 오늘 일출, 그 뒤 블루아워가 끝나기 전엔 오늘 노을, 그 뒤엔 내일 일출. 피드 노을 카드도 같습니다. 일출도 같은 식으로 계산합니다(구름은 해 뜨는 쪽).
|
||||||
|
- 노을 탭 히어로는 답만 보여 줍니다: '오늘은 애매해요'(결론), '18:10쯤 가장 붉어요', 쉬운 말 이유 한 줄(예: 구름은 좋은데 공기가 뿌예서 색이 흐릴 거예요). 더 나은 날이 있으면 바로 아래, 점수·구름·예보 모델 수는 '자세히'에 접어 둡니다.
|
||||||
|
- 점수는 **지금 하늘이 아니라 해 질(뜰) 무렵 예보**로 낸 값입니다. 노을 탭에 "해 질 무렵(18시) 예보 기준"으로 적습니다.
|
||||||
|
- 화면 결론(나가 볼 만해요·애매해요·쉬어요)은 **하늘 상황 기준**이고, **공기 보정이 0.7배 미만이면 한 단계 낮춥니다.** 이때 이유에 숫자 없이 "먼 건물이 흐릿할 만큼 공기가 뿌옇고 습해서 노을 색이 바래 보일 거예요"(가시거리 20km 미만 = 먼 건물이 흐릿함, 습도 70% 이상 = 습함)를 붙이고, 히어로·피드 카드의 상황 줄도 이 말로 바꿉니다. 예) 분당구 10/12: 구름 57점 × 공기 0.50(가시거리 6.5km 0.62 · 습도 80% 0.81) = 29점 잿빛 → '하늘이 넓게 물들 수 있어요'였던 결론이 '애매해요'로. 상황이 없을 때만 점수로 정합니다(60↑ 나가 볼 만해요, 40↑ 애매해요).
|
||||||
|
- 확신도: 모델별 점수의 표준편차가 8 미만이면 높음, 15 미만이면 보통, 그 이상이거나 모델이 1개면 낮음.
|
||||||
|
- 노을 순위: 대표 30곳을 노을 점수순으로 정렬합니다. 70% 이상이 같은 상황이면 한 줄 요약을 붙입니다.
|
||||||
|
|
||||||
|
## 7. 노을 시각
|
||||||
|
|
||||||
|
| 시각 | 정의 |
|
||||||
|
|---|---|
|
||||||
|
| 골든아워 | 해 고도가 **6°**로 내려온 때부터 해 질 때까지. 햇빛이 낮게 비쳐 금빛으로 보이는 시간 |
|
||||||
|
| 해 져요 | 일몰 |
|
||||||
|
| 가장 붉을 때 | 일몰 + 10분 + (20km 상층 구름 % ÷ 10)분. 상층 구름이 많을수록 늦게까지 물듦 |
|
||||||
|
| 블루아워 | 해가 진 뒤 해 고도 **−6°**(시민박명 끝)가 되는 때. 해는 졌지만 하늘이 푸르게 남는 시간 |
|
||||||
|
|
||||||
|
노을 시간표는 골든아워 → 해 져요 → 가장 붉을 때 → 블루아워, 일출 시간표는 블루아워(해 뜨기 전 해 고도 −6°) → 가장 붉을 때 → 해 떠요 → 골든아워(해 고도 6°까지 올라오는 때)입니다. 해 짐·뜸은 해 고도 −0.833°, 모두 구 중심 좌표와 날짜로 계산(NOAA 근사식)합니다. '가장 붉을 때'는 해 뜨기 10분 + (상층 구름 % ÷ 10)분 전입니다.
|
||||||
|
|
||||||
|
## 8. 달 모양·잘 보이는지
|
||||||
|
|
||||||
|
'달 밝기 N%'는 쓰지 않습니다. 초승달도 달 자체는 밝게 보이므로, 퍼센트는 밝기가 아니라 모양(빛나는 면)일 뿐이기 때문입니다.
|
||||||
|
|
||||||
|
- **모양**: 달과 해의 황경 차이(0° 삭 → 180° 보름)로 정합니다. 빛나는 면 = (1 − cos 황경 차이) ÷ 2, 모양 이름은 차이 구간으로(삭·초승달·상현달·차오르는 달·보름달·기우는 달·하현달·그믐달). 히어로 달 그림에 씁니다.
|
||||||
|
- **뜨고 지는 시각**: 그날 19시~다음 날 5시를 10분 간격으로 달 고도(Meeus 간이식, 지표 기준)를 계산해 −0.83°를 넘나드는 때.
|
||||||
|
- **잘 보이는지** (위에서부터 먼저 걸리는 것):
|
||||||
|
|
||||||
|
| 조건 | 문구 |
|
||||||
|
|---|---|
|
||||||
|
| 빛나는 면 3% 미만 (삭 무렵) | 해와 같은 쪽에 있어 안 보여요 |
|
||||||
|
| 19시~5시에 한 번도 안 뜸, 차오르는 달 | 해 진 뒤 곧 져서 밤엔 안 보여요 |
|
||||||
|
| 19시~5시에 한 번도 안 뜸, 기우는 달 | 새벽 늦게 떠서 밤엔 안 보여요 |
|
||||||
|
| 저녁 7~9시 사이가 아니라 밤늦게 뜸 | 새벽 2시에 떠요 |
|
||||||
|
| 달이 떠 있는 시각의 하늘이 흐림 쪽 (맑음 0 · 구름많음 0.5 · 흐림 1의 평균 0.6 이상) | 흐려서 구름에 가려요 |
|
||||||
|
| 같은 평균 0.3 이상 | 구름 사이로 보여요 |
|
||||||
|
| 밤사이 짐 | 밤 11시까지 보여요 |
|
||||||
|
| 그 밖 | 밤새 잘 보여요 |
|
||||||
|
|
||||||
|
- 히어로 '오늘 밤 달' 칸: '모양, 잘 보이는지' (예: 상현달, 밤 11시까지 보여요).
|
||||||
|
- 달 포스트: 모양 + 잘 보이는지 + 달 뜸·짐 시각.
|
||||||
|
- 별보기각 '시간' 요소: 달이 비추는 정도 = 빛나는 면 × 21~26시 중 달이 떠 있는 비율, 점수 = 20 + 80 × (1 − 그 값). 근거 문구는 '모양, 잘 보이는지'(구름 제외).
|
||||||
|
|
||||||
|
## 9. 불쾌지수
|
||||||
|
|
||||||
|
- **불쾌지수 = 0.81 × 기온 + 0.01 × 습도 × (0.99 × 기온 − 14.3) + 46.3**
|
||||||
|
- 68 미만 쾌적 · 75 미만 보통 · 80 미만 불쾌 · 그 이상 매우 불쾌
|
||||||
@@ -0,0 +1,73 @@
|
|||||||
|
# 태그·키워드 정의서
|
||||||
|
|
||||||
|
검색 등록을 위해 넣은 HTML 태그, 검색어, 해시태그 사전을 정리한 문서입니다. (10/8 회의 결정: 넣은 태그·키워드는 정의서로 정리해 대표 보고)
|
||||||
|
|
||||||
|
- 기준: 2026년 10월 12일
|
||||||
|
- 적용 파일: `frontend/index.html`, `frontend/public/robots.txt`, `frontend/public/sitemap.xml`
|
||||||
|
- 상태: ○ 들어가 있음 · △ 문구 검토 중 · ✕ 없음
|
||||||
|
|
||||||
|
## 1. 검색·공유용 HTML 태그
|
||||||
|
|
||||||
|
| 태그 | 내용 | 상태 |
|
||||||
|
|---|---|:---:|
|
||||||
|
| `<title>` | 날씨각 · 오늘 날씨 지수, 노을, 주말 행사 | ○ |
|
||||||
|
| description | 세차각·빨래각·러닝각처럼 오늘 날씨에 맞는 일을 점수로. 노을이 예쁜 시간과 명소, 이번 주말 가까운 축제까지 날씨각에서 확인하세요. | ○ |
|
||||||
|
| keywords | 2장의 검색어 15개, 쉼표로 구분 | △ |
|
||||||
|
| canonical | https://weather.o2o.kr/ | ○ |
|
||||||
|
| og:site_name | 날씨각 | ○ |
|
||||||
|
| og:title / og:description | title, description과 같음 | ○ |
|
||||||
|
| og:type / og:locale | website / ko_KR | ○ |
|
||||||
|
| og:url | https://weather.o2o.kr/ | ○ |
|
||||||
|
| og:image (+ 크기) | /og.png, 1200×630 | ○ |
|
||||||
|
| og:image:alt | 날씨각, 오늘 날씨에 맞는 일을 점수로 알려 주는 서비스 | △ |
|
||||||
|
| twitter:card | summary_large_image | ○ |
|
||||||
|
| twitter:title / description / image | og 값과 같음 | △ |
|
||||||
|
| 구글 소유 확인 | google-site-verification | ○ |
|
||||||
|
| 네이버 소유 확인 | naver-site-verification | ○ (배포 전) |
|
||||||
|
| theme-color | #d6ebff | ○ |
|
||||||
|
| manifest | 이름 '날씨각', 색 #d6ebff | △ |
|
||||||
|
|
||||||
|
## 2. 검색어 (keywords 메타)
|
||||||
|
|
||||||
|
검색엔진이 사이트 주제를 파악하는 데 참고합니다. 구글은 거의 보지 않고 다음 등 일부가 참고합니다.
|
||||||
|
|
||||||
|
날씨각, 오늘 날씨, 날씨 지수, 세차하기 좋은 날, 빨래하기 좋은 날, 러닝하기 좋은 날씨, 오늘 노을, 노을 시간, 일몰 시간, 노을 명소, 주말 날씨, 주말 나들이, 이번 주말 축제, 미세먼지, 오늘 밤 달
|
||||||
|
|
||||||
|
## 3. 해시태그 사전
|
||||||
|
|
||||||
|
서비스 주제를 분류하는 기준 단어입니다. HTML 태그와는 별개이며, SNS 게시물, 블로그 글, 검색 광고 키워드, 앞으로 만들 검색용 페이지 이름에 같은 말을 씁니다. 2장 검색어는 이 사전에서 골랐습니다.
|
||||||
|
|
||||||
|
| 분류 | 해시태그 |
|
||||||
|
|---|---|
|
||||||
|
| 기본 | #날씨각 #오늘날씨 #동네날씨 #날씨지수 |
|
||||||
|
| 오늘의 각 | #세차각 #빨래각 #러닝각 #피크닉각 #산책각 #캠핑각 #등산각 #야장각 #치맥각 #별보기각 |
|
||||||
|
| 노을·하늘 | #오늘노을 #노을시간 #일몰시간 #노을명소 #골든아워 #블루아워 #오늘밤달 |
|
||||||
|
| 주말·행사 | #주말날씨 #주말나들이 #당일치기 #이번주말축제 #전시 #공연 #팝업스토어 |
|
||||||
|
| 생활 날씨 | #미세먼지 #체감온도 #불쾌지수 #기상특보 |
|
||||||
|
| 계절·상식 | #계절소식 #날씨상식 |
|
||||||
|
|
||||||
|
총 34개. 각은 34개 중 검색이 많을 만한 10개만 넣었습니다(전체 목록은 `docs/각_계산기준.md`).
|
||||||
|
|
||||||
|
## 4. 구조화 데이터 (JSON-LD)
|
||||||
|
|
||||||
|
검색엔진과 AI가 사이트를 정확히 이해하도록 넣는 데이터입니다. 화면에는 보이지 않습니다.
|
||||||
|
|
||||||
|
| 종류 | 내용 | 상태 |
|
||||||
|
|---|---|:---:|
|
||||||
|
| WebSite | 이름 날씨각, 주소, 한국어 | ○ |
|
||||||
|
| WebApplication | 날씨 분류, 무료, 한국어 | △ |
|
||||||
|
| Organization | 운영사 이름(날씨각 또는 회사명, 결정 필요), 주소 | △ |
|
||||||
|
| FAQPage | 자주 묻는 질문 7개 | △ |
|
||||||
|
|
||||||
|
## 5. 로봇용 소개 본문
|
||||||
|
|
||||||
|
네이버 로봇과 AI 크롤러는 화면을 그리는 스크립트를 실행하지 않아 메타 태그만 읽습니다. 그래서 앱이 뜨기 전 HTML에 서비스 소개 글(오늘의 각, 노을, 주말·행사, 계절·상식)을 넣고, 앱이 뜨면 화면으로 바뀌게 합니다. 상태: △
|
||||||
|
|
||||||
|
## 6. 검색 등록 현황
|
||||||
|
|
||||||
|
| 할 일 | 상태 |
|
||||||
|
|---|:---:|
|
||||||
|
| robots.txt (모든 로봇 허용, sitemap 위치) | ○ |
|
||||||
|
| sitemap.xml (메인 주소 한 줄) | ○ |
|
||||||
|
| 구글 서치 콘솔 등록·sitemap 제출 | 배포 뒤 |
|
||||||
|
| 네이버 서치어드바이저 소유 확인·sitemap 제출 | 배포 뒤 |
|
||||||
+5
-5
@@ -140,7 +140,7 @@ td .note{display:block;color:var(--muted);font-size:12px;margin-top:3px;line-hei
|
|||||||
|
|
||||||
<article class="card">
|
<article class="card">
|
||||||
<header><h3>주말 플랜</h3><span class="kind">계획 · 날마다 1장</span><span class="state always">매일</span></header>
|
<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>
|
||||||
<dl><dt>② 운영</dt><dd>날마다 내용이 달라 주말 직전까지 볼 이유가 생기고, "토요일 이렇게 놀자" 공유 카드가 됩니다.</dd></dl>
|
<dl><dt>② 운영</dt><dd>날마다 내용이 달라 주말 직전까지 볼 이유가 생기고, "토요일 이렇게 놀자" 공유 카드가 됩니다.</dd></dl>
|
||||||
</article>
|
</article>
|
||||||
@@ -184,8 +184,8 @@ td .note{display:block;color:var(--muted);font-size:12px;margin-top:3px;line-hei
|
|||||||
<th>카드</th>
|
<th>카드</th>
|
||||||
<th class="m">아침<small>05–11시</small></th>
|
<th class="m">아침<small>05–11시</small></th>
|
||||||
<th class="d">낮<small>11시–일몰 2시간 전</small></th>
|
<th class="d">낮<small>11시–일몰 2시간 전</small></th>
|
||||||
<th class="e">저녁<small>일몰 2시간 전–21시</small></th>
|
<th class="e">저녁<small>일몰 2시간 전–일몰 1시간 뒤</small></th>
|
||||||
<th class="n">밤<small>21–05시</small></th>
|
<th class="n">밤<small>일몰 1시간 뒤–05시</small></th>
|
||||||
</tr></thead>
|
</tr></thead>
|
||||||
<tbody>
|
<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>
|
<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">1</span><p>히어로는 맨 위 고정. 히어로에는 날씨와 오늘 1위 각만 작게 두고, 1~3위 상세는 카드에서 보여 줍니다(확정).</p></div>
|
||||||
<div><span class="n">2</span><p>같은 종류 카드는 붙이지 않습니다(확정). 각 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">3</span><p>조건이 안 맞는 카드는 아예 빼고, 빈 카드나 "오늘은 없어요" 카드는 만들지 않습니다.<small>예외: 노을은 흐린 날에도 한 줄로 남깁니다(확정).</small></p></div>
|
||||||
<div><span class="n">4</span><p>좋아요·댓글은 카드에 붙고, 전국 사용자가 같이 봅니다. 순서가 바뀌어도 같은 카드면 좋아요가 이어집니다.</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">5</span><p>시간대가 바뀌는 순간(05·11시, 일몰 2시간 전·일몰 1시간 뒤)과 일몰 시각, 예보 갱신 때 피드가 새로 짜입니다.<small>앞에서 문제가 됐던 "새 칸이 늦게 보이는 문제"가 생기지 않습니다.</small></p></div>
|
||||||
<div><span class="n">6</span><p>카드마다 보낼 문구가 있고, 보내면 카드 그대로 이미지+링크로 갑니다(확정).</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">7</span><p>UI는 따로 고민하지 않고 인스타그램·페이스북 방식을 그대로 따릅니다(확정, 10/2).</p></div>
|
||||||
<div><span class="n">8</span><p>지역은 날씨를 가져오는 시군구 단위 그대로입니다. 수원시 장안구 같은 일반구도 따로 봅니다(확정, 10/2, 256곳).</p></div>
|
<div><span class="n">8</span><p>지역은 날씨를 가져오는 시군구 단위 그대로입니다. 수원시 장안구 같은 일반구도 따로 봅니다(확정, 10/2, 256곳).</p></div>
|
||||||
|
|||||||
+22
-19
@@ -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:* 전부 삭제
|
└─ Redis feed:* 전부 삭제
|
||||||
|
|
||||||
[사용자가 /v1/feed?region=구]
|
[사용자가 /v1/feed?region=구]
|
||||||
@@ -18,11 +18,14 @@
|
|||||||
⑤ 좋아요·댓글 수, 내가 누른 표시를 DB에서 읽어 덮어쓴다 → 응답
|
⑤ 좋아요·댓글 수, 내가 누른 표시를 DB에서 읽어 덮어쓴다 → 응답
|
||||||
```
|
```
|
||||||
|
|
||||||
## 1. 틀 만들기 (하루 한 번, 전국 공통)
|
## 1. 틀 만들기 (하루 한 번)
|
||||||
|
|
||||||
- **언제**: 매일 03:00 worker가 `build_feed_day`를 돌린다. 하루는 03:00에 시작해 다음 날 03:00에 끝난다.
|
- **언제**: 매일 03:00 worker가 `build_feed_day`를 돌린다. 하루는 03:00에 시작해 다음 날 03:00에 끝난다.
|
||||||
피드 요청이 올 때마다 같은 함수가 한 번 더 돈다. 이미 있는 칸은 그대로 두고, 빠진 칸(03:00 작업을 놓쳤거나 배포로 새 종류가 생긴 경우)만 더한다.
|
피드 요청이 올 때마다 같은 함수가 한 번 더 돈다. 이미 있는 칸은 그대로 두고, 빠진 칸(03:00 작업을 놓쳤거나 배포로 새 종류가 생긴 경우)만 더한다.
|
||||||
- **어디에**: PostgreSQL `post` 테이블에 하루 19줄.
|
- **어디에**: PostgreSQL `post` 테이블. 줄마다 `scope`가 있다 — `'00'`은 전국, 그 밖은 시도 코드(`region.code` 앞 2자리).
|
||||||
|
계절 소식·날씨 상식·한 문장·달 칸은 전국 한 줄, 나머지 칸은 시도마다 한 줄(시도 16곳, 광주·전남이 같은 `12`). 하루 약 260줄.
|
||||||
|
같은 날짜·칸·`scope`는 한 줄만(`uq_post_feed_scope`).
|
||||||
|
- **피드에서 읽을 때**: 그 구의 시도 줄과 전국 줄을 같이 읽는다. 같은 칸에 둘 다 있으면 전국 줄을 쓴다(시도 나누기 전에 만든 날을 위해).
|
||||||
- **한 줄에 들어가는 것**: 글 번호, 날짜, 칸 번호, 종류, 같은 종류 중 몇 번째인지, 유효 시간, 좋아요·댓글 수.
|
- **한 줄에 들어가는 것**: 글 번호, 날짜, 칸 번호, 종류, 같은 종류 중 몇 번째인지, 유효 시간, 좋아요·댓글 수.
|
||||||
계절 소식·날씨 상식 칸만 그날 보여줄 글 번호를 미리 정해 둔다(날짜마다 돌아가며).
|
계절 소식·날씨 상식 칸만 그날 보여줄 글 번호를 미리 정해 둔다(날짜마다 돌아가며).
|
||||||
- **들어가지 않는 것**: 점수, 문장, 숫자 같은 내용. 내용은 구마다 다르므로 열 때 채운다.
|
- **들어가지 않는 것**: 점수, 문장, 숫자 같은 내용. 내용은 구마다 다르므로 열 때 채운다.
|
||||||
@@ -32,7 +35,7 @@
|
|||||||
| 1 | 오늘·내일 날씨 | | 오늘 예보가 있으면 |
|
| 1 | 오늘·내일 날씨 | | 오늘 예보가 있으면 |
|
||||||
| 2 | 생활 알림(특보) | | 그 구에 특보가 있을 때 |
|
| 2 | 생활 알림(특보) | | 그 구에 특보가 있을 때 |
|
||||||
| 3~5 | 오늘의 각 | 1·2·3위 | 각 점수가 있으면 |
|
| 3~5 | 오늘의 각 | 1·2·3위 | 각 점수가 있으면 |
|
||||||
| 6 | 노을 | | 노을 계산이 있으면. 하늘 상황으로 말하고, 결론이 '쉬어요'(구름에 가려요·낮은 구름이 덮어요)면 한 줄 카드 |
|
| 6 | 노을 | | 노을 탭 결론과 같은 것(해 뜨기 전·블루아워 뒤엔 일출, 그 사이엔 노을). 하늘 상황으로 말하고, 결론이 '쉬어요'(구름에 가려요·낮은 구름이 덮어요)면 한 줄 카드 |
|
||||||
| 7 | 내일 미리보기 | | 저녁·밤에만 |
|
| 7 | 내일 미리보기 | | 저녁·밤에만 |
|
||||||
| 8 | 주말 예보 | | 주말 예보가 있으면 |
|
| 8 | 주말 예보 | | 주말 예보가 있으면 |
|
||||||
| 9, 13, 14 | 가까운 행사 | 1·2·3번째 | 7일 안에 열리는 행사가 그만큼 있으면 |
|
| 9, 13, 14 | 가까운 행사 | 1·2·3번째 | 7일 안에 열리는 행사가 그만큼 있으면 |
|
||||||
@@ -42,7 +45,7 @@
|
|||||||
| 15·16 | 주말 플랜 | 토·일 | 주말 예보가 있으면 |
|
| 15·16 | 주말 플랜 | 토·일 | 주말 예보가 있으면 |
|
||||||
| 17 | 미세먼지 | | 측정값이 3시간 안이면 |
|
| 17 | 미세먼지 | | 측정값이 3시간 안이면 |
|
||||||
| 18 | 당일치기 | | 1~2시간 거리 후보 도시 1위가 있으면 |
|
| 18 | 당일치기 | | 1~2시간 거리 후보 도시 1위가 있으면 |
|
||||||
| 19 | 오늘 밤 달 | | 늘 켜짐. 보름·삭인 밤이면 그 이야기, 아니면 달 모양·밝기·다음 보름 |
|
| 19 | 오늘 밤 달 | | 늘 켜짐. 보름·삭인 밤이면 그 이야기, 아니면 달 모양·잘 보이는지(구름·뜨고 지는 시각)·다음 보름 |
|
||||||
|
|
||||||
## 2. 칸 채우기 (누가 열 때, 구마다)
|
## 2. 칸 채우기 (누가 열 때, 구마다)
|
||||||
|
|
||||||
@@ -73,8 +76,8 @@
|
|||||||
|---|---|---|
|
|---|---|---|
|
||||||
| 아침 | 05:00~11:00 | 05:00~11:00 |
|
| 아침 | 05:00~11:00 | 05:00~11:00 |
|
||||||
| 낮 | 11:00~일몰 2시간 전 | 11:00~16:05 |
|
| 낮 | 11:00~일몰 2시간 전 | 11:00~16:05 |
|
||||||
| 저녁 | 일몰 2시간 전~21:00 | 16:05~21:00 |
|
| 저녁 | 일몰 2시간 전~일몰 1시간 뒤 | 16:05~19:05 |
|
||||||
| 밤 | 21:00~다음 날 05:00 | 21:00~05:00 |
|
| 밤 | 일몰 1시간 뒤~다음 날 05:00 (계절 따라 18시대~21시대 시작) | 19:05~05:00 |
|
||||||
|
|
||||||
시간대가 바뀌면 캐시 키(`feed:{구}:{시간대}`)가 달라져서 그 순간 새 순서로 다시 만들어진다.
|
시간대가 바뀌면 캐시 키(`feed:{구}:{시간대}`)가 달라져서 그 순간 새 순서로 다시 만들어진다.
|
||||||
|
|
||||||
@@ -84,15 +87,15 @@
|
|||||||
|---|---|
|
|---|---|
|
||||||
| 아침 | 특보 → 미세먼지 → 각 1·2·3 → 계절 소식 → 노을 → 날씨 상식 → 주말 예보 → 주말 플랜(토) → 주말 플랜(일) → 당일치기 → 달 → 한 문장 |
|
| 아침 | 특보 → 미세먼지 → 각 1·2·3 → 계절 소식 → 노을 → 날씨 상식 → 주말 예보 → 주말 플랜(토) → 주말 플랜(일) → 당일치기 → 달 → 한 문장 |
|
||||||
| 낮 | 각 → 특보 → 미세먼지 → 각 → 각 → 노을 → 주말 예보 → 주말 플랜 → 계절 소식 → 주말 플랜 → 당일치기 → 날씨 상식 → 달 → 한 문장 |
|
| 낮 | 각 → 특보 → 미세먼지 → 각 → 각 → 노을 → 주말 예보 → 주말 플랜 → 계절 소식 → 주말 플랜 → 당일치기 → 날씨 상식 → 달 → 한 문장 |
|
||||||
| 저녁 | 노을 → 각 → 특보 → 각 → 각 → 미세먼지 → 내일 미리보기 → 주말 예보 → 주말 플랜 → 계절 소식 → 주말 플랜 → 당일치기 → 날씨 상식 → 달 → 한 문장 |
|
| 저녁 | 노을 → 각 → 달 → 특보 → 각 → 각 → 미세먼지 → 내일 미리보기 → 주말 예보 → 주말 플랜 → 계절 소식 → 주말 플랜 → 당일치기 → 날씨 상식 → 한 문장 |
|
||||||
| 밤 | 내일 미리보기 → 특보 → 노을 → 주말 예보 → 각 → 주말 플랜 → 각 → 각 → 주말 플랜 → 당일치기 → 미세먼지 → 계절 소식 → 날씨 상식 → 달 → 한 문장 |
|
| 밤 | 내일 미리보기 → 달 → 특보 → 노을 → 주말 예보 → 각 → 주말 플랜 → 각 → 각 → 주말 플랜 → 당일치기 → 미세먼지 → 계절 소식 → 날씨 상식 → 한 문장 |
|
||||||
|
|
||||||
뜻: 아침엔 "나가기 전에 볼 것"(특보·공기·오늘 각), 낮엔 각을 맨 위로, 저녁엔 노을을 맨 위로, 밤엔 내일 준비(내일 미리보기)와 주말 계획을 앞으로. 내일 미리보기는 저녁·밤에만 나온다.
|
뜻: 아침엔 "나가기 전에 볼 것"(특보·공기·오늘 각), 낮엔 각을 맨 위로, 저녁엔 노을을 맨 위로, 밤엔 내일 준비(내일 미리보기)와 주말 계획을 앞으로. 저녁·밤엔 하늘을 볼 시간이라 달을 위로. 내일 미리보기는 저녁·밤에만 나온다.
|
||||||
|
|
||||||
**기본 순서 위에 덧붙는 규칙**
|
**기본 순서 위에 덧붙는 규칙**
|
||||||
1. **특보가 있으면** 맨 위(히어로 바로 아래), 그다음 오늘·내일 날씨. 특보가 없으면 날씨가 맨 위.
|
1. **특보가 있으면** 맨 위(히어로 바로 아래), 그다음 오늘·내일 날씨. 특보가 없으면 날씨가 맨 위.
|
||||||
2. **금요일 저녁**엔 주말 예보를 노을 바로 다음(2번째)으로 올린다.
|
2. **금요일 저녁**엔 주말 예보를 노을 바로 다음(2번째)으로 올린다.
|
||||||
3. **저녁에 해가 진 뒤**엔 노을 카드가 내일 노을로 바뀌고, 맨 위에서 세 번째로 내려간다.
|
3. **저녁에 해가 진 뒤**엔 노을 카드가 맨 위에서 세 번째로 내려가고, 블루아워가 끝나면 내일 일출 카드로 바뀐다.
|
||||||
4. **밤**엔 한 문장을 맨 끝으로.
|
4. **밤**엔 한 문장을 맨 끝으로.
|
||||||
5. **같은 종류가 붙으면** 뒤에서 다른 종류를 당겨 끼운다(각·각·각이 연달아 나오지 않게).
|
5. **같은 종류가 붙으면** 뒤에서 다른 종류를 당겨 끼운다(각·각·각이 연달아 나오지 않게).
|
||||||
6. **행사 카드(최대 3장)**는 위 순서와 따로, "날짜+구"를 씨앗으로 고른 자리에 끼운다. 같은 날 같은 구는 시간대가 바뀌어도 늘 같은 몇 번째 자리에 들어간다.
|
6. **행사 카드(최대 3장)**는 위 순서와 따로, "날짜+구"를 씨앗으로 고른 자리에 끼운다. 같은 날 같은 구는 시간대가 바뀌어도 늘 같은 몇 번째 자리에 들어간다.
|
||||||
@@ -104,13 +107,13 @@
|
|||||||
- 각 점수와 순위 자체는 새 예보·미세먼지가 들어올 때 다시 계산되므로(하루 8번 예보 + 매시 미세먼지), 그때 캐시가 끝나면 1·2·3위가 바뀔 수 있다.
|
- 각 점수와 순위 자체는 새 예보·미세먼지가 들어올 때 다시 계산되므로(하루 8번 예보 + 매시 미세먼지), 그때 캐시가 끝나면 1·2·3위가 바뀔 수 있다.
|
||||||
|
|
||||||
**히어로·띠의 순서**
|
**히어로·띠의 순서**
|
||||||
- 오늘의 각 줄(27개)과 띠의 각 순위(5개): 오늘 점수 높은 순.
|
- 오늘의 각 줄(34개): 지금 구간(아침·낮·저녁·밤) 점수 높은 순. 각 시간대가 지금 구간과 안 겹치는 각은 맨 뒤에 '지금 아님'으로.
|
||||||
- 히어로 1위 각: 오늘 점수 1위.
|
- 띠의 각 순위(5개)·피드 각 카드 1~3위·히어로 1위 각: 지금 구간에 해당하는 각만, 지금 구간 점수 순.
|
||||||
- 띠의 행사: 30km 안 행사 중 시작일이 오늘과 가까운 순(같으면 가까운 거리 순) 4개. 계절 소식: 이번 주 글.
|
- 띠의 행사: 30km 안 행사 중 시작일이 오늘과 가까운 순(같으면 가까운 거리 순) 4개. 계절 소식: 이번 주 글.
|
||||||
|
|
||||||
### 같이 만드는 것
|
### 같이 만드는 것
|
||||||
- 히어로: 지금 기온·체감, 불쾌지수, 날씨 점수, 1위 각, 말풍선, 오늘 밤 달 모양·밝기
|
- 히어로: 지금 날씨 점수, 아래 네 칸(지금 기온·습도·불쾌지수·챙길 것 한 칸), 1위 각, 말풍선, 오늘 밤 달 모양·잘 보이는지
|
||||||
- 오늘의 각 줄: 27개 이름·점수·순위
|
- 오늘의 각 줄: 34개 이름·점수·순위 (지금 구간에 안 맞는 각은 '지금 아님')
|
||||||
- 띠: 행사 4개, 각 순위 5개, 계절 소식
|
- 띠: 행사 4개, 각 순위 5개, 계절 소식
|
||||||
|
|
||||||
## 3. 저장과 갱신
|
## 3. 저장과 갱신
|
||||||
@@ -119,7 +122,7 @@
|
|||||||
- 키: `feed:{구 코드}:{시간대}` (예: `feed:4113500000:morning`)
|
- 키: `feed:{구 코드}:{시간대}` (예: `feed:4113500000:morning`)
|
||||||
- DB에는 완성본을 저장하지 않는다. Redis가 비어도 DB의 틀과 재료로 다시 만든다.
|
- DB에는 완성본을 저장하지 않는다. Redis가 비어도 DB의 틀과 재료로 다시 만든다.
|
||||||
- **얼마나 두나**: 다음에 내용이 바뀌는 시각까지, 최대 1시간.
|
- **얼마나 두나**: 다음에 내용이 바뀌는 시각까지, 최대 1시간.
|
||||||
바뀌는 시각 = 03:00, 05시, 11시, 일몰 2시간 전, 일몰, 21시, 다음 단기예보 제공 시각, 매시 20분(미세먼지)
|
바뀌는 시각 = 03:00, 05시, 11시, 일몰 2시간 전, 일몰, 일몰 1시간 뒤, 다음 단기예보 제공 시각, 매시 20분(미세먼지)
|
||||||
- **재료 중 하나라도 못 가져왔으면 60초**만 둔다. 다음 요청이 다시 채우게 하려고.
|
- **재료 중 하나라도 못 가져왔으면 60초**만 둔다. 다음 요청이 다시 채우게 하려고.
|
||||||
|
|
||||||
### 언제 새로 만들어지나
|
### 언제 새로 만들어지나
|
||||||
@@ -136,6 +139,6 @@
|
|||||||
|
|
||||||
## 4. 알아 둘 점
|
## 4. 알아 둘 점
|
||||||
|
|
||||||
- **좋아요·댓글은 전국이 같은 글에 쌓인다.** 글 번호가 전국 공통이라, 분당구의 "각 1위(환기각)"와 마포구의 "각 1위(야장각)"가 같은 글 번호를 쓴다.
|
- **좋아요·댓글은 같은 시도끼리 같은 글에 쌓인다.** 지역 카드는 시도마다 글 번호가 따로라, 강남구와 마포구의 "각 1위"는 같은 글 번호(서울)를, 부산 구는 다른 글 번호를 쓴다. 계절 소식·날씨 상식·한 문장·달은 전국이 같은 글 번호.
|
||||||
- **공유 링크(`/v1/feed/post/{id}`)는 지금 그 구의 피드에서 글을 찾는다.** 어제 글이나 지금 꺼진 글은 "없는 글"이 된다. 공유한 글을 다시 보여줄 계획이 생기면 그때 공유한 글만 따로 저장한다.
|
- **공유 링크(`/v1/feed/post/{id}`)는 지금 그 구의 피드에서 글을 찾는다.** 어제 글이나 지금 꺼진 글은 "없는 글"이 된다. 공유한 글을 다시 보여줄 계획이 생기면 그때 공유한 글만 따로 저장한다.
|
||||||
- **아무도 안 여는 구는 만들지 않는다.** 외부 API 호출도 그 구를 누가 열 때만 일어난다.
|
- **아무도 안 여는 구는 만들지 않는다.** 외부 API 호출도 그 구를 누가 열 때만 일어난다.
|
||||||
+86
-6
@@ -1,21 +1,87 @@
|
|||||||
<!doctype html>
|
<!doctype html>
|
||||||
<html lang="ko">
|
<html lang="ko">
|
||||||
<head>
|
<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" />
|
<meta charset="UTF-8" />
|
||||||
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
|
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
|
||||||
<link rel="apple-touch-icon" href="/apple-touch-icon.png" />
|
<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="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1, user-scalable=no, viewport-fit=cover" />
|
||||||
<meta name="description" content="오늘 날씨를 지수로. 노을, 야장각, 주말 계획까지 날씨각에서 확인하세요." />
|
<meta name="theme-color" content="#d6ebff" />
|
||||||
<title>날씨각</title>
|
<meta name="description" content="세차각·빨래각·러닝각처럼 오늘 날씨에 맞는 일을 점수로. 노을이 예쁜 시간과 명소, 이번 주말 가까운 축제까지 날씨각에서 확인하세요." />
|
||||||
|
<meta name="keywords" content="날씨각, 오늘 날씨, 날씨 지수, 세차하기 좋은 날, 빨래하기 좋은 날, 러닝하기 좋은 날씨, 오늘 노을, 노을 시간, 일몰 시간, 노을 명소, 주말 날씨, 주말 나들이, 이번 주말 축제, 미세먼지, 오늘 밤 달" />
|
||||||
|
<title>날씨각 · 오늘 날씨 지수, 노을, 주말 행사</title>
|
||||||
|
<link rel="manifest" href="/manifest.webmanifest" />
|
||||||
<meta property="og:type" content="website" />
|
<meta property="og:type" content="website" />
|
||||||
<meta property="og:site_name" content="날씨각" />
|
<meta property="og:site_name" content="날씨각" />
|
||||||
<meta property="og:title" content="날씨각" />
|
<meta property="og:title" content="날씨각 · 오늘 날씨 지수, 노을, 주말 행사" />
|
||||||
<meta property="og:description" content="오늘 날씨를 지수로. 노을, 야장각, 주말 계획까지 날씨각에서 확인하세요." />
|
<meta property="og:description" content="세차각·빨래각·러닝각처럼 오늘 날씨에 맞는 일을 점수로. 노을이 예쁜 시간과 명소, 이번 주말 가까운 축제까지 날씨각에서 확인하세요." />
|
||||||
<meta property="og:url" content="%VITE_SITE_URL%/" />
|
<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" content="%VITE_SITE_URL%/og.png" />
|
||||||
<meta property="og:image:width" content="1200" />
|
<meta property="og:image:width" content="1200" />
|
||||||
<meta property="og:image:height" content="630" />
|
<meta property="og:image:height" content="630" />
|
||||||
|
<meta property="og:image:alt" content="날씨각, 오늘 날씨에 맞는 일을 점수로 알려 주는 서비스" />
|
||||||
<meta name="twitter:card" content="summary_large_image" />
|
<meta name="twitter:card" content="summary_large_image" />
|
||||||
|
<meta name="twitter:title" content="날씨각 · 오늘 날씨 지수, 노을, 주말 행사" />
|
||||||
|
<meta name="twitter:description" content="세차각·빨래각·러닝각처럼 오늘 날씨에 맞는 일을 점수로. 노을이 예쁜 시간과 명소, 이번 주말 가까운 축제까지 날씨각에서 확인하세요." />
|
||||||
|
<meta name="twitter:image" content="%VITE_SITE_URL%/og.png" />
|
||||||
|
<meta property="og:locale" content="ko_KR" />
|
||||||
|
<meta name="google-site-verification" content="ageFc5cYyqCTlRxsQTu4d3uetA4WG7y7yUPR1f7muVk" />
|
||||||
|
<meta name="naver-site-verification" content="9b97570f87046a31676e01747caf3f527b39ec6d" />
|
||||||
|
<script type="application/ld+json">
|
||||||
|
{
|
||||||
|
"@context": "https://schema.org",
|
||||||
|
"@graph": [
|
||||||
|
{
|
||||||
|
"@type": "WebSite",
|
||||||
|
"@id": "%VITE_SITE_URL%/#website",
|
||||||
|
"name": "날씨각",
|
||||||
|
"url": "%VITE_SITE_URL%/",
|
||||||
|
"inLanguage": "ko-KR",
|
||||||
|
"publisher": { "@id": "%VITE_SITE_URL%/#organization" }
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"@type": "Organization",
|
||||||
|
"@id": "%VITE_SITE_URL%/#organization",
|
||||||
|
"name": "날씨각",
|
||||||
|
"url": "%VITE_SITE_URL%/",
|
||||||
|
"logo": "%VITE_SITE_URL%/apple-touch-icon.png"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"@type": "WebApplication",
|
||||||
|
"name": "날씨각",
|
||||||
|
"url": "%VITE_SITE_URL%/",
|
||||||
|
"description": "세차각·빨래각·러닝각처럼 오늘 날씨에 맞는 일을 점수로. 노을이 예쁜 시간과 명소, 이번 주말 가까운 축제까지 날씨각에서 확인하세요.",
|
||||||
|
"applicationCategory": "WeatherApplication",
|
||||||
|
"operatingSystem": "All",
|
||||||
|
"inLanguage": "ko-KR",
|
||||||
|
"image": "%VITE_SITE_URL%/og.png",
|
||||||
|
"offers": { "@type": "Offer", "price": "0", "priceCurrency": "KRW" },
|
||||||
|
"publisher": { "@id": "%VITE_SITE_URL%/#organization" }
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"@type": "FAQPage",
|
||||||
|
"mainEntity": [
|
||||||
|
{ "@type": "Question", "name": "날씨각은 어떤 서비스인가요?", "acceptedAnswer": { "@type": "Answer", "text": "우리 동네 날씨로 세차, 빨래, 러닝 같은 일을 하기 좋은지 점수로 알려 주는 서비스예요. 오늘 노을이 예쁜 시간과 이번 주말 행사도 함께 볼 수 있어요." } },
|
||||||
|
{ "@type": "Question", "name": "세차하기 좋은 날은 어떻게 알 수 있나요?", "acceptedAnswer": { "@type": "Answer", "text": "세차각 점수를 보면 돼요. 오늘뿐 아니라 이틀 뒤까지 비 소식을 함께 봐서, 세차하고 곧 비가 오는 날은 점수가 낮아요." } },
|
||||||
|
{ "@type": "Question", "name": "빨래가 잘 마르는 날은 언제인가요?", "acceptedAnswer": { "@type": "Answer", "text": "빨래각 점수를 보면 돼요. 비가 안 오고, 따뜻하고, 바람이 적당히 불고, 덜 습할수록 점수가 높아요." } },
|
||||||
|
{ "@type": "Question", "name": "러닝하기 좋은 시간은 언제인가요?", "acceptedAnswer": { "@type": "Answer", "text": "러닝각은 아침 6~8시와 저녁 7~10시 날씨로 계산해요. 선선하고 비와 바람이 적을수록 점수가 높아요." } },
|
||||||
|
{ "@type": "Question", "name": "오늘 노을은 몇 시에 가장 예쁜가요?", "acceptedAnswer": { "@type": "Answer", "text": "노을 탭에서 우리 동네 노을이 가장 붉은 시각을 알려 드려요. 보통 해 지고 10~20분 뒤예요. 오늘 노을이 얼마나 물들지와 가까운 노을 명소도 함께 볼 수 있어요." } },
|
||||||
|
{ "@type": "Question", "name": "이번 주말 가 볼 만한 축제는 어디서 보나요?", "acceptedAnswer": { "@type": "Answer", "text": "주말·행사 탭에서 가까운 축제, 전시, 공연, 팝업을 볼 수 있어요. 주말 날씨와 나들이하기 좋은 곳도 함께 알려 드려요." } },
|
||||||
|
{ "@type": "Question", "name": "날씨 정보는 얼마나 자주 바뀌나요?", "acceptedAnswer": { "@type": "Answer", "text": "기상청 예보가 나올 때마다 하루 8번, 미세먼지는 매시간 새로 반영해요." } }
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
</script>
|
||||||
<link rel="preconnect" href="https://fonts.googleapis.com" />
|
<link rel="preconnect" href="https://fonts.googleapis.com" />
|
||||||
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
|
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
|
||||||
<link
|
<link
|
||||||
@@ -30,7 +96,21 @@
|
|||||||
/>
|
/>
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<div id="root"></div>
|
<div id="root">
|
||||||
|
<main>
|
||||||
|
<h1>날씨각</h1>
|
||||||
|
<p>오늘 하고 싶은 일이 날씨에 맞는지 점수로 알려 드려요. 세차, 빨래, 러닝, 피크닉처럼 일상의 일을 우리 동네 날씨로 바로 확인하세요.</p>
|
||||||
|
<h2><a href="/gak">오늘의 각</a></h2>
|
||||||
|
<p>세차각, 빨래각, 러닝각 등 34가지 일을 지금 동네 날씨로 점수 매겨요. 아침, 낮, 저녁, 밤마다 따로 알려 드려요.</p>
|
||||||
|
<h2><a href="/sky">노을</a></h2>
|
||||||
|
<p>오늘 노을이 얼마나 붉게 물들지, 몇 시에 가장 붉은지, 가까운 노을 명소는 어디인지 알려 드려요. 사흘 치를 미리 볼 수 있어요.</p>
|
||||||
|
<h2><a href="/week">주말·행사</a></h2>
|
||||||
|
<p>이번 주말 날씨와 나들이하기 좋은 곳, 가까운 축제와 전시, 공연을 모아 드려요.</p>
|
||||||
|
<h2><a href="/season">계절·상식</a></h2>
|
||||||
|
<p>지금 계절에 볼 만한 소식과 알아 두면 좋은 날씨 상식을 읽을 수 있어요.</p>
|
||||||
|
<p>기상청 예보와 에어코리아 미세먼지 정보로 매일 새로 계산해요.</p>
|
||||||
|
</main>
|
||||||
|
</div>
|
||||||
<script type="module" src="/src/main.tsx"></script>
|
<script type="module" src="/src/main.tsx"></script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
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,14 @@
|
|||||||
|
{
|
||||||
|
"name": "날씨각",
|
||||||
|
"short_name": "날씨각",
|
||||||
|
"description": "오늘 날씨에 맞는 일을 점수로. 노을이 예쁜 시간과 이번 주말 가까운 축제까지.",
|
||||||
|
"lang": "ko-KR",
|
||||||
|
"start_url": "/",
|
||||||
|
"display": "standalone",
|
||||||
|
"background_color": "#d6ebff",
|
||||||
|
"theme_color": "#d6ebff",
|
||||||
|
"icons": [
|
||||||
|
{ "src": "/favicon.svg", "sizes": "any", "type": "image/svg+xml" },
|
||||||
|
{ "src": "/apple-touch-icon.png", "sizes": "180x180", "type": "image/png" }
|
||||||
|
]
|
||||||
|
}
|
||||||
@@ -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>
|
||||||
@@ -150,7 +150,7 @@ export const getSkyRankingOptions = (options?: Options<GetSkyRankingData>) => qu
|
|||||||
export const listIndicesQueryKey = (options: Options<ListIndicesData>) => createQueryKey('listIndices', options);
|
export const listIndicesQueryKey = (options: Options<ListIndicesData>) => createQueryKey('listIndices', options);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 지수 목록 (점수순, 1~3위, 오늘 날씨 점수)
|
* 지수 목록 (지금 구간 점수순, 1~3위, 지금 날씨 점수)
|
||||||
*/
|
*/
|
||||||
export const listIndicesOptions = (options: Options<ListIndicesData>) => queryOptions<ListIndicesResponse, ListIndicesError, ListIndicesResponse, ReturnType<typeof listIndicesQueryKey>>({
|
export const listIndicesOptions = (options: Options<ListIndicesData>) => queryOptions<ListIndicesResponse, ListIndicesError, ListIndicesResponse, ReturnType<typeof listIndicesQueryKey>>({
|
||||||
queryFn: async ({ queryKey, signal }) => {
|
queryFn: async ({ queryKey, signal }) => {
|
||||||
@@ -222,7 +222,7 @@ export const getWeekRankingOptions = (options?: Options<GetWeekRankingData>) =>
|
|||||||
export const listPlacesQueryKey = (options: Options<ListPlacesData>) => createQueryKey('listPlaces', options);
|
export const listPlacesQueryKey = (options: Options<ListPlacesData>) => createQueryKey('listPlaces', options);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 날씨 맞춤 데이트 명소
|
* 날씨 맞춤 데이트 명소 (구 중심 30km 안, 없으면 가장 가까운 곳)
|
||||||
*/
|
*/
|
||||||
export const listPlacesOptions = (options: Options<ListPlacesData>) => queryOptions<ListPlacesResponse, ListPlacesError, ListPlacesResponse, ReturnType<typeof listPlacesQueryKey>>({
|
export const listPlacesOptions = (options: Options<ListPlacesData>) => queryOptions<ListPlacesResponse, ListPlacesError, ListPlacesResponse, ReturnType<typeof listPlacesQueryKey>>({
|
||||||
queryFn: async ({ queryKey, signal }) => {
|
queryFn: async ({ queryKey, signal }) => {
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
// This file is auto-generated by @hey-api/openapi-ts
|
// This file is auto-generated by @hey-api/openapi-ts
|
||||||
|
|
||||||
export { addComment, deleteComment, getArticle, getFeed, getImage, getIndex, getPost, getSeasonWeek, getSky, getSkyRanking, getWatchSummary, getWeatherNow, getWeatherToday, getWeek, getWeekRanking, healthzHealthzGet, likeComment, likePost, listArticles, listComments, listEvents, listIndices, listPlaces, listRegions, listSaved, login, logout, me, nearestRegion, type Options, refresh, savePost, signup, unlikeComment, unlikePost, unsavePost, updateMe } from './sdk.gen';
|
export { addComment, deleteComment, getArticle, getFeed, getImage, getIndex, getPost, getSeasonWeek, getSky, getSkyRanking, getWatchSummary, getWeatherNow, getWeatherToday, getWeek, getWeekRanking, healthzHealthzGet, likeComment, likePost, listArticles, listComments, listEvents, listIndices, listPlaces, listRegions, listSaved, login, logout, me, nearestRegion, type Options, refresh, savePost, signup, unlikeComment, unlikePost, unsavePost, updateMe } from './sdk.gen';
|
||||||
export { type AddCommentData, type AddCommentError, type AddCommentErrors, type AddCommentResponse, type AddCommentResponses, type AirData, AirGrade, ArticleCategory, type ArticleSummary, AuthProvider, type BandArticle, type BandEvent, type Bands, type BestTime, type ClientOptions, type CommentData, type CommuteData, Confidence, type Cut, type DayData, type DeleteCommentData, type DeleteCommentError, type DeleteCommentErrors, type DeleteCommentResponse, type DeleteCommentResponses, type ErrorInfo, type EventData, type Factor, type GakSlide, type GetArticleData, type GetArticleError, type GetArticleErrors, type GetArticleResponse, type GetArticleResponses, type GetFeedData, type GetFeedError, type GetFeedErrors, type GetFeedResponse, type GetFeedResponses, type GetImageData, type GetImageError, type GetImageErrors, type GetImageResponses, type GetIndexData, type GetIndexError, type GetIndexErrors, type GetIndexResponse, type GetIndexResponses, type GetPostData, type GetPostError, type GetPostErrors, type GetPostResponse, type GetPostResponses, type GetSeasonWeekData, type GetSeasonWeekResponse, type GetSeasonWeekResponses, type GetSkyData, type GetSkyError, type GetSkyErrors, type GetSkyRankingData, type GetSkyRankingResponse, type GetSkyRankingResponses, type GetSkyResponse, type GetSkyResponses, type GetWatchSummaryData, type GetWatchSummaryError, type GetWatchSummaryErrors, type GetWatchSummaryResponse, type GetWatchSummaryResponses, type GetWeatherNowData, type GetWeatherNowError, type GetWeatherNowErrors, type GetWeatherNowResponse, type GetWeatherNowResponses, type GetWeatherTodayData, type GetWeatherTodayError, type GetWeatherTodayErrors, type GetWeatherTodayResponse, type GetWeatherTodayResponses, type GetWeekData, type GetWeekError, type GetWeekErrors, type GetWeekRankingData, type GetWeekRankingResponse, type GetWeekRankingResponses, type GetWeekResponse, type GetWeekResponses, type HealthzHealthzGetData, type HealthzHealthzGetResponse, type HealthzHealthzGetResponses, type Hero, type HeroStat, type HourCell, type HoursSlide, type HttpValidationError, IndexCategory, type IndexSummary, type LikeCommentData, type LikeCommentError, type LikeCommentErrors, type LikeCommentResponse, type LikeCommentResponses, type LikePostData, type LikePostError, type LikePostErrors, type LikePostResponse, type LikePostResponses, type ListArticlesData, type ListArticlesError, type ListArticlesErrors, type ListArticlesResponse, type ListArticlesResponses, type ListCommentsData, type ListCommentsError, type ListCommentsErrors, type ListCommentsResponse, type ListCommentsResponses, type ListEventsData, type ListEventsError, type ListEventsErrors, type ListEventsResponse, type ListEventsResponses, type ListIndicesData, type ListIndicesError, type ListIndicesErrors, type ListIndicesResponse, type ListIndicesResponses, type ListPlacesData, type ListPlacesError, type ListPlacesErrors, type ListPlacesResponse, type ListPlacesResponses, type ListRegionsData, type ListRegionsError, type ListRegionsErrors, type ListRegionsResponse, type ListRegionsResponses, type ListSavedData, type ListSavedError, type ListSavedErrors, type ListSavedResponse, type ListSavedResponses, type LoginData, type LoginError, type LoginErrors, type LoginResponse, type LoginResponses, type LogoutData, type LogoutError, type LogoutErrors, type LogoutResponse, type LogoutResponses, type Me, type MeData, type MeError, type MeErrors, type MeResponse, type MeResponses, type NearestRegionData, type NearestRegionError, type NearestRegionErrors, type NearestRegionResponse, type NearestRegionResponses, type PlaceData, type PlanSlide, type PlanSpot, type PlanStep, type PostData, PostType, type Rain2h, type RainHourData, RainType, type RankData, type RefreshData, type RefreshError, type RefreshErrors, type RefreshResponse, type RefreshResponses, type RegionData, type ReqComment, type ReqLogin, type ReqRefresh, type ReqSignup, type ReqUpdateMe, type ResArticle, type ResArticleList, type ResAuth, type ResComment, type ResCommentLike, type ResCommentList, type ResEventList, type ResFeed, type ResHealth, type ResIndexDetail, type ResIndexList, type ResLogout, type ResMe, type ResPlaceList, type ResPost, type ResPostLike, type ResPostSave, type ResRegion, type ResRegionList, type ResSavedList, type ResSeasonWeek, type ResSky, type ResSkyRanking, type ResWatchSummary, type ResWeatherNow, type ResWeatherToday, type ResWebPacketProtocol, type ResWeek, type ResWeekRanking, type Row, type RowsSlide, type SavedPost, type SavePostData, type SavePostError, type SavePostErrors, type SavePostResponse, type SavePostResponses, type ScoreBand, type SignupData, type SignupError, type SignupErrors, type SignupResponse, type SignupResponses, Sky, SkyGrade, type SkyPlanData, type SkyScoreData, SkySituation, SkyType, SlotTone, type SpotData, type SunsetSlide, type TermData, type Tomorrow, type TopIndex, type TrendPoint, type UnlikeCommentData, type UnlikeCommentError, type UnlikeCommentErLine truncated
|
export { type AddCommentData, type AddCommentError, type AddCommentErrors, type AddCommentResponse, type AddCommentResponses, type AirData, AirGrade, ArticleCategory, type ArticleSummary, AuthProvider, type BandArticle, type BandEvent, type Bands, type BestTime, type ClientOptions, type CommentData, type CommuteData, Confidence, type Cut, type DayData, type DeleteCommentData, type DeleteCommentError, type DeleteCommentErrors, type DeleteCommentResponse, type DeleteCommentResponses, type ErrorInfo, type EventData, type Factor, type GakSlide, type GetArticleData, type GetArticleError, type GetArticleErrors, type GetArticleResponse, type GetArticleResponses, type GetFeedData, type GetFeedError, type GetFeedErrors, type GetFeedResponse, type GetFeedResponses, type GetImageData, type GetImageError, type GetImageErrors, type GetImageResponses, type GetIndexData, type GetIndexError, type GetIndexErrors, type GetIndexResponse, type GetIndexResponses, type GetPostData, type GetPostError, type GetPostErrors, type GetPostResponse, type GetPostResponses, type GetSeasonWeekData, type GetSeasonWeekResponse, type GetSeasonWeekResponses, type GetSkyData, type GetSkyError, type GetSkyErrors, type GetSkyRankingData, type GetSkyRankingResponse, type GetSkyRankingResponses, type GetSkyResponse, type GetSkyResponses, type GetWatchSummaryData, type GetWatchSummaryError, type GetWatchSummaryErrors, type GetWatchSummaryResponse, type GetWatchSummaryResponses, type GetWeatherNowData, type GetWeatherNowError, type GetWeatherNowErrors, type GetWeatherNowResponse, type GetWeatherNowResponses, type GetWeatherTodayData, type GetWeatherTodayError, type GetWeatherTodayErrors, type GetWeatherTodayResponse, type GetWeatherTodayResponses, type GetWeekData, type GetWeekError, type GetWeekErrors, type GetWeekRankingData, type GetWeekRankingResponse, type GetWeekRankingResponses, type GetWeekResponse, type GetWeekResponses, type HealthzHealthzGetData, type HealthzHealthzGetResponse, type HealthzHealthzGetResponses, type Hero, type HeroStat, type HourCell, type HoursSlide, type HttpValidationError, IndexCategory, type IndexSummary, type LikeCommentData, type LikeCommentError, type LikeCommentErrors, type LikeCommentResponse, type LikeCommentResponses, type LikePostData, type LikePostError, type LikePostErrors, type LikePostResponse, type LikePostResponses, type ListArticlesData, type ListArticlesError, type ListArticlesErrors, type ListArticlesResponse, type ListArticlesResponses, type ListCommentsData, type ListCommentsError, type ListCommentsErrors, type ListCommentsResponse, type ListCommentsResponses, type ListEventsData, type ListEventsError, type ListEventsErrors, type ListEventsResponse, type ListEventsResponses, type ListIndicesData, type ListIndicesError, type ListIndicesErrors, type ListIndicesResponse, type ListIndicesResponses, type ListPlacesData, type ListPlacesError, type ListPlacesErrors, type ListPlacesResponse, type ListPlacesResponses, type ListRegionsData, type ListRegionsError, type ListRegionsErrors, type ListRegionsResponse, type ListRegionsResponses, type ListSavedData, type ListSavedError, type ListSavedErrors, type ListSavedResponse, type ListSavedResponses, type LoginData, type LoginError, type LoginErrors, type LoginResponse, type LoginResponses, type LogoutData, type LogoutError, type LogoutErrors, type LogoutResponse, type LogoutResponses, type Me, type MeData, type MeError, type MeErrors, type MeResponse, type MeResponses, type NearestRegionData, type NearestRegionError, type NearestRegionErrors, type NearestRegionResponse, type NearestRegionResponses, type PlaceData, type PlanSlide, type PlanSpot, type PlanStep, type PostData, PostType, type Rain2h, type RainHourData, RainType, type RankData, type RefreshData, type RefreshError, type RefreshErrors, type RefreshResponse, type RefreshResponses, type RegionData, type ReqComment, type ReqLogin, type ReqRefresh, type ReqSignup, type ReqUpdateMe, type ResArticle, type ResArticleList, type ResAuth, type ResComment, type ResCommentLike, type ResCommentList, type ResEventList, type ResFeed, type ResHealth, type ResIndexDetail, type ResIndexList, type ResLogout, type ResMe, type ResPlaceList, type ResPost, type ResPostLike, type ResPostSave, type ResRegion, type ResRegionList, type ResSavedList, type ResSeasonWeek, type ResSky, type ResSkyRanking, type ResWatchSummary, type ResWeatherNow, type ResWeatherToday, type ResWebPacketProtocol, type ResWeek, type ResWeekRanking, type Row, type RowsSlide, type SavedPost, type SavePostData, type SavePostError, type SavePostErrors, type SavePostResponse, type SavePostResponses, type ScoreBand, type SignupData, type SignupError, type SignupErrors, type SignupResponse, type SignupResponses, Sky, SkyGrade, type SkyPlanData, type SkyScoreData, SkySituation, SkyType, type SlotPoint, SlotTone, type SpotData, type SunsetSlide, type TermData, type Tomorrow, type TopIndex, type TrendPoint, type UnlikeCommentData, type UnlikeCommentError, typeLine truncated
|
||||||
@@ -49,7 +49,7 @@ export const getSky = <ThrowOnError extends boolean = true>(options: Options<Get
|
|||||||
export const getSkyRanking = <ThrowOnError extends boolean = true>(options?: Options<GetSkyRankingData, ThrowOnError>): RequestResult<GetSkyRankingResponses, unknown, ThrowOnError> => (options?.client ?? client).get<GetSkyRankingResponses, unknown, ThrowOnError>({ url: '/v1/sky/ranking', ...options });
|
export const getSkyRanking = <ThrowOnError extends boolean = true>(options?: Options<GetSkyRankingData, ThrowOnError>): RequestResult<GetSkyRankingResponses, unknown, ThrowOnError> => (options?.client ?? client).get<GetSkyRankingResponses, unknown, ThrowOnError>({ url: '/v1/sky/ranking', ...options });
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 지수 목록 (점수순, 1~3위, 오늘 날씨 점수)
|
* 지수 목록 (지금 구간 점수순, 1~3위, 지금 날씨 점수)
|
||||||
*/
|
*/
|
||||||
export const listIndices = <ThrowOnError extends boolean = true>(options: Options<ListIndicesData, ThrowOnError>): RequestResult<ListIndicesResponses, ListIndicesErrors, ThrowOnError> => (options.client ?? client).get<ListIndicesResponses, ListIndicesErrors, ThrowOnError>({ url: '/v1/index/list', ...options });
|
export const listIndices = <ThrowOnError extends boolean = true>(options: Options<ListIndicesData, ThrowOnError>): RequestResult<ListIndicesResponses, ListIndicesErrors, ThrowOnError> => (options.client ?? client).get<ListIndicesResponses, ListIndicesErrors, ThrowOnError>({ url: '/v1/index/list', ...options });
|
||||||
|
|
||||||
@@ -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 });
|
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 });
|
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 });
|
||||||
|
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
// This file is auto-generated by @hey-api/openapi-ts
|
// This file is auto-generated by @hey-api/openapi-ts
|
||||||
|
|
||||||
export type ClientOptions = {
|
export type ClientOptions = {
|
||||||
baseUrl: `${string}://openapi.gen.json` | (string & {});
|
baseUrl: `${string}://${string}` | (string & {});
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -110,6 +110,14 @@ export type ArticleSummary = {
|
|||||||
* Icon
|
* Icon
|
||||||
*/
|
*/
|
||||||
icon: string;
|
icon: string;
|
||||||
|
/**
|
||||||
|
* Image
|
||||||
|
*/
|
||||||
|
image?: string | null;
|
||||||
|
/**
|
||||||
|
* Image Credit
|
||||||
|
*/
|
||||||
|
image_credit?: string | null;
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -148,6 +156,14 @@ export type BandArticle = {
|
|||||||
* Icon
|
* Icon
|
||||||
*/
|
*/
|
||||||
icon: string;
|
icon: string;
|
||||||
|
/**
|
||||||
|
* Image
|
||||||
|
*/
|
||||||
|
image?: string | null;
|
||||||
|
/**
|
||||||
|
* Image Credit
|
||||||
|
*/
|
||||||
|
image_credit?: string | null;
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -214,6 +230,12 @@ export type BestTime = {
|
|||||||
* Label
|
* Label
|
||||||
*/
|
*/
|
||||||
label: string;
|
label: string;
|
||||||
|
/**
|
||||||
|
* End
|
||||||
|
*
|
||||||
|
* 구간이면 끝 시각 (골든아워·블루아워)
|
||||||
|
*/
|
||||||
|
end?: string | null;
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -545,8 +567,16 @@ export type Hero = {
|
|||||||
* Feels C
|
* Feels C
|
||||||
*/
|
*/
|
||||||
feels_c?: number | null;
|
feels_c?: number | null;
|
||||||
|
/**
|
||||||
|
* Humidity
|
||||||
|
*
|
||||||
|
* 지금 습도 %. 히어로에 늘 보인다
|
||||||
|
*/
|
||||||
|
humidity?: number | null;
|
||||||
/**
|
/**
|
||||||
* Discomfort
|
* Discomfort
|
||||||
|
*
|
||||||
|
* 지금 불쾌지수. 히어로에 늘 보인다
|
||||||
*/
|
*/
|
||||||
discomfort?: number | null;
|
discomfort?: number | null;
|
||||||
/**
|
/**
|
||||||
@@ -565,6 +595,14 @@ export type Hero = {
|
|||||||
* Weather Score
|
* Weather Score
|
||||||
*/
|
*/
|
||||||
weather_score?: number | null;
|
weather_score?: number | null;
|
||||||
|
/**
|
||||||
|
* Weather Slots
|
||||||
|
*
|
||||||
|
* 오늘 구간별 날씨 점수 {morning·day·evening·night: 점수}
|
||||||
|
*/
|
||||||
|
weather_slots?: {
|
||||||
|
[key: string]: number;
|
||||||
|
};
|
||||||
top1?: TopIndex | null;
|
top1?: TopIndex | null;
|
||||||
/**
|
/**
|
||||||
* Bubble
|
* Bubble
|
||||||
@@ -579,15 +617,21 @@ export type Hero = {
|
|||||||
/**
|
/**
|
||||||
* Moon Pct
|
* Moon Pct
|
||||||
*
|
*
|
||||||
* 달이 밝게 보이는 비율 0~100
|
* 달에서 빛나는 면의 비율 0~100 (모양 그림용, 밝기 아님)
|
||||||
*/
|
*/
|
||||||
moon_pct?: number | null;
|
moon_pct?: number | null;
|
||||||
/**
|
/**
|
||||||
* Stats
|
* Stats
|
||||||
*
|
*
|
||||||
* 히어로 두 칸. 지금 챙길 것(비·미세먼지·자외선·일교차·체감·불쾌지수) 먼저
|
* 히어로 상황 칸 1개. 지금 챙길 것(비·미세먼지·자외선·일교차·체감) 먼저
|
||||||
*/
|
*/
|
||||||
stats?: Array<HeroStat>;
|
stats?: Array<HeroStat>;
|
||||||
|
/**
|
||||||
|
* Status
|
||||||
|
*
|
||||||
|
* 히어로 상태 한 줄: 습도·불쾌지수·자외선(낮에만)·미세먼지 단계 이름. tone=warn 이면 조심(앱이 주황 글자로)
|
||||||
|
*/
|
||||||
|
status?: Array<HeroStat>;
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -727,6 +771,24 @@ export type IndexSummary = {
|
|||||||
* Trend
|
* Trend
|
||||||
*/
|
*/
|
||||||
trend?: Array<TrendPoint>;
|
trend?: Array<TrendPoint>;
|
||||||
|
/**
|
||||||
|
* Active
|
||||||
|
*
|
||||||
|
* 지금 구간이 이 각의 시간대와 겹침. false 면 순위 밖, score 는 하루 점수
|
||||||
|
*/
|
||||||
|
active?: boolean;
|
||||||
|
/**
|
||||||
|
* Slot
|
||||||
|
*
|
||||||
|
* score 가 어느 구간 점수인지 (지금 구간)
|
||||||
|
*/
|
||||||
|
slot?: string | null;
|
||||||
|
/**
|
||||||
|
* Slots
|
||||||
|
*
|
||||||
|
* 오늘 구간별 점수. 각 시간대와 안 겹치는 구간은 없음
|
||||||
|
*/
|
||||||
|
slots?: Array<SlotPoint>;
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -792,6 +854,18 @@ export type PlaceData = {
|
|||||||
* Is Good
|
* Is Good
|
||||||
*/
|
*/
|
||||||
is_good: boolean;
|
is_good: boolean;
|
||||||
|
/**
|
||||||
|
* Distance Km
|
||||||
|
*/
|
||||||
|
distance_km: number;
|
||||||
|
/**
|
||||||
|
* Image
|
||||||
|
*/
|
||||||
|
image?: string | null;
|
||||||
|
/**
|
||||||
|
* Image Credit
|
||||||
|
*/
|
||||||
|
image_credit?: string | null;
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -1412,6 +1486,8 @@ export type ResIndexList = {
|
|||||||
day?: string | null;
|
day?: string | null;
|
||||||
/**
|
/**
|
||||||
* Weather Score
|
* Weather Score
|
||||||
|
*
|
||||||
|
* 지금 날씨 점수 (지금 구간 기준)
|
||||||
*/
|
*/
|
||||||
weather_score?: number | null;
|
weather_score?: number | null;
|
||||||
/**
|
/**
|
||||||
@@ -1639,6 +1715,12 @@ export type ResSky = {
|
|||||||
*/
|
*/
|
||||||
spots?: Array<SpotData>;
|
spots?: Array<SpotData>;
|
||||||
plan?: SkyPlanData | null;
|
plan?: SkyPlanData | null;
|
||||||
|
/**
|
||||||
|
* Plans
|
||||||
|
*
|
||||||
|
* plan 과 같은 종류로 아직 안 끝난 날 최대 3일 (날짜 타일, 누르면 그날로)
|
||||||
|
*/
|
||||||
|
plans?: Array<SkyPlanData>;
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -1843,6 +1925,12 @@ export type Row = {
|
|||||||
* 위치가 정해진 장소면 지도에서 찾을 이름 (앱이 네이버 지도 링크를 건다)
|
* 위치가 정해진 장소면 지도에서 찾을 이름 (앱이 네이버 지도 링크를 건다)
|
||||||
*/
|
*/
|
||||||
place?: string | null;
|
place?: string | null;
|
||||||
|
/**
|
||||||
|
* Level
|
||||||
|
*
|
||||||
|
* 자외선 단계 1 낮음 ~ 5 위험. 있으면 앱이 값을 단계 색 칩으로 그린다
|
||||||
|
*/
|
||||||
|
level?: number | null;
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -1980,6 +2068,18 @@ export type SkyGrade = typeof SkyGrade[keyof typeof SkyGrade];
|
|||||||
* SkyPlanData
|
* SkyPlanData
|
||||||
*/
|
*/
|
||||||
export type SkyPlanData = {
|
export type SkyPlanData = {
|
||||||
|
/**
|
||||||
|
* Kind
|
||||||
|
*
|
||||||
|
* 다음에 오는 것: 해 뜨기 전·밤엔 일출, 그 사이엔 노을
|
||||||
|
*/
|
||||||
|
kind: 'sunset' | 'sunrise';
|
||||||
|
/**
|
||||||
|
* Title
|
||||||
|
*
|
||||||
|
* 하늘이 어떻게 보일지 한 문장 (오늘 노을은 물들긴 하는데 색이 흐릴 거예요). 히어로 제목
|
||||||
|
*/
|
||||||
|
title: string;
|
||||||
/**
|
/**
|
||||||
* Day
|
* Day
|
||||||
*/
|
*/
|
||||||
@@ -2126,6 +2226,28 @@ export const SkyType = { /**
|
|||||||
*/
|
*/
|
||||||
export type SkyType = typeof SkyType[keyof typeof SkyType];
|
export type SkyType = typeof SkyType[keyof typeof SkyType];
|
||||||
|
|
||||||
|
/**
|
||||||
|
* SlotPoint
|
||||||
|
*/
|
||||||
|
export type SlotPoint = {
|
||||||
|
/**
|
||||||
|
* Slot
|
||||||
|
*
|
||||||
|
* morning / day / evening / night
|
||||||
|
*/
|
||||||
|
slot: string;
|
||||||
|
/**
|
||||||
|
* Label
|
||||||
|
*
|
||||||
|
* 아침 / 낮 / 저녁 / 밤
|
||||||
|
*/
|
||||||
|
label: string;
|
||||||
|
/**
|
||||||
|
* Score
|
||||||
|
*/
|
||||||
|
score: number;
|
||||||
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* SlotTone
|
* SlotTone
|
||||||
*/
|
*/
|
||||||
@@ -2217,6 +2339,18 @@ export type SunsetSlide = {
|
|||||||
* 하늘 상황. 앱이 카드 하늘 색을 고른다
|
* 하늘 상황. 앱이 카드 하늘 색을 고른다
|
||||||
*/
|
*/
|
||||||
situation?: SkySituation | null;
|
situation?: SkySituation | null;
|
||||||
|
/**
|
||||||
|
* Headline
|
||||||
|
*
|
||||||
|
* 결론 (나가 볼 만해요 · 애매해요 · 쉬어요). 카드 맨 위에 크게
|
||||||
|
*/
|
||||||
|
headline?: string | null;
|
||||||
|
/**
|
||||||
|
* Peak At
|
||||||
|
*
|
||||||
|
* 가장 붉을 때
|
||||||
|
*/
|
||||||
|
peak_at?: string | null;
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -2283,6 +2417,28 @@ export type TopIndex = {
|
|||||||
* Summary
|
* Summary
|
||||||
*/
|
*/
|
||||||
summary?: string | null;
|
summary?: string | null;
|
||||||
|
/**
|
||||||
|
* Active
|
||||||
|
*
|
||||||
|
* 지금 구간이 이 각의 시간대와 겹침. false 면 순위 밖, score 는 하루 점수
|
||||||
|
*/
|
||||||
|
active?: boolean;
|
||||||
|
/**
|
||||||
|
* Slots
|
||||||
|
*
|
||||||
|
* 오늘 구간별 점수 {morning·day·evening·night: 점수}. 각 시간대와 안 겹치는 구간은 없음
|
||||||
|
*/
|
||||||
|
slots?: {
|
||||||
|
[key: string]: number;
|
||||||
|
};
|
||||||
|
/**
|
||||||
|
* Slot Ranks
|
||||||
|
*
|
||||||
|
* 오늘 구간별 순위 (점수 × 중요도 가중치). 각 시간대와 안 겹치는 구간은 없음
|
||||||
|
*/
|
||||||
|
slot_ranks?: {
|
||||||
|
[key: string]: number;
|
||||||
|
};
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -2604,6 +2760,34 @@ export type WeekDay = {
|
|||||||
* Rain Prob
|
* Rain Prob
|
||||||
*/
|
*/
|
||||||
rain_prob?: number | null;
|
rain_prob?: number | null;
|
||||||
|
/**
|
||||||
|
* Gaks
|
||||||
|
*
|
||||||
|
* 그날 대표 각 (점수 × 중요도 순 3개). 각 점수가 아직 없는 날은 비어 있음
|
||||||
|
*/
|
||||||
|
gaks?: Array<WeekGak>;
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* WeekGak
|
||||||
|
*/
|
||||||
|
export type WeekGak = {
|
||||||
|
/**
|
||||||
|
* Index Id
|
||||||
|
*/
|
||||||
|
index_id: number;
|
||||||
|
/**
|
||||||
|
* Name
|
||||||
|
*/
|
||||||
|
name: string;
|
||||||
|
/**
|
||||||
|
* Icon
|
||||||
|
*/
|
||||||
|
icon: string;
|
||||||
|
/**
|
||||||
|
* Score
|
||||||
|
*/
|
||||||
|
score: number;
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
+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 { NavLink, Outlet, useLocation } from 'react-router'
|
||||||
import { cx } from '../lib/utils'
|
import { cx } from '../lib/utils'
|
||||||
import { kindOfHour, kst, type TimeKind } from './lib'
|
import { kindOfHour, kst, type TimeKind } from './lib'
|
||||||
@@ -30,7 +30,7 @@ function TopBar() {
|
|||||||
const tab = TABS.find((t) => t.to !== '/' && pathname.startsWith(t.to))
|
const tab = TABS.find((t) => t.to !== '/' && pathname.startsWith(t.to))
|
||||||
|
|
||||||
return (
|
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>}
|
{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
|
<button
|
||||||
type="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 }) {
|
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 [serverKind, setServerKind] = useState<TimeKind | null>(null)
|
||||||
const [now, setNow] = useState(() => new Date())
|
const [now, setNow] = useState(() => new Date())
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@@ -113,35 +137,58 @@ function SkyProvider({ children }: { children: ReactNode }) {
|
|||||||
}, [])
|
}, [])
|
||||||
const t = kst(now)
|
const t = kst(now)
|
||||||
const kind = preview ?? serverKind ?? kindOfHour(t.h, t.mo, t.mi)
|
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 (
|
return (
|
||||||
<SkyContext value={api}>{children}</SkyContext>
|
<SkyContext value={api}>{children}</SkyContext>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 노치 띠·상태바 색: 하늘 맨 위 색에 .b-topbg 를 겹친 색
|
||||||
|
const NOTCH_BG: Record<TimeKind, string> = {
|
||||||
|
morning: '#ffe6cf',
|
||||||
|
day: '#d6ebff',
|
||||||
|
sunset: '#ffd8c2',
|
||||||
|
night: '#0e1433',
|
||||||
|
}
|
||||||
|
|
||||||
function Shell() {
|
function Shell() {
|
||||||
const { pathname } = useLocation()
|
const { pathname } = useLocation()
|
||||||
|
const { kind } = useSky()
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
window.scrollTo({ top: 0 })
|
window.scrollTo({ top: 0 })
|
||||||
}, [pathname])
|
}, [pathname])
|
||||||
|
useEffect(() => {
|
||||||
|
document.querySelector('meta[name="theme-color"]')?.setAttribute('content', NOTCH_BG[kind])
|
||||||
|
}, [kind])
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="min-h-dvh text-(--ink)">
|
<div className="min-h-dvh text-(--ink)">
|
||||||
<SkyBg />
|
<SkyBg />
|
||||||
{/* 위·아래 바: 띠는 화면 끝까지, 내용은 가운데 440px 안 */}
|
{/* 위·아래 바: 띠는 화면 끝까지, 내용은 가운데 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))]">
|
<div className="relative mx-auto min-h-dvh max-w-[440px] overflow-x-clip pb-[calc(70px+env(safe-area-inset-bottom,0px))]">
|
||||||
<TopBar />
|
<TopBar />
|
||||||
<main className="relative z-[1]">
|
<main className="relative z-[1]">
|
||||||
<Outlet />
|
<Outlet />
|
||||||
</main>
|
</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]">
|
<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) => (
|
{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]')}>
|
t.key === 'today' ? (
|
||||||
<TabIcon name={t.key} className="size-[25px]" />
|
// 메인 탭: 막대 위로 솟은 큰 주황 동그라미
|
||||||
{t.label}
|
<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)')}>
|
||||||
</NavLink>
|
<span className="b-keep-bg 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>
|
</nav>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -124,12 +124,16 @@ export function GakPage() {
|
|||||||
<div className={cx('grid grid-cols-3 gap-2 p-3 transition-opacity', q.isPlaceholderData && 'opacity-60')}>
|
<div className={cx('grid grid-cols-3 gap-2 p-3 transition-opacity', q.isPlaceholderData && 'opacity-60')}>
|
||||||
{items.map((g) => {
|
{items.map((g) => {
|
||||||
return (
|
return (
|
||||||
<button key={g.index_id} type="button" onClick={() => open({ type: 'gak', indexId: g.index_id })} aria-label={`${g.rank}위 ${g.name} ${g.score}점`} className="relative flex cursor-pointer flex-col items-center rounded-[22px] bg-white px-1.5 pt-3 pb-2.5 shadow-[inset_0_-5px_0_var(--shade)]">
|
<button key={g.index_id} type="button" onClick={() => open({ type: 'gak', indexId: g.index_id })} aria-label={g.active ? `${g.rank}위 ${g.name} ${g.score}점` : `${g.name}, 지금 시간대 아님`} className={cx('relative flex cursor-pointer flex-col items-center rounded-[22px] bg-white px-1.5 pt-3 pb-2.5 shadow-[inset_0_-5px_0_var(--shade)]', !g.active && 'opacity-55')}>
|
||||||
<span className="absolute top-[7px] left-[9px] font-jua text-[13px] text-(--ink3)">{g.rank}</span>
|
{g.active && <span className="absolute top-[7px] left-[9px] font-jua text-[13px] text-(--ink3)">{g.rank}</span>}
|
||||||
{g.is_core && <span className="absolute top-2 right-2 text-[10.5px] font-extrabold text-[#1f9d62]">가을</span>}
|
{g.is_core && <span className="absolute top-2 right-2 text-[10.5px] font-extrabold text-[#1f9d62]">가을</span>}
|
||||||
<Ic name={g.icon} className="w-[50px]" />
|
<Ic name={g.icon} className="w-[50px]" />
|
||||||
<b className="mt-1 font-jua text-[15px] font-normal">{g.name}</b>
|
<b className="mt-1 font-jua text-[15px] font-normal">{g.name}</b>
|
||||||
<em className={cx('font-bagel text-[22px] leading-[1.1] not-italic', g.score < 50 ? 'text-(--ink3)' : 'text-(--orange)')}>{g.score}</em>
|
{g.active ? (
|
||||||
|
<em className={cx('font-bagel text-[22px] leading-[1.1] not-italic', g.score < 50 ? 'text-(--ink3)' : 'text-(--orange)')}>{g.score}</em>
|
||||||
|
) : (
|
||||||
|
<small className="py-1 text-[12px] leading-[1.1] font-extrabold text-(--ink3)">지금 아님</small>
|
||||||
|
)}
|
||||||
</button>
|
</button>
|
||||||
)
|
)
|
||||||
})}
|
})}
|
||||||
|
|||||||
+26
-16
@@ -11,8 +11,7 @@ import { useAuth } from './authContext'
|
|||||||
import { useSheet } from './sheetContext'
|
import { useSheet } from './sheetContext'
|
||||||
import { CommentIcon, HeartIcon, SendIcon } from './svg'
|
import { CommentIcon, HeartIcon, SendIcon } from './svg'
|
||||||
import { useCarousel } from './carousel'
|
import { useCarousel } from './carousel'
|
||||||
import { shareLink } from './shareLink'
|
import { Arrows, Credit, Ic, Rows, Skel, TAP44, Thumb } from './ui'
|
||||||
import { Arrows, Credit, Ic, Rows, ScreenNote, Skel, Thumb } from './ui'
|
|
||||||
|
|
||||||
const ACCOUNTS: Record<PostType, readonly [string, string]> = {
|
const ACCOUNTS: Record<PostType, readonly [string, string]> = {
|
||||||
[PostType.WEATHER]: ['오늘 날씨', 'sun'],
|
[PostType.WEATHER]: ['오늘 날씨', 'sun'],
|
||||||
@@ -131,10 +130,9 @@ function SlideView({ slide, bg }: { slide: Slide; bg: SlideBg }) {
|
|||||||
return (
|
return (
|
||||||
<div className={cx(slideBase, slide.situation ? `b-sit-${slide.situation}` : 'b-bg-dusk')}>
|
<div className={cx(slideBase, slide.situation ? `b-sit-${slide.situation}` : 'b-bg-dusk')}>
|
||||||
<Eyebrow>{slide.eyebrow}</Eyebrow>
|
<Eyebrow>{slide.eyebrow}</Eyebrow>
|
||||||
<Big>
|
{/* 노을 탭 히어로와 같은 순서: 결론 → 가장 붉을 때 → 쉬운 이유. 점수는 노을 탭 '자세히'에 */}
|
||||||
<Lines text={slide.line} />
|
<Big>{slide.headline ?? slide.grade_label}</Big>
|
||||||
</Big>
|
{slide.line && <p className="m-0 mt-0.5 font-jua text-[18px]">{slide.line}</p>}
|
||||||
<small className="mt-1 text-[12.5px] font-bold opacity-85">노을 점수 {slide.score}</small>
|
|
||||||
<div className="mt-3 flex flex-1 flex-col gap-2">
|
<div className="mt-3 flex flex-1 flex-col gap-2">
|
||||||
{slide.cuts.map((c, i) => (
|
{slide.cuts.map((c, i) => (
|
||||||
<div key={c.kind} className={cx('b-skyline relative flex-1 overflow-hidden rounded-2xl px-3 py-2 font-bagel text-[21px] text-white', `b-cut-${Math.min(i + 1, 3)}`)}>
|
<div key={c.kind} className={cx('b-skyline relative flex-1 overflow-hidden rounded-2xl px-3 py-2 font-bagel text-[21px] text-white', `b-cut-${Math.min(i + 1, 3)}`)}>
|
||||||
@@ -154,7 +152,8 @@ function SlideView({ slide, bg }: { slide: Slide; bg: SlideBg }) {
|
|||||||
<Big>
|
<Big>
|
||||||
<Lines text={slide.line} />
|
<Lines text={slide.line} />
|
||||||
</Big>
|
</Big>
|
||||||
<div className="mt-auto grid grid-cols-2 gap-2.5">
|
{/* 칸은 제목 바로 아래, 팁만 맨 아래로. 칸을 바닥에 붙이면 가운데가 비어 덜 그려진 화면처럼 보인다 */}
|
||||||
|
<div className="mt-4 grid grid-cols-2 gap-2.5">
|
||||||
{slide.days.map((d) => (
|
{slide.days.map((d) => (
|
||||||
<div key={d.day} className="flex flex-col gap-0.5 rounded-[18px] bg-white/85 px-3 py-2.5 shadow-[inset_0_-5px_0_rgb(217_229_244/0.9)]">
|
<div key={d.day} className="flex flex-col gap-0.5 rounded-[18px] bg-white/85 px-3 py-2.5 shadow-[inset_0_-5px_0_rgb(217_229_244/0.9)]">
|
||||||
<Ic name={d.icon} className="w-[34px]" />
|
<Ic name={d.icon} className="w-[34px]" />
|
||||||
@@ -167,10 +166,22 @@ function SlideView({ slide, bg }: { slide: Slide; bg: SlideBg }) {
|
|||||||
<small className="text-xs font-bold text-(--ink2)">
|
<small className="text-xs font-bold text-(--ink2)">
|
||||||
비 {d.rain_prob ?? '?'}%{d.temp_min_c != null && d.temp_max_c != null && ` · 일교차 ${Math.round(d.temp_max_c - d.temp_min_c)}°`}
|
비 {d.rain_prob ?? '?'}%{d.temp_min_c != null && d.temp_max_c != null && ` · 일교차 ${Math.round(d.temp_max_c - d.temp_min_c)}°`}
|
||||||
</small>
|
</small>
|
||||||
|
{d.gaks && d.gaks.length > 0 && (
|
||||||
|
<ul className="mt-2 flex flex-col gap-1.5 border-t border-[rgb(217_229_244)] pt-2" aria-label={`${d.weekday}요일 대표 각`}>
|
||||||
|
<li className="text-[11px] font-extrabold text-(--ink2)">이날 할 만한 각</li>
|
||||||
|
{d.gaks.map((g) => (
|
||||||
|
<li key={g.index_id} className="flex items-center gap-1.5">
|
||||||
|
<Ic name={g.icon} className="w-[26px] shrink-0" />
|
||||||
|
<span className="min-w-0 flex-1 truncate text-[14px] font-bold">{g.name}</span>
|
||||||
|
<em className="font-bagel text-[16px] text-(--orange) not-italic">{g.score}</em>
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
{slide.tip && <p className="mt-3 rounded-[14px] bg-(--ink) px-3 py-2.5 text-[13px] leading-snug font-bold text-white">{slide.tip}</p>}
|
{slide.tip && <p className="mt-auto rounded-[14px] bg-(--ink) px-3 py-2.5 text-[13px] leading-snug font-bold text-white">{slide.tip}</p>}
|
||||||
</div>
|
</div>
|
||||||
)
|
)
|
||||||
if (slide.kind === 'plan') {
|
if (slide.kind === 'plan') {
|
||||||
@@ -311,11 +322,11 @@ function FullCard({ post }: PostProps) {
|
|||||||
const [pop, setPop] = useState(0)
|
const [pop, setPop] = useState(0)
|
||||||
const [likeFailed, setLikeFailed] = useState(0)
|
const [likeFailed, setLikeFailed] = useState(0)
|
||||||
const lastTap = useRef(0)
|
const lastTap = useRef(0)
|
||||||
|
const trackRef = useRef<HTMLDivElement>(null)
|
||||||
const [account, avatar] = ACCOUNTS[post.post_type]
|
const [account, avatar] = ACCOUNTS[post.post_type]
|
||||||
const n = post.slides.length
|
const n = post.slides.length
|
||||||
const bgs = post.slides.map((sl) => slideBg(post, sl))
|
const bgs = post.slides.map((sl) => slideBg(post, sl))
|
||||||
const [note, setNote] = useState('')
|
const share = () => open({ type: 'share', share: { title: post.title, slides: Array.from(trackRef.current?.children ?? []).filter((c) => c instanceof HTMLElement) } })
|
||||||
const share = () => void shareLink().then((m) => m && setNote(m))
|
|
||||||
const comments = () => open({ type: 'comments', postId: post.post_id })
|
const comments = () => open({ type: 'comments', postId: post.post_id })
|
||||||
const patch = (values: Partial<PostData>) => patchFeed(queryClient, post.post_id, values)
|
const patch = (values: Partial<PostData>) => patchFeed(queryClient, post.post_id, values)
|
||||||
|
|
||||||
@@ -373,7 +384,7 @@ function FullCard({ post }: PostProps) {
|
|||||||
</div>
|
</div>
|
||||||
<div className="relative aspect-[4/5] overflow-hidden" onClick={onTap}>
|
<div className="relative aspect-[4/5] overflow-hidden" onClick={onTap}>
|
||||||
{n > 1 && (
|
{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}
|
{index + 1}/{n}
|
||||||
</span>
|
</span>
|
||||||
)}
|
)}
|
||||||
@@ -388,7 +399,7 @@ function FullCard({ post }: PostProps) {
|
|||||||
if (e.key === 'ArrowRight') slider?.scrollNext()
|
if (e.key === 'ArrowRight') slider?.scrollNext()
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<div className="flex h-full">
|
<div ref={trackRef} className="flex h-full">
|
||||||
{post.slides.map((s, i) => (
|
{post.slides.map((s, i) => (
|
||||||
<SlideView key={i} slide={s} bg={bgs[i]} />
|
<SlideView key={i} slide={s} bg={bgs[i]} />
|
||||||
))}
|
))}
|
||||||
@@ -416,7 +427,6 @@ function FullCard({ post }: PostProps) {
|
|||||||
</div>,
|
</div>,
|
||||||
document.body,
|
document.body,
|
||||||
)}
|
)}
|
||||||
<ScreenNote text={note} setText={setNote} />
|
|
||||||
{likeFailed > 0 && createPortal(
|
{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">
|
<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>
|
<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 +435,13 @@ function FullCard({ post }: PostProps) {
|
|||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
<div className="flex items-center gap-3.5 px-3 pt-2.5 pb-1 [&_svg]:size-[26px] [&_svg]:stroke-[1.9]">
|
<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)'} />
|
<HeartIcon className={liked ? 'fill-(--heart) stroke-(--heart)' : 'fill-none stroke-(--ink)'} />
|
||||||
</button>
|
</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]" />
|
<CommentIcon className="fill-none stroke-(--ink) [stroke-linejoin:round]" />
|
||||||
</button>
|
</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]" />
|
<SendIcon className="fill-none stroke-(--ink) [stroke-linecap:round] [stroke-linejoin:round]" />
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ import { ArticleCategory } from '../api/client/types.gen'
|
|||||||
import { cx } from '../lib/utils'
|
import { cx } from '../lib/utils'
|
||||||
import { ARTICLE_CAT, cardBg, dateRange, fall, loadOf, shortDay } from './lib'
|
import { ARTICLE_CAT, cardBg, dateRange, fall, loadOf, shortDay } from './lib'
|
||||||
import { useSheet } from './sheetContext'
|
import { useSheet } from './sheetContext'
|
||||||
import { Chips, Ic, Skel, StateBox } from './ui'
|
import { Chips, Ic, Skel, StateBox, Thumb } from './ui'
|
||||||
|
|
||||||
const CATS = [
|
const CATS = [
|
||||||
['all', '전체'],
|
['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>
|
<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>
|
<small className="mt-1 block text-xs font-semibold text-(--ink3)">{a.read_minutes}분 읽기</small>
|
||||||
</span>
|
</span>
|
||||||
<span className={cx('grid h-[84px] place-items-center rounded-[18px]', `b-bg-${cardBg(a.icon, a.article_id)}`)}>
|
<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!" />
|
||||||
<Ic name={a.icon} className="w-[54px]" />
|
|
||||||
</span>
|
|
||||||
</button>
|
</button>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
+194
-23
@@ -1,6 +1,7 @@
|
|||||||
import { useInfiniteQuery, useMutation, useQuery, useQueryClient, type InfiniteData } from '@tanstack/react-query'
|
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 { useCallback, useDeferredValue, useEffect, useMemo, useRef, useState, type FormEvent, type ReactNode } from 'react'
|
||||||
import { setTokens, subscribeAuth } from '../api/auth'
|
import { setTokens, subscribeAuth } from '../api/auth'
|
||||||
|
import { SITE_URL } from '../api/setup'
|
||||||
import {
|
import {
|
||||||
addCommentMutation,
|
addCommentMutation,
|
||||||
deleteCommentMutation,
|
deleteCommentMutation,
|
||||||
@@ -19,23 +20,48 @@ import {
|
|||||||
updateMeMutation,
|
updateMeMutation,
|
||||||
} from '../api/client/@tanstack/react-query.gen'
|
} from '../api/client/@tanstack/react-query.gen'
|
||||||
import type { CommentData, Factor, ResAuth, ResCommentList, ResIndexDetail } from '../api/client/types.gen'
|
import type { CommentData, Factor, ResAuth, ResCommentList, ResIndexDetail } from '../api/client/types.gen'
|
||||||
|
import { track } from '../lib/analytics'
|
||||||
import { cx } from '../lib/utils'
|
import { cx } from '../lib/utils'
|
||||||
import { useAuth } from './authContext'
|
import { useAuth } from './authContext'
|
||||||
import { ago, ARTICLE_CAT, articleMeta, AVATAR_COLORS, cardBg, CHARACTERS, dateRange, loadOf, MOODS, shortDay } from './lib'
|
import { ago, ARTICLE_CAT, articleMeta, AVATAR_COLORS, cardBg, CHARACTERS, dateRange, loadOf, MOODS, shortDay } from './lib'
|
||||||
import { useRegion } from './regionContext'
|
import { useRegion } from './regionContext'
|
||||||
import { useSky } from './skyContext'
|
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 { 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 }) {
|
export function SheetProvider({ children }: { children: ReactNode }) {
|
||||||
const [state, setState] = useState<SheetState>(null)
|
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])
|
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을 받으면 로그인 창을 띄운다
|
// 로그인이 필요한 요청이 401을 받으면 로그인 창을 띄운다
|
||||||
useEffect(() => subscribeAuth((reason) => reason === 'required' && setState({ type: 'login' })), [])
|
useEffect(() => subscribeAuth((reason) => reason === 'required' && open({ type: 'login' })), [open])
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<SheetContext value={api}>
|
<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·포커스 가두기·포커스 되돌리기가 기본으로 된다 */
|
/** 아래에서 올라오는 창: 네이티브 <dialog>라 ESC·포커스 가두기·포커스 되돌리기가 기본으로 된다 */
|
||||||
function SheetHost({ state, onClose }: { state: SheetState; onClose: () => void }) {
|
function SheetHost({ state, onClose }: { state: SheetState; onClose: () => void }) {
|
||||||
const ref = useRef<HTMLDialogElement>(null)
|
const ref = useRef<HTMLDialogElement>(null)
|
||||||
const { kind } = useSky()
|
const { kind } = useSky()
|
||||||
|
const { open } = useSheet()
|
||||||
const [gakTitle, setGakTitle] = useState('')
|
const [gakTitle, setGakTitle] = useState('')
|
||||||
const [articleTitle, setArticleTitle] = useState('')
|
const [articleTitle, setArticleTitle] = useState('')
|
||||||
|
|
||||||
@@ -73,6 +100,7 @@ function SheetHost({ state, onClose }: { state: SheetState; onClose: () => void
|
|||||||
}
|
}
|
||||||
}, [isOpen])
|
}, [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]
|
const title = !state ? '' : state.type === 'gak' ? gakTitle : state.type === 'article' ? articleTitle || TITLES.article : TITLES[state.type]
|
||||||
|
|
||||||
return (
|
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)"
|
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 && (
|
{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="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" />
|
<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>
|
<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>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
{state.type === 'gak' && <GakSheet indexId={state.indexId} onTitle={setGakTitle} />}
|
{state.type === 'gak' && <GakSheet indexId={state.indexId} onTitle={setGakTitle} />}
|
||||||
{state.type === 'article' && <ArticleSheet articleId={state.articleId} onTitle={setArticleTitle} />}
|
{state.type === 'article' && <ArticleSheet articleId={state.articleId} onTitle={setArticleTitle} />}
|
||||||
{state.type === 'seasonWeek' && <SeasonWeekSheet />}
|
{state.type === 'seasonWeek' && <SeasonWeekSheet />}
|
||||||
{state.type === 'comments' && <CommentsSheet postId={state.postId} />}
|
{state.type === 'share' && <ShareSheet share={state.share} />}
|
||||||
{state.type === 'login' && <LoginSheet onDone={onClose} />}
|
{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 === 'me' && <MeSheet onDone={onClose} />}
|
||||||
{state.type === 'region' && <RegionSheet onDone={onClose} />}
|
{state.type === 'region' && <RegionSheet onDone={onClose} />}
|
||||||
</div>
|
</div>
|
||||||
@@ -128,6 +157,8 @@ function Swap({ labels, at }: { labels: readonly ReactNode[]; at: number }) {
|
|||||||
/* ---------- 시트 스켈레톤: 완료 화면과 같은 틀·같은 줄 높이 ---------- */
|
/* ---------- 시트 스켈레톤: 완료 화면과 같은 틀·같은 줄 높이 ---------- */
|
||||||
const N3 = [0, 1, 2]
|
const N3 = [0, 1, 2]
|
||||||
const N4 = [0, 1, 2, 3]
|
const N4 = [0, 1, 2, 3]
|
||||||
|
const SLOT_KEYS = ['morning', 'day', 'evening', 'night'] as const
|
||||||
|
const SLOT_NAMES = { morning: '아침', day: '낮', evening: '저녁', night: '밤' } as const
|
||||||
const N6 = [0, 1, 2, 3, 4, 5]
|
const N6 = [0, 1, 2, 3, 4, 5]
|
||||||
const N14 = Array.from({ length: 14 }, (_, i) => i)
|
const N14 = Array.from({ length: 14 }, (_, i) => i)
|
||||||
|
|
||||||
@@ -298,6 +329,14 @@ function GakSheet({ indexId, onTitle }: { indexId: number; onTitle: (t: string)
|
|||||||
onTitle(g ? `${g.rank}위 ${g.name}` : '계산 근거')
|
onTitle(g ? `${g.rank}위 ${g.name}` : '계산 근거')
|
||||||
}, [g, onTitle])
|
}, [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)
|
const load = loadOf(q)
|
||||||
if (!g) return <Body>{load === 'loading' ? <GakSkel /> : <StateBox load={load} onRetry={() => q.refetch()} empty="이 각의 계산 근거가 아직 없어요." hold={<GakSkel />} className="inset-0" />}</Body>
|
if (!g) return <Body>{load === 'loading' ? <GakSkel /> : <StateBox load={load} onRetry={() => q.refetch()} empty="이 각의 계산 근거가 아직 없어요." hold={<GakSkel />} className="inset-0" />}</Body>
|
||||||
const factors = d.factors ?? []
|
const factors = d.factors ?? []
|
||||||
@@ -311,8 +350,9 @@ function GakSheet({ indexId, onTitle }: { indexId: number; onTitle: (t: string)
|
|||||||
<h4 className="m-0 font-jua text-[22px] font-normal">{g.name}</h4>
|
<h4 className="m-0 font-jua text-[22px] font-normal">{g.name}</h4>
|
||||||
{d.description && <p className="mt-0.5 text-[13.5px] font-semibold text-(--ink2)">{d.description}</p>}
|
{d.description && <p className="mt-0.5 text-[13.5px] font-semibold text-(--ink2)">{d.description}</p>}
|
||||||
</div>
|
</div>
|
||||||
<b className="ml-auto font-bagel text-[42px] font-normal text-(--orange)">{g.score}</b>
|
<b className={cx('ml-auto font-bagel text-[42px] font-normal', g.active ? 'text-(--orange)' : 'text-(--ink3)')}>{g.score}</b>
|
||||||
</div>
|
</div>
|
||||||
|
{!g.active && <p className="mt-2 text-[13px] font-bold text-(--ink2)">지금 시간대엔 해당 없어요. 점수는 오늘 가장 좋은 시간대 기준이에요.</p>}
|
||||||
{now && (
|
{now && (
|
||||||
<p className="mt-3 rounded-2xl bg-[#fff4ec] px-3.5 py-2.5 text-[14.5px] font-bold">
|
<p className="mt-3 rounded-2xl bg-[#fff4ec] px-3.5 py-2.5 text-[14.5px] font-bold">
|
||||||
<b className="mr-1.5 font-jua font-normal text-(--orange)">{now.low}~{now.high}점</b>
|
<b className="mr-1.5 font-jua font-normal text-(--orange)">{now.low}~{now.high}점</b>
|
||||||
@@ -320,6 +360,23 @@ function GakSheet({ indexId, onTitle }: { indexId: number; onTitle: (t: string)
|
|||||||
</p>
|
</p>
|
||||||
)}
|
)}
|
||||||
{factors.length > 2 && <Radar name={g.name} factors={factors} />}
|
{factors.length > 2 && <Radar name={g.name} factors={factors} />}
|
||||||
|
{g.slots && g.slots.length > 0 && (
|
||||||
|
<div className="mt-2.5 grid grid-cols-4 gap-1.5" aria-label="오늘 시간대별 점수">
|
||||||
|
{SLOT_KEYS.map((k) => {
|
||||||
|
const s = g.slots?.find((x) => x.slot === k)
|
||||||
|
const cur = g.active && g.slot === k
|
||||||
|
return (
|
||||||
|
<div key={k} className={cx('rounded-2xl px-1 py-2 text-center', cur ? 'bg-[#fff4ec]' : 'bg-[#f3f6fb]')}>
|
||||||
|
<small className="block text-xs font-extrabold text-(--ink2)">
|
||||||
|
{SLOT_NAMES[k]}
|
||||||
|
{cur && ' · 지금'}
|
||||||
|
</small>
|
||||||
|
<b className={cx('block font-bagel text-xl font-normal', s ? 'text-(--orange)' : 'text-(--ink3)')}>{s ? s.score : '–'}</b>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
{g.trend && g.trend.length > 0 && (
|
{g.trend && g.trend.length > 0 && (
|
||||||
<div className="mt-2.5 grid grid-cols-4 gap-1.5">
|
<div className="mt-2.5 grid grid-cols-4 gap-1.5">
|
||||||
{g.trend.map((t) => (
|
{g.trend.map((t) => (
|
||||||
@@ -348,7 +405,7 @@ function GakSheet({ indexId, onTitle }: { indexId: number; onTitle: (t: string)
|
|||||||
<div key={f.axis} className="grid grid-cols-[84px_1fr_52px] items-center gap-x-2.5 text-[13.5px] font-bold">
|
<div key={f.axis} className="grid grid-cols-[84px_1fr_52px] items-center gap-x-2.5 text-[13.5px] font-bold">
|
||||||
<span>{f.label}</span>
|
<span>{f.label}</span>
|
||||||
<i className="block h-[9px] overflow-hidden rounded-full bg-[#e3eaf4]">
|
<i className="block h-[9px] overflow-hidden rounded-full bg-[#e3eaf4]">
|
||||||
<s className="block h-full bg-[linear-gradient(90deg,#ffc86e,var(--orange))]" style={{ width: `${f.value}%` }} />
|
<s className="b-keep-bg block h-full bg-[linear-gradient(90deg,#ffc86e,var(--orange))]" style={{ width: `${f.value}%` }} />
|
||||||
</i>
|
</i>
|
||||||
<em className="text-right text-xs text-(--ink2) not-italic">비중 {f.weight}%</em>
|
<em className="text-right text-xs text-(--ink2) not-italic">비중 {f.weight}%</em>
|
||||||
<p className="col-start-2 col-end-4 -mt-0.5 text-[12.5px] font-semibold text-(--ink2)">{f.note}</p>
|
<p className="col-start-2 col-end-4 -mt-0.5 text-[12.5px] font-semibold text-(--ink2)">{f.note}</p>
|
||||||
@@ -390,13 +447,18 @@ function ArticleSheet({ articleId, onTitle }: { articleId: number; onTitle: (t:
|
|||||||
onTitle(a ? (ARTICLE_CAT[a.category]?.[0] ?? '') : '')
|
onTitle(a ? (ARTICLE_CAT[a.category]?.[0] ?? '') : '')
|
||||||
}, [a, onTitle])
|
}, [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)
|
const load = loadOf(q)
|
||||||
if (!a) return <Body>{load === 'loading' ? <ArticleSkel /> : <StateBox load={load} onRetry={() => q.refetch()} empty="글을 찾지 못했어요." hold={<ArticleSkel />} className="inset-0" />}</Body>
|
if (!a) return <Body>{load === 'loading' ? <ArticleSkel /> : <StateBox load={load} onRetry={() => q.refetch()} empty="글을 찾지 못했어요." hold={<ArticleSkel />} className="inset-0" />}</Body>
|
||||||
return (
|
return (
|
||||||
<Body>
|
<Body>
|
||||||
<div className={cx('mb-3.5 grid h-[150px] place-items-center rounded-[20px]', `b-bg-${cardBg(a.icon, a.article_id)}`)}>
|
<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" />
|
||||||
<Ic name={a.icon} className="w-24" />
|
|
||||||
</div>
|
|
||||||
<p className="text-[13px] font-extrabold text-(--ink2)">{articleMeta(a)}</p>
|
<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>
|
<h4 className="mt-1.5 mb-2.5 font-jua text-2xl leading-tight font-normal">{a.title}</h4>
|
||||||
{(q.data?.body ?? []).map((t) => (
|
{(q.data?.body ?? []).map((t) => (
|
||||||
@@ -443,6 +505,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
|
const NOT_FOUND = 3001 // 서버 ErrorType.NOT_FOUND
|
||||||
@@ -535,14 +697,14 @@ function CommentRow({ c, postId }: { c: CommentData; postId: number }) {
|
|||||||
)}
|
)}
|
||||||
</small>
|
</small>
|
||||||
</div>
|
</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)')} />
|
<HeartIcon className={cx('size-4 stroke-2', liked ? 'fill-(--heart) stroke-(--heart)' : 'fill-none stroke-(--ink3)')} />
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
function CommentsSheet({ postId }: { postId: number }) {
|
function CommentsSheet({ postId, draft }: { postId: number; draft?: string }) {
|
||||||
const { region } = useRegion()
|
const { region } = useRegion()
|
||||||
const { open } = useSheet()
|
const { open } = useSheet()
|
||||||
const { loggedIn, me } = useAuth()
|
const { loggedIn, me } = useAuth()
|
||||||
@@ -554,13 +716,13 @@ function CommentsSheet({ postId }: { postId: number }) {
|
|||||||
})
|
})
|
||||||
const add = useMutation(addCommentMutation())
|
const add = useMutation(addCommentMutation())
|
||||||
const [addFailed, setAddFailed] = useState(false)
|
const [addFailed, setAddFailed] = useState(false)
|
||||||
const [text, setText] = useState('')
|
const [text, setText] = useState(draft ?? '')
|
||||||
const inputRef = useRef<HTMLInputElement>(null)
|
const inputRef = useRef<HTMLInputElement>(null)
|
||||||
const comments = list.data?.pages.flatMap((p) => p.comments ?? []) ?? []
|
const comments = list.data?.pages.flatMap((p) => p.comments ?? []) ?? []
|
||||||
|
|
||||||
const submit = (e: FormEvent) => {
|
const submit = (e: FormEvent) => {
|
||||||
e.preventDefault()
|
e.preventDefault()
|
||||||
if (!loggedIn) return open({ type: 'login' })
|
if (!loggedIn) return open({ type: 'login', then: { type: 'comments', postId, draft: text } })
|
||||||
const body = text.trim()
|
const body = text.trim()
|
||||||
if (!body || add.isPending) return
|
if (!body || add.isPending) return
|
||||||
setAddFailed(false)
|
setAddFailed(false)
|
||||||
@@ -617,7 +779,7 @@ function CommentsSheet({ postId }: { postId: number }) {
|
|||||||
<p className="h-4 px-4 text-center text-xs leading-4 font-bold text-(--heart)" role="alert">
|
<p className="h-4 px-4 text-center text-xs leading-4 font-bold text-(--heart)" role="alert">
|
||||||
{addFailed && '댓글을 올리지 못했어요. 다시 해 주세요.'}
|
{addFailed && '댓글을 올리지 못했어요. 다시 해 주세요.'}
|
||||||
</p>
|
</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" />
|
<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">
|
<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} />
|
<Swap labels={['게시', '올리는 중…']} at={add.isPending ? 1 : 0} />
|
||||||
@@ -634,7 +796,7 @@ const AUTH_ERRORS: Record<string, string> = {
|
|||||||
INVALID_INPUT: '아이디는 영어 소문자·숫자·_ 4~20자, 비밀번호는 8~64자, 닉네임은 2~12자로 써 주세요.',
|
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 { me } = useAuth()
|
||||||
const [mode, setMode] = useState<'login' | 'signup'>('login')
|
const [mode, setMode] = useState<'login' | 'signup'>('login')
|
||||||
const [loginId, setLoginId] = useState('')
|
const [loginId, setLoginId] = useState('')
|
||||||
@@ -651,7 +813,8 @@ function LoginSheet({ onDone }: { onDone: () => void }) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
setTokens(res.access_token, res.refresh_token ?? null)
|
setTokens(res.access_token, res.refresh_token ?? null)
|
||||||
onDone()
|
track(mode === 'login' ? 'login' : 'sign_up', { method: 'id' })
|
||||||
|
onLoggedIn()
|
||||||
}
|
}
|
||||||
const fail = () => setError('서버에 닿지 못했어요. 잠시 뒤에 다시 해 주세요.')
|
const fail = () => setError('서버에 닿지 못했어요. 잠시 뒤에 다시 해 주세요.')
|
||||||
|
|
||||||
@@ -828,6 +991,13 @@ function RegionSheet({ onDone }: { onDone: () => void }) {
|
|||||||
const { region, setRegion, locate, locateStatus } = useRegion()
|
const { region, setRegion, locate, locateStatus } = useRegion()
|
||||||
const { me, logout } = useAuth()
|
const { me, logout } = useAuth()
|
||||||
const { open } = useSheet()
|
const { open } = useSheet()
|
||||||
|
const alive = useRef(true)
|
||||||
|
useEffect(() => {
|
||||||
|
alive.current = true
|
||||||
|
return () => {
|
||||||
|
alive.current = false
|
||||||
|
}
|
||||||
|
}, [])
|
||||||
const [q, setQ] = useState('')
|
const [q, setQ] = useState('')
|
||||||
const deferred = useDeferredValue(q.trim())
|
const deferred = useDeferredValue(q.trim())
|
||||||
const list = useQuery(listRegionsOptions(deferred ? { query: { q: deferred } } : undefined))
|
const list = useQuery(listRegionsOptions(deferred ? { query: { q: deferred } } : undefined))
|
||||||
@@ -836,7 +1006,7 @@ function RegionSheet({ onDone }: { onDone: () => void }) {
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<Body>
|
<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>
|
</button>
|
||||||
<p className="mt-2 min-h-5 text-center text-[13px] font-bold text-(--ink2)" aria-live="polite">
|
<p className="mt-2 min-h-5 text-center text-[13px] font-bold text-(--ink2)" aria-live="polite">
|
||||||
@@ -853,6 +1023,7 @@ function RegionSheet({ onDone }: { onDone: () => void }) {
|
|||||||
aria-current={r.code === region.code ? 'true' : undefined}
|
aria-current={r.code === region.code ? 'true' : undefined}
|
||||||
onClick={() => {
|
onClick={() => {
|
||||||
setRegion(r)
|
setRegion(r)
|
||||||
|
track('region_change', { region_name: r.name, method: 'list' })
|
||||||
onDone()
|
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)')}
|
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)')}
|
||||||
|
|||||||
+96
-43
@@ -1,5 +1,5 @@
|
|||||||
import { useQuery } from '@tanstack/react-query'
|
import { useQuery } from '@tanstack/react-query'
|
||||||
import type { ReactNode } from 'react'
|
import { useState, type ReactNode } from 'react'
|
||||||
import { getSkyOptions, getSkyRankingOptions } from '../api/client/@tanstack/react-query.gen'
|
import { getSkyOptions, getSkyRankingOptions } from '../api/client/@tanstack/react-query.gen'
|
||||||
import type { BestTime, SkyPlanData } from '../api/client/types.gen'
|
import type { BestTime, SkyPlanData } from '../api/client/types.gen'
|
||||||
import { cx } from '../lib/utils'
|
import { cx } from '../lib/utils'
|
||||||
@@ -31,48 +31,104 @@ function LiSkel({ ghost = false }: { ghost?: boolean }) {
|
|||||||
// 다른 탭 히어로보다 짧게. 배경은 하늘 상황별 색(b-sit-1~5), 아래에 동네 실루엣
|
// 다른 탭 히어로보다 짧게. 배경은 하늘 상황별 색(b-sit-1~5), 아래에 동네 실루엣
|
||||||
const HERO = 'relative mx-3 mt-1 min-h-[230px] overflow-hidden rounded-[32px] px-5 pt-5 pb-14 text-white'
|
const HERO = 'relative mx-3 mt-1 min-h-[230px] overflow-hidden rounded-[32px] px-5 pt-5 pb-14 text-white'
|
||||||
const THREE = [0, 1, 2]
|
const THREE = [0, 1, 2]
|
||||||
|
const FOUR = [0, 1, 2, 3]
|
||||||
const RANK_SKELS = Array.from({ length: 8 }, (_, i) => i)
|
const RANK_SKELS = Array.from({ length: 8 }, (_, i) => i)
|
||||||
|
|
||||||
/** 히어로엔 해 지는 시각과 하늘 상황 한 줄만. 결론·이유는 아래 카드로 */
|
/** 점수 등급별 하늘색: 히어로 배경과 3일 타일이 같은 색. b-keep-bg 는 밤 화면에서도 이 색을 지킨다 */
|
||||||
function HeroBody({ plan, sunset }: { plan?: SkyPlanData; sunset?: string }) {
|
const GRADE_SKY: Record<string, { hero: string; tile: string }> = {
|
||||||
|
잿빛: { hero: 'b-keep-bg bg-[linear-gradient(180deg,#6f7690,#9aa0b4_55%,#b9b4c0)]', tile: 'b-keep-bg bg-[linear-gradient(160deg,#8f8aa5,#b9b0bf)]' },
|
||||||
|
은은함: { hero: 'b-keep-bg bg-[linear-gradient(180deg,#4b5aa8,#7f86c6_40%,#e9b9a8_78%,#ffb27a)]', tile: 'b-keep-bg bg-[linear-gradient(160deg,#7f86c6,#e9b9a8_70%,#f6b07a)]' },
|
||||||
|
고움: { hero: 'b-keep-bg bg-[linear-gradient(180deg,#5b3f9e,#c2559a_45%,#ff7a6a_78%,#ffb35c)]', tile: 'b-keep-bg bg-[linear-gradient(160deg,#5b3f9e,#c2559a_55%,#ff7a6a)]' },
|
||||||
|
붉음: { hero: 'b-keep-bg bg-[linear-gradient(180deg,#4a2a8a,#b0306a_40%,#ff4a3a_72%,#ff9a3c)]', tile: 'b-keep-bg bg-[linear-gradient(160deg,#4a2a8a,#b0306a_50%,#ff4a3a)]' },
|
||||||
|
}
|
||||||
|
const skyOf = (p?: SkyPlanData) => GRADE_SKY[p?.grade_label ?? ''] ?? GRADE_SKY['은은함']
|
||||||
|
|
||||||
|
/** 히어로엔 답만: 등급에 따라 노을 피크 시각과 어떻게 물드는지, 잿빛이면 왜 안 보이는지 */
|
||||||
|
function HeroBody({ plan }: { plan?: SkyPlanData }) {
|
||||||
const v = (node: ReactNode, w: string) => (plan ? node : <Skel className={w} />)
|
const v = (node: ReactNode, w: string) => (plan ? node : <Skel className={w} />)
|
||||||
return (
|
return (
|
||||||
<div className="relative z-[1] [text-shadow:0_2px_10px_rgb(50_25_70/0.35)]" aria-hidden={plan ? undefined : true}>
|
<div className="relative z-[1] [text-shadow:0_2px_10px_rgb(50_25_70/0.35)]" aria-hidden={plan ? undefined : true}>
|
||||||
<p className="m-0 mt-2.5 font-bagel text-[52px] leading-none">{v(sunset && clockShort(sunset), 'w-[150px]')}</p>
|
<p className="m-0 font-jua text-[28px] leading-tight text-balance">{v(plan?.title, 'w-[230px]')}</p>
|
||||||
<p className="m-0 mt-1.5 font-jua text-[21px]">{v(plan?.situation_label ?? plan?.headline, 'w-[190px]')}</p>
|
{(!plan || plan.situation_label) && <p className="m-0 mt-1.5 text-[15px] font-bold">{v(plan?.situation_label, 'w-[180px]')}</p>}
|
||||||
</div>
|
</div>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 결론과 이유, 예보 모델이 얼마나 같은 예보를 냈는지, 점수(작게) */
|
/** 오늘·내일·모레를 그날 예상 하늘색 타일로. 누르면 그날로 */
|
||||||
function Verdict({ plan }: { plan?: SkyPlanData }) {
|
function DayTiles({ plans, day, onPick }: { plans: SkyPlanData[]; day?: string; onPick: (day: string) => void }) {
|
||||||
const v = (node: ReactNode, w: string) => (plan ? node : <Skel className={w} />)
|
|
||||||
const agree = plan?.models_total ? `예보 모델 ${plan.models_total}개 중 ${plan.models_agree}개가 같은 예보` : ''
|
|
||||||
return (
|
return (
|
||||||
<div className="mx-3 mt-3 rounded-[22px] bg-white px-4 py-3 text-[14px] font-semibold shadow-[inset_0_-5px_0_var(--shade)]" aria-hidden={plan ? undefined : true}>
|
<div className="mx-3 mt-2.5 grid grid-cols-3 gap-2">
|
||||||
<p className="m-0">
|
{plans.map((p) => (
|
||||||
<b className="mr-1.5 font-jua text-[17px] font-normal">{v(plan?.headline, 'w-20')}</b>
|
<button
|
||||||
{v(plan?.reason, 'w-[220px]')}
|
key={p.day}
|
||||||
|
type="button"
|
||||||
|
aria-pressed={p.day === day}
|
||||||
|
onClick={() => onPick(p.day)}
|
||||||
|
className={cx(
|
||||||
|
'grid cursor-pointer gap-px rounded-2xl px-2.5 pt-2 pb-2.5 text-left text-white [text-shadow:0_1px_4px_rgb(40_20_50/0.35)]',
|
||||||
|
skyOf(p).tile,
|
||||||
|
p.day === day && 'outline-[3px] outline-offset-2 outline-(--ink) outline-solid',
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
<small className="text-[11.5px] font-extrabold">{p.when}</small>
|
||||||
|
<b className="font-jua text-lg leading-tight font-normal">{p.best_at ? clockShort(p.best_at) : '–'}</b>
|
||||||
|
<span className="text-[11.5px] font-bold">
|
||||||
|
{p.grade_label} {p.score}
|
||||||
|
</span>
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 노을 점수 뜻. 지금 하늘이 아니라 해 질(뜰) 무렵 예보라는 것도 */
|
||||||
|
function ScoreHelp({ plan }: { plan: SkyPlanData }) {
|
||||||
|
const sunAt = plan.timeline?.find((t) => t.kind === 'sun')?.at
|
||||||
|
return (
|
||||||
|
<details className="mx-3 mt-1.5 px-1 text-[12px] font-bold text-(--ink2)">
|
||||||
|
<summary className="flex cursor-pointer list-none items-center justify-between [&::-webkit-details-marker]:hidden">
|
||||||
|
노을 점수 100점 만점 · 높을수록 붉어요
|
||||||
|
<span className="grid size-[18px] place-items-center rounded-full bg-white/80 text-[11px] font-extrabold">?</span>
|
||||||
|
</summary>
|
||||||
|
<p className="m-0 mt-1.5 rounded-xl bg-white/70 px-2.5 py-2 leading-snug font-semibold">
|
||||||
|
80점 넘으면 붉게, 60점 넘으면 곱게, 40점 넘으면 은은하게 물들어요.
|
||||||
|
{sunAt && ` 해 ${plan.kind === 'sunrise' ? '뜰' : '질'} 무렵(${new Date(sunAt).getHours()}시) 날씨 예보로 계산했고, 노을 피크 시각은 해 ${plan.kind === 'sunrise' ? '뜨기 10~20분 전' : '지고 10~20분 뒤'}로 어림한 거라 실제와 다를 수 있어요.`}
|
||||||
</p>
|
</p>
|
||||||
<small className="mt-1 block text-[12px] font-bold text-(--ink2)">{v(plan && [agree, `노을 점수 ${plan.score}`].filter(Boolean).join(' · '), 'w-48')}</small>
|
</details>
|
||||||
</div>
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 골든아워 → 해 짐 → 블루아워 */
|
/** 언제 보면 좋을까: 왼쪽 세로 줄 색이 그 시각 하늘색, 노을 피크만 강조. 용어 뜻은 ?를 눌러야 */
|
||||||
function Timeline({ rows }: { rows?: BestTime[] }) {
|
function Timeline({ rows, kind = 'sunset' }: { rows?: BestTime[]; kind?: SkyPlanData['kind'] }) {
|
||||||
|
const rail = kind === 'sunrise' ? 'bg-[linear-gradient(180deg,#2d3f8f,#8c5aa6_25%,#e8506a_45%,#f6844e_60%,#f2b84b)]' : 'bg-[linear-gradient(180deg,#f2b84b,#f6844e_45%,#e8506a_62%,#8c5aa6_82%,#2d3f8f)]'
|
||||||
return (
|
return (
|
||||||
<div className="mx-3 mt-3 rounded-[22px] bg-white px-2 pt-4 pb-3 shadow-[inset_0_-5px_0_var(--shade)]" aria-hidden={rows ? undefined : true}>
|
<div className="mx-3 mt-3 rounded-[22px] bg-white px-4 pt-3.5 pb-3 shadow-[inset_0_-5px_0_var(--shade)]" aria-hidden={rows ? undefined : true}>
|
||||||
<ol className="relative grid grid-cols-3">
|
<div className="grid grid-cols-[12px_1fr] gap-x-3">
|
||||||
<span className="absolute inset-x-[16.6%] top-[6px] h-0.5 bg-(--line)" aria-hidden="true" />
|
<span className={cx('row-span-4 rounded-full', rail)} aria-hidden="true" />
|
||||||
{(rows ?? THREE.map(() => undefined)).map((t, i) => (
|
{(rows ?? FOUR.map(() => undefined)).map((t, i) => (
|
||||||
<li key={t?.kind ?? i} className="relative flex flex-col items-center text-center">
|
<p
|
||||||
<span className={cx('size-3 rounded-full border-2 border-(--line) bg-white', t?.kind === 'sun' && 'border-(--orange) bg-(--orange)')} />
|
key={t?.kind ?? i}
|
||||||
<b className="mt-1.5 font-bagel text-lg leading-tight font-normal">{t ? clockShort(t.at) : <Skel className="w-12" />}</b>
|
className={cx('m-0 flex items-baseline gap-2.5 py-1.5', t?.kind === 'peak' ? '-mx-1.5 my-0.5 rounded-xl bg-[#fff1f2] px-2.5 py-2' : 'border-b border-(--line) last:border-b-0')}
|
||||||
<span className="text-[12px] font-bold text-(--ink2)">{t ? t.label : <Skel className="w-11" />}</span>
|
>
|
||||||
</li>
|
<b className={cx('min-w-[96px] font-jua font-normal tabular-nums', t?.kind === 'peak' ? 'text-[20px] text-[#d23d5a]' : 'text-[17px]')}>
|
||||||
|
{t ? (t.end ? `${clockShort(t.at)}~${clockShort(t.end)}` : clockShort(t.at)) : <Skel className="w-11" />}
|
||||||
|
</b>
|
||||||
|
<span className={cx(t?.kind === 'peak' ? 'font-jua text-base text-[#d23d5a]' : 'text-[13.5px] font-bold text-(--ink2)')}>{t ? t.label : <Skel className="w-20" />}</span>
|
||||||
|
</p>
|
||||||
))}
|
))}
|
||||||
</ol>
|
</div>
|
||||||
|
{rows && (
|
||||||
|
<details className="mt-2 text-[12px] text-(--ink2)">
|
||||||
|
<summary className="inline-flex cursor-pointer list-none items-center gap-1.5 font-bold [&::-webkit-details-marker]:hidden">
|
||||||
|
<span className="grid size-[18px] place-items-center rounded-full bg-[#f1ebe3] text-[11px] font-extrabold">?</span>골든아워·블루아워가 뭐예요
|
||||||
|
</summary>
|
||||||
|
<p className="m-0 mt-1.5 rounded-xl bg-[#faf6f1] px-2.5 py-2 leading-snug">
|
||||||
|
<b className="text-(--ink)">골든아워</b> 해가 {kind === 'sunrise' ? '뜬 뒤' : '지기 전'}, 햇빛이 금빛으로 물드는 시간
|
||||||
|
<br />
|
||||||
|
<b className="text-(--ink)">블루아워</b> 해가 {kind === 'sunrise' ? '뜨기 전' : '진 뒤'}, 하늘이 짙은 파랑으로 남는 시간
|
||||||
|
</p>
|
||||||
|
</details>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -121,39 +177,36 @@ export function SkyPage() {
|
|||||||
const ranking = useQuery(getSkyRankingOptions())
|
const ranking = useQuery(getSkyRankingOptions())
|
||||||
const load = loadOf(sky)
|
const load = loadOf(sky)
|
||||||
const rankLoad = loadOf(ranking)
|
const rankLoad = loadOf(ranking)
|
||||||
const plan = sky.data?.plan ?? undefined
|
const plans = sky.data?.plans ?? []
|
||||||
|
const [picked, setPicked] = useState<string>()
|
||||||
|
// 타일을 누르면 그날, 아니면 다음에 오는 날
|
||||||
|
const plan = plans.find((p) => p.day === picked) ?? sky.data?.plan ?? undefined
|
||||||
const spots = (sky.data?.spots ?? []).slice(0, 3)
|
const spots = (sky.data?.spots ?? []).slice(0, 3)
|
||||||
const items = (ranking.data?.items ?? []).slice(0, 8)
|
const items = (ranking.data?.items ?? []).slice(0, 8)
|
||||||
const target = sky.data?.days?.find((d) => d.day === plan?.day)
|
const rise = plan?.kind === 'sunrise'
|
||||||
const sunset = plan?.timeline?.find((t) => t.kind === 'sun')?.at
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<section aria-label="노을" aria-busy={load === 'loading'} className={cx('transition-opacity', sky.isPlaceholderData && 'opacity-60')}>
|
<section aria-label="노을" aria-busy={load === 'loading'} className={cx('transition-opacity', sky.isPlaceholderData && 'opacity-60')}>
|
||||||
{/* 히어로 상자는 불러오는 중·실패·빈 값 모두 같은 크기 */}
|
{/* 히어로 상자는 불러오는 중·실패·빈 값 모두 같은 크기 */}
|
||||||
<div className={cx(HERO, `b-sit-${target?.situation ?? 3}`)}>
|
<div className={cx(HERO, skyOf(plan).hero)}>
|
||||||
<i className="b-sit-sun pointer-events-none absolute bottom-6 left-1/2 -ml-[56px] size-[112px] rounded-full" aria-hidden="true" />
|
<i className="b-sit-sun pointer-events-none absolute bottom-6 left-1/2 -ml-[56px] size-[112px] rounded-full" aria-hidden="true" />
|
||||||
<div className="b-skyline pointer-events-none absolute inset-0 [--sky-h:22%]" aria-hidden="true" />
|
<div className="b-skyline pointer-events-none absolute inset-0 [--sky-h:22%]" aria-hidden="true" />
|
||||||
{/* 하늘 위 흰 글씨 대비가 모자라 어두운 바탕을 깐다 */}
|
|
||||||
<p className="relative z-[1] m-0 self-start rounded-full bg-[rgb(30_18_60/0.35)] px-2.5 py-0.5 text-[13px] font-extrabold">
|
|
||||||
{plan?.when ?? '오늘'} 노을 · {region.name}
|
|
||||||
</p>
|
|
||||||
{plan || load === 'loading' ? (
|
{plan || load === 'loading' ? (
|
||||||
<HeroBody plan={plan} sunset={sunset} />
|
<HeroBody plan={plan} />
|
||||||
) : (
|
) : (
|
||||||
<StateBox load={load} onRetry={() => sky.refetch()} empty="오늘 노을 정보가 없어요." hold={<HeroBody />} className="inset-x-0 top-1.5 bottom-0" />
|
<StateBox load={load} onRetry={() => sky.refetch()} empty="오늘 노을 정보가 없어요." hold={<HeroBody />} className="inset-x-0 top-1.5 bottom-0" />
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
{(plan || load === 'loading') && <Verdict plan={plan} />}
|
{plans.length > 1 && <DayTiles plans={plans} day={plan?.day} onPick={setPicked} />}
|
||||||
<Sec title="언제 보면 좋을까" sub="보통 해 진 뒤 10~20분이 가장 붉어요" />
|
{plan && <ScoreHelp plan={plan} />}
|
||||||
|
<Sec title="언제 보면 좋을까" />
|
||||||
{plan?.timeline?.length || load === 'loading' ? (
|
{plan?.timeline?.length || load === 'loading' ? (
|
||||||
<Timeline rows={plan?.timeline} />
|
<Timeline rows={plan?.timeline} kind={plan?.kind} />
|
||||||
) : (
|
) : (
|
||||||
<StateBox load="ready" empty={load === 'ready' ? '노을 시간 정보가 없어요.' : '노을 시간을 불러오지 못했어요.'} hold={<Timeline />} className="inset-x-3 top-3 bottom-0" />
|
<StateBox load="ready" empty={load === 'ready' ? '노을 시간 정보가 없어요.' : '노을 시간을 불러오지 못했어요.'} hold={<Timeline />} className="inset-x-3 top-3 bottom-0" />
|
||||||
)}
|
)}
|
||||||
{/* 더 나은 날이 있을 때만 */}
|
{!rise && <Sec title="가까운 노을 명소" sub="가까운 순 · 방향은 내 동네에서 본 쪽" />}
|
||||||
{plan?.outlook && <p className="mx-3 mt-3 mb-0 rounded-[22px] bg-[#ffe6ec] px-4 py-3 text-[14px] font-bold text-[#7a2a4a]">{plan.outlook}</p>}
|
{rise ? null : spots.length ? (
|
||||||
<Sec title="가까운 노을 명소" sub="가까운 순 · 방향은 내 동네에서 본 쪽" />
|
|
||||||
{spots.length ? (
|
|
||||||
<ul className="mx-3 mt-1.5 flex flex-col">
|
<ul className="mx-3 mt-1.5 flex flex-col">
|
||||||
{spots.map((p) => (
|
{spots.map((p) => (
|
||||||
<Li key={p.no} no={p.no} title={p.name} sub={p.direction ? `${p.direction}쪽` : null} right={`${p.distance_km}km`} place={p.name} />
|
<Li key={p.no} no={p.no} title={p.name} sub={p.direction ? `${p.direction}쪽` : null} right={`${p.distance_km}km`} place={p.name} />
|
||||||
|
|||||||
+131
-85
@@ -2,7 +2,7 @@ import { Fragment, useEffect, useState, type ReactNode } from 'react'
|
|||||||
import { Link } from 'react-router'
|
import { Link } from 'react-router'
|
||||||
import { useQuery } from '@tanstack/react-query'
|
import { useQuery } from '@tanstack/react-query'
|
||||||
import { getFeedOptions, getWeatherTodayOptions } from '../api/client/@tanstack/react-query.gen'
|
import { getFeedOptions, getWeatherTodayOptions } from '../api/client/@tanstack/react-query.gen'
|
||||||
import type { BandArticle, BandEvent, Hero as HeroData, HeroStat as HeroStatData, ResWeatherToday, TopIndex } from '../api/client/types.gen'
|
import { RainType, Sky, type BandArticle, type BandEvent, type Hero as HeroData, type ResWeatherToday, type TopIndex, type WeatherSlot } from '../api/client/types.gen'
|
||||||
import { cx } from '../lib/utils'
|
import { cx } from '../lib/utils'
|
||||||
import { cardBg, fall, kindOfHour, kst, type Load, loadOf, MEDALS, type TimeKind, WEEKDAYS } from './lib'
|
import { cardBg, fall, kindOfHour, kst, type Load, loadOf, MEDALS, type TimeKind, WEEKDAYS } from './lib'
|
||||||
import { PostCard, PostCardSkel } from './Post'
|
import { PostCard, PostCardSkel } from './Post'
|
||||||
@@ -10,26 +10,23 @@ import { useRegion } from './regionContext'
|
|||||||
import { useSheet } from './sheetContext'
|
import { useSheet } from './sheetContext'
|
||||||
import { useSky } from './skyContext'
|
import { useSky } from './skyContext'
|
||||||
import { Ic, Rail, Sec, Skel, SkelRail, StateBox, Thumb } from './ui'
|
import { Ic, Rail, Sec, Skel, SkelRail, StateBox, Thumb } from './ui'
|
||||||
import { deg, skyText, slotAt } from './weatherText'
|
import { deg, slotAt } from './weatherText'
|
||||||
|
|
||||||
type Mode = 'now' | TimeKind
|
type Mode = 'now' | TimeKind
|
||||||
|
|
||||||
const MODES: [Mode, string][] = [
|
// 하루 흐름 칸 순서와 칸마다 볼 예보 시각
|
||||||
['now', '지금'],
|
const KINDS: TimeKind[] = ['morning', 'day', 'sunset', 'night']
|
||||||
['morning', '아침'],
|
const PREVIEW: Record<TimeKind, { label: string; hour: number }> = {
|
||||||
['day', '낮'],
|
morning: { label: '아침', hour: 7 },
|
||||||
['sunset', '저녁'],
|
day: { label: '낮', hour: 13 },
|
||||||
['night', '밤'],
|
sunset: { label: '저녁', hour: 18 },
|
||||||
]
|
night: { label: '밤', hour: 22 },
|
||||||
|
|
||||||
// 미리보기 시간대마다 보여 줄 시계와 그 시각의 예보 칸
|
|
||||||
const PREVIEW: Record<TimeKind, { label: string; clock: string; hour: number }> = {
|
|
||||||
morning: { label: '아침', clock: '07:40', hour: 7 },
|
|
||||||
day: { label: '낮', clock: '13:20', hour: 13 },
|
|
||||||
sunset: { label: '저녁', clock: '18:25', hour: 18 },
|
|
||||||
night: { label: '밤', clock: '22:10', hour: 22 },
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 비·눈 줄기: 위치·주기를 엇갈려 고르게
|
||||||
|
const DROPS = Array.from({ length: 22 }, (_, i) => ({ left: `${(i * 41) % 100}%`, '--top': `${(i * 29) % 90}%`, '--dl': `${((i * 37) % 100) / 100}s`, '--dur': `${0.55 + ((i * 13) % 5) / 10}s` }))
|
||||||
|
const FLAKES = Array.from({ length: 16 }, (_, i) => ({ left: `${(i * 47) % 100}%`, '--top': `${(i * 31) % 90}%`, '--dl': `${((i * 53) % 100) / 25}s`, '--dur': `${3.2 + ((i * 7) % 5) / 2}s` }))
|
||||||
|
|
||||||
const STARS = Array.from({ length: 26 }, (_, i) => ({ left: `${(i * 37) % 100}%`, top: `${(i * 53) % 60}%`, opacity: 0.4 + ((i * 7) % 6) / 10 }))
|
const STARS = Array.from({ length: 26 }, (_, i) => ({ left: `${(i * 37) % 100}%`, top: `${(i * 53) % 60}%`, opacity: 0.4 + ((i * 7) % 6) / 10 }))
|
||||||
// 별똥별 셋: 위치·길이·주기를 엇갈려 하나씩 떨어지게
|
// 별똥별 셋: 위치·길이·주기를 엇갈려 하나씩 떨어지게
|
||||||
const SHOOTS = [
|
const SHOOTS = [
|
||||||
@@ -67,34 +64,74 @@ function heroVal(load: Load, v: ReactNode, skel: string) {
|
|||||||
|
|
||||||
const failed = (load: Load) => load === 'error' || load === 'retrying'
|
const failed = (load: Load) => load === 'error' || load === 'retrying'
|
||||||
|
|
||||||
type HeroProps = { hero?: HeroData | null; today?: ResWeatherToday; feedLoad: Load; todayLoad: Load }
|
// 미리보기 탭과 서버 구간 이름. 저녁 탭(노을 하늘)은 서버의 evening 구간
|
||||||
|
const SLOT_KEY: Record<TimeKind, string> = { morning: 'morning', day: 'day', sunset: 'evening', night: 'night' }
|
||||||
|
|
||||||
function Hero({ hero, today, feedLoad, todayLoad }: HeroProps) {
|
/** 미리보기 시간대면 이미 받은 구간 점수·순위로 다시 줄 세운다. 그 구간과 안 겹치는 각은 흐리게 끝으로. 구간 값이 없으면(예전 캐시) 그대로 */
|
||||||
|
function atSlot(items: TopIndex[], kind: TimeKind | null): TopIndex[] {
|
||||||
|
const k = kind && SLOT_KEY[kind]
|
||||||
|
if (!k || !items.some((g) => Object.keys(g.slot_ranks ?? {}).length)) return items
|
||||||
|
const on = items.filter((g) => g.slot_ranks?.[k] != null && g.slots?.[k] != null)
|
||||||
|
return [
|
||||||
|
...on.map((g) => ({ ...g, score: g.slots![k], rank: g.slot_ranks![k], active: true })).sort((a, b) => a.rank - b.rank),
|
||||||
|
...items.filter((g) => !on.includes(g)).map((g) => ({ ...g, active: false })),
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
type HeroProps = { hero?: HeroData | null; today?: ResWeatherToday; ranked: TopIndex[]; feedLoad: Load; todayLoad: Load }
|
||||||
|
|
||||||
|
type Weather = 'clear' | 'partly' | 'cloudy' | 'rain' | 'snow' | 'sleet'
|
||||||
|
|
||||||
|
/** 예보 칸 하나의 하늘: 비·눈이 오면 그걸, 아니면 구름 양 */
|
||||||
|
function weatherOf(slot?: WeatherSlot): Weather {
|
||||||
|
const r = slot?.rain_type
|
||||||
|
if (r === RainType.RAIN || r === RainType.SHOWER) return 'rain'
|
||||||
|
if (r === RainType.SNOW) return 'snow'
|
||||||
|
if (r === RainType.SLEET) return 'sleet'
|
||||||
|
return slot?.sky === Sky.CLOUDY ? 'cloudy' : slot?.sky === Sky.PARTLY ? 'partly' : 'clear'
|
||||||
|
}
|
||||||
|
|
||||||
|
const WEATHER_ICON: Record<Weather, string> = { clear: 'sun', partly: 'sun_cloud', cloudy: 'cloud', rain: 'rain', snow: 'snow', sleet: 'snow' }
|
||||||
|
// 구름 수: 구름 많음 둘, 흐림·비·눈 셋
|
||||||
|
const CLOUDS = [
|
||||||
|
{ cls: 'top-9 left-[5%] h-8 w-[84px]', d: '.1s', f: '6s' },
|
||||||
|
{ cls: 'top-[96px] left-[63%] h-9 w-[96px]', d: '.25s', f: '6.4s' },
|
||||||
|
{ cls: 'top-[30px] left-[72%] h-7 w-[64px]', d: '.4s', f: '5.4s' },
|
||||||
|
]
|
||||||
|
const CLOUD_N: Record<Weather, number> = { clear: 0, partly: 2, cloudy: 3, rain: 3, snow: 3, sleet: 3 }
|
||||||
|
|
||||||
|
function Hero({ hero, today, ranked, feedLoad, todayLoad }: HeroProps) {
|
||||||
const { open } = useSheet()
|
const { open } = useSheet()
|
||||||
const [mode, setMode] = useState<Mode>('now')
|
const { preview, setServerKind, setPreview } = useSky()
|
||||||
|
const mode: Mode = preview ?? 'now'
|
||||||
const clock = useNow()
|
const clock = useNow()
|
||||||
const t = kst(clock)
|
const t = kst(clock)
|
||||||
const kind = mode === 'now' ? (hero?.sky_mode ?? kindOfHour(t.h, t.mo, t.mi)) : mode
|
const nowKind = hero?.sky_mode ?? kindOfHour(t.h, t.mo, t.mi)
|
||||||
const { setServerKind, setPreview } = useSky()
|
const kind = mode === 'now' ? nowKind : mode
|
||||||
// 화면 전체 하늘 배경도 같은 시간대로 맞춘다
|
// 화면 전체 하늘 배경도 같은 시간대로 맞춘다
|
||||||
useEffect(() => setServerKind(hero?.sky_mode ?? null), [hero?.sky_mode, setServerKind])
|
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 slots = today?.slots ?? []
|
||||||
const slot = slots.length ? slotAt(slots, mode === 'now' ? t.h : PREVIEW[mode].hour) : undefined
|
// 그 시각 칸, 비어 있으면(지난 새벽 칸 등) 그 뒤 첫 예보 칸
|
||||||
// 지금은 /v1/feed hero 값을, 미리보기는 그 시각의 예보 칸을 쓴다
|
const slotOf = (k: TimeKind | 'now') => {
|
||||||
const temp = mode === 'now' && hero ? hero.temp_c : slot?.temp_c
|
const h = k === 'now' ? t.h : PREVIEW[k].hour
|
||||||
const top1 = hero?.top1
|
const s = slots.length ? slotAt(slots, h) : undefined
|
||||||
const who = kind === 'night' ? 'bear' : 'rabbit'
|
return s?.temp_c != null ? s : (slots.find((x) => kst(x.at).h > h && x.temp_c != null) ?? s)
|
||||||
|
}
|
||||||
|
const weather = weatherOf(slotOf(mode))
|
||||||
|
const slotScore = mode === 'now' ? undefined : hero?.weather_slots?.[SLOT_KEY[mode]]
|
||||||
|
const score = slotScore ?? hero?.weather_score
|
||||||
|
const slotTop = mode === 'now' ? undefined : ranked.find((g) => g.active)
|
||||||
|
const top1 = slotTop ?? hero?.top1
|
||||||
// 저녁(노을)부터는 가운데 동그라미가 오늘 밤 달 모양이 된다
|
// 저녁(노을)부터는 가운데 동그라미가 오늘 밤 달 모양이 된다
|
||||||
const moon = (kind === 'sunset' || kind === 'night') && hero?.moon_name && hero.moon_pct != null ? { name: hero.moon_name, pct: hero.moon_pct, waning: WANING.includes(hero.moon_name) } : null
|
const moon = (kind === 'sunset' || kind === 'night') && hero?.moon_name && hero.moon_pct != null ? { name: hero.moon_name, pct: hero.moon_pct, waning: WANING.includes(hero.moon_name) } : null
|
||||||
const tempLoad = mode === 'now' ? feedLoad : todayLoad
|
const bubble = slotTop ? (slotTop.score >= 70 ? `오늘은 ${slotTop.name}!` : '오늘은 쉬어 가요') : hero ? (hero.bubble ?? '오늘은 쉬어 가요') : failed(feedLoad) ? '앗, 날씨를 못 불러왔어요' : null
|
||||||
const tempChip = temp != null ? `${deg(temp)}${slot ? ` ${skyText(slot)}` : ''}` : null
|
const status = hero?.status ?? []
|
||||||
const bubble = hero ? (hero.bubble ?? '오늘은 쉬어 가요') : failed(feedLoad) ? '앗, 날씨를 못 불러왔어요' : null
|
const rain = weather === 'rain' || weather === 'sleet'
|
||||||
|
const snow = weather === 'snow' || weather === 'sleet'
|
||||||
|
|
||||||
// 시안 A: 점수 해가 주인공. 위에 시간대 탭과 날짜, 가운데 큰 해, 아래 칩 한 줄과 캐릭터 말풍선(1위 각)
|
// 시안 D4-2: 가운데 해(점수)와 하늘 날씨, 결론 두 줄, 상태 한 줄, 아래 하루 흐름 칸(누르면 그 시간대 하늘로)
|
||||||
return (
|
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} data-sky={weather}>
|
||||||
<div className="b-stars pointer-events-none absolute inset-0" aria-hidden="true">
|
<div className="b-stars pointer-events-none absolute inset-0" aria-hidden="true">
|
||||||
{STARS.map((s, i) => (
|
{STARS.map((s, i) => (
|
||||||
<i key={i} className="absolute size-[3px] rounded-full shadow-[0_0_6px_#fff]" style={s} />
|
<i key={i} className="absolute size-[3px] rounded-full shadow-[0_0_6px_#fff]" style={s} />
|
||||||
@@ -103,19 +140,20 @@ function Hero({ hero, today, feedLoad, todayLoad }: HeroProps) {
|
|||||||
<span key={i} className="b-shoot" style={s} />
|
<span key={i} className="b-shoot" style={s} />
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
<div className="relative z-[3] grid grid-cols-5 rounded-full bg-white/45 p-1" role="tablist" aria-label="시간대 배경 미리보기">
|
{(rain || snow) && (
|
||||||
{MODES.map(([m, l]) => (
|
<div className="pointer-events-none absolute inset-0 z-[2]" aria-hidden="true">
|
||||||
<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')}>
|
{rain && DROPS.map((s, i) => <i key={i} className="b-drop" style={s} />)}
|
||||||
{l}
|
{snow && FLAKES.map((s, i) => <i key={i} className="b-flake" style={s} />)}
|
||||||
</button>
|
</div>
|
||||||
))}
|
)}
|
||||||
</div>
|
<p className="relative z-[3] m-0 text-[14px] font-bold opacity-80">
|
||||||
<p className="relative z-[3] mt-3 mb-0 text-[15px] font-bold opacity-90">
|
{t.mo}월 {t.d}일 {WEEKDAYS[t.wd]}요일
|
||||||
{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>
|
</p>
|
||||||
<div className="relative h-[262px]">
|
<div className="relative h-[146px]">
|
||||||
<span className="b-cloud b-fall top-6 left-[2%] h-9 w-[100px]" style={fall('.1s', '6s')} aria-hidden="true" />
|
{CLOUDS.slice(0, CLOUD_N[weather]).map((c) => (
|
||||||
<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')}>
|
<span key={c.cls} className={cx('b-cloud b-fall z-[1]', c.cls)} style={fall(c.d, c.f)} aria-hidden="true" />
|
||||||
|
))}
|
||||||
|
<div className="b-sun b-fall absolute top-2 left-1/2 -ml-16 grid aspect-square w-32 place-items-center rounded-full text-center" style={fall('0s', '5.6s', '8px')}>
|
||||||
{/* 안 보이는 쪽을 덮어 오늘 밤 달 모양으로 */}
|
{/* 안 보이는 쪽을 덮어 오늘 밤 달 모양으로 */}
|
||||||
{moon && (
|
{moon && (
|
||||||
<svg viewBox="-1 -1 2 2" className="pointer-events-none absolute inset-0 size-full" aria-hidden="true">
|
<svg viewBox="-1 -1 2 2" className="pointer-events-none absolute inset-0 size-full" aria-hidden="true">
|
||||||
@@ -123,48 +161,52 @@ function Hero({ hero, today, feedLoad, todayLoad }: HeroProps) {
|
|||||||
</svg>
|
</svg>
|
||||||
)}
|
)}
|
||||||
<span className={cx('relative', moon && '[text-shadow:0_0_6px_#fff,0_0_12px_#fff]')}>
|
<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>
|
<small className="block font-jua text-[12px]">{failed(feedLoad) ? '점수를 못 불러왔어요' : `${slotScore != null && mode !== 'now' ? PREVIEW[mode].label : '지금'} 날씨 점수`}</small>
|
||||||
<b className="block font-bagel text-[96px] leading-[0.95] font-normal">{heroVal(feedLoad, hero?.weather_score, 'w-[120px]')}</b>
|
<b className="block font-bagel text-[52px] leading-[0.95] font-normal">{heroVal(feedLoad, score, 'w-[84px]')}</b>
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
<span className="b-cloud b-fall top-[188px] left-[58%] h-11 w-[118px]" style={fall('.25s', '6.4s')} aria-hidden="true" />
|
|
||||||
</div>
|
</div>
|
||||||
{/* 기온 + 서버가 고른 챙길 것(비·미세먼지·자외선·일교차 등)을 한 줄 칩으로 */}
|
<div className="relative z-[3] text-center">
|
||||||
<div className="relative z-[3] mt-2 flex flex-wrap justify-center gap-2">
|
|
||||||
<Chip>{heroVal(tempLoad, tempChip, 'w-16')}</Chip>
|
|
||||||
{hero?.stats?.length
|
|
||||||
? hero.stats.map((s) => (
|
|
||||||
<Chip key={s.label} tone={s.tone}>
|
|
||||||
{s.label} {s.value}
|
|
||||||
</Chip>
|
|
||||||
))
|
|
||||||
: feedLoad === 'loading' && <Chip>{heroVal(feedLoad, null, 'w-20')}</Chip>}
|
|
||||||
</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)]" />
|
|
||||||
{top1 ? (
|
{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">
|
<button type="button" onClick={() => open({ type: 'gak', indexId: top1.index_id })} aria-label={`${bubble ?? ''} 1위 ${top1.name} ${top1.score}점, 계산 근거 보기`} className="cursor-pointer font-jua text-[24px] leading-tight">
|
||||||
<span className="min-w-0 flex-1 truncate font-jua text-[17px]">{bubble}</span>
|
{bubble}
|
||||||
<Ic name={top1.icon} className="w-8 shrink-0" />
|
|
||||||
<em className="font-bagel text-[17px] text-(--orange) not-italic">{top1.score}</em>
|
|
||||||
</button>
|
</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>
|
<p className="m-0 font-jua text-[24px] leading-tight">{bubble ?? <Skel className="w-[160px]" />}</p>
|
||||||
|
)}
|
||||||
|
<p className="m-0 mt-0.5 text-[15px] font-bold opacity-80">{top1?.summary ?? (feedLoad === 'loading' ? <Skel className="w-[140px]" /> : null)}</p>
|
||||||
|
{/* 상태 한 줄: 습도·불쾌지수·자외선·미세먼지 단계 이름. 조심할 것만 색 */}
|
||||||
|
{status.length > 0 && (
|
||||||
|
<p className="m-0 mt-1.5 flex flex-wrap justify-center gap-x-1.5 font-jua text-[14px]">
|
||||||
|
{status.map((x, i) => (
|
||||||
|
<Fragment key={x.label}>
|
||||||
|
{i > 0 && <span className="opacity-30" aria-hidden="true">·</span>}
|
||||||
|
<span className={cx('whitespace-nowrap', x.tone === 'warn' && 'b-warn')}>
|
||||||
|
<span className={cx(x.tone !== 'warn' && 'opacity-75')}>{x.label}</span> <b className="font-normal">{x.value}</b>
|
||||||
|
</span>
|
||||||
|
</Fragment>
|
||||||
|
))}
|
||||||
|
</p>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
<div className="b-strip relative z-[3] mt-2.5 grid grid-cols-4 gap-1 rounded-[18px] p-[3px]" role="tablist" aria-label="하루 흐름, 누르면 그 시간대 하늘로">
|
||||||
|
{KINDS.map((k) => {
|
||||||
|
const s = slotOf(k)
|
||||||
|
const on = k === kind
|
||||||
|
const isNow = k === nowKind
|
||||||
|
return (
|
||||||
|
<button key={k} type="button" role="tab" aria-selected={on} onClick={() => setPreview(isNow ? null : k)} className={cx('flex cursor-pointer flex-col items-center rounded-[14px] py-1.5', on && 'b-strip-on')}>
|
||||||
|
<span className={cx('text-[13px] font-bold', on ? 'text-(--orange-deep)' : 'opacity-75')}>{isNow ? '지금' : PREVIEW[k].label}</span>
|
||||||
|
<Ic name={k === 'night' && weatherOf(s) === 'clear' ? 'moon' : WEATHER_ICON[weatherOf(s)]} className="my-0.5 h-[22px] w-[22px] object-contain" />
|
||||||
|
<b className="font-jua text-[15px] font-normal">{heroVal(todayLoad, s?.temp_c != null ? deg(s.temp_c) : null, 'w-7')}</b>
|
||||||
|
</button>
|
||||||
|
)
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 히어로 아래 한 줄 칩. tone 은 서버가 정한 상태(비·경고)로 색을 바꾼다 */
|
|
||||||
function Chip({ tone = 'normal', children }: { 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>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
const WANING = ['기우는 달', '하현달', '그믐달']
|
const WANING = ['기우는 달', '하현달', '그믐달']
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -182,15 +224,19 @@ function Stories({ items }: { items: TopIndex[] }) {
|
|||||||
return (
|
return (
|
||||||
<Rail label="오늘의 각 순위">
|
<Rail label="오늘의 각 순위">
|
||||||
{items.map((g, i) => (
|
{items.map((g, i) => (
|
||||||
<button key={g.index_id} type="button" onClick={() => open({ type: 'gak', indexId: g.index_id })} aria-label={`${g.rank}위 ${g.name} ${g.score}점`} className="flex w-[72px] cursor-pointer flex-col items-center gap-1">
|
<button key={g.index_id} type="button" onClick={() => open({ type: 'gak', indexId: g.index_id })} aria-label={g.active ? `${g.rank}위 ${g.name} ${g.score}점` : `${g.name}, 지금 시간대 아님`} className={cx('flex w-[72px] cursor-pointer flex-col items-center gap-1', !g.active && 'opacity-55')}>
|
||||||
<span className={cx('relative size-[68px] rounded-full p-[3px]', g.score < 50 ? 'bg-[#d6deea]' : 'b-ring')}>
|
<span className={cx('relative size-[68px] rounded-full p-[3px]', !g.active || g.score < 50 ? 'bg-[#d6deea]' : 'b-ring')}>
|
||||||
<i className="grid size-full place-items-center rounded-full border-[3px] border-(--page) bg-(--page)">
|
<i className="grid size-full place-items-center rounded-full border-[3px] border-(--page) bg-(--page)">
|
||||||
<Ic name={g.icon} className="w-[42px]" />
|
<Ic name={g.icon} className="w-[42px]" />
|
||||||
</i>
|
</i>
|
||||||
{i < 3 && <Ic name={MEDALS[i]} className="absolute -right-1 -bottom-1 w-[25px]" />}
|
{i < 3 && g.active && <Ic name={MEDALS[i]} className="absolute -right-1 -bottom-1 w-[25px]" />}
|
||||||
</span>
|
</span>
|
||||||
<b className="font-jua text-[13px] font-normal whitespace-nowrap">{g.name}</b>
|
<b className="font-jua text-[13px] font-normal whitespace-nowrap">{g.name}</b>
|
||||||
<em className="font-bagel text-[12.5px] leading-none text-(--orange) not-italic">{g.score}</em>
|
{g.active ? (
|
||||||
|
<em className="font-bagel text-[12.5px] leading-none text-(--orange) not-italic">{g.score}</em>
|
||||||
|
) : (
|
||||||
|
<small className="text-[11px] leading-none font-extrabold text-(--ink3)">지금 아님</small>
|
||||||
|
)}
|
||||||
</button>
|
</button>
|
||||||
))}
|
))}
|
||||||
</Rail>
|
</Rail>
|
||||||
@@ -281,9 +327,7 @@ function SeasonBand({ news }: { news: BandArticle[] }) {
|
|||||||
<Rail>
|
<Rail>
|
||||||
{news.map((a) => (
|
{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)]">
|
<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)}`)}>
|
<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]" />
|
||||||
<Ic name={a.icon} className="w-[76px]" />
|
|
||||||
</span>
|
|
||||||
<span className="block px-3 pt-2.5 pb-3">
|
<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>
|
<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>
|
<small className="text-[12.5px] font-semibold text-(--ink2)">{a.meta}</small>
|
||||||
@@ -299,9 +343,11 @@ export function TodayPage() {
|
|||||||
const { region } = useRegion()
|
const { region } = useRegion()
|
||||||
const feed = useQuery(getFeedOptions({ query: { region: region.code } }))
|
const feed = useQuery(getFeedOptions({ query: { region: region.code } }))
|
||||||
const today = useQuery(getWeatherTodayOptions({ query: { region: region.code } }))
|
const today = useQuery(getWeatherTodayOptions({ query: { region: region.code } }))
|
||||||
|
const { preview } = useSky()
|
||||||
const f = feed.data
|
const f = feed.data
|
||||||
const posts = f?.posts ?? []
|
const posts = f?.posts ?? []
|
||||||
const stories = f?.stories ?? []
|
const stories = atSlot(f?.stories ?? [], preview)
|
||||||
|
const sloted = preview != null && stories !== f?.stories
|
||||||
const bands = f?.bands
|
const bands = f?.bands
|
||||||
const nowAt = f?.hero?.now_at
|
const nowAt = f?.hero?.now_at
|
||||||
const load = loadOf(feed)
|
const load = loadOf(feed)
|
||||||
@@ -313,14 +359,14 @@ export function TodayPage() {
|
|||||||
// 디자인대로 3·6·9번째 글 뒤에 띠를 넣고, 글이 모자라면 남은 띠는 맨 뒤에 붙인다
|
// 디자인대로 3·6·9번째 글 뒤에 띠를 넣고, 글이 모자라면 남은 띠는 맨 뒤에 붙인다
|
||||||
const bandAt: [number, ReactNode][] = [
|
const bandAt: [number, ReactNode][] = [
|
||||||
[3, bands?.events?.length ? <EventsBand key="events" events={bands.events} /> : null],
|
[3, bands?.events?.length ? <EventsBand key="events" events={bands.events} /> : null],
|
||||||
[6, bands?.top5?.length ? <TopBand key="top5" items={bands.top5} sub={nowAt ? `${kst(nowAt).h}시 기준` : '오늘 기준'} /> : null],
|
[6, bands?.top5?.length ? <TopBand key="top5" items={sloted ? stories.filter((g) => g.active) : bands.top5} sub={sloted ? `${PREVIEW[preview].label} 기준` : nowAt ? `${kst(nowAt).h}시 기준` : '오늘 기준'} /> : null],
|
||||||
[9, bands?.season?.length ? <SeasonBand key="season" news={bands.season} /> : null],
|
[9, bands?.season?.length ? <SeasonBand key="season" news={bands.season} /> : null],
|
||||||
]
|
]
|
||||||
|
|
||||||
return (
|
return (
|
||||||
// 피드 칸은 전국 공통이라 지역이 바뀌어도 글 번호가 같다. 지역마다 새로 그려 넘긴 슬라이드·펼친 상태가 남지 않게 한다
|
// 피드 칸은 전국 공통이라 지역이 바뀌어도 글 번호가 같다. 지역마다 새로 그려 넘긴 슬라이드·펼친 상태가 남지 않게 한다
|
||||||
<section key={region.code} aria-label="오늘" aria-busy={load === 'loading'} className={cx('transition-opacity', feed.isPlaceholderData && 'opacity-60')}>
|
<section key={region.code} aria-label="오늘" aria-busy={load === 'loading'} className={cx('transition-opacity', feed.isPlaceholderData && 'opacity-60')}>
|
||||||
<Hero hero={f?.hero} today={today.data} feedLoad={load} todayLoad={loadOf(today)} />
|
<Hero hero={f?.hero} today={today.data} ranked={stories} feedLoad={load} todayLoad={loadOf(today)} />
|
||||||
<Sec title="오늘의 각" sub="누르면 계산 근거를 보여 줘요" more={{ to: '/gak' }} />
|
<Sec title="오늘의 각" sub="누르면 계산 근거를 보여 줘요" more={{ to: '/gak' }} />
|
||||||
{/* 실패 안내는 여기 한 번만, 각 줄 스켈레톤과 같은 크기로 */}
|
{/* 실패 안내는 여기 한 번만, 각 줄 스켈레톤과 같은 크기로 */}
|
||||||
{stories.length ? <Stories items={stories} /> : load === 'loading' ? <StoriesSkel /> : <StateBox load={load} onRetry={() => feed.refetch()} empty="오늘 계산된 각이 없어요." hold={<StoriesSkel />} className="inset-x-3 top-3 bottom-1" />}
|
{stories.length ? <Stories items={stories} /> : load === 'loading' ? <StoriesSkel /> : <StateBox load={load} onRetry={() => feed.refetch()} empty="오늘 계산된 각이 없어요." hold={<StoriesSkel />} className="inset-x-3 top-3 bottom-1" />}
|
||||||
|
|||||||
+19
-18
@@ -1,11 +1,11 @@
|
|||||||
import { useState, type ReactNode } from 'react'
|
import { useRef, useState, type ReactNode } from 'react'
|
||||||
import { useQuery } from '@tanstack/react-query'
|
import { useQuery } from '@tanstack/react-query'
|
||||||
import { getWeekOptions, getWeekRankingOptions, listEventsOptions, listPlacesOptions } from '../api/client/@tanstack/react-query.gen'
|
import { getWeekOptions, getWeekRankingOptions, listEventsOptions, listPlacesOptions } from '../api/client/@tanstack/react-query.gen'
|
||||||
import { cx } from '../lib/utils'
|
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 { useRegion } from './regionContext'
|
||||||
import { shareLink } from './shareLink'
|
import { useSheet } from './sheetContext'
|
||||||
import { Arrows, Chips, Ic, MapLink, Rail, ScreenNote, Sec, Skel, SkelRail, StateBox, Thumb } from './ui'
|
import { Arrows, Chips, Ic, MapLink, Rail, Sec, Skel, SkelRail, StateBox, Thumb } from './ui'
|
||||||
import { useCarousel } from './carousel'
|
import { useCarousel } from './carousel'
|
||||||
|
|
||||||
const TEN = Array.from({ length: 10 }, (_, i) => i)
|
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() {
|
export function WeekPage() {
|
||||||
const { region } = useRegion()
|
const { region } = useRegion()
|
||||||
|
const { open } = useSheet()
|
||||||
const week = useQuery(getWeekOptions({ query: { region: region.code } }))
|
const week = useQuery(getWeekOptions({ query: { region: region.code } }))
|
||||||
const days = week.data?.days ?? []
|
const days = week.data?.days ?? []
|
||||||
const [picked, setPicked] = useState<string | null>(null)
|
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 rankDay = rankDays.find((d) => d.day === rankPick) ?? rankDays[0]
|
||||||
const rankItems = (rankDay?.items ?? []).slice(0, 10)
|
const rankItems = (rankDay?.items ?? []).slice(0, 10)
|
||||||
const rankLoad = loadOf(ranking)
|
const rankLoad = loadOf(ranking)
|
||||||
const sido = sidoOf(region.name)
|
|
||||||
const areas = places.data?.areas ?? []
|
const areas = places.data?.areas ?? []
|
||||||
const rainy = places.data?.rainy ?? sel?.is_rainy
|
const rainy = places.data?.rainy ?? sel?.is_rainy
|
||||||
const placeList = places.data?.places ?? []
|
const placeList = places.data?.places ?? []
|
||||||
@@ -164,12 +164,14 @@ export function WeekPage() {
|
|||||||
// 날씨(고른 날)가 와야 명소를 부를 수 있다
|
// 날씨(고른 날)가 와야 명소를 부를 수 있다
|
||||||
const placeLoad = sel ? loadOf(places) : weekLoad === 'loading' ? 'loading' : 'ready'
|
const placeLoad = sel ? loadOf(places) : weekLoad === 'loading' ? 'loading' : 'ready'
|
||||||
|
|
||||||
const [note, setNote] = useState('')
|
const pickRef = useRef<HTMLDivElement>(null)
|
||||||
const sendPlan = () => void shareLink().then((m) => m && setNote(m))
|
const sendPlan = () => {
|
||||||
|
if (!sel || !pickRef.current) return
|
||||||
|
open({ type: 'share', share: { title: `${sel.weekday}요일 일정`, slides: [pickRef.current] } })
|
||||||
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<section aria-label="주말·행사" aria-busy={weekLoad === 'loading'}>
|
<section aria-label="주말·행사" aria-busy={weekLoad === 'loading'}>
|
||||||
<ScreenNote text={note} setText={setNote} />
|
|
||||||
<Sec title="열흘 날씨" sub="날짜를 누르면 그날 추천이 바뀌어요" />
|
<Sec title="열흘 날씨" sub="날짜를 누르면 그날 추천이 바뀌어요" />
|
||||||
{days.length ? (
|
{days.length ? (
|
||||||
<DayStrip dim={week.isPlaceholderData}>
|
<DayStrip dim={week.isPlaceholderData}>
|
||||||
@@ -212,7 +214,7 @@ export function WeekPage() {
|
|||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
{sel && (
|
{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" />
|
<Ic name={sel.icon} className="w-16" />
|
||||||
<div>
|
<div>
|
||||||
<b className="block font-jua text-[19px] font-normal">{sel.headline}</b>
|
<b className="block font-jua text-[19px] font-normal">{sel.headline}</b>
|
||||||
@@ -224,7 +226,7 @@ export function WeekPage() {
|
|||||||
{(sel || weekLoad !== 'ready') && (
|
{(sel || weekLoad !== 'ready') && (
|
||||||
<div className="mx-3 mt-3.5 flex items-center justify-between">
|
<div className="mx-3 mt-3.5 flex items-center justify-between">
|
||||||
<label htmlFor="b-area" className="text-[13.5px] font-bold text-(--ink2)">
|
<label htmlFor="b-area" className="text-[13.5px] font-bold text-(--ink2)">
|
||||||
{sido} · 데이트 명소
|
30km 안 · 데이트 명소
|
||||||
</label>
|
</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">
|
<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) => (
|
{['전체', ...areas].map((a) => (
|
||||||
@@ -233,7 +235,7 @@ export function WeekPage() {
|
|||||||
</select>
|
</select>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
{/* 명소 데이터가 없는 지역은 칸 전체를 숨긴다 (지금은 서울만 있음) */}
|
{/* 명소 데이터가 없으면 칸 전체를 숨긴다 */}
|
||||||
{!(placeLoad === 'ready' && !placeList.length) && (
|
{!(placeLoad === 'ready' && !placeList.length) && (
|
||||||
<>
|
<>
|
||||||
<Sec title="날씨 맞춤 데이트 명소" sub={sel ? `${sel.weekday}요일은 ${rainy ? '비가 와서 실내 명소를 먼저' : sel.icon === 'sun' ? '맑아서 야외 명소를 먼저' : '비 소식이 없어 야외 명소를 먼저'} 보여 줘요` : weekLoad === 'loading' ? <Skel className="w-56" /> : '날씨에 맞춰 골라 보여 줘요'} className="pt-3" />
|
<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')}>
|
<Rail className={cx('transition-opacity', places.isPlaceholderData && 'opacity-60')}>
|
||||||
{placeList.map((p, i) => (
|
{placeList.map((p, i) => (
|
||||||
<div key={p.place_id} className={PLACE_CARD}>
|
<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>}
|
{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]" />
|
</Thumb>
|
||||||
</span>
|
|
||||||
<span className="block px-3 pt-2.5 pb-3">
|
<span className="block px-3 pt-2.5 pb-3">
|
||||||
<span className="text-[11.5px] font-extrabold text-(--ink3)">
|
<span className="text-[11.5px] font-extrabold text-(--ink3)">
|
||||||
{p.area} · {p.is_outdoor ? '야외' : '실내'}
|
{p.area} · {p.distance_km}km · {p.is_outdoor ? '야외' : '실내'}
|
||||||
</span>
|
</span>
|
||||||
<b className="block font-jua text-[16.5px] font-normal">
|
<b className="block font-jua text-[16.5px] font-normal">
|
||||||
<MapLink place={p.name}>{p.name}</MapLink>
|
<MapLink place={p.name}>{p.name}</MapLink>
|
||||||
@@ -264,7 +265,7 @@ export function WeekPage() {
|
|||||||
) : placeLoad === 'loading' ? (
|
) : placeLoad === 'loading' ? (
|
||||||
<PlacesSkel />
|
<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 ? (
|
{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={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 ? (
|
{rankItems.length ? (
|
||||||
<ul className={cx('mx-3 mt-1.5 flex flex-col transition-opacity', ranking.isPlaceholderData && 'opacity-60')}>
|
<ul className={cx('mx-3 mt-1.5 flex flex-col transition-opacity', ranking.isPlaceholderData && 'opacity-60')}>
|
||||||
@@ -291,7 +292,7 @@ export function WeekPage() {
|
|||||||
{r.estimated && ' · 예상'}
|
{r.estimated && ' · 예상'}
|
||||||
</small>
|
</small>
|
||||||
<span className="mt-[5px] block h-1.5 overflow-hidden rounded-full bg-[#eef1f6]">
|
<span className="mt-[5px] block h-1.5 overflow-hidden rounded-full bg-[#eef1f6]">
|
||||||
<s className="block h-full bg-[linear-gradient(90deg,#9be7c4,#1f9d62)]" style={{ width: `${r.score}%` }} />
|
<s className="b-keep-bg block h-full bg-[linear-gradient(90deg,#9be7c4,#1f9d62)]" style={{ width: `${r.score}%` }} />
|
||||||
</span>
|
</span>
|
||||||
</span>
|
</span>
|
||||||
<em className="flex items-center gap-1 font-jua text-base not-italic">
|
<em className="flex items-center gap-1 font-jua text-base not-italic">
|
||||||
|
|||||||
+73
-30
@@ -170,39 +170,72 @@
|
|||||||
.b-stars i {
|
.b-stars i {
|
||||||
background: #fff;
|
background: #fff;
|
||||||
}
|
}
|
||||||
.b-stat {
|
/* 히어로 하루 흐름 칸: 한 판 위에 고른 칸만 흰 바탕 */
|
||||||
background: rgb(255 255 255 / 0.72);
|
.b-strip {
|
||||||
color: var(--ink);
|
background: rgb(255 255 255 / 0.42);
|
||||||
box-shadow: inset 0 -5px 0 rgb(217 229 244 / 0.9);
|
|
||||||
}
|
}
|
||||||
.b-hero[data-t='night'] .b-stat,
|
.b-hero[data-t='sunset'] .b-strip,
|
||||||
.b-hero[data-t='sunset'] .b-stat {
|
.b-hero[data-t='night'] .b-strip {
|
||||||
background: rgb(255 255 255 / 0.18);
|
background: rgb(255 255 255 / 0.14);
|
||||||
color: #fff;
|
|
||||||
box-shadow: inset 0 -5px 0 rgb(255 255 255 / 0.12);
|
|
||||||
}
|
}
|
||||||
.b-hero[data-t='sunset'] .b-stat {
|
.b-strip-on {
|
||||||
background: rgb(30 16 80 / 0.2);
|
|
||||||
}
|
|
||||||
/* 히어로 칸 강조: 조심(노랑)·비(파랑). 시간대 배경과 상관없이 같은 색 */
|
|
||||||
.b-hero .b-stat[data-tone='warn'] {
|
|
||||||
background: #fff3d6;
|
|
||||||
color: var(--ink);
|
|
||||||
box-shadow: inset 0 -5px 0 #ffd98a;
|
|
||||||
}
|
|
||||||
.b-hero .b-stat[data-tone='rain'] {
|
|
||||||
background: #dcecff;
|
|
||||||
color: var(--ink);
|
|
||||||
box-shadow: inset 0 -5px 0 #a9cdf5;
|
|
||||||
}
|
|
||||||
.b-bubble {
|
|
||||||
background: #fff;
|
background: #fff;
|
||||||
color: var(--ink);
|
color: #28304a; /* 밤엔 --ink 가 밝은 색이라 고정 */
|
||||||
box-shadow: 0 8px 16px rgb(40 48 74 / 0.1);
|
box-shadow: 0 4px 12px rgb(40 48 74 / 0.1);
|
||||||
}
|
}
|
||||||
.b-hero[data-t='night'] .b-bubble {
|
/* 상태 한 줄에서 조심할 것. 밤·노을 배경에선 밝은 주황 */
|
||||||
background: rgb(30 34 70 / 0.85);
|
.b-warn {
|
||||||
color: #fff;
|
color: var(--orange-deep);
|
||||||
|
}
|
||||||
|
.b-hero[data-t='sunset'] .b-warn,
|
||||||
|
.b-hero[data-t='night'] .b-warn {
|
||||||
|
color: #ffb38a;
|
||||||
|
}
|
||||||
|
/* 흐리거나 비·눈 오는 아침·낮은 하늘을 잿빛으로 */
|
||||||
|
.b-hero[data-t='morning']:is([data-sky='cloudy'], [data-sky='rain'], [data-sky='snow'], [data-sky='sleet']),
|
||||||
|
.b-hero[data-t='day']:is([data-sky='cloudy'], [data-sky='rain'], [data-sky='snow'], [data-sky='sleet']) {
|
||||||
|
background: linear-gradient(180deg, #a9bbd0, #cbd7e4 55%, #eef2f7);
|
||||||
|
}
|
||||||
|
.b-hero:is([data-sky='cloudy'], [data-sky='rain'], [data-sky='snow'], [data-sky='sleet']) .b-sun {
|
||||||
|
filter: saturate(0.7) brightness(0.96);
|
||||||
|
}
|
||||||
|
.b-drop,
|
||||||
|
.b-flake {
|
||||||
|
position: absolute;
|
||||||
|
top: -24px;
|
||||||
|
animation: b-fallsky var(--dur) linear var(--dl) infinite;
|
||||||
|
}
|
||||||
|
.b-drop {
|
||||||
|
width: 2px;
|
||||||
|
height: 18px;
|
||||||
|
border-radius: 2px;
|
||||||
|
background: linear-gradient(transparent, rgb(80 130 200 / 0.7));
|
||||||
|
}
|
||||||
|
.b-hero[data-t='sunset'] .b-drop,
|
||||||
|
.b-hero[data-t='night'] .b-drop {
|
||||||
|
background: linear-gradient(transparent, rgb(220 230 255 / 0.7));
|
||||||
|
}
|
||||||
|
.b-flake {
|
||||||
|
width: 7px;
|
||||||
|
height: 7px;
|
||||||
|
border-radius: 50%;
|
||||||
|
background: #fff;
|
||||||
|
box-shadow: 0 0 4px rgb(120 150 200 / 0.5);
|
||||||
|
}
|
||||||
|
@keyframes b-fallsky {
|
||||||
|
to {
|
||||||
|
transform: translate(var(--drift, -8px), 440px);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.b-flake {
|
||||||
|
--drift: 18px;
|
||||||
|
}
|
||||||
|
@media (prefers-reduced-motion: reduce) {
|
||||||
|
.b-drop,
|
||||||
|
.b-flake {
|
||||||
|
animation: none;
|
||||||
|
top: var(--top);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
.b-orb-label {
|
.b-orb-label {
|
||||||
text-shadow: 0 2px 0 rgb(255 255 255 / 0.7);
|
text-shadow: 0 2px 0 rgb(255 255 255 / 0.7);
|
||||||
@@ -501,6 +534,7 @@
|
|||||||
}
|
}
|
||||||
.b-tabbar {
|
.b-tabbar {
|
||||||
background: rgb(255 255 255 / 0.6);
|
background: rgb(255 255 255 / 0.6);
|
||||||
|
overflow: visible;
|
||||||
border-color: rgb(255 255 255 / 0.4);
|
border-color: rgb(255 255 255 / 0.4);
|
||||||
}
|
}
|
||||||
.b-app[data-t='night'] .b-topbg {
|
.b-app[data-t='night'] .b-topbg {
|
||||||
@@ -535,7 +569,7 @@
|
|||||||
.b-app[data-t='night'] [class*='bg-white/'] {
|
.b-app[data-t='night'] [class*='bg-white/'] {
|
||||||
background-color: rgb(34 42 92 / 0.85);
|
background-color: rgb(34 42 92 / 0.85);
|
||||||
}
|
}
|
||||||
.b-app[data-t='night'] :is([class*='bg-[#f'], [class*='bg-[#e'], [class*='bg-[#d'], [class*='bg-[#c'], [class*='bg-[linear-gradient']) {
|
.b-app[data-t='night'] :is([class*='bg-[#f'], [class*='bg-[#e'], [class*='bg-[#d'], [class*='bg-[#c'], [class*='bg-[linear-gradient']):not(.b-keep-bg) {
|
||||||
background: var(--chip);
|
background: var(--chip);
|
||||||
}
|
}
|
||||||
.b-app[data-t='night'] [class*='border-[#dfe5ee]'] {
|
.b-app[data-t='night'] [class*='border-[#dfe5ee]'] {
|
||||||
@@ -593,3 +627,12 @@
|
|||||||
.b-app[data-t='night'] .b-band-3 {
|
.b-app[data-t='night'] .b-band-3 {
|
||||||
background: linear-gradient(180deg, rgb(110 230 180 / 0.12), rgb(255 255 255 / 0));
|
background: linear-gradient(180deg, rgb(110 230 180 / 0.12), rgb(255 255 255 / 0));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.b-app[data-t='night'] img[data-dark] {
|
||||||
|
filter: drop-shadow(0 0 1px rgb(255 255 255 / 0.9)) drop-shadow(0 0 6px rgb(255 255 255 / 0.3));
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 밤엔 메인 탭 동그라미 테두리를 막대 색에 맞춘다 */
|
||||||
|
.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'
|
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'])
|
const OWN = new Set(['fireworks', 'bulb', 'calendar', 'thermo', 'sheaf', 'popup', 'exhibition', 'concert'])
|
||||||
|
|
||||||
/** 아이콘 이름 → 파일 경로 (공용 public/icons, B 전용 public/b/icons). 'none'(데이터 없는 칸)은 그림 없음 */
|
/** 아이콘 이름 → 파일 경로 (공용 public/icons, B 전용 public/b/icons). 'none'(데이터 없는 칸)은 그림 없음 */
|
||||||
@@ -97,11 +97,12 @@ export type TimeKind = 'morning' | 'day' | 'sunset' | 'night'
|
|||||||
// 서울 월별 대략 일몰 시각(시). 서버 값(/v1/feed hero.sky_mode)이 없을 때만 쓴다
|
// 서울 월별 대략 일몰 시각(시). 서버 값(/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]
|
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 {
|
export function kindOfHour(h: number, month = new Date().getMonth() + 1, minute = 0): TimeKind {
|
||||||
const at = h + minute / 60
|
const at = h + minute / 60
|
||||||
|
const sunset = SUNSET_HOUR[month - 1]
|
||||||
if (at >= 5 && at < 11) return 'morning'
|
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'
|
return 'night'
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import { useCallback, useEffect, useMemo, useState, type ReactNode } from 'react'
|
import { useCallback, useEffect, useMemo, useState, type ReactNode } from 'react'
|
||||||
import { nearestRegion } from '../api/client/sdk.gen'
|
import { nearestRegion } from '../api/client/sdk.gen'
|
||||||
import type { RegionData } from '../api/client/types.gen'
|
import type { RegionData } from '../api/client/types.gen'
|
||||||
|
import { track } from '../lib/analytics'
|
||||||
import { DEFAULT_REGION, RegionContext, type LocateStatus } from './regionContext'
|
import { DEFAULT_REGION, RegionContext, type LocateStatus } from './regionContext'
|
||||||
|
|
||||||
const KEY = 'nalssigak.b.region'
|
const KEY = 'nalssigak.b.region'
|
||||||
@@ -35,7 +36,7 @@ export function RegionProvider({ children }: { children: ReactNode }) {
|
|||||||
writeStored(r)
|
writeStored(r)
|
||||||
}, [])
|
}, [])
|
||||||
|
|
||||||
const findNearest = useCallback(() => {
|
const findNearest = useCallback((onFound?: () => void) => {
|
||||||
navigator.geolocation.getCurrentPosition(
|
navigator.geolocation.getCurrentPosition(
|
||||||
(pos) => {
|
(pos) => {
|
||||||
nearestRegion({ query: { lat: pos.coords.latitude, lon: pos.coords.longitude } })
|
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('가까운 구를 찾지 못함')
|
if (!res.region) throw new Error('가까운 구를 찾지 못함')
|
||||||
setRegion(res.region)
|
setRegion(res.region)
|
||||||
setLocateStatus('idle')
|
setLocateStatus('idle')
|
||||||
|
track('region_change', { region_name: res.region.name, method: 'location' })
|
||||||
|
onFound?.()
|
||||||
})
|
})
|
||||||
.catch(() => setLocateStatus('error'))
|
.catch(() => setLocateStatus('error'))
|
||||||
},
|
},
|
||||||
@@ -51,13 +54,13 @@ export function RegionProvider({ children }: { children: ReactNode }) {
|
|||||||
)
|
)
|
||||||
}, [setRegion])
|
}, [setRegion])
|
||||||
|
|
||||||
const locate = useCallback(() => {
|
const locate = useCallback((onFound?: () => void) => {
|
||||||
if (!canLocate) {
|
if (!canLocate) {
|
||||||
setLocateStatus('error')
|
setLocateStatus('error')
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
setLocateStatus('locating')
|
setLocateStatus('locating')
|
||||||
findNearest()
|
findNearest(onFound)
|
||||||
}, [canLocate, findNearest])
|
}, [canLocate, findNearest])
|
||||||
|
|
||||||
// 처음 온 사람만 위치 권한을 물어 가장 가까운 구로 맞춘다
|
// 처음 온 사람만 위치 권한을 물어 가장 가까운 구로 맞춘다
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ import type { RegionData } from '../api/client/types.gen'
|
|||||||
|
|
||||||
export type LocateStatus = 'idle' | 'locating' | 'denied' | 'error'
|
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 }
|
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'
|
import { createContext, use } from 'react'
|
||||||
|
export type SharePayload = { title: string; slides: HTMLElement[] }
|
||||||
|
|
||||||
|
type CommentsState = { type: 'comments'; postId: number; draft?: string }
|
||||||
|
|
||||||
export type SheetState =
|
export type SheetState =
|
||||||
| { type: 'gak'; indexId: number }
|
| { type: 'gak'; indexId: number }
|
||||||
| { type: 'article'; articleId: number }
|
| { type: 'article'; articleId: number }
|
||||||
| { type: 'comments'; postId: number }
|
| { type: 'share'; share: SharePayload }
|
||||||
|
| CommentsState
|
||||||
| { type: 'seasonWeek' }
|
| { type: 'seasonWeek' }
|
||||||
| { type: 'login' }
|
| { type: 'login'; then?: CommentsState }
|
||||||
| { type: 'me' }
|
| { type: 'me' }
|
||||||
| { type: 'region' }
|
| { type: 'region' }
|
||||||
| null
|
| null
|
||||||
|
|||||||
Loaded 100 of 106 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user