Merge remote-tracking branch 'origin/main' into feat/watch-summary
This commit is contained in:
commit
f6ec296130
84 files changed
+3406
-879
No files matched your search
@@ -3,6 +3,8 @@
|
||||
# ── 백엔드: 외부 API
|
||||
# 공공데이터포털(data.go.kr) 일반 인증키.
|
||||
DATA_GO_KR_SERVICE_KEY=
|
||||
# 행사 수집(7일마다) 완료 알림 — Microsoft Teams Workflows 수신 webhook. 비우면 보내지 않는다.
|
||||
TEAMS_WEBHOOK_URL=
|
||||
|
||||
# ── 백엔드: DB·Redis (네이티브 실행 기준. compose 안에서는 compose.yaml 이 host·port 를 덮어쓴다)
|
||||
DB_HOST=localhost
|
||||
@@ -19,3 +21,11 @@ PORT=9810
|
||||
# 생성: python -c "import secrets; print(secrets.token_urlsafe(48))"
|
||||
JWT_ACCESS_SECRET=
|
||||
JWT_REFRESH_SECRET=
|
||||
|
||||
# ── 배포(compose): 비우면 로컬 기본값. 킹서버 예: FRONT_PORT=30040, API_BIND=127.0.0.1:9810, PG_BIND=127.0.0.1:5440, REDIS_BIND=127.0.0.1:6390
|
||||
FRONT_PORT=
|
||||
API_BIND=
|
||||
PG_BIND=
|
||||
REDIS_BIND=
|
||||
# 프론트가 부를 API 주소. 비우면 같은 주소의 /v1 (nginx 가 backend 로 넘김)
|
||||
VITE_API_BASE_URL=
|
||||
@@ -15,3 +15,9 @@ venv/
|
||||
|
||||
# 생성물: python backend/scripts/export_openapi.py 로 다시 만든다
|
||||
backend/openapi.json
|
||||
|
||||
# 도구 캐시·설정 (impeccable 디자인 도구)
|
||||
.impeccable/
|
||||
|
||||
# 디자인 도구(impeccable) 캐시
|
||||
.impeccable/
|
||||
@@ -14,24 +14,24 @@
|
||||
|
||||
| 상태 | 할 일 | 이유 | 관련 파일 |
|
||||
|---|---|---|---|
|
||||
| [ ] | 서버 배포 + 공유 링크 | 10/6 회의 핵심 업무 | `compose.yaml` |
|
||||
| [x] | 각 점수 하향, 100점은 완벽 조건만 | 10/6 회의 결정 | `backend/services/calc/index_calc.py`, `backend/seed/index_definition.json` |
|
||||
| [ ] | 가중치 재검토 | 10/6 회의 | `backend/seed/index_definition.json` |
|
||||
| [ ] | 서버 배포 + 공유 링크 | 10/2 회의 핵심 업무 | `compose.yaml` |
|
||||
| [x] | 각 점수 하향, 100점은 완벽 조건만 | 10/2 회의 결정 | `backend/services/calc/index_calc.py`, `backend/seed/index_definition.json` |
|
||||
| [ ] | 가중치 재검토 | 10/2 회의 | `backend/seed/index_definition.json` |
|
||||
| [x] | 댓글·좋아요·로그인 API 테스트 (화면 확인은 아직) | 시연 때 미검증 | `backend/services/reaction_service.py`, `backend/services/auth_service.py` |
|
||||
| [x] | 주말 날씨 평일 상시 노출 + 다음 주 주말까지 (예보 닿는 +10일부터) | 10/6 회의 | `backend/services/week_service.py` |
|
||||
| [x] | 행사 독립 카드 최대 3장, 피드 무작위 노출 (하루 같은 자리) | 10/6 회의 | `backend/services/feed_service.py` |
|
||||
| [x] | 계절 소식 제철 7개 추가 (햇밤·햇땅콩·은행·고구마·귤·부사·김장) — 피드백 대기 | 10/6 회의 | `backend/seed/article.json` |
|
||||
| [x] | 새 각 추가 (야구·공부·넷플릭스·군밤) | 10/6 회의 | `backend/seed/index_definition.json` |
|
||||
| [x] | 주말 전국 지역 랭킹 — 노을 순위 대표 30곳의 토·일 '나들이 날씨 점수'(낮 10~17시 비 40·기온 35·하늘 15·바람 10, 비 60%↑면 최대 30점) 순위. `GET /v1/week/ranking`, 주말 화면 '이번 주말 전국 날씨 순위'(토/일 탭, 10위까지). 워커가 06:40·18:40에 계산해 Redis에 13시간 저장, 없으면 API가 그 자리에서 계산 | 10/6 회의 최종 그림 | `backend/services/weekend_rank.py`, `backend/services/calc/index_calc.py` (`outing`), `frontend/src/b/WeekPage.tsx` |
|
||||
| [x] | 노을 명소 지역별 목록 연결 — 지금 명소 데이터가 서울 마포구 3곳뿐이고 구 코드로만 찾아서 분당구 등은 하나도 안 나옴 | 10/6 회의 (추후), 사용자 지적 | `backend/seed/sunset_spot.csv`, `backend/services/sky_service.py` |
|
||||
| [x] | 주말 날씨 평일 상시 노출 + 다음 주 주말까지 (예보 닿는 +10일부터) | 10/2 회의 | `backend/services/week_service.py` |
|
||||
| [x] | 행사 독립 카드 최대 3장, 피드 무작위 노출 (하루 같은 자리) | 10/2 회의 | `backend/services/feed_service.py` |
|
||||
| [x] | 계절 소식 제철 7개 추가 (햇밤·햇땅콩·은행·고구마·귤·부사·김장) — 피드백 대기 | 10/2 회의 | `backend/seed/article.json` |
|
||||
| [x] | 새 각 추가 (야구·공부·넷플릭스·군밤) | 10/2 회의 | `backend/seed/index_definition.json` |
|
||||
| [x] | 주말 전국 지역 랭킹 — 노을 순위 대표 30곳의 토·일 '나들이 날씨 점수'(낮 10~17시 비 40·기온 35·하늘 15·바람 10, 비 60%↑면 최대 30점) 순위. `GET /v1/week/ranking`, 주말 화면 '이번 주말 전국 날씨 순위'(토/일 탭, 10위까지). 워커가 06:40·18:40에 계산해 Redis에 13시간 저장, 없으면 API가 그 자리에서 계산 | 10/2 회의 최종 그림 | `backend/services/weekend_rank.py`, `backend/services/calc/index_calc.py` (`outing`), `frontend/src/b/WeekPage.tsx` |
|
||||
| [x] | 노을 명소 지역별 목록 연결 — 지금 명소 데이터가 서울 마포구 3곳뿐이고 구 코드로만 찾아서 분당구 등은 하나도 안 나옴 | 10/2 회의 (추후), 사용자 지적 | `backend/seed/sunset_spot.csv`, `backend/services/sky_service.py` |
|
||||
| [ ] | 노을 명소 30km 안에 하나도 없는 구 89/256 — 광주·대전·세종·충북·강원·경북 내륙·전북 내륙 등. TourAPI 키워드로는 안 잡혀 직접 추가하거나 반경을 넓힐지 결정 필요 | 명소 확충 결과 | `backend/seed/sunset_spot.csv`, `backend/services/sky_service.py` |
|
||||
| [ ] | 명소 '서쪽이 트임'(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` |
|
||||
| [x] | 서울·경기 반영 범위 확인 — 서울 25구·경기 31시군(구 있는 시는 구 단위, 부천 3구·화성 4구 포함) 모두 있고 코드도 기상청 격자표(2607) 현행 코드와 일치 | 10/6 회의 확인 필요 | `backend/seed/region.csv` |
|
||||
| [x] | 습도 편한 범위 30~60%, 최적 35% | 10/6 회의 예시 "습도 30%" | `backend/seed/index_definition.json` |
|
||||
| [x] | 서울·경기 반영 범위 확인 — 서울 25구·경기 31시군(구 있는 시는 구 단위, 부천 3구·화성 4구 포함) 모두 있고 코드도 기상청 격자표(2607) 현행 코드와 일치 | 10/2 회의 확인 필요 | `backend/seed/region.csv` |
|
||||
| [x] | 습도 편한 범위 30~60%, 최적 35% | 10/2 회의 예시 "습도 30%" | `backend/seed/index_definition.json` |
|
||||
| [x] | 지역 격자(nx/ny)가 좌표와 안 맞는 2곳 확인 (4775000000, 4812900000) — 둘 다 기상청 격자표 값 그대로라 수정 없음. 좌표가 격자 경계(0.01칸 이내)라 공식 반올림과 1칸 갈림. 전체 256곳 좌표·격자 기상청 격자표와 일치 | 지역 데이터 점검 중 발견 | `backend/seed/region.csv` |
|
||||
| [x] | 재료 일부를 못 가져온 피드는 60초만 캐시 (예전엔 최대 1시간) | 행사 카드 확인 중 발견 (부산 해운대구) | `backend/services/feed_service.py` |
|
||||
| [ ] | 각 점수 구간별 설명을 자세하게 (예: 0~30이면 ~해서 별로, 80~100이면 ~해서 딱 좋음) — 말투는 통통 튀게 | 사용자 요청 | `backend/seed/index_definition.json`, `backend/services/calc/index_calc.py` |
|
||||
| [x] | 각 점수 구간별 설명을 자세하게 (0~29·30~59·60~79·80~100 네 구간, 상세 창에 표시) (예: 0~30이면 ~해서 별로, 80~100이면 ~해서 딱 좋음) — 말투는 통통 튀게 | 사용자 요청 | `backend/seed/index_definition.json`, `backend/services/calc/index_calc.py` |
|
||||
| [x] | 히어로 UI 다듬기 — 지금은 조잡하고 빡빡함, 더 세련되게 | 사용자 요청 | `frontend/src/b/TodayPage.tsx`, `frontend/src/b/b.css` |
|
||||
| [ ] | 포스트 작성자 닉네임이 모두 '날씨각' — 방안: 굵은 이름 자리에 종류별 계정명(`ACCOUNTS`, 예: 노을·행사·오늘의 각)을 올리고, 아래 작은 줄은 지역·시간으로 바꾼다. 계정명은 '노을각'처럼 '~각'으로 통일할지 결정 필요 | 사용자 요청 | `frontend/src/b/Post.tsx` |
|
||||
| [x] | 미세먼지를 '오늘 하루 날씨' 2번째 슬라이드에서 빼서 따로 포스트로 — `PostType.AIR`(12), 오늘 날씨 본문은 2시간 비 소식만. 이미 만든 날에도 빠진 카드 번호만 더해 바로 보임 | 사용자 요청 | `backend/services/feed_service.py`, `backend/common/enums.py`, `backend/services/air_service.py`, `frontend/src/b/Post.tsx` |
|
||||
@@ -49,7 +49,7 @@
|
||||
| [ ] | 기상청 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] | 각 상세 창 점수 칸을 오늘/내일/토/일로 — 단기예보(시간별)는 약 4일 뒤까지라 월~수엔 주말 점수를 같은 방식으로 못 냄. 안: 범위 밖 주말은 중기예보(기온·비 확률)로 대략 점수 + "예상" 표시, 오늘·내일이 주말이면 다음 주말 표시 | 사용자 요청 | `backend/services/index_service.py` (`DAYS = 3`), `frontend/src/b/Sheets.tsx` |
|
||||
| [ ] | **[결정 필요]** 그날 밤 달 모양(초승·상현·보름·하현·그믐) 보여 줄 화면 정하기 — 계산은 `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` |
|
||||
| [ ] | **[결정 필요]** 계절 이야기 사진 — CC BY-SA 등 8장은 저작자·라이선스 표시 필요(표시 위치 정하기), `howgak` 글은 맞는 사진 없음(일러스트/아이콘), `tangerine`(퍼블릭 도메인) 사용 여부, `di`(매미)·`peanut_new`(일본 삶은 땅콩) 주제 적합성 | 사진 수집 중 발견 | `frontend/public/season/sources.json` |
|
||||
| [x] | 포스트 본문이 슬라이드 내용 반복 — 축제("N월 N일부터…까지예요" = 기간 줄), 오늘 날씨, 생활 알림, 내일 미리보기, 한 문장, 각, 노을. 본문엔 슬라이드에 없는 한 줄만 | 전체 검수 | `backend/services/feed_service.py` |
|
||||
@@ -66,7 +66,7 @@
|
||||
| [ ] | 전시 썸네일 저작권 확인 — 데이터셋은 '이용허락범위 제한 없음'이나 원저작권이 주최 기관에 있을 수 있음 | 전시 연결 중 발견 | `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] | (로컬 반영함, 운영 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] | (로컬 반영함) seed 다시 넣기 — 밤 문장 아이콘 `moon`, 한 문장 8개의 내부 메모 출처 줄 삭제가 DB에 반영되도록 `docker exec o2o-weather-backend-1 python scripts/load_seed.py` | 뜻 모를 표시 수정 | `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` |
|
||||
@@ -74,9 +74,27 @@
|
||||
| [ ] | 마스크 아이콘 없음 — 미세먼지 포스트가 좋음·보통은 `vent`, 나쁨 이상은 `cloud`를 씀 | 미세먼지 포스트 작업 중 발견 | `frontend/public/icons/`, `backend/services/feed_service.py` (`_air`) |
|
||||
| [ ] | **[결정 필요]** 주말 화면 '데이트 명소'는 아직 시도 기준(`places`) — 행사처럼 거리 기준으로 바꿀지. 지금 명소 데이터는 10곳뿐 | 행사 거리 기준 작업 중 발견 | `backend/services/week_service.py` (`places`), `frontend/src/b/WeekPage.tsx` |
|
||||
| [ ] | 행사 수집이 사용자 한 명당 주변 시도 2~4곳으로 늘어 TourAPI·문화정보 API 호출이 시도 수만큼 늘어남(시도별 하루 1회 캐시) — 운영 배포 때 일일 호출 한도 확인 | 행사 거리 기준 작업 중 발견 | `backend/services/week_service.py` (`_ensure_events`), `backend/docs/load-estimate.md` |
|
||||
| [ ] | 다른 문서의 포스트 종류 목록·행사 시도 기준 설명 갱신 (`PostType` 12 미세먼지, 30km 행사) — `docs/포스트타입별_내용.html`만 고침 | 문서 점검 | `backend/docs/`, `docs/화면별_데이터출처.html`, `docs/데이터흐름.html`, `docs/콘텐츠설계서.md` |
|
||||
| [ ] | 다른 문서의 포스트 종류 목록·행사 시도 기준 설명 갱신 (`PostType` 12 미세먼지, 30km 행사) — `docs/포스트_종류별_내용.html`만 고침 | 문서 점검 | `backend/docs/`, `docs/화면별_데이터_출처.html`, `docs/데이터_흐름.html`, `docs/콘텐츠_설계서.md` |
|
||||
| [ ] | **[결정 필요]** 스켈레톤 작업에서 바뀐 디자인 — 댓글 없음 안내가 글자 두 줄 → 상자(스켈레톤 3줄 크기) | 스켈레톤 작업 중 발견 | `frontend/src/b/Sheets.tsx` (`CommentsSheet`) |
|
||||
| [ ] | **[결정 필요]** 히어로 다듬기에서 정한 것 — ① 큰 시계 → 날짜 줄 작은 시각, 기온이 가장 큰 글자 ② 구름·별·별똥별·토끼/곰·1위 아이콘 뺌, 점수 해(밤엔 달)만 남김 ③ 1위 각은 '오늘의 각 · 오늘은 ○○각! · 근거 보기' 한 줄(아이콘·점수는 아래 '오늘의 각' 줄에만) ④ 불쾌지수는 6~9월에만, 그 밖엔 '오늘 최저·최고'(3시간 칸 기준) ⑤ 비 문구 '비 안 와요'/'비, 우산 챙겨요' ⑥ 실패 시 문구 없이 '?'만(안내는 바로 아래 각 줄 상자 한 곳) ⑦ 저녁 히어로 배경을 깊은 보라로(흰 글자 AA) | 히어로 다듬기 | `frontend/src/b/TodayPage.tsx`, `frontend/src/b/b.css` |
|
||||
| [ ] | 댓글 좋아요 실패 시 알림 없음 (화면은 되돌아감) | 댓글 대기 표시 작업 중 발견 | `frontend/src/b/Sheets.tsx` (`CommentRow`) |
|
||||
| [ ] | **[결정 필요]** 노을 탭 재정리에서 정한 것 — ① 노을 등급 '흐림' → '잿빛'(피드 노을 포스트 문구도 같이 바뀜) ② 히어로에 '가장 붉을 때' 시각 하나는 결론('몇 시에')으로 남기고 나머지 시각은 시간표 한 곳에만 ③ '나가 볼 만해요/애매해요/쉬어요' 기준 60·40점, 내일·모레는 10점 넘게 높을 때만 '더 나아요' ④ '쉬어요'면 명소 추천 안 함 ⑤ 블루아워 시각은 시민박명 끝(-6°), 골든아워는 해 고도 6° | 노을 탭 재정리 | `backend/services/calc/sky_score.py`, `backend/services/sky_service.py`, `frontend/src/b/SkyPage.tsx` |
|
||||
| [ ] | 노을 히어로 맨 윗줄("오늘 노을 · 구")이 보라 배경 위 흰 13px라 대비 약 3.9:1 (AA 4.5 미달) — 결론·근거·시각·점수는 어두운 상자 안으로 옮김 | 노을 탭 재정리 중 발견 | `frontend/src/b/SkyPage.tsx` |
|
||||
| [ ] | **[결정 필요]** 히어로 시안 A/B/C 중 선택 — 지금은 이전 히어로로 롤백 | 히어로 다듬기 | `frontend/src/b/TodayPage.tsx`, `frontend/src/b/b.css` |
|
||||
| [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] | 노을 히어로 맨 윗줄("오늘 노을 · 구")이 보라 배경 위 흰 13px라 대비 약 3.9:1 (AA 4.5 미달) — 결론·근거·시각·점수는 어두운 상자 안으로 옮김, → 어두운 바탕을 깔아 6.7:1 | 노을 탭 재정리 중 발견 | `frontend/src/b/SkyPage.tsx` |
|
||||
| [ ] | 오늘 화면 불러오기 실패 → 다시 불러온 뒤 글 목록 첫 블록이 14px 내려감 (y881→895) | 히어로 롤백 측정 중 발견 | `frontend/src/b/TodayPage.tsx` |
|
||||
| [x] | 낮 히어로 해 안 흰 글씨 "오늘 날씨 점수"가 주황 위라 대비 부족, → 글씨를 짙은 갈색으로 (5.6~8:1) | 히어로 롤백 중 발견 | `frontend/src/b/b.css` |
|
||||
| [x] | **[결정 필요]** 노을 탭 명소 지도가 가짜 배경(블록·도로)에 축척 없이 핀을 늘려 찍어 17km 떨어진 곳도 바로 옆처럼 보이고, '서쪽이 트인 곳'이 내 위치 서쪽으로 오해됨. 안: 지도 빼고 "반포한강공원 · 남서쪽 18km" 목록으로 → 지도 뺌, 명소는 이름·방향·거리만 (10/7) | 사용자 지적 | `frontend/src/b/SkyPage.tsx` (`SpotMap`) |
|
||||
| [x] | [출시 전] 외부 API가 응답 없이 멈출 때 빨리 포기하기 (재시도 포함 8초·Open-Meteo 10초에서 끊고, 응답 없던 API는 2분간 건너뜀) — 화면 요청 안에서는 5초쯤에서 끊고, 실패한 API는 몇 분간 다시 부르지 않고, 그동안 저장된 값을 보여줌. 지금은 기상청이 멈추면 피드를 연 사람 일부가 약 100초 기다리다 에러를 봄 | 운영 점검 (10/6) | `backend/services/external/data_go_kr.py`, `backend/services/now_service.py`, `backend/services/week_service.py` |
|
||||
| [x] | [출시 전] 운영 DB에 스키마 변경 반영 — `deploy.sh`가 배포마다 `init.sql`과 seed를 다시 적용. `init.sql`은 여러 번 돌려도 안전한 문장만 쓰고, 칸 이름·타입 변경·삭제는 따로 SQL | 운영 점검 (10/6) | `deploy.sh`, `backend/postgres-init/init.sql` |
|
||||
| [ ] | [출시 전] Open-Meteo 유료 여부 결정 — 무료판은 비상업용(하루 1만·월 30만 호출). 노을 구름에 쓰는 중 | 운영 점검 (10/6), 기획 때 보류한 결정 | `backend/services/external/open_meteo.py` |
|
||||
| [x] | 지역(위치)을 바꾸면 피드를 새로 그리기 — 맨 위로 스크롤하고 새 지역 피드로 다시 불러옴 | 사용자 요청 | `frontend/src/b/TodayPage.tsx`, `frontend/src/b/region.tsx` |
|
||||
| [ ] | 기상청이 멈췄을 때 첫 사용자가 약 9초 기다림 — 저장된 값이 있으면 기다리지 말고 바로 보여주고 새 값은 뒤에서 받기 (지금은 화면 요청 안에서 최대 8초 기다림) | 사용자 지적 (9초는 너무 김) | `backend/services/now_service.py`, `backend/services/week_service.py`, `backend/services/external/guard.py` |
|
||||
| [ ] | 전남(46)은 TourAPI 축제·문화정보원 전시·콘서트 모두 0건 — 시도 코드·이름이 API 기대값과 다른지 확인 | 행사 수집 점검 중 발견 | `backend/services/external/tour_api.py`, `backend/services/external/culture_api.py` |
|
||||
| [ ] | **[결정 필요]** 팝가 팝업 사진 — 출처 표기 방식이 정해지지 않아 `image_url` 을 비워 둠. 이용약관도 못 찾아 수집 허용 여부 미확인 (robots.txt 는 `/popup` 허용) | 팝업 수집 | `backend/services/external/popga.py`, `backend/services/week_service.py` (`image_credit`) |
|
||||
| [ ] | 팝가에 공연·축제도 있음(`PERFORMANCE`·`FESTIVAL`) — 지금은 팝업(`STORE`)만 받음. 다른 출처와 겹침 처리 정하면 추가 | 팝업 수집 | `backend/services/external/popga.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`) |
|
||||
| [ ] | 히어로 내용 전체 다시 보기 — 아이콘이 뜻과 안 맞음: 불쾌지수에 온도계(불쾌지수는 기온+습도), '지금 비'는 비가 안 와도 우산. 칸마다 무엇을 보여줄지(불쾌지수가 필요한지 포함)부터 다시 정하기 | 사용자 지적 | `frontend/src/b/TodayPage.tsx` (`HeroStat`) |
|
||||
| [ ] | 검색 노출(SEO·AEO) 대응 빌드 방식 정하기 — 지금은 브라우저에서만 그리는 React(Vite)라 검색엔진·AI가 내용을 못 읽음. SSR 말고도 미리 그려 두는 방식(정적 사전 렌더링), 일부 페이지만 서버에서 그리기 등을 비교해 추천안 내기 | 지시 사항 (SEO·AEO 필요) | `frontend/vite.config.ts`, `frontend/nginx.conf` |
|
||||
| [x] | 세션 여러 개가 같은 테스트 DB·Redis를 쓰면 서로 지움 — `TEST_DB_NAME`·`TEST_REDIS_DB`로 폴더마다 다르게 줄 수 있게 함 | 테스트 충돌 (10/7 두 번) | `backend/tests/conftest.py` |
|
||||
| [x] | 피드 행사 카드·띠를 축제→팝업→전시→콘서트 차례로 돌아가며 고름 (사용자 결정). 피드 행사 카드(최대 3장)가 연주회로 채워짐 — 시작일이 오늘에 가까운 순이라 하루짜리 콘서트(서울 170건)가 위를 차지. 기획엔 "축제·행사"만 있고 콘서트·팝업을 어떻게 섞을지 없음. 안: 종류별 1장씩(축제·전시·팝업 우선) 또는 피드에서 콘서트 제외 | 사용자 지적 | `backend/services/week_service.py` (`events` 정렬), `backend/services/feed_service.py` (`PostType.EVENT`), `docs/피드_기획.html` |
|
||||
| [ ] | 노을 하늘 상황 판정이 실제와 맞는지 확인할 방법 정하기 — 기준값(중·높은 구름 25~75% 등)은 추정값. 사진 기록·사용자 반응 등 후보 | 노을 탭 다시 기획 (10/7) | `backend/services/calc/sky_score.py` (`situation`) |
|
||||
@@ -101,8 +101,9 @@ class WeatherWarning(Base):
|
||||
class CloudHourly(Base):
|
||||
__tablename__ = "cloud_hourly"
|
||||
|
||||
lat: Mapped[Decimal] = mapped_column(Numeric(5, 2), primary_key=True)
|
||||
lon: Mapped[Decimal] = mapped_column(Numeric(5, 2), primary_key=True)
|
||||
region_code: Mapped[str] = mapped_column(String(10), primary_key=True)
|
||||
kind: Mapped[int] = mapped_column(SmallInteger, primary_key=True)
|
||||
distance_km: Mapped[int] = mapped_column(SmallInteger, primary_key=True)
|
||||
forecast_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), primary_key=True)
|
||||
model: Mapped[int] = mapped_column(SmallInteger, primary_key=True)
|
||||
cloud_low: Mapped[int] = mapped_column(SmallInteger)
|
||||
@@ -110,6 +111,23 @@ class CloudHourly(Base):
|
||||
cloud_high: Mapped[int] = mapped_column(SmallInteger)
|
||||
|
||||
|
||||
class OpenMeteoHourly(Base):
|
||||
__tablename__ = "openmeteo_hourly"
|
||||
|
||||
region_code: Mapped[str] = mapped_column(String(10), primary_key=True)
|
||||
forecast_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), primary_key=True)
|
||||
uv_index: Mapped[Optional[Decimal]] = mapped_column(Numeric(4, 2), nullable=True)
|
||||
uv_index_clear_sky: Mapped[Optional[Decimal]] = mapped_column(Numeric(4, 2), nullable=True)
|
||||
visibility_m: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
|
||||
wind_gust_ms: Mapped[Optional[Decimal]] = mapped_column(Numeric(4, 1), nullable=True)
|
||||
pressure_hpa: Mapped[Optional[Decimal]] = mapped_column(Numeric(5, 1), nullable=True)
|
||||
soil_temp_c: Mapped[Optional[Decimal]] = mapped_column(Numeric(4, 1), nullable=True)
|
||||
sunshine_s: Mapped[Optional[int]] = mapped_column(SmallInteger, nullable=True)
|
||||
shortwave_avg_wm2: Mapped[Optional[int]] = mapped_column(SmallInteger, nullable=True)
|
||||
shortwave_max_wm2: Mapped[Optional[int]] = mapped_column(SmallInteger, nullable=True)
|
||||
fetched_at: Mapped[datetime] = mapped_column(DateTime(timezone=True))
|
||||
|
||||
|
||||
class SkyScore(Base):
|
||||
__tablename__ = "sky_score"
|
||||
|
||||
@@ -121,6 +139,9 @@ class SkyScore(Base):
|
||||
confidence: Mapped[int] = mapped_column(SmallInteger)
|
||||
best_times: Mapped[list] = mapped_column(JSONB)
|
||||
computed_at: Mapped[datetime] = mapped_column(DateTime(timezone=True))
|
||||
situation: 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)
|
||||
|
||||
|
||||
class SunsetSpot(Base):
|
||||
@@ -153,6 +174,9 @@ class IndexDefinition(Base):
|
||||
weight_wind: Mapped[int] = mapped_column(SmallInteger)
|
||||
weight_humidity: Mapped[int] = mapped_column(SmallInteger)
|
||||
weight_air: Mapped[int] = mapped_column(SmallInteger)
|
||||
weight_uv: Mapped[int] = mapped_column(SmallInteger, default=0, server_default="0")
|
||||
weight_sun: Mapped[int] = mapped_column(SmallInteger, default=0, server_default="0")
|
||||
weight_view: Mapped[int] = mapped_column(SmallInteger, default=0, server_default="0")
|
||||
weight_time: Mapped[int] = mapped_column(SmallInteger)
|
||||
factor_rules: Mapped[dict] = mapped_column(JSONB)
|
||||
zero_rules: Mapped[list] = mapped_column(JSONB)
|
||||
@@ -174,6 +198,9 @@ class IndexScore(Base):
|
||||
wind_score: Mapped[int] = mapped_column(SmallInteger)
|
||||
humidity_score: Mapped[int] = mapped_column(SmallInteger)
|
||||
air_score: Mapped[int] = mapped_column(SmallInteger)
|
||||
uv_score: Mapped[int] = mapped_column(SmallInteger, default=0, server_default="0")
|
||||
sun_score: Mapped[int] = mapped_column(SmallInteger, default=0, server_default="0")
|
||||
view_score: Mapped[int] = mapped_column(SmallInteger, default=0, server_default="0")
|
||||
time_score: Mapped[int] = mapped_column(SmallInteger)
|
||||
zero_reason: Mapped[Optional[str]] = mapped_column(String(100), nullable=True)
|
||||
notes: Mapped[dict] = mapped_column(JSONB)
|
||||
@@ -220,6 +247,7 @@ class Event(Base):
|
||||
image_url: Mapped[Optional[str]] = mapped_column(String(500), nullable=True)
|
||||
lat: Mapped[Optional[Decimal]] = mapped_column(Numeric(8, 5), nullable=True)
|
||||
lon: Mapped[Optional[Decimal]] = mapped_column(Numeric(8, 5), nullable=True)
|
||||
kind: Mapped[int] = mapped_column(SmallInteger, default=1)
|
||||
|
||||
|
||||
class SolarTerm(Base):
|
||||
|
||||
@@ -91,6 +91,15 @@ class SkyGrade(CodeEnum):
|
||||
RED = 4
|
||||
|
||||
|
||||
class SkySituation(CodeEnum):
|
||||
"""노을·일출 하늘 상황. 구름 층으로 고른다 (sky_score.situation)."""
|
||||
COVERED = 1 # 해 지는 쪽 먼 하늘이 막힘
|
||||
LOW_CLOUD = 2 # 머리 위 낮은 구름
|
||||
FEW = 3 # 물들 구름이 적음 (맑은 날 대부분)
|
||||
GLOW = 4 # 중·높은 구름이 알맞음
|
||||
THICK = 5 # 중·높은 구름이 두꺼움
|
||||
|
||||
|
||||
class Confidence(CodeEnum):
|
||||
HIGH = 1
|
||||
NORMAL = 2
|
||||
@@ -125,6 +134,18 @@ class PostType(CodeEnum):
|
||||
WEEKEND_PLAN = 11
|
||||
AIR = 12
|
||||
DAY_TRIP = 13 # 당일치기: 1~2시간 거리 후보 도시 중 주말 날씨 1위 + 그곳 행사
|
||||
MOON = 14 # 오늘 밤 달 (보름·삭이면 그 이야기)
|
||||
|
||||
|
||||
class EventKind(CodeEnum):
|
||||
FESTIVAL = 1
|
||||
EXHIBITION = 2
|
||||
CONCERT = 3
|
||||
POPUP = 4
|
||||
|
||||
|
||||
# 행사 종류별 아이콘 (사진이 없을 때 보인다, 프론트 public/b/icons)
|
||||
EVENT_ICON = {EventKind.FESTIVAL: "fireworks", EventKind.EXHIBITION: "exhibition", EventKind.CONCERT: "concert", EventKind.POPUP: "popup"}
|
||||
|
||||
|
||||
class RefType(CodeEnum):
|
||||
|
||||
@@ -10,6 +10,14 @@ def haversine_km(lat1: float, lon1: float, lat2: float, lon2: float) -> float:
|
||||
return 2 * _EARTH_RADIUS_KM * math.asin(math.sqrt(a))
|
||||
|
||||
|
||||
def bearing_deg(lat1: float, lon1: float, lat2: float, lon2: float) -> float:
|
||||
"""1에서 2를 보는 방위각 (북 0°, 동 90°)."""
|
||||
p1, p2, dl = math.radians(lat1), math.radians(lat2), math.radians(lon2 - lon1)
|
||||
y = math.sin(dl) * math.cos(p2)
|
||||
x = math.cos(p1) * math.sin(p2) - math.sin(p1) * math.cos(p2) * math.cos(dl)
|
||||
return (math.degrees(math.atan2(y, x)) + 360) % 360
|
||||
|
||||
|
||||
def destination(lat: float, lon: float, bearing_deg: float, km: float) -> tuple[float, float]:
|
||||
"""출발점에서 방위각 방향으로 km 떨어진 지점."""
|
||||
d = km / _EARTH_RADIUS_KM
|
||||
|
||||
@@ -27,6 +27,7 @@ class Settings(BaseSettings):
|
||||
redis_db: int = 0
|
||||
|
||||
data_go_kr_service_key: str = ""
|
||||
teams_webhook_url: str = ""
|
||||
|
||||
jwt_access_secret: str = ""
|
||||
jwt_refresh_secret: str = ""
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
from datetime import date, datetime
|
||||
|
||||
from sqlalchemy import and_, delete, or_, select
|
||||
from sqlalchemy import delete, select
|
||||
from sqlalchemy.dialects.postgresql import insert
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
@@ -14,13 +14,13 @@ class SkyCRUD:
|
||||
for i in range(0, len(rows), _CHUNK):
|
||||
stmt = insert(CloudHourly).values(rows[i:i + _CHUNK])
|
||||
await s.execute(stmt.on_conflict_do_update(
|
||||
index_elements=["lat", "lon", "forecast_at", "model"],
|
||||
index_elements=["region_code", "kind", "distance_km", "forecast_at", "model"],
|
||||
set_={k: stmt.excluded[k] for k in ("cloud_low", "cloud_mid", "cloud_high")},
|
||||
))
|
||||
|
||||
async def clouds_at(self, s: AsyncSession, points: list[tuple[float, float]], at: datetime) -> list[CloudHourly]:
|
||||
cond = or_(*[and_(CloudHourly.lat == round(lat, 2), CloudHourly.lon == round(lon, 2)) for lat, lon in points])
|
||||
return list((await s.scalars(select(CloudHourly).where(cond, CloudHourly.forecast_at == at))).all())
|
||||
async def clouds_at(self, s: AsyncSession, region_code: str, at: datetime) -> list[CloudHourly]:
|
||||
stmt = select(CloudHourly).where(CloudHourly.region_code == region_code, CloudHourly.forecast_at == at)
|
||||
return list((await s.scalars(stmt)).all())
|
||||
|
||||
async def upsert_scores(self, s: AsyncSession, rows: list[dict]) -> None:
|
||||
if not rows:
|
||||
@@ -28,7 +28,7 @@ class SkyCRUD:
|
||||
stmt = insert(SkyScore).values(rows)
|
||||
await s.execute(stmt.on_conflict_do_update(
|
||||
index_elements=["region_code", "score_date", "sky_type"],
|
||||
set_={k: stmt.excluded[k] for k in ("score", "grade", "confidence", "best_times", "computed_at")},
|
||||
set_={k: stmt.excluded[k] for k in ("score", "grade", "confidence", "best_times", "computed_at", "situation", "models_total", "models_agree")},
|
||||
))
|
||||
|
||||
async def scores(self, s: AsyncSession, region_codes: list[str], since: date) -> list[SkyScore]:
|
||||
|
||||
@@ -5,7 +5,9 @@ from sqlalchemy import func, select
|
||||
from sqlalchemy.dialects.postgresql import insert
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from common.database.model.models import SunTime, WeatherDaily, WeatherHourly
|
||||
from common.database.model.models import OpenMeteoHourly, SunTime, WeatherDaily, WeatherHourly
|
||||
|
||||
_CHUNK = 1000
|
||||
|
||||
|
||||
def _upsert_newer(model, rows: list[dict], keys: list[str]):
|
||||
@@ -27,6 +29,26 @@ class WeatherCRUD:
|
||||
if rows:
|
||||
await s.execute(_upsert_newer(WeatherDaily, rows, ["region_code", "forecast_date"]))
|
||||
|
||||
async def upsert_openmeteo(self, s: AsyncSession, rows: list[dict]) -> None:
|
||||
"""같은 (구, 시각)이면 덮어쓰되, 새 응답에서 값이 비어 오면(NULL) 그 칼럼은 이전 값을 지키고 받은 시각만 갱신한다."""
|
||||
keys = ["region_code", "forecast_at"]
|
||||
table = OpenMeteoHourly.__table__
|
||||
for i in range(0, len(rows), _CHUNK):
|
||||
stmt = insert(OpenMeteoHourly).values(rows[i:i + _CHUNK])
|
||||
set_ = {
|
||||
c.name: stmt.excluded[c.name] if c.name == "fetched_at" else func.coalesce(stmt.excluded[c.name], table.c[c.name])
|
||||
for c in table.columns if c.name not in keys
|
||||
}
|
||||
await s.execute(stmt.on_conflict_do_update(index_elements=keys, set_=set_))
|
||||
|
||||
async def openmeteo_between(self, s: AsyncSession, region_code: str, start: datetime, end: datetime) -> list[OpenMeteoHourly]:
|
||||
stmt = (
|
||||
select(OpenMeteoHourly)
|
||||
.where(OpenMeteoHourly.region_code == region_code, OpenMeteoHourly.forecast_at >= start, OpenMeteoHourly.forecast_at <= end)
|
||||
.order_by(OpenMeteoHourly.forecast_at)
|
||||
)
|
||||
return list((await s.scalars(stmt)).all())
|
||||
|
||||
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))
|
||||
|
||||
|
||||
@@ -45,7 +45,7 @@ class WeekCRUD:
|
||||
stmt = insert(Event).values(rows)
|
||||
await s.execute(stmt.on_conflict_do_update(
|
||||
index_elements=["source_id"],
|
||||
set_={k: stmt.excluded[k] for k in ("name", "place_name", "start_date", "end_date", "is_confirmed", "image_url", "lat", "lon")},
|
||||
set_={k: stmt.excluded[k] for k in ("name", "place_name", "start_date", "end_date", "is_confirmed", "image_url", "lat", "lon", "kind", "icon")},
|
||||
))
|
||||
|
||||
async def replace_manual_events(self, s: AsyncSession, rows: list[dict]) -> None:
|
||||
|
||||
@@ -2,8 +2,8 @@
|
||||
|
||||
| 문서 | 내용 | 아티팩트 |
|
||||
|---|---|---|
|
||||
| `../../docs/데이터흐름.html` | 데이터 흐름: 어디서 받는지와 그 이유, 피드 하나를 열면 무엇을 언제 받아 어디에 두는지, 하루 시계, 화면별 데이터 | https://claude.ai/artifact/CcdToNRntavNvo3XKNokqJ |
|
||||
| `data-pipeline.md` (`.html` 은 같은 내용) | 외부 API를 언제 받아 어디에 저장·캐시하는지, 피드 칸, 하루 1번 스케줄, 테스트 DB | https://claude.ai/artifact/A4cE22L5aPnMfU53mKCSps |
|
||||
| `../../docs/데이터_흐름.html` | 데이터 흐름: 어디서 받는지와 그 이유, 피드 하나를 열면 무엇을 언제 받아 어디에 두는지, 하루 시계, 화면별 데이터 | https://claude.ai/artifact/CcdToNRntavNvo3XKNokqJ |
|
||||
| `openmeteo-data.md` | Open-Meteo로 받는 구름(JMA·ICON, 20·100km)과 보조값(자외선·가시거리·돌풍·기압·일조·일사·지면온도)의 변수, 3시간 집계, 저장·갱신, 호출량, 지수 활용 후보, DB 적용 SQL | - |
|
||||
| `api.html` | API 목록, 응답 예시, 프론트 연결(Hey API) | https://claude.ai/artifact/LjVYpLzomBTrkMxjDvAoDD |
|
||||
| `index-draft.html` | 활동 지수 기준 초안 (실제 값은 `seed/index_definition.json`) | https://claude.ai/artifact/RrgaKozLCycwduymWPXz4s |
|
||||
| `api-codegen.html` | 프론트 코드 생성 도구 비교 (Hey API 로 결정) | https://claude.ai/artifact/FPuknSnajrmxTM7hEpPKek |
|
||||
|
||||
@@ -1,83 +0,0 @@
|
||||
<title>날씨각 데이터 흐름</title>
|
||||
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Gowun+Dodum&family=IBM+Plex+Sans+KR:wght@400;600&family=IBM+Plex+Mono:wght@400&display=swap">
|
||||
<style>
|
||||
/* 한 단 문서: data-pipeline.md 와 같은 내용 */
|
||||
:root{
|
||||
--bg:#f5f7fb; --fg:#1c2433; --muted:#3f4a5c; --line:#d4dbe7; --soft:#e8edf5; --accent:#2457a6; --warn:#8f3c17; --ok:#1d6b46;
|
||||
--display:"Gowun Dodum","Apple SD Gothic Neo",sans-serif;
|
||||
--body:"IBM Plex Sans KR","Apple SD Gothic Neo","Malgun Gothic",sans-serif;
|
||||
--mono:"IBM Plex Mono",ui-monospace,Menlo,monospace;
|
||||
}
|
||||
@media (prefers-color-scheme: dark){:root:not([data-theme="light"]){--bg:#11161f;--fg:#e3e8f1;--muted:#a9b4c5;--line:#2a3443;--soft:#18202c;--accent:#8fb4f0;--warn:#f0a07a;--ok:#7fd8ab;color-scheme:dark}}
|
||||
:root[data-theme="dark"]{--bg:#11161f;--fg:#e3e8f1;--muted:#a9b4c5;--line:#2a3443;--soft:#18202c;--accent:#8fb4f0;--warn:#f0a07a;--ok:#7fd8ab;color-scheme:dark}
|
||||
body{background:var(--bg);color:var(--fg);font-family:var(--body);font-size:14.5px;line-height:1.65}
|
||||
main{max-width:1080px;margin:0 auto;padding-inline:20px;padding-block:32px 72px;display:flex;flex-direction:column;gap:34px}
|
||||
h1{font-family:var(--display);font-size:30px;margin:0;text-wrap:balance}
|
||||
h2{font-family:var(--display);font-size:22px;margin:0 0 10px;text-wrap:balance}
|
||||
h3{font-size:15px;margin:14px 0 6px}
|
||||
p,li{max-width:76ch}
|
||||
p{margin:0 0 8px}
|
||||
ol,ul{margin:0;padding-left:22px;display:flex;flex-direction:column;gap:5px}
|
||||
.sub{color:var(--muted)}
|
||||
code{font-family:var(--mono);font-size:12.5px;background:var(--soft);padding:2px 6px;border-radius:3px;overflow-wrap:anywhere}
|
||||
.wrap{overflow-x:auto;border:1px solid var(--line);border-radius:6px}
|
||||
table{border-collapse:collapse;width:100%;min-width:780px;font-variant-numeric:tabular-nums}
|
||||
th,td{text-align:left;vertical-align:top;padding:9px 11px;border-bottom:1px solid var(--line)}
|
||||
th{background:var(--soft);font-size:12.5px;font-weight:600;letter-spacing:.02em;white-space:nowrap}
|
||||
tr:last-child td{border-bottom:0}
|
||||
.tag{display:inline-block;font-size:11.5px;line-height:1.5;padding:1px 7px;border-radius:3px;border:1px solid currentColor;white-space:nowrap}
|
||||
.t-view{color:var(--accent)} .t-time{color:var(--ok)} .t-plan{color:var(--warn)}
|
||||
.ok{color:var(--ok);font-weight:600}
|
||||
blockquote{margin:8px 0;padding:10px 14px;border-left:3px solid var(--warn);background:var(--soft);max-width:76ch}
|
||||
</style>
|
||||
<main>
|
||||
<header><h1>날씨각 데이터 흐름</h1>
|
||||
<p class="sub">기준 화면: 시안 B 피드. 무엇을, 언제, 어디서 받아서, 어디에 저장하고, 얼마나 캐시하는지.</p>
|
||||
</header>
|
||||
<section><h2>원칙</h2>
|
||||
<ol><li>외부 API는 <b>첫 사용자가 볼 때</b> 받는다. 캐시가 오래됐을 때만 부르고, 나머지 사용자는 그 값을 같이 쓴다.</li><li>받자마자 우리 형식으로 바꿔 <b>PostgreSQL</b>에 저장한다. 원본 응답은 저장하지 않는다.</li><li>계산(체감기온, 지수, 노을 점수)은 <b>데이터가 들어올 때 한 번</b> 하고 저장한다.</li><li><b>그날 카드는 처음부터 다 보인다.</b> 매일 03:00 스케줄러가 그날 카드(<code>post</code>)를 만들고, 카드 안의 숫자·문장은 볼 때 그 구 데이터로 채운다. 시각별로 카드를 하나씩 공개하지 않는다. 순서는 시간대(아침·낮·저녁·밤)에 따라 바뀌고, 조건이 맞는 카드만 켜진다.</li><li><b>Redis</b>는 지워져도 되는 것만 담는다. 비면 PostgreSQL로 다시 만든다.</li><li>스케줄은 <b>하루 1번</b>(매일 03:00, worker)만 돈다.</li></ol>
|
||||
</section>
|
||||
<section><h2>한눈에</h2>
|
||||
<div class="wrap"><table><tr><th>데이터</th><th>출처</th><th>언제 받나</th><th>저장 (DB)</th><th>캐시 (Redis)</th></tr><tr><td>시간별·하루 날씨</td><td>기상청 단기예보</td><td>새 발표(02·05·08·11·14·17·20·23시 +10분) 후 그 구를 처음 볼 때</td><td><code>weather_hourly</code> <code>weather_daily</code></td><td>피드 완성본에 포함</td></tr><tr><td>앞으로 2시간 비</td><td>기상청 초단기예보</td><td>매시 45분 이후 그 구를 처음 볼 때</td><td>저장 안 함</td><td><code>ultra:{구}</code></td></tr><tr><td>4~7일 뒤 날씨</td><td>기상청 중기예보</td><td>새 발표(06·18시 +30분) 후 주말 탭·행사를 처음 볼 때</td><td><code>weather_daily</code> (단기예보가 8시간 미만인 날은 중기 값 유지)</td><td>—</td></tr><tr><td>층별 구름</td><td>Open-Meteo (ECMWF·GFS·JMA·ICON)</td><td>오전·13시(노을)·21시(일출) 시간대마다 처음 볼 때. 좌표 24개씩 나눠 동시에 요청</td><td><code>cloud_hourly</code> (일출·일몰 시각 값만)</td><td>—</td></tr><tr><td>미세먼지</td><td>에어코리아 실시간</td><td>매시 20분 이후 처음 볼 때, 전국 1번</td><td><code>air_quality</code></td><td>—</td></tr><tr><td>기상특보</td><td>기상청 기상특보</td><td>매시 정각 이후 처음 볼 때, 전국 1번</td><td><code>weather_warning</code></td><td>—</td></tr><tr><td>축제·행사</td><td>TourAPI (<code>lDongRegnCd</code> = 구 코드 앞 2자리)</td><td>그 시도를 그날 처음 볼 때. 60일 넘게 이어지는 상설 행사는 목록에서 뺌</td><td><code>event</code></td><td>—</td></tr><tr><td>해 시각</td><td>서버 계산 (API 없음)</td><td>그 구의 그날 값이 없을 때</td><td><code>sun_time</code></td><td>—</td></tr><tr><td>측정소 위치</td><td>에어코리아 측정소</td><td>처음 볼 때 + 하루 1번 스케줄</td><td><code>air_station</code></td><td>—</td></tr><tr><td>공휴일 · 24절기</td><td>천문연 특일정보</td><td>그해 값이 없을 때 처음 볼 때 1년치</td><td><code>holiday</code> <code>solar_term</code></td><td>—</td></tr><tr><td>지수·노을 점수</td><td>위 값으로 계산</td><td>재료가 새로 들어온 직후</td><td><code>index_score</code> <code>sky_score</code></td><td>피드 완성본에 포함</td></tr><tr><td>그날 피드 카드</td><td>스케줄러</td><td>매일 03:00</td><td><code>post</code></td><td>—</td></tr><tr><td>피드 완성본</td><td>위 테이블 조립</td><td>캐시가 없을 때 (시간대마다 따로)</td><td>—</td><td><code>feed:{구}:{시간대}</code></td></tr></table></div>
|
||||
</section>
|
||||
<section><h2>저장하는 곳</h2>
|
||||
<div class="wrap"><table><tr><th>곳</th><th>담는 것</th><th>지워지면</th></tr><tr><td>PostgreSQL</td><td>받아 온 값(우리 형식), 계산 결과, 포스트, 사람이 쓴 내용</td><td>볼륨에 둬서 지워지지 않음. 원본은 여기</td></tr><tr><td>Redis</td><td>피드 완성본, 초단기예보, 전국 노을 순위, 동시 호출 잠금</td><td>문제없음. 다음 요청 때 PostgreSQL로 다시 만듦</td></tr><tr><td>시드 파일 (저장소)</td><td>구 목록, 지수 정의·문장 틀, 명소, 절기, 계절 책, 읽을거리</td><td>git에 있음. 배포할 때 PostgreSQL로 불러옴</td></tr></table></div>
|
||||
</section>
|
||||
<section><h2>화면 요청 하나가 처리되는 순서</h2>
|
||||
<p>예: 17:20에 마포구 메인 피드를 연다.</p>
|
||||
<ol><li><b>Redis <code>feed:마포구:저녁</code> 확인.</b> (10월 17:20은 일몰 2시간 전이 지나 저녁 시간대) 있으면 그대로 돌려준다. 대부분 여기서 끝난다.</li><li><b>없으면 재료가 최신인지 확인.</b><ul><li>단기예보: DB에 17시 발표가 있나 (17:10부터 받을 수 있음)</li><li>초단기예보: Redis <code>ultra:마포구</code>가 있나</li><li>미세먼지·특보: 이번 시각 갱신분이 DB에 있나 (전국 공용이라 한 사람이 받으면 모두 같이 씀)</li><li>해 시각: 없으면 계산한다</li></ul></li><li><b>오래된 것만 외부에서 받는다.</b><ul><li>여러 API는 <b>동시에</b> 부른다 (가장 느린 하나만큼만 걸림).</li><li>Redis 잠금 <code>lock:{API}:{구}</code>를 잡아, 같은 구를 여러 명이 동시에 열어도 호출은 1번.</li><li>DB에 직전 값이 있으면 <b>그 값으로 먼저 응답</b>하고, 새 값은 받는 대로 저장해 다음 요청부터 반영한다.</li></ul></li><li><b>받은 값을 우리 형식으로 바꿔 DB에 저장.</b> 체감기온·불쾌지수도 이때 계산.</li><li><b>재료가 바뀌었으면 계산.</b> 지수 24개 × 오늘·내일·모레 → <code>index_score</code>.</li><li><b>피드 완성본 조립.</b> 오늘 <code>post</code> 카드 중 켜질 조건이 맞는 것만 골라 저녁 시간대 순서로 놓고, 카드마다 그 구 데이터로 제목·캡션·슬라이드·보내기 문구를 만든다. Redis에 넣고 돌려준다.</li></ol>
|
||||
<p>실패할 때:</p>
|
||||
<ul><li>외부 호출이 실패하면 DB의 직전 값으로 응답하고 로그를 남긴다. 완성본은 5분만 캐시해서 5분 뒤 다시 시도.</li><li>잠금을 못 잡으면(다른 요청이 받는 중) 최대 3초 기다렸다가 DB에서 읽는다.</li></ul>
|
||||
</section>
|
||||
<section><h2>최신인지 판단하는 법</h2>
|
||||
<div class="wrap"><table><tr><th>데이터</th><th>"최신" 기준</th></tr><tr><td>단기예보</td><td>02·05·08·11·14·17·20·23시 중 "발표 + 10분"이 지난 마지막 발표. DB의 <code>issued_at</code>이 그보다 이르면 다시 받음</td></tr><tr><td>초단기예보</td><td>매시 30분 발표, 45분부터 제공. Redis에 없으면 다시 받음</td></tr><tr><td>중기예보</td><td>06·18시 발표. DB의 <code>issued_at</code>이 그보다 이르면 다시 받음</td></tr><tr><td>미세먼지</td><td><code>measured_at</code>이 이번 시각(매시 20분 기준)보다 이르면 전국을 다시 받음</td></tr><tr><td>기상특보</td><td>마지막으로 받은 시각이 이번 정시보다 이르면 다시 받음</td></tr><tr><td>층별 구름</td><td>오늘 13시(노을)·21시(일출) 이후에 받은 값이 없으면 다시 받음</td></tr><tr><td>지수 점수</td><td><code>index_score.computed_at</code>이 단기예보 <code>issued_at</code>이나 미세먼지 <code>measured_at</code>보다 이르면 다시 계산</td></tr></table></div>
|
||||
</section>
|
||||
<section><h2>Redis 캐시 키</h2>
|
||||
<div class="wrap"><table><tr><th>키</th><th>담는 것</th><th>만료</th><th>미리 지우는 경우</th></tr><tr><td><code>feed:{구 코드}:{시간대}</code></td><td>메인 피드 응답 완성본</td><td>다음 시간대 경계(05·11·21시, 일몰 2시간 전), 다음 단기예보 제공 시각, 다음 정시 20분(미세먼지) 중 가장 빠른 쪽. 최대 1시간</td><td>03:00 새 피드가 정해졌을 때 (전체)</td></tr><tr><td><code>ultra:{구 코드}</code></td><td>초단기예보 6시간</td><td>다음 정시 45분</td><td>—</td></tr><tr><td><code>rank:sunset:{날짜}</code></td><td>전국 노을 순위 (대표 30곳)</td><td>다음 날 00:00</td><td>—</td></tr><tr><td><code>lock:{API}:{구 코드}</code></td><td>동시 호출 잠금</td><td>10초</td><td>호출이 끝나면 바로 풂</td></tr></table></div>
|
||||
<p>Redis는 compose에서 볼륨 + <code>appendonly yes</code>로 띄운다. 도커를 내렸다 올려도 값이 남는다.</p>
|
||||
</section>
|
||||
<section><h2>출처 주소</h2>
|
||||
<p>모든 data.go.kr API는 최상위 <code>.env</code>의 <code>DATA_GO_KR_SERVICE_KEY</code> 하나를 쓴다 (API마다 활용신청 필요).</p>
|
||||
<div class="wrap"><table><tr><th>출처</th><th>주소</th><th>한 번에 받는 범위</th></tr><tr><td>기상청 단기예보</td><td><code>https://apis.data.go.kr/1360000/VilageFcstInfoService_2.0/getVilageFcst</code></td><td>구 1곳 (5km 칸 <code>nx</code>,<code>ny</code>). 오늘~모레 1시간 간격, 글피 3시간 간격</td></tr><tr><td>기상청 초단기예보</td><td><code>https://apis.data.go.kr/1360000/VilageFcstInfoService_2.0/getUltraSrtFcst</code></td><td>구 1곳, 6시간</td></tr><tr><td>기상청 중기예보</td><td><code>https://apis.data.go.kr/1360000/MidFcstInfoService/getMidLandFcst</code> · <code>getMidTa</code></td><td>예보 구역 1곳</td></tr><tr><td>기상청 기상특보</td><td><code>https://apis.data.go.kr/1360000/WthrWrnInfoService/getPwnCd</code></td><td>전국</td></tr><tr><td>에어코리아 실시간</td><td><code>https://apis.data.go.kr/B552584/ArpltnInforInqireSvc/getCtprvnRltmMesureDnsty</code> (<code>sidoName=전국</code>)</td><td>전국 측정소</td></tr><tr><td>에어코리아 측정소</td><td><code>https://apis.data.go.kr/B552584/MsrstnInfoInqireSvc/getMsrstnList</code></td><td>전국 측정소</td></tr><tr><td>TourAPI 축제</td><td><code>https://apis.data.go.kr/B551011/KorService2/searchFestival2</code> (지역은 <code>lDongRegnCd</code>, <code>areaCode</code> 아님)</td><td>시도 1곳</td></tr><tr><td>천문연 특일정보</td><td><code>https://apis.data.go.kr/B090041/openapi/service/SpcdeInfoService/getRestDeInfo</code></td><td>1개월</td></tr><tr><td>Open-Meteo</td><td><code>https://api.open-meteo.com/v1/forecast?hourly=cloud_cover_low,cloud_cover_mid,cloud_cover_high</code></td><td>좌표 여러 개, 3일. ECMWF·GFS·JMA·ICON 모델 사용 (KMA 모델은 값이 비어 있음)</td></tr></table></div>
|
||||
</section>
|
||||
<section><h2>계산 (데이터가 들어올 때 한 번)</h2>
|
||||
<div class="wrap"><table><tr><th>계산</th><th>계산하는 순간</th><th>재료</th><th>저장</th></tr><tr><td>체감기온, 불쾌지수</td><td>단기예보 저장할 때</td><td>기온·습도·바람</td><td><code>weather_hourly</code></td></tr><tr><td>지수 24개 × 오늘·내일·모레</td><td>단기예보 저장 직후 / 미세먼지 갱신 뒤 첫 조회</td><td>날씨, 미세먼지, 해 시각, 지수 정의</td><td><code>index_score</code></td></tr><tr><td>노을·일출 점수, 3컷 시각</td><td>층별 구름 저장 직후</td><td>구름, 해 시각</td><td><code>sky_score</code></td></tr><tr><td>전국 노을 순위</td><td>13시 이후 순위를 처음 볼 때</td><td><code>sky_score</code></td><td>Redis <code>rank:sunset</code></td></tr><tr><td>포스트 문장</td><td>피드 완성본을 조립할 때</td><td>위 결과 + 문장 틀</td><td>Redis <code>feed:{구}</code></td></tr></table></div>
|
||||
</section>
|
||||
<section><h2>그날 피드 (매일 03:00 스케줄러가 만듦, 안 돌았으면 첫 요청에서)</h2>
|
||||
<p>기획: <code>docs/피드기획_v2.html</code>. 스케줄러는 그날 카드를 <code>post</code>에 넣는다. 공개 시각은 없고 모든 카드는 03:00부터 다음 날 03:00까지 유효하다. 좋아요·댓글은 카드(<code>post_id</code>)에 붙으므로 순서가 바뀌어도 이어지고, 전국 사용자가 같이 본다.</p>
|
||||
<h3>시간대</h3>
|
||||
<div class="wrap"><table><tr><th>시간대</th><th>범위</th></tr><tr><td>아침</td><td>05:00–11:00</td></tr><tr><td>낮</td><td>11:00–일몰 2시간 전</td></tr><tr><td>저녁</td><td>일몰 2시간 전–21:00 (그 구 <code>sun_time</code> 기준)</td></tr><tr><td>밤</td><td>21:00–05:00</td></tr></table></div>
|
||||
<h3>카드와 켜지는 조건</h3>
|
||||
<div class="wrap"><table><tr><th>카드</th><th>켜지는 조건</th><th>볼 때 채우는 내용</th></tr><tr><td>지금 날씨 (히어로)</td><td>항상, 맨 위 고정</td><td>현재 기온·체감·불쾌지수, 오늘 날씨 점수, 앞으로 2시간 비, 오늘 1위 각(작게)</td></tr><tr><td>오늘 하루 날씨</td><td>항상, 히어로 바로 아래 고정 (특보가 있으면 특보 다음)</td><td>3시간 칸, 미세먼지. 우산은 우산·특보 카드에서</td></tr><tr><td>우산·특보</td><td>오늘 남은 시간·내일 출퇴근(8·19시) 강수확률 40% 이상, 또는 그 구 특보</td><td>비 오는 시각, 특보 종류. 특보는 히어로 바로 아래</td></tr><tr><td>각 1·2·3위</td><td>항상 (3장)</td><td>그날 하루 기준 순위. 밤에도 오늘 순위 유지</td></tr><tr><td>노을</td><td>항상. 60점 미만이면 한 줄 카드</td><td>점수·가장 예쁜 시각·명소. 일몰 뒤에는 내일 일출·노을</td></tr><tr><td>내일 미리보기</td><td>저녁·밤</td><td>내일 날씨 한 줄, 내일 1위 각, 출근길 비</td></tr><tr><td>주말 추천</td><td>목~일</td><td>그 구 토·일 날씨와 추천</td></tr><tr><td>행사</td><td>그 시도에 7일 안 행사가 있을 때</td><td>가장 가까운 행사와 그날 날씨</td></tr><tr><td>계절 소식</td><td>매일 1장 (<code>article</code>, 날마다 돌아가며)</td><td>글 첫 문단</td></tr><tr><td>날씨 상식</td><td>매일 1장 (<code>article</code>, 그날 날씨와 이어지는 글 우선)</td><td>글 첫 문단</td></tr><tr><td>한 문장·시</td><td>매일 1장</td><td>오늘 날씨에 맞는 문장. 밤에는 맨 끝 고정</td></tr></table></div>
|
||||
<h3>시간대별 순서 (히어로 제외)</h3>
|
||||
<div class="wrap"><table><tr><th>카드</th><th>아침</th><th>낮</th><th>저녁</th><th>밤</th></tr><tr><td>우산·특보</td><td>1</td><td>2</td><td>3</td><td>2</td></tr><tr><td>각 1·2·3위</td><td>2–4</td><td>1–3</td><td>2–4</td><td>5–7</td></tr><tr><td>노을</td><td>6</td><td>4</td><td>1</td><td>3</td></tr><tr><td>내일 미리보기</td><td>꺼짐</td><td>꺼짐</td><td>5</td><td>1</td></tr><tr><td>주말 추천</td><td>8</td><td>6</td><td>6 (금 2)</td><td>4</td></tr><tr><td>행사</td><td>9</td><td>5</td><td>7</td><td>8</td></tr><tr><td>계절 소식</td><td>5</td><td>7</td><td>8</td><td>6</td></tr><tr><td>날씨 상식</td><td>7</td><td>8</td><td>9</td><td>9</td></tr><tr><td>한 문장·시</td><td>10</td><td>9</td><td>10</td><td>맨 끝</td></tr></table></div>
|
||||
<ul><li>같은 시간대 안의 각 3장은 하기 좋은 시간이 가까운 각을 앞에, 시간이 지난 각을 뒤에 둔다.</li><li>같은 종류 카드는 붙이지 않는다. 각 3장 사이에는 다른 카드를 하나씩 끼운다.</li><li>꺼진 카드는 빼고 뒤 카드를 올린다. 빈 카드는 만들지 않는다 (노을 한 줄 카드만 예외).</li><li>좋아요·댓글 수와 내가 누른 표시는 캐시와 상관없이 매번 DB에서 덮어쓴다.</li></ul>
|
||||
<blockquote>구현: <code>services/feed_service.py</code>의 <code>LINEUP</code>(그날 카드)·<code>ORDER</code>(시간대별 순서)·<code>arrange</code>. 한 문장·시는 <code>article</code> 의 <code>category=4</code>(코드 앞머리 <code>quote-rain-</code>·<code>quote-cloud-</code>·<code>quote-clear-</code>·<code>quote-night-</code>·<code>quote-any-</code>로 날씨에 맞춰 고름). seed 문장은 검수 전 예시다.</blockquote>
|
||||
</section>
|
||||
<section><h2>하루 1번 스케줄 (매일 03:00, worker)</h2>
|
||||
<div class="wrap"><table><tr><th>하는 일</th><th>이유</th></tr><tr><td>그날 피드 카드를 <code>post</code>에 넣고 Redis <code>feed:*</code> 비우기</td><td>하루 카드 목록</td></tr><tr><td>7일 지난 날씨·해 시각·각 점수·노을 점수, 2일 지난 구름, 끝난 지 30일 지난 행사 지우기</td><td>테이블이 계속 커지지 않게</td></tr><tr><td>에어코리아 측정소 목록 갱신 (전국 1번)</td><td>측정소가 새로 생기거나 없어질 때 반영</td></tr></table></div>
|
||||
</section>
|
||||
<section><h2>테스트</h2>
|
||||
<p><code>pytest</code>는 개발 DB를 건드리지 않는다. 실행할 때마다 <code>nalssigak_test</code> DB를 <code>init.sql</code>로 새로 만들고 시드를 넣으며, Redis는 15번을 쓴다. 테스트마다 외부에서 받은 데이터와 Redis를 비운다. 외부 API는 가짜 값으로 바꾼다 (<code>tests/conftest.py</code>의 <code>offline</code>).</p>
|
||||
</section>
|
||||
</main>
|
||||
@@ -1,171 +0,0 @@
|
||||
# 날씨각 데이터 흐름
|
||||
|
||||
기준 화면: 시안 B 피드. 무엇을, 언제, 어디서 받아서, 어디에 저장하고, 얼마나 캐시하는지.
|
||||
|
||||
## 원칙
|
||||
|
||||
1. 외부 API는 **첫 사용자가 볼 때** 받는다. 캐시가 오래됐을 때만 부르고, 나머지 사용자는 그 값을 같이 쓴다.
|
||||
2. 받자마자 우리 형식으로 바꿔 **PostgreSQL**에 저장한다. 원본 응답은 저장하지 않는다.
|
||||
3. 계산(체감기온, 지수, 노을 점수)은 **데이터가 들어올 때 한 번** 하고 저장한다.
|
||||
4. **그날 카드는 처음부터 다 보인다.** 매일 03:00 스케줄러가 그날 카드(`post`)를 만들고, 카드 안의 숫자·문장은 볼 때 그 구 데이터로 채운다. 시각별로 카드를 하나씩 공개하지 않는다. 순서는 시간대(아침·낮·저녁·밤)에 따라 바뀌고, 조건이 맞는 카드만 켜진다.
|
||||
5. **Redis**는 지워져도 되는 것만 담는다. 비면 PostgreSQL로 다시 만든다.
|
||||
6. 스케줄은 **하루 1번**(매일 03:00, worker)만 돈다.
|
||||
|
||||
## 한눈에
|
||||
|
||||
| 데이터 | 출처 | 언제 받나 | 저장 (DB) | 캐시 (Redis) |
|
||||
|---|---|---|---|---|
|
||||
| 시간별·하루 날씨 | 기상청 단기예보 | 새 발표(02·05·08·11·14·17·20·23시 +10분) 후 그 구를 처음 볼 때 | `weather_hourly` `weather_daily` | 피드 완성본에 포함 |
|
||||
| 앞으로 2시간 비 | 기상청 초단기예보 | 매시 45분 이후 그 구를 처음 볼 때 | 저장 안 함 | `ultra:{구}` |
|
||||
| 4~7일 뒤 날씨 | 기상청 중기예보 | 새 발표(06·18시 +30분) 후 주말 탭·행사를 처음 볼 때 | `weather_daily` (단기예보가 8시간 미만인 날은 중기 값 유지) | — |
|
||||
| 층별 구름 | Open-Meteo (ECMWF·GFS·JMA·ICON) | 오전·13시(노을)·21시(일출) 시간대마다 처음 볼 때. 좌표 24개씩 나눠 동시에 요청 | `cloud_hourly` (일출·일몰 시각 값만) | — |
|
||||
| 미세먼지 | 에어코리아 실시간 | 매시 20분 이후 처음 볼 때, 전국 1번 | `air_quality` | — |
|
||||
| 기상특보 | 기상청 기상특보 | 매시 정각 이후 처음 볼 때, 전국 1번 | `weather_warning` | — |
|
||||
| 축제·행사 | TourAPI (`lDongRegnCd` = 구 코드 앞 2자리) | 그 시도를 그날 처음 볼 때. 60일 넘게 이어지는 상설 행사는 목록에서 뺌 | `event` | — |
|
||||
| 해 시각 | 서버 계산 (API 없음) | 그 구의 그날 값이 없을 때 | `sun_time` | — |
|
||||
| 측정소 위치 | 에어코리아 측정소 | 처음 볼 때 + 하루 1번 스케줄 | `air_station` | — |
|
||||
| 공휴일 · 24절기 | 천문연 특일정보 | 그해 값이 없을 때 처음 볼 때 1년치 | `holiday` `solar_term` | — |
|
||||
| 지수·노을 점수 | 위 값으로 계산 | 재료가 새로 들어온 직후 | `index_score` `sky_score` | 피드 완성본에 포함 |
|
||||
| 그날 피드 카드 | 스케줄러 | 매일 03:00 | `post` | — |
|
||||
| 피드 완성본 | 위 테이블 조립 | 캐시가 없을 때 (시간대마다 따로) | — | `feed:{구}:{시간대}` |
|
||||
|
||||
## 저장하는 곳
|
||||
|
||||
| 곳 | 담는 것 | 지워지면 |
|
||||
|---|---|---|
|
||||
| PostgreSQL | 받아 온 값(우리 형식), 계산 결과, 포스트, 사람이 쓴 내용 | 볼륨에 둬서 지워지지 않음. 원본은 여기 |
|
||||
| Redis | 피드 완성본, 초단기예보, 전국 노을 순위, 동시 호출 잠금 | 문제없음. 다음 요청 때 PostgreSQL로 다시 만듦 |
|
||||
| 시드 파일 (저장소) | 구 목록, 지수 정의·문장 틀, 명소, 절기, 계절 책, 읽을거리 | git에 있음. 배포할 때 PostgreSQL로 불러옴 |
|
||||
|
||||
## 화면 요청 하나가 처리되는 순서
|
||||
|
||||
예: 17:20에 마포구 메인 피드를 연다.
|
||||
|
||||
1. **Redis `feed:마포구:저녁` 확인.** (10월 17:20은 일몰 2시간 전이 지나 저녁 시간대) 있으면 그대로 돌려준다. 대부분 여기서 끝난다.
|
||||
2. **없으면 재료가 최신인지 확인.**
|
||||
- 단기예보: DB에 17시 발표가 있나 (17:10부터 받을 수 있음)
|
||||
- 초단기예보: Redis `ultra:마포구`가 있나
|
||||
- 미세먼지·특보: 이번 시각 갱신분이 DB에 있나 (전국 공용이라 한 사람이 받으면 모두 같이 씀)
|
||||
- 해 시각: 없으면 계산한다
|
||||
3. **오래된 것만 외부에서 받는다.**
|
||||
- 여러 API는 **동시에** 부른다 (가장 느린 하나만큼만 걸림).
|
||||
- Redis 잠금 `lock:{API}:{구}`를 잡아, 같은 구를 여러 명이 동시에 열어도 호출은 1번.
|
||||
- DB에 직전 값이 있으면 **그 값으로 먼저 응답**하고, 새 값은 받는 대로 저장해 다음 요청부터 반영한다.
|
||||
4. **받은 값을 우리 형식으로 바꿔 DB에 저장.** 체감기온·불쾌지수도 이때 계산.
|
||||
5. **재료가 바뀌었으면 계산.** 지수 24개 × 오늘·내일·모레 → `index_score`.
|
||||
6. **피드 완성본 조립.** 오늘 `post` 카드 중 켜질 조건이 맞는 것만 골라 저녁 시간대 순서로 놓고, 카드마다 그 구 데이터로 제목·캡션·슬라이드·보내기 문구를 만든다. Redis에 넣고 돌려준다.
|
||||
|
||||
실패할 때:
|
||||
- 외부 호출이 실패하면 DB의 직전 값으로 응답하고 로그를 남긴다. 완성본은 5분만 캐시해서 5분 뒤 다시 시도.
|
||||
- 잠금을 못 잡으면(다른 요청이 받는 중) 최대 3초 기다렸다가 DB에서 읽는다.
|
||||
|
||||
## 최신인지 판단하는 법
|
||||
|
||||
| 데이터 | "최신" 기준 |
|
||||
|---|---|
|
||||
| 단기예보 | 02·05·08·11·14·17·20·23시 중 "발표 + 10분"이 지난 마지막 발표. DB의 `issued_at`이 그보다 이르면 다시 받음 |
|
||||
| 초단기예보 | 매시 30분 발표, 45분부터 제공. Redis에 없으면 다시 받음 |
|
||||
| 중기예보 | 06·18시 발표. DB의 `issued_at`이 그보다 이르면 다시 받음 |
|
||||
| 미세먼지 | `measured_at`이 이번 시각(매시 20분 기준)보다 이르면 전국을 다시 받음 |
|
||||
| 기상특보 | 마지막으로 받은 시각이 이번 정시보다 이르면 다시 받음 |
|
||||
| 층별 구름 | 오늘 13시(노을)·21시(일출) 이후에 받은 값이 없으면 다시 받음 |
|
||||
| 지수 점수 | `index_score.computed_at`이 단기예보 `issued_at`이나 미세먼지 `measured_at`보다 이르면 다시 계산 |
|
||||
|
||||
## Redis 캐시 키
|
||||
|
||||
| 키 | 담는 것 | 만료 | 미리 지우는 경우 |
|
||||
|---|---|---|---|
|
||||
| `feed:{구 코드}:{시간대}` | 메인 피드 응답 완성본 | 다음 시간대 경계(05·11·21시, 일몰 2시간 전), 다음 단기예보 제공 시각, 다음 정시 20분(미세먼지) 중 가장 빠른 쪽. 최대 1시간 | 03:00 새 피드가 정해졌을 때 (전체) |
|
||||
| `ultra:{구 코드}` | 초단기예보 6시간 | 다음 정시 45분 | — |
|
||||
| `rank:sunset:{날짜}` | 전국 노을 순위 (대표 30곳) | 다음 날 00:00 | — |
|
||||
| `lock:{API}:{구 코드}` | 동시 호출 잠금 | 10초 | 호출이 끝나면 바로 풂 |
|
||||
|
||||
Redis는 compose에서 볼륨 + `appendonly yes`로 띄운다. 도커를 내렸다 올려도 값이 남는다.
|
||||
|
||||
## 출처 주소
|
||||
|
||||
모든 data.go.kr API는 최상위 `.env`의 `DATA_GO_KR_SERVICE_KEY` 하나를 쓴다 (API마다 활용신청 필요).
|
||||
|
||||
| 출처 | 주소 | 한 번에 받는 범위 |
|
||||
|---|---|---|
|
||||
| 기상청 단기예보 | `https://apis.data.go.kr/1360000/VilageFcstInfoService_2.0/getVilageFcst` | 구 1곳 (5km 칸 `nx`,`ny`). 오늘~모레 1시간 간격, 글피 3시간 간격 |
|
||||
| 기상청 초단기예보 | `https://apis.data.go.kr/1360000/VilageFcstInfoService_2.0/getUltraSrtFcst` | 구 1곳, 6시간 |
|
||||
| 기상청 중기예보 | `https://apis.data.go.kr/1360000/MidFcstInfoService/getMidLandFcst` · `getMidTa` | 예보 구역 1곳 |
|
||||
| 기상청 기상특보 | `https://apis.data.go.kr/1360000/WthrWrnInfoService/getPwnCd` | 전국 |
|
||||
| 에어코리아 실시간 | `https://apis.data.go.kr/B552584/ArpltnInforInqireSvc/getCtprvnRltmMesureDnsty` (`sidoName=전국`) | 전국 측정소 |
|
||||
| 에어코리아 측정소 | `https://apis.data.go.kr/B552584/MsrstnInfoInqireSvc/getMsrstnList` | 전국 측정소 |
|
||||
| TourAPI 축제 | `https://apis.data.go.kr/B551011/KorService2/searchFestival2` (지역은 `lDongRegnCd`, `areaCode` 아님) | 시도 1곳 |
|
||||
| 천문연 특일정보 | `https://apis.data.go.kr/B090041/openapi/service/SpcdeInfoService/getRestDeInfo` | 1개월 |
|
||||
| Open-Meteo | `https://api.open-meteo.com/v1/forecast?hourly=cloud_cover_low,cloud_cover_mid,cloud_cover_high` | 좌표 여러 개, 3일. ECMWF·GFS·JMA·ICON 모델 사용 (KMA 모델은 값이 비어 있음) |
|
||||
|
||||
## 계산 (데이터가 들어올 때 한 번)
|
||||
|
||||
| 계산 | 계산하는 순간 | 재료 | 저장 |
|
||||
|---|---|---|---|
|
||||
| 체감기온, 불쾌지수 | 단기예보 저장할 때 | 기온·습도·바람 | `weather_hourly` |
|
||||
| 지수 24개 × 오늘·내일·모레 | 단기예보 저장 직후 / 미세먼지 갱신 뒤 첫 조회 | 날씨, 미세먼지, 해 시각, 지수 정의 | `index_score` |
|
||||
| 노을·일출 점수, 3컷 시각 | 층별 구름 저장 직후 | 구름, 해 시각 | `sky_score` |
|
||||
| 전국 노을 순위 | 13시 이후 순위를 처음 볼 때 | `sky_score` | Redis `rank:sunset` |
|
||||
| 포스트 문장 | 피드 완성본을 조립할 때 | 위 결과 + 문장 틀 | Redis `feed:{구}` |
|
||||
|
||||
## 그날 피드 (매일 03:00 스케줄러가 만듦, 안 돌았으면 첫 요청에서)
|
||||
|
||||
기획: `docs/피드기획_v2.html`. 스케줄러는 그날 카드를 `post`에 넣는다. 공개 시각은 없고 모든 카드는 03:00부터 다음 날 03:00까지 유효하다. 좋아요·댓글은 카드(`post_id`)에 붙으므로 순서가 바뀌어도 이어지고, 전국 사용자가 같이 본다.
|
||||
|
||||
### 시간대
|
||||
|
||||
| 시간대 | 범위 |
|
||||
|---|---|
|
||||
| 아침 | 05:00–11:00 |
|
||||
| 낮 | 11:00–일몰 2시간 전 |
|
||||
| 저녁 | 일몰 2시간 전–21:00 (그 구 `sun_time` 기준) |
|
||||
| 밤 | 21:00–05:00 |
|
||||
|
||||
### 카드와 켜지는 조건
|
||||
|
||||
| 카드 | 켜지는 조건 | 볼 때 채우는 내용 |
|
||||
|---|---|---|
|
||||
| 지금 날씨 (히어로) | 항상, 맨 위 고정 | 현재 기온·체감·불쾌지수, 오늘 날씨 점수, 앞으로 2시간 비, 오늘 1위 각(작게) |
|
||||
| 오늘 하루 날씨 | 항상, 히어로 바로 아래 고정 (특보가 있으면 특보 다음) | 3시간 칸, 미세먼지. 우산은 우산·특보 카드에서 |
|
||||
| 우산·특보 | 오늘 남은 시간·내일 출퇴근(8·19시) 강수확률 40% 이상, 또는 그 구 특보 | 비 오는 시각, 특보 종류. 특보는 히어로 바로 아래 |
|
||||
| 각 1·2·3위 | 항상 (3장) | 그날 하루 기준 순위. 밤에도 오늘 순위 유지 |
|
||||
| 노을 | 항상. 60점 미만이면 한 줄 카드 | 점수·가장 예쁜 시각·명소. 일몰 뒤에는 내일 일출·노을 |
|
||||
| 내일 미리보기 | 저녁·밤 | 내일 날씨 한 줄, 내일 1위 각, 출근길 비 |
|
||||
| 주말 추천 | 목~일 | 그 구 토·일 날씨와 추천 |
|
||||
| 행사 | 그 시도에 7일 안 행사가 있을 때 | 가장 가까운 행사와 그날 날씨 |
|
||||
| 계절 소식 | 매일 1장 (`article`, 날마다 돌아가며) | 글 첫 문단 |
|
||||
| 날씨 상식 | 매일 1장 (`article`, 그날 날씨와 이어지는 글 우선) | 글 첫 문단 |
|
||||
| 한 문장·시 | 매일 1장 | 오늘 날씨에 맞는 문장. 밤에는 맨 끝 고정 |
|
||||
|
||||
### 시간대별 순서 (히어로 제외)
|
||||
|
||||
| 카드 | 아침 | 낮 | 저녁 | 밤 |
|
||||
|---|---|---|---|---|
|
||||
| 우산·특보 | 1 | 2 | 3 | 2 |
|
||||
| 각 1·2·3위 | 2–4 | 1–3 | 2–4 | 5–7 |
|
||||
| 노을 | 6 | 4 | 1 | 3 |
|
||||
| 내일 미리보기 | 꺼짐 | 꺼짐 | 5 | 1 |
|
||||
| 주말 추천 | 8 | 6 | 6 (금 2) | 4 |
|
||||
| 행사 | 9 | 5 | 7 | 8 |
|
||||
| 계절 소식 | 5 | 7 | 8 | 6 |
|
||||
| 날씨 상식 | 7 | 8 | 9 | 9 |
|
||||
| 한 문장·시 | 10 | 9 | 10 | 맨 끝 |
|
||||
|
||||
- 같은 시간대 안의 각 3장은 하기 좋은 시간이 가까운 각을 앞에, 시간이 지난 각을 뒤에 둔다.
|
||||
- 같은 종류 카드는 붙이지 않는다. 각 3장 사이에는 다른 카드를 하나씩 끼운다.
|
||||
- 꺼진 카드는 빼고 뒤 카드를 올린다. 빈 카드는 만들지 않는다 (노을 한 줄 카드만 예외).
|
||||
- 좋아요·댓글 수와 내가 누른 표시는 캐시와 상관없이 매번 DB에서 덮어쓴다.
|
||||
|
||||
> 구현: `services/feed_service.py`의 `LINEUP`(그날 카드)·`ORDER`(시간대별 순서)·`arrange`. 한 문장·시는 `article` 의 `category=4`(코드 앞머리 `quote-rain-`·`quote-cloud-`·`quote-clear-`·`quote-night-`·`quote-any-`로 날씨에 맞춰 고름). seed 문장은 검수 전 예시다.
|
||||
|
||||
## 하루 1번 스케줄 (매일 03:00, worker)
|
||||
|
||||
| 하는 일 | 이유 |
|
||||
|---|---|
|
||||
| 그날 피드 카드를 `post`에 넣고 Redis `feed:*` 비우기 | 하루 카드 목록 |
|
||||
| 7일 지난 날씨·해 시각·각 점수·노을 점수, 2일 지난 구름, 끝난 지 30일 지난 행사 지우기 | 테이블이 계속 커지지 않게 |
|
||||
| 에어코리아 측정소 목록 갱신 (전국 1번) | 측정소가 새로 생기거나 없어질 때 반영 |
|
||||
|
||||
## 테스트
|
||||
|
||||
`pytest`는 개발 DB를 건드리지 않는다. 실행할 때마다 `nalssigak_test` DB를 `init.sql`로 새로 만들고 시드를 넣으며, Redis는 15번을 쓴다. 테스트마다 외부에서 받은 데이터와 Redis를 비운다. 외부 API는 가짜 값으로 바꾼다 (`tests/conftest.py`의 `offline`).
|
||||
@@ -1,6 +1,6 @@
|
||||
# 날씨각 호출량·DB 크기 추정
|
||||
|
||||
2026-10-02 기준 코드와 개발 DB 실측으로 계산했다. 동작 방식은 `data-pipeline.md` 참고.
|
||||
2026-10-02 기준 코드와 개발 DB 실측으로 계산했다. 동작 방식은 `../../docs/데이터_흐름.html` 참고.
|
||||
|
||||
## 핵심
|
||||
|
||||
|
||||
@@ -0,0 +1,272 @@
|
||||
# Open-Meteo 데이터
|
||||
|
||||
Open-Meteo(`api.open-meteo.com/v1/forecast`)에서 받는 데이터와 저장 방식. 인증키는 쓰지 않는다. 전체 데이터 흐름은 `data-pipeline.md`, 이 문서는 Open-Meteo 쪽만 자세히 적는다.
|
||||
|
||||
> 수치(소요 시간, 값 분포 등)는 2026-10-06 로컬에서 실제 호출해 잰 값이다. 운영에서 달라질 수 있다.
|
||||
|
||||
## 한눈에
|
||||
|
||||
| 구분 | 테이블 | 담는 것 | 좌표 | 모델 | 언제 받나 |
|
||||
|---|---|---|---|---|---|
|
||||
| 층별 구름 | `cloud_hourly` | 저·중·상층 구름 %. 노을·일출 점수용 | 구마다 해 지는 쪽·뜨는 쪽 **20·100km 지점 4곳** | **JMA·ICON** 각각 | 사용자가 볼 때. 오전·13시 이후·21시 이후 구별 하루 3번 |
|
||||
| 보조값 | `openmeteo_hourly` | 자외선·가시거리·돌풍·기압·일조·일사·지면온도 | **구 중심 1곳** (256곳) | 지정 안 함 (Open-Meteo 기본) | worker가 03·09·15·21시 10분(KST)에 전국 일괄 |
|
||||
|
||||
두 테이블은 서로 다른 출처·좌표·주기로 쌓이고 합쳐지지 않는다. 보조값은 활동 지수 10개의 점수에 쓰인다 (3절).
|
||||
|
||||
## 1. 층별 구름 (`cloud_hourly`)
|
||||
|
||||
### 저장 구조
|
||||
|
||||
| 칼럼 | 설명 |
|
||||
|---|---|
|
||||
| `region_code`, `kind`, `distance_km`, `forecast_at`, `model` | 키. `kind` 1=일몰 방향 2=일출 방향, `distance_km` 20 또는 100, `model` 3=JMA 4=ICON |
|
||||
| `cloud_low`, `cloud_mid`, `cloud_high` | 낮은(약 2km 아래)·중간·높은(약 6km 위) 구름 % |
|
||||
|
||||
- 점수에 쓰는 시각(그날 일몰·일출에 가장 가까운 정시) 값만 저장한다. 구마다 2종류 × 2거리 × 3일 × 2모델 = **24행**.
|
||||
- 정리: 예보 시각이 **2일** 지난 행을 매일 03:00에 지운다.
|
||||
|
||||
### 좌표와 시각
|
||||
|
||||
1. 그날 일몰·일출 방위각을 계산한다 (`services/calc/sun.py`). 오늘 값 하나를 3일치에 같이 쓴다.
|
||||
2. 구 중심에서 그 방향으로 20km, 100km 떨어진 점을 구한다 (`common/utils/geo.py`의 `destination`, 소수 둘째 자리 반올림).
|
||||
3. 일몰(일출) 시각에서 가장 가까운 정시(30분을 더해 정시로 내림, GMT)의 값을 쓴다.
|
||||
|
||||
### 점수에 쓰는 방식 (`services/calc/sky_score.py`)
|
||||
|
||||
| 거리 | 쓰는 값 | 역할 |
|
||||
|---|---|---|
|
||||
| 20km | 저·중·상층 | 머리 위 하늘. 중·상층 구름이 50% 안팎이면 물들고, 저층이 많으면 가려져 감점 |
|
||||
| 100km | 저층 + 중층(절반) | 해 쪽 지평선. 막히면 햇빛이 못 들어와 전체를 최대 75% 깎음 |
|
||||
|
||||
```
|
||||
canvas = max(mid20, high20)
|
||||
f_canvas = 0.3 (canvas < 10) / max(0, 1 - |canvas-50|/50)
|
||||
f_near = 1 - 0.8 × low20 / 100
|
||||
light = 1 - min(low100 + 0.5×mid100, 100) / 100
|
||||
점수 = round(100 × (0.75×f_canvas + 0.25×f_near) × (0.25 + 0.75×light))
|
||||
```
|
||||
|
||||
- 모델마다 따로 계산해 **평균**을 최종 점수로 쓰고, 모델 점수의 표준편차로 신뢰도를 정한다 (8 미만 높음, 15 미만 보통, 그 이상 낮음). 모델이 2개 미만이면 낮음.
|
||||
- 등급: 80 이상 붉음, 60 이상 고움, 40 이상 은은함, 그 미만 흐림.
|
||||
|
||||
### 이렇게 정한 이유 (검증 기록)
|
||||
|
||||
- **20·100km 두 지점**: 기존 6점(20·50·100km)과 같은 구름 데이터로 비교하면 점수 차이 평균 0.4점, 최대 7점, 상관 0.97, 등급 일치 185/186 (구 31곳 × 3일 × 일몰/일출). 20km 한 점만 쓰면 상관이 0.18~0.28로 떨어져 구 순위가 맞지 않는다. 50km는 20km와 역할이 겹친다.
|
||||
- **JMA·ICON 두 모델**: 4모델(ECMWF·GFS·JMA·ICON) 평균과 비교하면 점수 차이 평균 1.9점, 최대 12점, 상관 0.91, 등급 일치 166/186. 모델 2개라 신뢰도 "낮음"이 186개 중 3개 나온다 (4모델은 0개). 구름이 거의 없는 날 데이터라 흐린 날에는 다를 수 있다.
|
||||
- 모델 성격(로컬 데이터 기준): ICON이 구름을 가장 많이 보고하고(저층 평균 10.4%), JMA는 중층을 상대적으로 많이 본다(평균 3.7%). 같은 지점·시각에서 한 층이라도 30%p 이상 갈리는 비율이 23%였다. 어느 모델이 한국 실제 구름과 맞는지는 관측으로 검증하지 않았다.
|
||||
|
||||
### 호출량
|
||||
|
||||
- 구마다 좌표 4개. 좌표 24개씩 나눠 동시에 요청하므로 요청 수는 `ceil(좌표 수 / 24)`.
|
||||
- 한 시간대에 전국 256곳을 한꺼번에 갱신하면 좌표 1,024개, 요청 43번. 구별로 따로 갱신하면 구마다 1번.
|
||||
- 구별 하루 최대 3번 갱신 (Redis 마커 `sky:{구}:{날짜}:{시간대}`, 24시간).
|
||||
|
||||
## 2. 보조값 (`openmeteo_hourly`)
|
||||
|
||||
### 받는 변수
|
||||
|
||||
요청: `hourly=<아래 8개>`, `wind_speed_unit=ms`, `forecast_days=4`, `timezone=GMT`, 모델 미지정. 좌표 24개씩 묶어 11번을 동시에 보낸다.
|
||||
|
||||
| Open-Meteo 변수 | 단위 | 칼럼 | 3시간 구간 값 |
|
||||
|---|---|---|---|
|
||||
| `uv_index` | 지수 | `uv_index` | 구간 끝 시각 값 |
|
||||
| `uv_index_clear_sky` | 지수 | `uv_index_clear_sky` | 구간 끝 시각 값. `uv_index ÷ 이 값` = 구름이 해를 가린 정도 |
|
||||
| `visibility` | m | `visibility_m` | 구간 끝 시각 값 |
|
||||
| `wind_gusts_10m` | m/s | `wind_gust_ms` | 구간 끝 시각 값 |
|
||||
| `pressure_msl` | hPa | `pressure_hpa` | 구간 끝 시각 값 |
|
||||
| `soil_temperature_0cm` | ℃ | `soil_temp_c` | 구간 끝 시각 값 |
|
||||
| `sunshine_duration` | 초 | `sunshine_s` | **직전 3시간 합** (0~10,800) |
|
||||
| `shortwave_radiation` | W/m² | `shortwave_avg_wm2`, `shortwave_max_wm2` | 직전 3시간 **평균**, 그중 가장 센 1시간 값 **최대** |
|
||||
|
||||
- 모델을 지정하지 않는 이유: `models`를 지정하면 자외선이 GFS에서만 값이 오고 ECMWF·JMA·ICON은 전부 null이었다. 지정하지 않으면 Open-Meteo가 고른 값 하나가 오는데 어느 모델인지는 응답에 없다. 그래서 이 테이블은 모델별 비교(신뢰도)를 할 수 없다.
|
||||
- 구 중심 256곳 전부, 4일(96시간) 동안 8개 변수 모두 값이 왔고 null은 없었다.
|
||||
|
||||
### 시각 규칙
|
||||
|
||||
- `forecast_at`은 3시간 구간의 **끝 시각**이다. GMT 0·3·6… 정시이고 KST로도 0·3·6… 정시라 단기예보 슬롯과 맞는다.
|
||||
- 일조·일사는 Open-Meteo가 "직전 1시간 값"으로 주므로, 끝 시각 t의 구간은 t-2·t-1·t 시 값 3개다. 3시간이 다 있는 구간만 저장한다.
|
||||
- 자외선·가시거리 등 나머지는 끝 시각 t의 순간값이다.
|
||||
- **밤 구간(21~06시 = 끝 시각 KST 00·03·06시)은 햇빛 값을 저장하지 않는다**: `uv_index`, `uv_index_clear_sky`, `sunshine_s`, `shortwave_avg_wm2`, `shortwave_max_wm2`는 NULL. 가시거리·돌풍·기압·지면온도는 그대로 저장한다. 지수 계산에서는 이 구간을 '정보 없음'이 아니라 자외선 0·일조 0으로 본다 (`is_dark_slot`).
|
||||
- 요청이 UTC 오늘 00시(= KST 09시)부터 96시간이라 한 번에 구간 31개가 나온다 (구 256곳 × 31 = 7,936행).
|
||||
- **KST 하루의 일조 합**은 끝 시각 09·12·15·18·21시 구간 5개를 더한다 (밤 구간은 NULL).
|
||||
- 일사 평균은 맑은 날에도 피크를 깎는다 (시간별 최대 762 → 3시간 평균 최대 694). 시각별 임계(예: 500W/m²)로 쓸 때는 `shortwave_max_wm2`를 같이 본다.
|
||||
|
||||
### 저장·갱신
|
||||
|
||||
| 항목 | 규칙 |
|
||||
|---|---|
|
||||
| 수집 | worker가 03·09·15·21시 10분(KST). 정각이 아닌 이유는 03:00 일일 작업과 겹치지 않게 하려는 것 |
|
||||
| 소요 시간 | 요청 11번 동시 호출 약 2.6~4.6초, 파싱 0.08초, 전체 약 5초 (DB 저장 7,936행 포함) |
|
||||
| 덮어쓰기 | `ON CONFLICT (region_code, forecast_at)`로 같은 (구, 시각)을 새 값으로 바꾼다. 이력은 남지 않는다 |
|
||||
| 값이 비어 올 때 | 새 값이 NULL이면 그 칼럼은 **이전 값을 유지**(`COALESCE`)하고 `fetched_at`만 갱신한다 |
|
||||
| 응답 범위 밖 지난 구간 | 새 응답에 없어서 덮이지 않고 마지막으로 받은 예보 값이 남는다 (실측값이 아님) |
|
||||
| 보관 | 예보 시각이 **7일** 지난 행을 매일 03:00에 지운다 |
|
||||
|
||||
- `fetched_at`은 "마지막 응답을 받은 시각"이다. 일부 칼럼이 계속 비어 오면 그 칼럼은 오래된 값이 남을 수 있다.
|
||||
- 오늘 KST 아침 구간(03·06·09시)은 03:10 수집이 채운다. 워커가 그 시각에 꺼져 있으면 그날 일조 합이 빈다 (요청에 `past_days=1`을 넣으면 해결, 아직 안 함).
|
||||
|
||||
### 호출량
|
||||
|
||||
- 한 번 11번 × 하루 4번 = **하루 44번**, 좌표로는 하루 1,024개.
|
||||
- 구름과 합치면 구름이 전국 일괄일 때 하루 약 4,100좌표 (구름 1,024좌표 × 3시간대 + 보조값 1,024).
|
||||
|
||||
## 3. 활동 지수에 쓰는 방식
|
||||
|
||||
활동 지수 27개 중 10개에 보조값을 적용했다 (`services/calc/index_calc.py`, `services/index_service.py`, `seed/index_definition.json`).
|
||||
|
||||
### 새 축 3개
|
||||
|
||||
| 축 | 값 (지수 계산 창 안에서) | 점수 규칙 (기본값, 지수별로 시드 JSON에서 바꿈) | 칼럼 |
|
||||
|---|---|---|---|
|
||||
| `uv` 자외선 | `uv_index` **최대** | 2 이하 100점, 8 이상 0점, 사이는 선형 | `weight_uv`, `uv_score` |
|
||||
| `sun` 햇빛 | 해 난 비율(`sunshine_s ÷ 10,800`)의 **평균** | 80% 이상 100점, 20% 이하 0점, 사이는 선형 | `weight_sun`, `sun_score` |
|
||||
| `view` 가시거리 | `visibility_m` **최소**(km) | 20km 이상 100점, 5km 이하 0점, 사이는 선형 | `weight_view`, `view_score` |
|
||||
|
||||
- 값이 없으면(수집 전, 구간 없음) 미세먼지처럼 **70점(정보 없음)**.
|
||||
- 비중이 0인 지수에서는 점수에 영향이 없고, 상세 API(`/v1/index/{id}`)에도 나오지 않는다. 기존 6개 축도 같은 규칙으로, 비중이 0이면 나오지 않는다.
|
||||
- 중기예보로 내는 예상 점수(`estimate`)에서는 값이 없으므로 비중이 있으면 70점(정보 없음)이다.
|
||||
- 0점 조건에 쓰는 필드 2개가 늘었다: `gust_ms`(돌풍 최대), `ground_c`(지표면 온도 최대).
|
||||
|
||||
### 지수별 적용
|
||||
|
||||
| 지수 | 새 비중 | 바뀐 기존 비중 (기온·비·바람·습도·공기) | 추가 0점 조건 |
|
||||
|---|---|---|---|
|
||||
| 빨래각 | 햇빛 25 | 15·30·15·10·0 | |
|
||||
| 멍뭉산책각 | 자외선 5 | 35·25·10·5·15 | 지표면 온도 45° 이상 |
|
||||
| 피크닉각 | 자외선 10 | 25·25·15·5·10 | |
|
||||
| 등산각 | 자외선 5, 가시거리 5 | 25·25·20·5·10 | |
|
||||
| 러닝각 | 자외선 5 | 35·20·10·15·10 | |
|
||||
| 가드닝각 | 자외선 5 | 25·30·10·15·10 | |
|
||||
| 별보기각 | 가시거리 15 | 5·10·5·5·15 (시간대 45 그대로) | |
|
||||
| 사진산책각 | 가시거리 10 | 10·25·10·5·10 (시간대 30 그대로) | |
|
||||
| 자전거각 | | 변경 없음 | 돌풍 15m/s 이상 |
|
||||
| 캠핑각 | | 변경 없음 | 돌풍 15m/s 이상 |
|
||||
|
||||
- 나머지 17개 지수는 점수가 바뀌지 않는다 (적용 전후 비교로 확인).
|
||||
- 비중·기준값은 초안이다. 수치는 `seed/index_definition.json`에서 바꾸고 `load_seed.py`로 다시 넣는다.
|
||||
|
||||
### 3시간 구간을 계산 창에 연결하는 규칙
|
||||
|
||||
지수 계산 창(예: 7~10시)의 시각 h마다 아래 구간을 붙인다.
|
||||
|
||||
| 값 | 쓰는 구간 | 이유 |
|
||||
|---|---|---|
|
||||
| 자외선·가시거리·돌풍·지표면 온도 (순간값) | h시~h+1시 한가운데에 **가장 가까운** 구간 끝 시각 (9시→9시, 10시→12시) | 순간값이라 가까운 구간이 맞다. 덮는 구간을 쓰면 아침 창(7~10시)에 정오 자외선이 들어간다 |
|
||||
| 일조 (직전 3시간 합) | h시~h+1시를 **덮는** 구간 (7시→9시, 12시→15시) | 구간 값이 직전 3시간이다 |
|
||||
|
||||
- 처음에는 모두 덮는 구간으로 연결했다가, 가드닝각(7~10시)이 정오 자외선 때문에 86 → 79로 크게 떨어지는 것을 비교에서 발견해 순간값을 가장 가까운 구간으로 바꿨다.
|
||||
- 창과 구간이 어긋나는 곳(11~16시, 7~12시 등)은 근사다.
|
||||
|
||||
### 재계산
|
||||
|
||||
`IndexService.ensure`가 점수를 다시 계산하는 기준에 `openmeteo_hourly.fetched_at`을 추가했다. 보조값이 새로 와야 지수가 새로 계산된다 (6시간마다).
|
||||
|
||||
### 적용 전후 (성남시 분당구 4113500000, 2026-10-06 로컬)
|
||||
|
||||
| 지수 | 10/6 | 10/7 | 10/8 | 비고 |
|
||||
|---|---|---|---|---|
|
||||
| 빨래각 | 84→86 | 81→84 | 81→84 | 해 난 비율 100% |
|
||||
| 멍뭉산책각 | 93→94 | 93→93 | 91→92 | |
|
||||
| 피크닉각 | 81→75 | 85→78 | 85→78 | 낮 자외선 5.0 → 자외선 점수 49 |
|
||||
| 등산각 | 77→76 | 78→77 | 79→78 | |
|
||||
| 러닝각 | 76→78 | 80→82 | 74→77 | |
|
||||
| 가드닝각 | 86→84 | 83→83 | 86→86 | |
|
||||
| 별보기각 | 72→75 | 78→81 | 77→80 | |
|
||||
| 사진산책각 | 73→73 | 73→73 | 72→73 | |
|
||||
| 자전거각, 캠핑각 | 변화 없음 | | | 돌풍 15m/s 미만 |
|
||||
|
||||
- 자외선 5(보통 수준)에 49점은 가혹할 수 있다. 여름 한낮 자외선(8 이상)은 0점이 되어 피크닉각이 크게 내려간다. 필요하면 시드 JSON의 `uv` 규칙(`zero`, `full`)을 조정한다.
|
||||
- 이 비교는 한 지역, 3일, 맑은 날 기준이다.
|
||||
|
||||
### 아직 안 쓴 것
|
||||
|
||||
- 기압(`pressure_hpa`): 등산·캠핑의 "기압 하락" 규칙은 6시간 변화 계산이 필요해 이번에 넣지 않았다.
|
||||
- 일사(`shortwave_*`): 쓰는 지수가 없다.
|
||||
- 문서 `날씨 데이터 및 지수 산출.html`의 새 지수(드라이브·도파민·뽀송·감정기복·센치·안개감성)는 아직 만들지 않았다.
|
||||
- 시간대 해상도가 3시간이라 1~2시간짜리 계산 창에서는 정확도가 떨어진다.
|
||||
|
||||
## 4. 알려진 한계와 주의
|
||||
|
||||
- **429**: 짧은 시간에 좌표를 몰아서 보내면 Open-Meteo가 429를 준다. 로컬에서 좌표 256개 × 3번을 연달아 보냈더니 3번째에 났고, 75초 쉰 뒤 정상이었다. 현재 재시도는 1초·2초 간격 3번이라 분당 한도에 걸리면 그 회차는 11개 요청 중 하나만 실패해도 전체가 저장되지 않는다. 다음 수집(6시간 뒤)까지 옛 값이 남는다.
|
||||
- **한도**: 문서(`날씨 데이터 및 지수 산출.html`)는 하루 1만 건, 시간당 5천 건, 분당 600건이라고 적는다. 좌표 수 기준인지 요청 수 기준인지 확정하지 못했다. 로컬 429는 좌표 수 기준을 시사한다.
|
||||
- **상업 이용**: Open-Meteo 무료 API는 비상업용이다. 서비스에 붙이려면 유료 플랜(API 키)이 필요하다.
|
||||
- **관측값이 아니다**: 전부 예보 모델 값이다. 가시거리·일조·기압은 기상청 관측과 대조하지 않았다. 기상청 ASOS·생활기상지수는 이 키로 호출이 막혔다 (403, 400).
|
||||
- **보조값이 비어 있으면 해당 축은 70점(정보 없음)**으로 계산되어 지수가 평범하게 보일 수 있다. 수집 실패가 길어지면 알아채기 어렵다.
|
||||
- 자외선 등 임계값은 한국 기준으로 검증되지 않은 초안이다.
|
||||
|
||||
## 5. 코드 위치
|
||||
|
||||
| 파일 | 역할 |
|
||||
|---|---|
|
||||
| `services/external/open_meteo.py` | `fetch_clouds`·`parse_clouds`(구름), `fetch_weather`·`parse_weather`(보조값, 3시간 집계), `MODELS` |
|
||||
| `services/sky_service.py` | 구름 갱신(`_refresh`), 구 코드 키 저장, 점수 계산 |
|
||||
| `services/calc/sky_score.py` | 점수·등급·신뢰도·추천 시각 |
|
||||
| `scheduler/jobs.py`, `worker_main.py` | 보조값 수집 job(`refresh_openmeteo_weather`)과 스케줄, 7일 정리 |
|
||||
| `crud/sky_crud.py`, `crud/weather_crud.py` | `cloud_hourly` 저장, `openmeteo_hourly` 저장(`upsert_openmeteo`, NULL 유지) |
|
||||
| `services/calc/index_calc.py` | 새 축 `uv_score`·`sun_score`·`view_score`, 0점 필드 `gust_ms`·`ground_c`, `evaluate` 반영 |
|
||||
| `services/index_service.py` | 3시간 구간 연결(`windows_for`, `_nearest_slot_end_hour`, `_slot_end_hour`), 재계산 기준에 `fetched_at` 추가 |
|
||||
| `router/v1/index/index.py` | 새 축 이름표, 비중 있는 새 축만 상세에 노출 |
|
||||
| `seed/index_definition.json` | 10개 지수의 새 비중·규칙·0점 조건 |
|
||||
| `common/database/model/models.py`, `postgres-init/init.sql` | `CloudHourly`, `OpenMeteoHourly`, 지수 새 축 칼럼 모델과 DDL |
|
||||
| `tests/test_openmeteo_weather.py`, `tests/test_sky_api.py`, `tests/test_sky_score.py`, `tests/test_index_calc.py`, `tests/test_index_api.py` | 집계·저장·덮어쓰기·점수·새 축·구간 연결·재계산 테스트 |
|
||||
|
||||
## 6. 이미 만들어진 DB에 적용할 SQL
|
||||
|
||||
`init.sql`은 DB를 처음 만들 때만 실행된다. 이미 있는 DB에는 아래를 직접 적용한다 (운영 DB는 코드 배포와 순서를 맞춘다).
|
||||
|
||||
```sql
|
||||
BEGIN;
|
||||
|
||||
-- cloud_hourly 구조 변경 (좌표 키 → 구 코드 키). 기존 행은 삭제된다 (외부 API 캐시).
|
||||
DROP TABLE IF EXISTS public.cloud_hourly;
|
||||
CREATE TABLE public.cloud_hourly (
|
||||
region_code VARCHAR(10) NOT NULL,
|
||||
kind SMALLINT NOT NULL, -- 1=일몰 방향 2=일출 방향
|
||||
distance_km SMALLINT NOT NULL, -- 20 또는 100
|
||||
forecast_at TIMESTAMPTZ NOT NULL,
|
||||
model SMALLINT NOT NULL, -- 3=JMA 4=ICON
|
||||
cloud_low SMALLINT NOT NULL,
|
||||
cloud_mid SMALLINT NOT NULL,
|
||||
cloud_high SMALLINT NOT NULL,
|
||||
PRIMARY KEY (region_code, kind, distance_km, forecast_at, model)
|
||||
);
|
||||
DELETE FROM public.sky_score; -- 옛 방식 점수를 비워 새 방식으로 다시 계산
|
||||
|
||||
-- openmeteo_hourly 신규 (추가만 함)
|
||||
CREATE TABLE IF NOT EXISTS public.openmeteo_hourly (
|
||||
region_code VARCHAR(10) NOT NULL,
|
||||
forecast_at TIMESTAMPTZ NOT NULL,
|
||||
uv_index NUMERIC(4,2) NULL,
|
||||
uv_index_clear_sky NUMERIC(4,2) NULL,
|
||||
visibility_m INTEGER NULL,
|
||||
wind_gust_ms NUMERIC(4,1) NULL,
|
||||
pressure_hpa NUMERIC(5,1) NULL,
|
||||
soil_temp_c NUMERIC(4,1) NULL,
|
||||
sunshine_s SMALLINT NULL,
|
||||
shortwave_avg_wm2 SMALLINT NULL,
|
||||
shortwave_max_wm2 SMALLINT NULL,
|
||||
fetched_at TIMESTAMPTZ NOT NULL,
|
||||
PRIMARY KEY (region_code, forecast_at)
|
||||
);
|
||||
|
||||
COMMIT;
|
||||
```
|
||||
|
||||
지수 테이블에 새 축 칼럼을 추가한다 (삭제 없음). 이어서 `seed/index_definition.json`을 `load_seed.py`로 다시 넣어야 새 비중이 반영된다.
|
||||
|
||||
```sql
|
||||
BEGIN;
|
||||
ALTER TABLE public.index_definition
|
||||
ADD COLUMN IF NOT EXISTS weight_uv SMALLINT NOT NULL DEFAULT 0,
|
||||
ADD COLUMN IF NOT EXISTS weight_sun SMALLINT NOT NULL DEFAULT 0,
|
||||
ADD COLUMN IF NOT EXISTS weight_view SMALLINT NOT NULL DEFAULT 0;
|
||||
ALTER TABLE public.index_score
|
||||
ADD COLUMN IF NOT EXISTS uv_score SMALLINT NOT NULL DEFAULT 0,
|
||||
ADD COLUMN IF NOT EXISTS sun_score SMALLINT NOT NULL DEFAULT 0,
|
||||
ADD COLUMN IF NOT EXISTS view_score SMALLINT NOT NULL DEFAULT 0;
|
||||
COMMIT;
|
||||
```
|
||||
|
||||
옛 정의로 계산된 `index_score`는 새 비중과 다르다. 지수를 새로 계산하려면 해당 지역의 `index_score` 행을 지우거나 `openmeteo_hourly`가 새로 갱신될 때까지 기다린다.
|
||||
|
||||
점수를 새 방식으로 다시 계산하려면 Redis의 `sky:*` 마커도 지운다 (`redis-cli --scan --pattern "sky:*" | xargs -r redis-cli del`).
|
||||
@@ -39,16 +39,46 @@ CREATE TABLE IF NOT EXISTS public.weather_daily (
|
||||
PRIMARY KEY (region_code, forecast_date)
|
||||
);
|
||||
|
||||
-- 지점별 층별 구름. 노을·일출 점수용 (구마다 해 지는 쪽·뜨는 쪽 20·50·100km 지점).
|
||||
-- 구별 층별 구름. 출처: Open-Meteo. 노을·일출 점수용 (구 중심에서 해 지는 쪽·뜨는 쪽 20·100km 지점).
|
||||
-- 점수에 쓰는 시각(그날 일몰·일출에 가장 가까운 정시) 값만 넣는다.
|
||||
-- 예전 구조(좌표 키)면 지우고 새로 만든다. 외부 API 에서 받은 임시 값이라 지워도 다시 받는다. 옛 방식 노을 점수도 같이 비워 다시 계산.
|
||||
DO $$ BEGIN
|
||||
IF EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema = 'public' AND table_name = 'cloud_hourly')
|
||||
AND NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema = 'public' AND table_name = 'cloud_hourly' AND column_name = 'region_code') THEN
|
||||
DROP TABLE public.cloud_hourly;
|
||||
IF EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema = 'public' AND table_name = 'sky_score') THEN
|
||||
DELETE FROM public.sky_score;
|
||||
END IF;
|
||||
END IF;
|
||||
END $$;
|
||||
CREATE TABLE IF NOT EXISTS public.cloud_hourly (
|
||||
lat NUMERIC(5,2) NOT NULL, -- 소수 둘째 자리 반올림 값
|
||||
lon NUMERIC(5,2) NOT NULL,
|
||||
forecast_at TIMESTAMPTZ NOT NULL,
|
||||
region_code VARCHAR(10) NOT NULL, -- region.code
|
||||
kind SMALLINT NOT NULL, -- SkyType: 1=일몰 방향 2=일출 방향
|
||||
distance_km SMALLINT NOT NULL, -- 구 중심에서 떨어진 거리: 20(머리 위) 또는 100(해 쪽 지평선)
|
||||
forecast_at TIMESTAMPTZ NOT NULL, -- 일몰·일출에 가장 가까운 정시
|
||||
model SMALLINT NOT NULL, -- CloudModel: 1=ECMWF 2=GFS 3=JMA 4=ICON (모델끼리 비교해 노을 확신을 낸다)
|
||||
cloud_low SMALLINT NOT NULL, -- 낮은 구름 % (약 2km 아래)
|
||||
cloud_mid SMALLINT NOT NULL, -- 중간 구름 %
|
||||
cloud_high SMALLINT NOT NULL, -- 높은 구름 % (약 6km 위)
|
||||
PRIMARY KEY (lat, lon, forecast_at, model)
|
||||
PRIMARY KEY (region_code, kind, distance_km, forecast_at, model)
|
||||
);
|
||||
|
||||
-- 구별 3시간 간격 날씨 보조값. 출처: Open-Meteo (구 중심 좌표, 모델 지정 없음). 6시간마다 새로 받아 같은 (구, 시각) 줄을 덮어쓴다.
|
||||
-- forecast_at 은 3시간 구간의 끝 시각(GMT 0·3·6… = KST 0·3·6…). 일조·일사는 그 직전 3시간 값이고 나머지는 끝 시각 순간값이다.
|
||||
CREATE TABLE IF NOT EXISTS public.openmeteo_hourly (
|
||||
region_code VARCHAR(10) NOT NULL, -- region.code
|
||||
forecast_at TIMESTAMPTZ NOT NULL, -- 3시간 구간의 끝 시각
|
||||
uv_index NUMERIC(4,2) NULL, -- 자외선지수 (순간값)
|
||||
uv_index_clear_sky NUMERIC(4,2) NULL, -- 구름이 없다고 볼 때의 자외선지수 (순간값). uv_index / 이 값 = 구름이 가린 정도
|
||||
visibility_m INTEGER NULL, -- 가시거리 m (순간값)
|
||||
wind_gust_ms NUMERIC(4,1) NULL, -- 돌풍 m/s
|
||||
pressure_hpa NUMERIC(5,1) NULL, -- 해면기압 hPa (순간값)
|
||||
soil_temp_c NUMERIC(4,1) NULL, -- 지표면 온도 ℃ (순간값)
|
||||
sunshine_s SMALLINT NULL, -- 직전 3시간 일조 합 초 (0~10800)
|
||||
shortwave_avg_wm2 SMALLINT NULL, -- 직전 3시간 전천일사량 평균 W/m²
|
||||
shortwave_max_wm2 SMALLINT NULL, -- 직전 3시간 중 가장 센 1시간 값 W/m²
|
||||
fetched_at TIMESTAMPTZ NOT NULL, -- 받은 시각
|
||||
PRIMARY KEY (region_code, forecast_at)
|
||||
);
|
||||
|
||||
-- 미세먼지 측정소. 출처: 에어코리아 측정소 정보 (하루 1번 갱신).
|
||||
@@ -100,6 +130,9 @@ CREATE TABLE IF NOT EXISTS public.sky_score (
|
||||
computed_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
PRIMARY KEY (region_code, score_date, sky_type)
|
||||
);
|
||||
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_agree SMALLINT NULL; -- 그중 같은 하늘 상황을 낸 모델 수
|
||||
|
||||
-- 구별 지수 점수. 오늘·내일·모레와 이번 주말을 날짜별 줄로 둔다 (각 상세 창 칸: 오늘·내일·토·일).
|
||||
CREATE TABLE IF NOT EXISTS public.index_score (
|
||||
@@ -113,6 +146,9 @@ CREATE TABLE IF NOT EXISTS public.index_score (
|
||||
wind_score SMALLINT NOT NULL,
|
||||
humidity_score SMALLINT NOT NULL,
|
||||
air_score SMALLINT NOT NULL,
|
||||
uv_score SMALLINT NOT NULL DEFAULT 0, -- 자외선·햇빛·가시거리은 비중이 있는 지수만 값이 있다 (없으면 0)
|
||||
sun_score SMALLINT NOT NULL DEFAULT 0,
|
||||
view_score SMALLINT NOT NULL DEFAULT 0,
|
||||
time_score SMALLINT NOT NULL,
|
||||
zero_reason VARCHAR(100) NULL, -- 0점이 된 이유 (걸리지 않았으면 NULL)
|
||||
notes JSONB NOT NULL, -- 요소별 근거 문장 {"temp": "체감 21°, 편한 범위 18~24° 안", ...}
|
||||
@@ -120,6 +156,9 @@ CREATE TABLE IF NOT EXISTS public.index_score (
|
||||
computed_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
PRIMARY KEY (region_code, score_date, index_id)
|
||||
);
|
||||
ALTER TABLE public.index_score ADD COLUMN IF NOT EXISTS uv_score SMALLINT NOT NULL DEFAULT 0;
|
||||
ALTER TABLE public.index_score ADD COLUMN IF NOT EXISTS sun_score SMALLINT NOT NULL DEFAULT 0;
|
||||
ALTER TABLE public.index_score ADD COLUMN IF NOT EXISTS view_score SMALLINT NOT NULL DEFAULT 0;
|
||||
|
||||
-- 피드 카드. 매일 03:00 스케줄러가 그날 카드를 전부 만들고, 볼 때 시간대에 따라 켜고 끄고 순서를 정해 그 구 데이터로 채운다.
|
||||
CREATE TABLE IF NOT EXISTS public.post (
|
||||
@@ -234,11 +273,14 @@ CREATE TABLE IF NOT EXISTS public.index_definition (
|
||||
has_detail BOOLEAN NOT NULL DEFAULT TRUE, -- 계산 근거 화면이 있는지
|
||||
description VARCHAR(100) NOT NULL, -- 무엇을 재는지
|
||||
windows JSONB NOT NULL, -- 계산 시간대 [{"from": 18, "to": 24}] 여러 개면 가장 좋은 쪽, {"around": "sunset"} 은 일몰 ±1시간
|
||||
weight_temp SMALLINT NOT NULL, -- 6요소 비중 (합 100)
|
||||
weight_temp SMALLINT NOT NULL, -- 요소 비중 (합 100)
|
||||
weight_rain SMALLINT NOT NULL,
|
||||
weight_wind SMALLINT NOT NULL,
|
||||
weight_humidity SMALLINT NOT NULL,
|
||||
weight_air SMALLINT NOT NULL,
|
||||
weight_uv SMALLINT NOT NULL DEFAULT 0, -- 자외선 (Open-Meteo). 해당 지수만 0 이 아니다
|
||||
weight_sun SMALLINT NOT NULL DEFAULT 0, -- 햇빛 = 해 난 비율 (Open-Meteo 일조)
|
||||
weight_view SMALLINT NOT NULL DEFAULT 0, -- 가시거리 (Open-Meteo)
|
||||
weight_time SMALLINT NOT NULL,
|
||||
factor_rules JSONB NOT NULL, -- 요소별 점수 규칙 {"temp": {"type": "range", "lo": 18, "hi": 24}, "rain": {...}, ...}
|
||||
zero_rules JSONB NOT NULL DEFAULT '[]', -- 바로 0점 조건 [{"field": "rain_prob", "op": ">=", "value": 80}]. 화면 문장은 여기서 만든다
|
||||
@@ -246,6 +288,9 @@ CREATE TABLE IF NOT EXISTS public.index_definition (
|
||||
sentences JSONB NOT NULL DEFAULT '{}', -- 문장 틀 {summary, headline, rabbit, bear, notes}
|
||||
sort_order 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_view SMALLINT NOT NULL DEFAULT 0;
|
||||
|
||||
-- 노을 명소.
|
||||
CREATE TABLE IF NOT EXISTS public.sunset_spot (
|
||||
@@ -287,11 +332,13 @@ CREATE TABLE IF NOT EXISTS public.event (
|
||||
source_url VARCHAR(500) NULL,
|
||||
image_url VARCHAR(500) NULL, -- TourAPI firstimage
|
||||
lat NUMERIC(8,5) NULL, -- TourAPI mapy (가까운 행사 고르기)
|
||||
lon NUMERIC(8,5) NULL -- TourAPI mapx
|
||||
lon NUMERIC(8,5) NULL, -- TourAPI mapx
|
||||
kind SMALLINT NOT NULL DEFAULT 1 -- EventKind: 1=축제 2=전시 3=콘서트 4=팝업
|
||||
);
|
||||
ALTER TABLE public.event ADD COLUMN IF NOT EXISTS image_url VARCHAR(500) NULL;
|
||||
ALTER TABLE public.event ADD COLUMN IF NOT EXISTS lat NUMERIC(8,5) NULL;
|
||||
ALTER TABLE public.event ADD COLUMN IF NOT EXISTS lon NUMERIC(8,5) NULL;
|
||||
ALTER TABLE public.event ADD COLUMN IF NOT EXISTS kind SMALLINT NOT NULL DEFAULT 1;
|
||||
|
||||
-- 공휴일 (주말·행사 탭의 "개천절").
|
||||
CREATE TABLE IF NOT EXISTS public.holiday (
|
||||
|
||||
@@ -3,13 +3,14 @@ from typing import Annotated, Literal, Optional, Union
|
||||
|
||||
from pydantic import Field
|
||||
|
||||
from common.enums import PostType, SlotTone
|
||||
from common.enums import PostType, SkySituation, SlotTone
|
||||
from common.models.gmodel import Res_WebPacketProtocol, WebPacketProtocol
|
||||
|
||||
|
||||
class Row(WebPacketProtocol):
|
||||
label: str
|
||||
value: str
|
||||
place: Optional[str] = Field(default=None, description="위치가 정해진 장소면 지도에서 찾을 이름 (앱이 네이버 지도 링크를 건다)")
|
||||
|
||||
|
||||
class HourCell(WebPacketProtocol):
|
||||
@@ -62,6 +63,7 @@ class SunsetSlide(WebPacketProtocol):
|
||||
score: int
|
||||
grade_label: str
|
||||
cuts: list[Cut]
|
||||
situation: Optional[SkySituation] = Field(default=None, description="하늘 상황. 앱이 카드 하늘 색을 고른다")
|
||||
|
||||
|
||||
class WeekDay(WebPacketProtocol):
|
||||
@@ -143,6 +145,8 @@ class Hero(WebPacketProtocol):
|
||||
weather_score: Optional[int] = None
|
||||
top1: Optional[TopIndex] = None
|
||||
bubble: Optional[str] = None
|
||||
moon_name: Optional[str] = Field(default=None, description="오늘 밤 달 모양: 삭·초승달·상현달·차오르는 달·보름달·기우는 달·하현달·그믐달")
|
||||
moon_pct: Optional[int] = Field(default=None, description="달이 밝게 보이는 비율 0~100")
|
||||
|
||||
|
||||
class BandEvent(WebPacketProtocol):
|
||||
|
||||
@@ -5,7 +5,7 @@ from fastapi import APIRouter, Depends, Path, Query
|
||||
|
||||
from common.enums import ErrorType, IndexCategory
|
||||
from common.models.errors import error_info
|
||||
from router.v1.index.protocol import Factor, IndexSummary, Res_IndexDetail, Res_IndexList, TrendPoint
|
||||
from router.v1.index.protocol import Factor, IndexSummary, Res_IndexDetail, Res_IndexList, ScoreBand, TrendPoint
|
||||
from services.calc.index_calc import AXES, axis_label, zero_rules_text
|
||||
from services.index_service import IndexItem, IndexService, slot_label
|
||||
|
||||
@@ -53,4 +53,12 @@ async def get_index(index_id: int = Path(...), region: str = Query(..., descript
|
||||
if getattr(d, f"weight_{a}")
|
||||
],
|
||||
zero_rules=zero_rules_text(d.zero_rules), zero_reason=s.zero_reason, limit=d.limit_description,
|
||||
bands=_bands(d.sentences or {}, s.score),
|
||||
)
|
||||
|
||||
|
||||
def _bands(sentences: dict, score: int) -> list[ScoreBand]:
|
||||
"""seed 의 sentences {"0": ..., "30": ..., "60": ..., "80": ...} 를 구간으로. 키는 구간 시작 점수."""
|
||||
lows = sorted(int(k) for k in sentences)
|
||||
highs = [lo - 1 for lo in lows[1:]] + [100]
|
||||
return [ScoreBand(low=lo, high=hi, text=sentences[str(lo)], current=lo <= score <= hi) for lo, hi in zip(lows, highs)]
|
||||
@@ -44,6 +44,13 @@ class Factor(WebPacketProtocol):
|
||||
note: str
|
||||
|
||||
|
||||
class ScoreBand(WebPacketProtocol):
|
||||
low: int
|
||||
high: int
|
||||
text: str = Field(description="이 점수 구간이면 어떤 날인지, 통통 튀는 말투 한 문장")
|
||||
current: bool = Field(description="오늘 점수가 이 구간에 있음")
|
||||
|
||||
|
||||
class Res_IndexDetail(Res_WebPacketProtocol):
|
||||
index: Optional[IndexSummary] = None
|
||||
description: Optional[str] = None
|
||||
@@ -51,3 +58,4 @@ class Res_IndexDetail(Res_WebPacketProtocol):
|
||||
zero_rules: Optional[str] = None
|
||||
zero_reason: Optional[str] = None
|
||||
limit: Optional[str] = None
|
||||
bands: list[ScoreBand] = Field(default=[], description="점수 구간별 설명 (0~29, 30~59, 60~79, 80~100)")
|
||||
@@ -1,7 +1,9 @@
|
||||
from datetime import date, datetime
|
||||
from typing import Literal, Optional
|
||||
|
||||
from common.enums import Confidence, SkyGrade, SkyType
|
||||
from pydantic import Field
|
||||
|
||||
from common.enums import Confidence, SkyGrade, SkySituation, SkyType
|
||||
from common.models.gmodel import Res_WebPacketProtocol, WebPacketProtocol
|
||||
|
||||
|
||||
@@ -19,6 +21,9 @@ class SkyScoreData(WebPacketProtocol):
|
||||
grade_label: str
|
||||
confidence: Confidence
|
||||
best_times: list[BestTime] = []
|
||||
situation: Optional[SkySituation] = None
|
||||
situation_label: Optional[str] = Field(default=None, description="하늘 상황 한 줄: 구름에 가려요 / 구름이 적어 짧게 끝나요 / 하늘이 넓게 물들 수 있어요 등")
|
||||
verdict: Optional[Literal["go", "maybe", "rest"]] = None
|
||||
|
||||
|
||||
class SpotData(WebPacketProtocol):
|
||||
@@ -28,6 +33,7 @@ class SpotData(WebPacketProtocol):
|
||||
lat: float
|
||||
lon: float
|
||||
distance_km: float
|
||||
direction: str = Field(default="", description="내 구에서 본 방향 (16방위, 예: 북서)")
|
||||
|
||||
|
||||
class PlanSpot(WebPacketProtocol):
|
||||
@@ -43,6 +49,9 @@ class SkyPlanData(WebPacketProtocol):
|
||||
reason: str
|
||||
score: int
|
||||
grade_label: str
|
||||
situation_label: Optional[str] = None
|
||||
models_total: Optional[int] = Field(default=None, description="계산에 쓴 예보 모델 수")
|
||||
models_agree: Optional[int] = Field(default=None, description="그중 같은 하늘 상황을 낸 모델 수")
|
||||
best_at: Optional[datetime] = None
|
||||
spot: Optional[PlanSpot] = None
|
||||
timeline: list[BestTime] = []
|
||||
@@ -66,8 +75,10 @@ class RankData(WebPacketProtocol):
|
||||
note: Optional[str] = None
|
||||
score: int
|
||||
grade: SkyGrade
|
||||
situation_label: Optional[str] = None
|
||||
|
||||
|
||||
class Res_SkyRanking(Res_WebPacketProtocol):
|
||||
day: Optional[date] = None
|
||||
summary: Optional[str] = Field(default=None, description="대부분 같은 하늘 상황인 날 한 줄 (예: 오늘은 전국이 맑아 대부분 짧게 끝나요)")
|
||||
items: list[RankData] = []
|
||||
@@ -1,12 +1,13 @@
|
||||
from fastapi import APIRouter, Depends, Query
|
||||
|
||||
from common.database.model.models import SkyScore
|
||||
from common.enums import Confidence, ErrorType, SkyGrade, SkyType
|
||||
from common.enums import Confidence, ErrorType, SkyGrade, SkySituation, SkyType
|
||||
from common.models.errors import error_info
|
||||
from common.utils.kma_time import now_kst
|
||||
from common.utils.text import compass
|
||||
from router.v1.sky.protocol import BestTime, PlanSpot, RankData, Res_Sky, Res_SkyRanking, SkyPlanData, SkyScoreData, SpotData
|
||||
from services.calc.sky_score import GRADE_LABEL
|
||||
from services.sky_service import SkyPlan, SkyService
|
||||
from services.calc.sky_score import GRADE_LABEL, SITUATION_LINE
|
||||
from services.sky_service import SkyPlan, SkyService, day_verdict, ranking_summary
|
||||
|
||||
router = APIRouter(prefix="/v1/sky", tags=["sky"])
|
||||
|
||||
@@ -15,12 +16,18 @@ def _score(x: SkyScore) -> SkyScoreData:
|
||||
return SkyScoreData(
|
||||
day=x.score_date, sky_type=SkyType(x.sky_type), score=x.score, grade=g, grade_label=GRADE_LABEL[g],
|
||||
confidence=Confidence(x.confidence), best_times=[BestTime(**b) for b in x.best_times],
|
||||
situation=SkySituation(x.situation) if x.situation else None, situation_label=_situation(x), verdict=day_verdict(x),
|
||||
)
|
||||
|
||||
|
||||
def _situation(x: SkyScore) -> str | None:
|
||||
return SITUATION_LINE[SkySituation(x.situation)] if x.situation else None
|
||||
|
||||
|
||||
def _plan(p: SkyPlan) -> SkyPlanData:
|
||||
return SkyPlanData(
|
||||
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,
|
||||
best_at=p.best_at, spot=PlanSpot(name=p.spot.spot.name, distance_km=p.spot.distance_km) if p.spot else None,
|
||||
timeline=[BestTime(**b) for b in p.timeline], outlook=p.outlook,
|
||||
)
|
||||
@@ -36,7 +43,8 @@ async def get_sky(region: str = Query(..., description="구 행정코드"), serv
|
||||
sunset=_score(view.sunset) if view.sunset else None, sunrise=_score(view.sunrise) if view.sunrise else None,
|
||||
days=[_score(x) for x in view.days],
|
||||
spots=[
|
||||
SpotData(no=i + 1, name=s.spot.name, description=s.spot.description, lat=float(s.spot.lat), lon=float(s.spot.lon), distance_km=s.distance_km)
|
||||
SpotData(no=i + 1, name=s.spot.name, description=s.spot.description, lat=float(s.spot.lat), lon=float(s.spot.lon), distance_km=s.distance_km,
|
||||
direction=compass(s.direction))
|
||||
for i, s in enumerate(view.spots)
|
||||
],
|
||||
plan=_plan(view.plan) if view.plan else None,
|
||||
@@ -49,9 +57,10 @@ async def get_sky_ranking(service: SkyService = Depends()) -> Res_SkyRanking:
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return Res_SkyRanking(result=error_info(err))
|
||||
return Res_SkyRanking(
|
||||
day=now_kst().date(),
|
||||
day=now_kst().date(), summary=ranking_summary(items),
|
||||
items=[
|
||||
RankData(rank=i.rank, region_code=i.region.code, name=i.region.name, note=i.region.ranking_note, score=i.score.score, grade=SkyGrade(i.score.grade))
|
||||
RankData(rank=i.rank, region_code=i.region.code, name=i.region.name, note=i.region.ranking_note, score=i.score.score, grade=SkyGrade(i.score.grade),
|
||||
situation_label=_situation(i.score))
|
||||
for i in items
|
||||
],
|
||||
)
|
||||
@@ -1,18 +1,36 @@
|
||||
import asyncio
|
||||
|
||||
import httpx
|
||||
from redis.exceptions import RedisError
|
||||
from sqlalchemy import text
|
||||
|
||||
from common.cache.redis_client import REDIS
|
||||
from common.database.db_session_manager import DB_SESSION_MNG
|
||||
from common.enums import ErrorType
|
||||
from common.logger import LOG
|
||||
from common.utils.kma_time import now_kst
|
||||
from crud.air_crud import AirCRUD
|
||||
from crud.feed_crud import FeedCRUD
|
||||
from crud.region_crud import RegionCRUD
|
||||
from crud.season_crud import SeasonCRUD
|
||||
from crud.week_crud import WeekCRUD
|
||||
from crud.weather_crud import WeatherCRUD
|
||||
from services.external.airkorea import fetch_stations, parse_stations
|
||||
from services.external import popga, teams_webhook
|
||||
from services.external.culture_api import SIDO_NAME
|
||||
from services.external.data_go_kr import DataGoKrNotConfigured, DataGoKrRequestFailed
|
||||
from services.external.open_meteo import OpenMeteoRequestFailed, fetch_weather, parse_weather
|
||||
from services.feed_service import build_feed_day, clear_feed_cache
|
||||
from services.week_service import collect_events
|
||||
from services.weekend_rank import WeekendRank
|
||||
|
||||
_POPGA_SEEN = "popga:lastmod" # {팝업 id: 마지막으로 읽은 lastmod}, 바뀐 페이지만 다시 읽는다
|
||||
_POPGA_BATCH = 100
|
||||
EVENTS_DONE = "events:collected" # 행사 수집을 마친 표시. 7일 유지, 없으면 worker 가 켜질 때 한 번 돈다
|
||||
_EVENTS_TTL_SEC = 7 * 86400
|
||||
_SIDO_GAP_SEC = 1.0
|
||||
_KIND_KO = {"festival": "축제", "exhibition": "전시", "concert": "콘서트"}
|
||||
|
||||
_CLEANUP_SQL = [
|
||||
"DELETE FROM public.weather_hourly WHERE forecast_at < now() - interval '7 days'",
|
||||
"DELETE FROM public.weather_daily WHERE forecast_date < (now() AT TIME ZONE 'Asia/Seoul')::date - 7",
|
||||
@@ -21,7 +39,9 @@ _CLEANUP_SQL = [
|
||||
"DELETE FROM public.sky_score WHERE score_date < (now() AT TIME ZONE 'Asia/Seoul')::date - 7",
|
||||
"DELETE FROM public.cloud_hourly WHERE forecast_at < now() - interval '2 days'",
|
||||
"DELETE FROM public.event WHERE end_date < (now() AT TIME ZONE 'Asia/Seoul')::date - 30",
|
||||
"DELETE FROM public.openmeteo_hourly WHERE forecast_at < now() - interval '7 days'",
|
||||
]
|
||||
_OPENMETEO_DAYS = 4
|
||||
|
||||
|
||||
async def cleanup_old_rows() -> ErrorType:
|
||||
@@ -50,8 +70,120 @@ async def refresh_weekend_rank(only_if_missing: bool = False) -> ErrorType:
|
||||
return err
|
||||
|
||||
|
||||
async def refresh_openmeteo_weather() -> ErrorType:
|
||||
"""전국 구 중심 좌표의 자외선·가시거리·돌풍·기압·일조·일사·지면온도를 3시간 구간으로 묶어 저장한다."""
|
||||
err, regions = await DB_SESSION_MNG.execute_lambda(lambda s: RegionCRUD().search(s))
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return err
|
||||
by_point: dict[tuple[float, float], list[str]] = {}
|
||||
for r in regions:
|
||||
by_point.setdefault((round(float(r.lat), 2), round(float(r.lon), 2)), []).append(r.code)
|
||||
points = sorted(by_point)
|
||||
try:
|
||||
async with httpx.AsyncClient(timeout=30) as client:
|
||||
data = await fetch_weather(client, points, days=_OPENMETEO_DAYS)
|
||||
except OpenMeteoRequestFailed as e:
|
||||
LOG.error(f"[scheduler] refresh_openmeteo_weather: {e}")
|
||||
return ErrorType.EXTERNAL_API_ERROR
|
||||
fetched_at = now_kst()
|
||||
rows = [
|
||||
{"region_code": code, "fetched_at": fetched_at, **slot}
|
||||
for point, d in zip(points, data)
|
||||
for slot in parse_weather(d)
|
||||
for code in by_point[point]
|
||||
]
|
||||
err = await DB_SESSION_MNG.execute_lambda_run([lambda s: WeatherCRUD().upsert_openmeteo(s, rows)])
|
||||
LOG.info(f"[scheduler] refresh_openmeteo_weather {len(points)} points rows {len(rows)}: {err.name}")
|
||||
return err
|
||||
|
||||
|
||||
async def build_today_feed() -> ErrorType:
|
||||
"""그날 전국 공통 피드 칸을 넣고, 구별 피드 캐시를 비운다."""
|
||||
err = await build_feed_day(now_kst().date(), FeedCRUD(), SeasonCRUD())
|
||||
await clear_feed_cache()
|
||||
return err
|
||||
|
||||
|
||||
async def _save_popups(rows: list[dict], seen: dict[str, str]) -> ErrorType:
|
||||
err = await DB_SESSION_MNG.execute_lambda_run([lambda s: WeekCRUD().upsert_events(s, rows)])
|
||||
if err is ErrorType.SUCCESS and seen:
|
||||
await REDIS.conn.hset(_POPGA_SEEN, mapping=seen)
|
||||
return err
|
||||
|
||||
|
||||
async def refresh_popups() -> ErrorType:
|
||||
"""팝가 팝업스토어 중 이번 달 1일 이후에 끝나는 것을 event 에 넣는다. 첫 실행은 전부, 그 뒤로는 바뀐 페이지만 읽는다."""
|
||||
since = now_kst().date().replace(day=1)
|
||||
saved = 0
|
||||
try:
|
||||
async with httpx.AsyncClient(timeout=20, headers={"User-Agent": "nalssigak-bot"}) as client:
|
||||
index = await popga.fetch_popup_index(client)
|
||||
known = await REDIS.conn.hgetall(_POPGA_SEEN)
|
||||
todo = sorted((i for i, mod in index.items() if known.get(str(i)) != mod), reverse=True)
|
||||
LOG.info(f"[scheduler] refresh_popups: {len(todo)}/{len(index)} pages to read")
|
||||
rows: list[dict] = []
|
||||
seen: dict[str, str] = {}
|
||||
for n, popup_id in enumerate(todo, 1):
|
||||
await asyncio.sleep(popga.REQUEST_GAP_SEC)
|
||||
try:
|
||||
page = await popga.fetch_popup_page(client, popup_id)
|
||||
except httpx.HTTPError as e:
|
||||
LOG.error(f"[scheduler] refresh_popups {popup_id}: {type(e).__name__}")
|
||||
continue
|
||||
row = popga.parse_popup(page, popup_id, since)
|
||||
if row:
|
||||
rows.append(row)
|
||||
seen[str(popup_id)] = index[popup_id]
|
||||
if n % _POPGA_BATCH == 0 or n == len(todo):
|
||||
if await _save_popups(rows, seen) is not ErrorType.SUCCESS:
|
||||
return ErrorType.DB_ERROR
|
||||
saved += len(rows)
|
||||
rows, seen = [], {}
|
||||
except (httpx.HTTPError, RedisError) as e:
|
||||
LOG.error(f"[scheduler] refresh_popups: {type(e).__name__} {e}")
|
||||
return ErrorType.EXTERNAL_API_ERROR
|
||||
LOG.info(f"[scheduler] refresh_popups saved {saved}")
|
||||
return ErrorType.SUCCESS
|
||||
|
||||
|
||||
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")
|
||||
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
|
||||
|
||||
|
||||
async def refresh_events(only_if_missing: bool = False) -> ErrorType:
|
||||
"""전국 축제·전시·콘서트·팝업을 받고 Teams 로 알린다. only_if_missing 이면 7일 안에 마친 기록이 있을 때 건너뛴다."""
|
||||
try:
|
||||
if only_if_missing and await REDIS.conn.exists(EVENTS_DONE):
|
||||
return ErrorType.SUCCESS
|
||||
except RedisError as e:
|
||||
LOG.error(f"[scheduler] refresh_events done check: {e}")
|
||||
today = now_kst().date()
|
||||
totals = dict.fromkeys(_KIND_KO, 0)
|
||||
failed: list[str] = []
|
||||
for sido, name in SIDO_NAME.items():
|
||||
err, counts = await collect_events(sido, today)
|
||||
if err is not ErrorType.SUCCESS:
|
||||
failed.append(name)
|
||||
for k, n in counts.items():
|
||||
totals[k] += n
|
||||
await asyncio.sleep(_SIDO_GAP_SEC)
|
||||
popup_err = await refresh_popups()
|
||||
popups = await _popup_count()
|
||||
|
||||
ok = not failed and popup_err is ErrorType.SUCCESS
|
||||
lines = [f"{_KIND_KO[k]} {n}" for k, n in totals.items()] + [f"팝업 {popups}"]
|
||||
detail = f"{today:%Y-%m-%d} · {', '.join(lines)} (진행 중·예정)"
|
||||
if failed:
|
||||
detail += f"\n실패한 시도: {', '.join(failed)}"
|
||||
if popup_err is not ErrorType.SUCCESS:
|
||||
detail += f"\n팝업 수집 실패: {popup_err.name}"
|
||||
await teams_webhook.send("행사 수집 완료" if ok else "행사 수집 일부 실패", detail)
|
||||
if ok:
|
||||
try:
|
||||
await REDIS.conn.set(EVENTS_DONE, today.isoformat(), ex=_EVENTS_TTL_SEC)
|
||||
except RedisError as e:
|
||||
LOG.error(f"[scheduler] refresh_events done mark: {e}")
|
||||
LOG.info(f"[scheduler] refresh_events: {detail}")
|
||||
return ErrorType.SUCCESS if ok else ErrorType.EXTERNAL_API_ERROR
|
||||
@@ -3,7 +3,7 @@ import os
|
||||
|
||||
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
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: "생활 고민"}
|
||||
WD = {"mon": "월", "tue": "화", "wed": "수", "thu": "목", "fri": "금", "sat": "토", "sun": "일", "holiday": "공휴일", "default": "그 외"}
|
||||
@@ -111,7 +111,10 @@ def main() -> None:
|
||||
if x.get("limit_description"):
|
||||
P(f"- 반영 못 하는 것: {x['limit_description']}")
|
||||
if x.get("sentences"):
|
||||
P(f"- 문장: {json.dumps(x['sentences'], ensure_ascii=False)}")
|
||||
lows = sorted(int(k) for k in x["sentences"])
|
||||
P("- 점수 구간별 설명 (상세 창에 나옴):")
|
||||
for lo, hi in zip(lows, [v - 1 for v in lows[1:]] + [100]):
|
||||
P(f" - {lo}~{hi}점: {x['sentences'][str(lo)]}")
|
||||
P("")
|
||||
with open(OUT, "w", encoding="utf-8") as f:
|
||||
f.write("\n".join(out) + "\n")
|
||||
|
||||
@@ -19,6 +19,9 @@
|
||||
"weight_wind": 15,
|
||||
"weight_humidity": 10,
|
||||
"weight_air": 10,
|
||||
"weight_uv": 0,
|
||||
"weight_sun": 0,
|
||||
"weight_view": 0,
|
||||
"weight_time": 10,
|
||||
"factor_rules": {
|
||||
"temp": {
|
||||
@@ -61,7 +64,12 @@
|
||||
}
|
||||
],
|
||||
"limit_description": "모기, 가게 영업 여부, 자리 경쟁은 반영하지 못해요",
|
||||
"sentences": {},
|
||||
"sentences": {
|
||||
"0": "비 오거나 바람이 쌩쌩, 오늘 야장은 접어요. 실내 포차로 피신!",
|
||||
"30": "앉을 순 있는데 춥거나 덥거나 눅눅해요. 겉옷이나 부채 필수!",
|
||||
"60": "꽤 괜찮은 저녁! 바람만 살랑 불어 주면 딱이에요.",
|
||||
"80": "18~24°에 바람 살랑, 비 걱정 없음! 오늘은 무조건 바깥 자리 🍻"
|
||||
},
|
||||
"sort_order": 1
|
||||
},
|
||||
{
|
||||
@@ -79,11 +87,14 @@
|
||||
"to": 16
|
||||
}
|
||||
],
|
||||
"weight_temp": 30,
|
||||
"weight_temp": 25,
|
||||
"weight_rain": 25,
|
||||
"weight_wind": 15,
|
||||
"weight_humidity": 10,
|
||||
"weight_humidity": 5,
|
||||
"weight_air": 10,
|
||||
"weight_uv": 10,
|
||||
"weight_sun": 0,
|
||||
"weight_view": 0,
|
||||
"weight_time": 10,
|
||||
"factor_rules": {
|
||||
"temp": {
|
||||
@@ -111,6 +122,10 @@
|
||||
"sun": 100,
|
||||
"holiday": 100,
|
||||
"default": 60
|
||||
},
|
||||
"uv": {
|
||||
"zero": 8,
|
||||
"full": 2
|
||||
}
|
||||
},
|
||||
"zero_rules": [
|
||||
@@ -121,7 +136,12 @@
|
||||
}
|
||||
],
|
||||
"limit_description": "잔디 상태, 공원 혼잡도는 반영하지 못해요",
|
||||
"sentences": {},
|
||||
"sentences": {
|
||||
"0": "비 소식이 있어요. 돗자리는 집에 고이 두기!",
|
||||
"30": "햇볕이 뜨겁거나 바람이 쌀쌀해요. 그늘이나 담요 챙기면 버틸 만!",
|
||||
"60": "돗자리 펴기 괜찮은 날! 바람막이 하나면 완벽해요.",
|
||||
"80": "20~26°에 바람 잔잔, 김밥 싸서 당장 출발! 🧺"
|
||||
},
|
||||
"sort_order": 2
|
||||
},
|
||||
{
|
||||
@@ -144,6 +164,9 @@
|
||||
"weight_wind": 15,
|
||||
"weight_humidity": 15,
|
||||
"weight_air": 10,
|
||||
"weight_uv": 0,
|
||||
"weight_sun": 0,
|
||||
"weight_view": 0,
|
||||
"weight_time": 10,
|
||||
"factor_rules": {
|
||||
"temp": {
|
||||
@@ -185,7 +208,12 @@
|
||||
}
|
||||
],
|
||||
"limit_description": "야구 경기 같은 이벤트는 아직 반영하지 못해요",
|
||||
"sentences": {},
|
||||
"sentences": {
|
||||
"0": "체감 10° 아래거나 비가 와요. 치킨은 배달, 맥주는 집에서!",
|
||||
"30": "바깥은 좀 쌀쌀하거나 후덥지근해요. 가게 안쪽 자리 추천!",
|
||||
"60": "바깥 테이블 괜찮아요! 얇은 겉옷 하나만 챙겨요.",
|
||||
"80": "20~27°의 선선한 저녁, 치킨에 맥주 부르는 날 🍗"
|
||||
},
|
||||
"sort_order": 3
|
||||
},
|
||||
{
|
||||
@@ -208,6 +236,9 @@
|
||||
"weight_wind": 15,
|
||||
"weight_humidity": 10,
|
||||
"weight_air": 15,
|
||||
"weight_uv": 0,
|
||||
"weight_sun": 0,
|
||||
"weight_view": 0,
|
||||
"weight_time": 5,
|
||||
"factor_rules": {
|
||||
"temp": {
|
||||
@@ -247,7 +278,12 @@
|
||||
}
|
||||
],
|
||||
"limit_description": "길 공사, 조명은 반영하지 못해요",
|
||||
"sentences": {},
|
||||
"sentences": {
|
||||
"0": "비가 쏟아지거나 초미세먼지가 매우 나빠요. 오늘은 실내 걷기로!",
|
||||
"30": "걸을 순 있는데 춥거나 덥거나 공기가 탁해요. 짧게 한 바퀴만!",
|
||||
"60": "한 바퀴 돌기 좋은 저녁! 이어폰 챙겨서 가볍게 나가요.",
|
||||
"80": "15~23°에 공기 맑고 바람 살랑, 동네 한 바퀴 무조건 🚶"
|
||||
},
|
||||
"sort_order": 4
|
||||
},
|
||||
{
|
||||
@@ -282,6 +318,9 @@
|
||||
"weight_wind": 15,
|
||||
"weight_humidity": 10,
|
||||
"weight_air": 45,
|
||||
"weight_uv": 0,
|
||||
"weight_sun": 0,
|
||||
"weight_view": 0,
|
||||
"weight_time": 5,
|
||||
"factor_rules": {
|
||||
"temp": {
|
||||
@@ -314,7 +353,12 @@
|
||||
}
|
||||
],
|
||||
"limit_description": "집 방향과 주변 공사 먼지는 반영하지 못해요",
|
||||
"sentences": {},
|
||||
"sentences": {
|
||||
"0": "초미세먼지가 매우 나빠요. 창문 꼭 닫고 공기청정기 ON!",
|
||||
"30": "공기가 탁하거나 비가 와요. 5분만 짧게 열고 닫기!",
|
||||
"60": "열어도 괜찮아요. 맞바람 나게 10분이면 충분!",
|
||||
"80": "공기 맑고 바람도 적당, 창문 활짝 열 시간 🌬️"
|
||||
},
|
||||
"sort_order": 5
|
||||
},
|
||||
{
|
||||
@@ -332,11 +376,14 @@
|
||||
"to": 12
|
||||
}
|
||||
],
|
||||
"weight_temp": 30,
|
||||
"weight_temp": 25,
|
||||
"weight_rain": 25,
|
||||
"weight_wind": 20,
|
||||
"weight_humidity": 10,
|
||||
"weight_humidity": 5,
|
||||
"weight_air": 10,
|
||||
"weight_uv": 5,
|
||||
"weight_sun": 0,
|
||||
"weight_view": 5,
|
||||
"weight_time": 5,
|
||||
"factor_rules": {
|
||||
"temp": {
|
||||
@@ -365,6 +412,14 @@
|
||||
"sun": 100,
|
||||
"holiday": 100,
|
||||
"default": 50
|
||||
},
|
||||
"uv": {
|
||||
"zero": 8,
|
||||
"full": 2
|
||||
},
|
||||
"view": {
|
||||
"zero": 5,
|
||||
"full": 20
|
||||
}
|
||||
},
|
||||
"zero_rules": [
|
||||
@@ -380,7 +435,12 @@
|
||||
}
|
||||
],
|
||||
"limit_description": "등산로 통제, 낙석 정보는 산림청 안내를 확인하세요",
|
||||
"sentences": {},
|
||||
"sentences": {
|
||||
"0": "비 소식이나 강풍 특보가 있어요. 오늘 산은 쉬어요!",
|
||||
"30": "산 위는 꽤 춥거나 더워요(6° 낮게 쳐요). 옷차림 단단히!",
|
||||
"60": "오를 만해요! 바람막이 챙기고 일찍 출발해요.",
|
||||
"80": "산 위도 선선하고 바람 잔잔, 정상 인증각 ⛰️"
|
||||
},
|
||||
"sort_order": 6
|
||||
},
|
||||
{
|
||||
@@ -404,6 +464,9 @@
|
||||
"weight_wind": 10,
|
||||
"weight_humidity": 10,
|
||||
"weight_air": 10,
|
||||
"weight_uv": 0,
|
||||
"weight_sun": 0,
|
||||
"weight_view": 0,
|
||||
"weight_time": 5,
|
||||
"factor_rules": {
|
||||
"temp": {
|
||||
@@ -436,7 +499,12 @@
|
||||
}
|
||||
],
|
||||
"limit_description": "황사·꽃가루 같은 하늘 먼지는 일부만 반영해요",
|
||||
"sentences": {},
|
||||
"sentences": {
|
||||
"0": "곧 비가 와요. 지금 세차하면 물 낭비!",
|
||||
"30": "비 기운이 남아 있어요. 하루쯤 미루는 게 이득!",
|
||||
"60": "세차해도 괜찮아요. 먼지는 좀 붙을 수 있어요.",
|
||||
"80": "비 걱정 없고 공기도 맑아요. 반짝반짝 오래가는 날 ✨"
|
||||
},
|
||||
"sort_order": 7
|
||||
},
|
||||
{
|
||||
@@ -459,6 +527,9 @@
|
||||
"weight_wind": 15,
|
||||
"weight_humidity": 15,
|
||||
"weight_air": 10,
|
||||
"weight_uv": 0,
|
||||
"weight_sun": 0,
|
||||
"weight_view": 0,
|
||||
"weight_time": 5,
|
||||
"factor_rules": {
|
||||
"temp": {
|
||||
@@ -494,10 +565,20 @@
|
||||
"field": "wind_ms",
|
||||
"op": ">=",
|
||||
"value": 14
|
||||
},
|
||||
{
|
||||
"field": "gust_ms",
|
||||
"op": ">=",
|
||||
"value": 15
|
||||
}
|
||||
],
|
||||
"limit_description": "캠핑장 예약 상황은 반영하지 못해요",
|
||||
"sentences": {},
|
||||
"sentences": {
|
||||
"0": "비가 오거나 바람이 너무 세요. 텐트 날아가요!",
|
||||
"30": "밤에 춥거나 습해요. 침낭은 두꺼운 걸로!",
|
||||
"60": "하룻밤 괜찮아요. 새벽엔 쌀쌀하니 담요 챙기기!",
|
||||
"80": "밤새 12~22°에 바람 잔잔, 불멍하기 딱 좋은 밤 🔥"
|
||||
},
|
||||
"sort_order": 8
|
||||
},
|
||||
{
|
||||
@@ -522,8 +603,11 @@
|
||||
"weight_temp": 35,
|
||||
"weight_rain": 20,
|
||||
"weight_wind": 10,
|
||||
"weight_humidity": 20,
|
||||
"weight_humidity": 15,
|
||||
"weight_air": 10,
|
||||
"weight_uv": 5,
|
||||
"weight_sun": 0,
|
||||
"weight_view": 0,
|
||||
"weight_time": 5,
|
||||
"factor_rules": {
|
||||
"temp": {
|
||||
@@ -545,6 +629,10 @@
|
||||
"time": {
|
||||
"type": "fixed",
|
||||
"value": 100
|
||||
},
|
||||
"uv": {
|
||||
"zero": 8,
|
||||
"full": 2
|
||||
}
|
||||
},
|
||||
"zero_rules": [
|
||||
@@ -560,7 +648,12 @@
|
||||
}
|
||||
],
|
||||
"limit_description": "노면 상태는 반영하지 못해요",
|
||||
"sentences": {},
|
||||
"sentences": {
|
||||
"0": "체감 35° 넘거나 비가 쏟아져요. 오늘은 러닝머신으로!",
|
||||
"30": "덥거나 눅눅해서 금방 지쳐요. 거리 줄이고 물 꼭!",
|
||||
"60": "뛸 만해요! 아침·저녁 중 시원한 쪽 고르기.",
|
||||
"80": "8~18°에 공기 보송, 기록 갱신각 🏃"
|
||||
},
|
||||
"sort_order": 9
|
||||
},
|
||||
{
|
||||
@@ -579,10 +672,13 @@
|
||||
}
|
||||
],
|
||||
"weight_temp": 5,
|
||||
"weight_rain": 15,
|
||||
"weight_rain": 10,
|
||||
"weight_wind": 5,
|
||||
"weight_humidity": 10,
|
||||
"weight_air": 20,
|
||||
"weight_humidity": 5,
|
||||
"weight_air": 15,
|
||||
"weight_uv": 0,
|
||||
"weight_sun": 0,
|
||||
"weight_view": 15,
|
||||
"weight_time": 45,
|
||||
"factor_rules": {
|
||||
"temp": {
|
||||
@@ -603,6 +699,10 @@
|
||||
},
|
||||
"time": {
|
||||
"type": "moon"
|
||||
},
|
||||
"view": {
|
||||
"zero": 5,
|
||||
"full": 20
|
||||
}
|
||||
},
|
||||
"zero_rules": [
|
||||
@@ -613,7 +713,12 @@
|
||||
}
|
||||
],
|
||||
"limit_description": "도시 불빛은 지역 평균으로만 반영해요",
|
||||
"sentences": {},
|
||||
"sentences": {
|
||||
"0": "구름이 하늘을 꽉 덮었어요. 별은 다음 기회에!",
|
||||
"30": "달이 밝거나 하늘이 뿌예서 큰 별 몇 개만 보여요.",
|
||||
"60": "꽤 보여요! 불빛 적은 곳으로 조금만 나가요.",
|
||||
"80": "달은 어둡고 공기는 맑아요. 은하수 노려볼 만한 밤 ✨"
|
||||
},
|
||||
"sort_order": 10
|
||||
},
|
||||
{
|
||||
@@ -640,6 +745,9 @@
|
||||
"weight_wind": 15,
|
||||
"weight_humidity": 10,
|
||||
"weight_air": 5,
|
||||
"weight_uv": 0,
|
||||
"weight_sun": 0,
|
||||
"weight_view": 0,
|
||||
"weight_time": 5,
|
||||
"factor_rules": {
|
||||
"temp": {
|
||||
@@ -663,7 +771,12 @@
|
||||
},
|
||||
"zero_rules": [],
|
||||
"limit_description": "실제 주문량으로 검증하기 전이에요",
|
||||
"sentences": {},
|
||||
"sentences": {
|
||||
"0": "25° 넘게 더워요. 국물보다 냉면이 당길 날!",
|
||||
"30": "국물이 살짝 생각나는 정도예요.",
|
||||
"60": "쌀쌀하거나 비 와서 국물 각 잡혀요!",
|
||||
"80": "춥고 비까지! 얼큰한 짬뽕 한 그릇 무조건 🍜"
|
||||
},
|
||||
"sort_order": 11
|
||||
},
|
||||
{
|
||||
@@ -686,6 +799,9 @@
|
||||
"weight_wind": 10,
|
||||
"weight_humidity": 15,
|
||||
"weight_air": 5,
|
||||
"weight_uv": 0,
|
||||
"weight_sun": 0,
|
||||
"weight_view": 0,
|
||||
"weight_time": 5,
|
||||
"factor_rules": {
|
||||
"temp": {
|
||||
@@ -711,7 +827,12 @@
|
||||
},
|
||||
"zero_rules": [],
|
||||
"limit_description": "실제 판매량으로 검증하기 전이에요",
|
||||
"sentences": {},
|
||||
"sentences": {
|
||||
"0": "비 소식이 없어요. 파전은 비 오는 날을 기다려요!",
|
||||
"30": "하늘이 꾸물꾸물, 막걸리 생각이 살짝 나요.",
|
||||
"60": "비 기운이 있어요. 파전 반죽 준비각!",
|
||||
"80": "비 오고 선선한 저녁, 파전에 막걸리 확정 🍶"
|
||||
},
|
||||
"sort_order": 12
|
||||
},
|
||||
{
|
||||
@@ -734,6 +855,9 @@
|
||||
"weight_wind": 15,
|
||||
"weight_humidity": 10,
|
||||
"weight_air": 5,
|
||||
"weight_uv": 0,
|
||||
"weight_sun": 0,
|
||||
"weight_view": 0,
|
||||
"weight_time": 10,
|
||||
"factor_rules": {
|
||||
"temp": {
|
||||
@@ -757,7 +881,12 @@
|
||||
},
|
||||
"zero_rules": [],
|
||||
"limit_description": "사람마다 달라서 재미로 봐 주세요",
|
||||
"sentences": {},
|
||||
"sentences": {
|
||||
"0": "아침부터 22° 넘어요. 아직은 아아의 계절!",
|
||||
"30": "아침이 살짝 선선해요. 아아 들다 손 시릴 수도?",
|
||||
"60": "아침 공기가 차요. 오늘은 뜨아로 갈아탈 때!",
|
||||
"80": "아침이 한 자릿수, 따뜻한 커피 없인 못 버텨요 ☕"
|
||||
},
|
||||
"sort_order": 13
|
||||
},
|
||||
{
|
||||
@@ -775,11 +904,14 @@
|
||||
"to": 16
|
||||
}
|
||||
],
|
||||
"weight_temp": 20,
|
||||
"weight_rain": 35,
|
||||
"weight_wind": 20,
|
||||
"weight_humidity": 20,
|
||||
"weight_temp": 15,
|
||||
"weight_rain": 30,
|
||||
"weight_wind": 15,
|
||||
"weight_humidity": 10,
|
||||
"weight_air": 0,
|
||||
"weight_uv": 0,
|
||||
"weight_sun": 25,
|
||||
"weight_view": 0,
|
||||
"weight_time": 5,
|
||||
"factor_rules": {
|
||||
"temp": {
|
||||
@@ -799,6 +931,10 @@
|
||||
"time": {
|
||||
"type": "fixed",
|
||||
"value": 100
|
||||
},
|
||||
"sun": {
|
||||
"zero": 0.2,
|
||||
"full": 0.8
|
||||
}
|
||||
},
|
||||
"zero_rules": [
|
||||
@@ -808,8 +944,13 @@
|
||||
"value": 60
|
||||
}
|
||||
],
|
||||
"limit_description": "집 일조량은 반영하지 못해요",
|
||||
"sentences": {},
|
||||
"limit_description": "집 방향·그늘 일조량은 반영하지 못해요",
|
||||
"sentences": {
|
||||
"0": "비 소식이 있어요. 오늘 빨래는 실내 건조로!",
|
||||
"30": "눅눅하거나 쌀쌀해서 잘 안 말라요. 얇은 것만 널어요.",
|
||||
"60": "잘 마르는 편이에요. 두꺼운 건 오후까지 두기!",
|
||||
"80": "따뜻하고 보송한데 바람까지 솔솔, 이불 빨래 가능한 날 ☀️"
|
||||
},
|
||||
"sort_order": 14
|
||||
},
|
||||
{
|
||||
@@ -832,6 +973,9 @@
|
||||
"weight_wind": 30,
|
||||
"weight_humidity": 5,
|
||||
"weight_air": 10,
|
||||
"weight_uv": 0,
|
||||
"weight_sun": 0,
|
||||
"weight_view": 0,
|
||||
"weight_time": 5,
|
||||
"factor_rules": {
|
||||
"temp": {
|
||||
@@ -871,10 +1015,20 @@
|
||||
"field": "wind_ms",
|
||||
"op": ">=",
|
||||
"value": 10
|
||||
},
|
||||
{
|
||||
"field": "gust_ms",
|
||||
"op": ">=",
|
||||
"value": 15
|
||||
}
|
||||
],
|
||||
"limit_description": "자전거 도로 공사는 반영하지 못해요",
|
||||
"sentences": {},
|
||||
"sentences": {
|
||||
"0": "비가 오거나 바람이 10m/s 넘어요. 자전거는 쉬어요!",
|
||||
"30": "맞바람이 세거나 기온이 애매해요. 짧은 코스만!",
|
||||
"60": "탈 만해요! 강변은 바람 좀 부니 바람막이 챙기기.",
|
||||
"80": "15~24°에 바람 잔잔, 멀리 달려도 좋은 날 🚲"
|
||||
},
|
||||
"sort_order": 15
|
||||
},
|
||||
{
|
||||
@@ -896,11 +1050,14 @@
|
||||
"to": 20
|
||||
}
|
||||
],
|
||||
"weight_temp": 40,
|
||||
"weight_temp": 35,
|
||||
"weight_rain": 25,
|
||||
"weight_wind": 10,
|
||||
"weight_humidity": 5,
|
||||
"weight_air": 15,
|
||||
"weight_uv": 5,
|
||||
"weight_sun": 0,
|
||||
"weight_view": 0,
|
||||
"weight_time": 5,
|
||||
"factor_rules": {
|
||||
"temp": {
|
||||
@@ -925,6 +1082,10 @@
|
||||
"time": {
|
||||
"type": "fixed",
|
||||
"value": 100
|
||||
},
|
||||
"uv": {
|
||||
"zero": 8,
|
||||
"full": 2
|
||||
}
|
||||
},
|
||||
"zero_rules": [
|
||||
@@ -937,10 +1098,20 @@
|
||||
"field": "pm25",
|
||||
"op": ">=",
|
||||
"value": 75
|
||||
},
|
||||
{
|
||||
"field": "ground_c",
|
||||
"op": ">=",
|
||||
"value": 45
|
||||
}
|
||||
],
|
||||
"limit_description": "노면 온도는 실측하지 못해요",
|
||||
"sentences": {},
|
||||
"limit_description": "지표면 온도는 예보 모델 값이라 실제 노면 온도와 달라요",
|
||||
"sentences": {
|
||||
"0": "체감 33° 넘거나 초미세먼지가 매우 나빠요. 발바닥도 폐도 위험, 실내 놀이로!",
|
||||
"30": "덥거나 공기가 탁해요. 짧게 볼일만 보고 들어와요.",
|
||||
"60": "산책 괜찮아요! 그늘 많은 길로 가요.",
|
||||
"80": "5~22°에 공기 맑음, 멍멍이 신나는 날 🐶"
|
||||
},
|
||||
"sort_order": 16
|
||||
},
|
||||
{
|
||||
@@ -963,6 +1134,9 @@
|
||||
"weight_wind": 5,
|
||||
"weight_humidity": 30,
|
||||
"weight_air": 0,
|
||||
"weight_uv": 0,
|
||||
"weight_sun": 0,
|
||||
"weight_view": 0,
|
||||
"weight_time": 5,
|
||||
"factor_rules": {
|
||||
"temp": {
|
||||
@@ -986,7 +1160,12 @@
|
||||
},
|
||||
"zero_rules": [],
|
||||
"limit_description": "실내 온도는 반영하지 못해요",
|
||||
"sentences": {},
|
||||
"sentences": {
|
||||
"0": "아침이 15° 넘게 따뜻해요. 안경 김 걱정 없어요!",
|
||||
"30": "실내 들어갈 때 살짝 뿌예질 수 있어요.",
|
||||
"60": "출근길 안경에 김 서려요. 닦을 천 챙기기!",
|
||||
"80": "영하권 아침에 습하기까지, 문 열자마자 앞이 하얘져요 👓"
|
||||
},
|
||||
"sort_order": 17
|
||||
},
|
||||
{
|
||||
@@ -1009,6 +1188,9 @@
|
||||
"weight_wind": 10,
|
||||
"weight_humidity": 35,
|
||||
"weight_air": 0,
|
||||
"weight_uv": 0,
|
||||
"weight_sun": 0,
|
||||
"weight_view": 0,
|
||||
"weight_time": 5,
|
||||
"factor_rules": {
|
||||
"temp": {
|
||||
@@ -1032,7 +1214,12 @@
|
||||
},
|
||||
"zero_rules": [],
|
||||
"limit_description": "피부 타입은 반영하지 못해요",
|
||||
"sentences": {},
|
||||
"sentences": {
|
||||
"0": "선선하고 보송해요. 화장 하루 종일 버텨요!",
|
||||
"30": "오후쯤 살짝 번들거릴 수 있어요.",
|
||||
"60": "덥고 습해서 무너지기 쉬워요. 픽서 챙기기!",
|
||||
"80": "30° 넘는 찜통에 습도까지, 기름종이 필수 🫠"
|
||||
},
|
||||
"sort_order": 18
|
||||
},
|
||||
{
|
||||
@@ -1055,6 +1242,9 @@
|
||||
"weight_wind": 5,
|
||||
"weight_humidity": 15,
|
||||
"weight_air": 5,
|
||||
"weight_uv": 0,
|
||||
"weight_sun": 0,
|
||||
"weight_view": 0,
|
||||
"weight_time": 5,
|
||||
"factor_rules": {
|
||||
"temp": {
|
||||
@@ -1080,7 +1270,12 @@
|
||||
},
|
||||
"zero_rules": [],
|
||||
"limit_description": "실제 주문량으로 검증하기 전이에요",
|
||||
"sentences": {},
|
||||
"sentences": {
|
||||
"0": "점심이 18° 아래로 선선해요. 냉면보다 국밥!",
|
||||
"30": "시원한 게 살짝 당기는 정도예요.",
|
||||
"60": "점심에 덥네요. 냉면 한 그릇 생각나요!",
|
||||
"80": "30° 넘는 한낮, 살얼음 동동 냉면 확정 🥶"
|
||||
},
|
||||
"sort_order": 19
|
||||
},
|
||||
{
|
||||
@@ -1103,6 +1298,9 @@
|
||||
"weight_wind": 10,
|
||||
"weight_humidity": 5,
|
||||
"weight_air": 0,
|
||||
"weight_uv": 0,
|
||||
"weight_sun": 0,
|
||||
"weight_view": 0,
|
||||
"weight_time": 15,
|
||||
"factor_rules": {
|
||||
"temp": {
|
||||
@@ -1128,7 +1326,12 @@
|
||||
},
|
||||
"zero_rules": [],
|
||||
"limit_description": "행사·공연 종료 시간은 반영하지 못해요",
|
||||
"sentences": {},
|
||||
"sentences": {
|
||||
"0": "맑고 포근한 밤, 택시 금방 잡혀요.",
|
||||
"30": "조금 기다릴 수 있어요. 앱 미리 켜두기!",
|
||||
"60": "비나 추위로 택시 잡기 힘들어요. 막차 시간 확인!",
|
||||
"80": "비 오는 추운 밤, 택시 전쟁이에요. 막차 타세요 🚕"
|
||||
},
|
||||
"sort_order": 20
|
||||
},
|
||||
{
|
||||
@@ -1151,6 +1354,9 @@
|
||||
"weight_wind": 10,
|
||||
"weight_humidity": 5,
|
||||
"weight_air": 5,
|
||||
"weight_uv": 0,
|
||||
"weight_sun": 0,
|
||||
"weight_view": 0,
|
||||
"weight_time": 10,
|
||||
"factor_rules": {
|
||||
"temp": {
|
||||
@@ -1177,7 +1383,12 @@
|
||||
},
|
||||
"zero_rules": [],
|
||||
"limit_description": "실제 배달 앱 지표로 검증하기 전이에요",
|
||||
"sentences": {},
|
||||
"sentences": {
|
||||
"0": "날씨 멀쩡해요. 배달 평소처럼 와요.",
|
||||
"30": "살짝 늦을 수 있어요.",
|
||||
"60": "비나 추위로 주문이 몰려요. 일찍 시키기!",
|
||||
"80": "비 오는 추운 저녁, 배달 한참 걸려요. 지금 바로 주문! 🛵"
|
||||
},
|
||||
"sort_order": 21
|
||||
},
|
||||
{
|
||||
@@ -1195,11 +1406,14 @@
|
||||
"to": 10
|
||||
}
|
||||
],
|
||||
"weight_temp": 30,
|
||||
"weight_temp": 25,
|
||||
"weight_rain": 30,
|
||||
"weight_wind": 10,
|
||||
"weight_humidity": 15,
|
||||
"weight_air": 10,
|
||||
"weight_uv": 5,
|
||||
"weight_sun": 0,
|
||||
"weight_view": 0,
|
||||
"weight_time": 5,
|
||||
"factor_rules": {
|
||||
"temp": {
|
||||
@@ -1224,6 +1438,10 @@
|
||||
"time": {
|
||||
"type": "fixed",
|
||||
"value": 100
|
||||
},
|
||||
"uv": {
|
||||
"zero": 8,
|
||||
"full": 2
|
||||
}
|
||||
},
|
||||
"zero_rules": [
|
||||
@@ -1234,7 +1452,12 @@
|
||||
}
|
||||
],
|
||||
"limit_description": "식물 종류는 반영하지 못해요",
|
||||
"sentences": {},
|
||||
"sentences": {
|
||||
"0": "비 소식이 있어요. 물 주기는 하늘에 맡겨요!",
|
||||
"30": "춥거나 더워요. 화분은 안으로, 물은 조금만.",
|
||||
"60": "화분 돌보기 괜찮아요. 아침에 물 듬뿍!",
|
||||
"80": "12~25°의 보송한 아침, 분갈이까지 해도 되는 날 🌱"
|
||||
},
|
||||
"sort_order": 22
|
||||
},
|
||||
{
|
||||
@@ -1252,11 +1475,14 @@
|
||||
"hours": 1
|
||||
}
|
||||
],
|
||||
"weight_temp": 15,
|
||||
"weight_temp": 10,
|
||||
"weight_rain": 25,
|
||||
"weight_wind": 10,
|
||||
"weight_humidity": 5,
|
||||
"weight_air": 15,
|
||||
"weight_air": 10,
|
||||
"weight_uv": 0,
|
||||
"weight_sun": 0,
|
||||
"weight_view": 10,
|
||||
"weight_time": 30,
|
||||
"factor_rules": {
|
||||
"temp": {
|
||||
@@ -1280,6 +1506,10 @@
|
||||
},
|
||||
"time": {
|
||||
"type": "sunset_score"
|
||||
},
|
||||
"view": {
|
||||
"zero": 5,
|
||||
"full": 20
|
||||
}
|
||||
},
|
||||
"zero_rules": [
|
||||
@@ -1290,7 +1520,12 @@
|
||||
}
|
||||
],
|
||||
"limit_description": "장소 혼잡도는 반영하지 못해요",
|
||||
"sentences": {},
|
||||
"sentences": {
|
||||
"0": "비가 와요. 카메라는 쉬어요!",
|
||||
"30": "노을이 약하거나 하늘이 흐려요. 골목 사진 위주로!",
|
||||
"60": "노을이 꽤 기대돼요. 해 지기 30분 전에 나가요.",
|
||||
"80": "노을 점수 높고 공기 맑음, 인생샷 각 📸"
|
||||
},
|
||||
"sort_order": 23
|
||||
},
|
||||
{
|
||||
@@ -1313,6 +1548,9 @@
|
||||
"weight_wind": 10,
|
||||
"weight_humidity": 5,
|
||||
"weight_air": 10,
|
||||
"weight_uv": 0,
|
||||
"weight_sun": 0,
|
||||
"weight_view": 0,
|
||||
"weight_time": 10,
|
||||
"factor_rules": {
|
||||
"temp": {
|
||||
@@ -1348,7 +1586,12 @@
|
||||
}
|
||||
],
|
||||
"limit_description": "경기 일정과 시즌(3~10월)은 반영하지 못해요",
|
||||
"sentences": {},
|
||||
"sentences": {
|
||||
"0": "비 70% 넘어요. 우천 취소 각!",
|
||||
"30": "쌀쌀하거나 비 기운이 있어요. 담요랑 우비 챙겨요.",
|
||||
"60": "직관 괜찮아요! 밤엔 선선하니 겉옷 하나.",
|
||||
"80": "15~25°에 비 걱정 없음, 응원가 목청껏 부르는 날 ⚾"
|
||||
},
|
||||
"sort_order": 24
|
||||
},
|
||||
{
|
||||
@@ -1371,6 +1614,9 @@
|
||||
"weight_wind": 10,
|
||||
"weight_humidity": 5,
|
||||
"weight_air": 5,
|
||||
"weight_uv": 0,
|
||||
"weight_sun": 0,
|
||||
"weight_view": 0,
|
||||
"weight_time": 10,
|
||||
"factor_rules": {
|
||||
"temp": {
|
||||
@@ -1397,7 +1643,12 @@
|
||||
},
|
||||
"zero_rules": [],
|
||||
"limit_description": "사람마다 달라서 재미로 봐 주세요",
|
||||
"sentences": {},
|
||||
"sentences": {
|
||||
"0": "밖이 너무 좋아요. 공부는… 내일의 내가 할게요!",
|
||||
"30": "나가고 싶은 마음 반, 공부 반이에요.",
|
||||
"60": "밖이 애매해서 책상에 앉을 만해요.",
|
||||
"80": "비 오고 춥거나 더워서 나갈 맛이 안 나요. 집중각 📚"
|
||||
},
|
||||
"sort_order": 25
|
||||
},
|
||||
{
|
||||
@@ -1420,6 +1671,9 @@
|
||||
"weight_wind": 15,
|
||||
"weight_humidity": 5,
|
||||
"weight_air": 0,
|
||||
"weight_uv": 0,
|
||||
"weight_sun": 0,
|
||||
"weight_view": 0,
|
||||
"weight_time": 15,
|
||||
"factor_rules": {
|
||||
"temp": {
|
||||
@@ -1445,7 +1699,12 @@
|
||||
},
|
||||
"zero_rules": [],
|
||||
"limit_description": "재미로 보는 지수예요",
|
||||
"sentences": {},
|
||||
"sentences": {
|
||||
"0": "밤 공기가 좋아서 밖이 더 끌려요.",
|
||||
"30": "한 편 정도 볼 만해요.",
|
||||
"60": "비 오거나 쌀쌀한 밤, 이불 속이 최고!",
|
||||
"80": "비 오는 주말 앞 밤, 정주행 시작각 🍿"
|
||||
},
|
||||
"sort_order": 26
|
||||
},
|
||||
{
|
||||
@@ -1468,6 +1727,9 @@
|
||||
"weight_wind": 10,
|
||||
"weight_humidity": 0,
|
||||
"weight_air": 5,
|
||||
"weight_uv": 0,
|
||||
"weight_sun": 0,
|
||||
"weight_view": 0,
|
||||
"weight_time": 5,
|
||||
"factor_rules": {
|
||||
"temp": {
|
||||
@@ -1491,7 +1753,12 @@
|
||||
},
|
||||
"zero_rules": [],
|
||||
"limit_description": "군밤 노점이 있는지는 반영하지 못해요",
|
||||
"sentences": {},
|
||||
"sentences": {
|
||||
"0": "아직 18° 넘어요. 군밤은 조금 더 추워지면!",
|
||||
"30": "저녁이 선선해졌어요. 군밤 노점이 슬슬 생각나요.",
|
||||
"60": "손이 시려요. 따끈한 군밤 한 봉지!",
|
||||
"80": "영하 가까운 저녁, 군밤 품고 걷는 날 🌰"
|
||||
},
|
||||
"sort_order": 27
|
||||
}
|
||||
]
|
||||
@@ -8,7 +8,7 @@ from typing import Optional
|
||||
from common.enums import RainType, Sky
|
||||
from common.utils.text import hour_label
|
||||
|
||||
AXES = ("temp", "rain", "wind", "humidity", "air", "time")
|
||||
AXES = ("temp", "rain", "wind", "humidity", "air", "uv", "sun", "view", "time")
|
||||
_WEEKDAY = ("mon", "tue", "wed", "thu", "fri", "sat", "sun")
|
||||
_WEEKDAY_KO = ("월", "화", "수", "목", "금", "토", "일")
|
||||
_UNKNOWN = 70
|
||||
@@ -25,6 +25,12 @@ class Hour:
|
||||
wind_ms: Optional[float]
|
||||
humidity: int
|
||||
sky: Sky
|
||||
# Open-Meteo 보조값. 3시간 구간에서 가져오며 수집 전이면 None.
|
||||
uv: Optional[float] = None
|
||||
sunshine_ratio: Optional[float] = None # 해 난 비율 0~1
|
||||
visibility_km: Optional[float] = None
|
||||
gust_ms: Optional[float] = None
|
||||
ground_c: Optional[float] = None
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -134,6 +140,24 @@ def air_score(pm25: Optional[int], label: Optional[str]) -> tuple[int, str]:
|
||||
return _linear(pm25, 75, 15), f"초미세먼지 {pm25}㎍/㎥{', ' + label if label else ''}"
|
||||
|
||||
|
||||
def uv_score(rule: dict, uv: Optional[float]) -> tuple[int, str]:
|
||||
if uv is None:
|
||||
return _UNKNOWN, "자외선 정보 없음"
|
||||
return _linear(uv, rule["zero"], rule["full"]), f"자외선 {uv:.1f}"
|
||||
|
||||
|
||||
def sun_score(rule: dict, ratio: Optional[float]) -> tuple[int, str]:
|
||||
if ratio is None:
|
||||
return _UNKNOWN, "햇빛 정보 없음"
|
||||
return _linear(ratio, rule["zero"], rule["full"]), f"해 난 비율 {round(ratio * 100)}%"
|
||||
|
||||
|
||||
def view_score(rule: dict, km: Optional[float]) -> tuple[int, str]:
|
||||
if km is None:
|
||||
return _UNKNOWN, "가시거리 정보 없음"
|
||||
return _linear(km, rule["zero"], rule["full"]), f"가시거리 {km:.1f}km"
|
||||
|
||||
|
||||
def time_score(rule: dict, ctx: Context) -> tuple[int, str]:
|
||||
kind = rule["type"]
|
||||
if kind == "weekday":
|
||||
@@ -153,10 +177,14 @@ _TEMP_LABEL = {"range": "기온 알맞음", "away": "덥거나 추움", "lower":
|
||||
_WIND_LABEL = {"calm": "바람 잔잔", "moderate": "바람 적당", "strong": "바람 셈", "ignore": "바람 무관"}
|
||||
_HUMIDITY_LABEL = {"range": "습도 알맞음", "higher": "습도 높음", "lower": "습도 낮음", "ignore": "습도 무관"}
|
||||
_TIME_LABEL = {"weekday": "요일 알맞음", "moon": "달 어두움", "sunset_score": "노을 예쁨", "fixed": "시간대 알맞음"}
|
||||
# Open-Meteo 보조 축. 비중이 있는 지수에만 나온다.
|
||||
_OM_LABEL = {"uv": "자외선", "sun": "햇빛", "view": "가시거리"}
|
||||
|
||||
|
||||
def axis_label(axis: str, rules: dict) -> str:
|
||||
"""축 값은 '이 각에 좋은 정도'라서, 라벨도 바깥으로 갈수록 좋아지는 쪽으로 읽히게 쓴다."""
|
||||
if axis in _OM_LABEL:
|
||||
return _OM_LABEL[axis]
|
||||
if axis == "rain":
|
||||
return "비 옴" if rules["rain"]["dir"] == "wet" else "비 안 옴"
|
||||
if axis == "air":
|
||||
@@ -180,8 +208,11 @@ def _zero(rules: list[dict], agg: dict) -> tuple[Optional[str], Optional[int]]:
|
||||
return None, None
|
||||
|
||||
|
||||
_FIELD_TEXT = {"rain_prob": "비 확률", "wind_ms": "바람", "feels_c": "체감", "pm25": "초미세먼지", "cloudy_ratio": "흐린 하늘"}
|
||||
_UNIT = {"rain_prob": "%", "wind_ms": "m/s", "feels_c": "°", "pm25": "㎍/㎥", "cloudy_ratio": "%"}
|
||||
_FIELD_TEXT = {
|
||||
"rain_prob": "비 확률", "wind_ms": "바람", "feels_c": "체감", "pm25": "초미세먼지", "cloudy_ratio": "흐린 하늘",
|
||||
"gust_ms": "돌풍", "ground_c": "지표면 온도",
|
||||
}
|
||||
_UNIT = {"rain_prob": "%", "wind_ms": "m/s", "feels_c": "°", "pm25": "㎍/㎥", "cloudy_ratio": "%", "gust_ms": "m/s", "ground_c": "°"}
|
||||
|
||||
|
||||
def _cond(r: dict) -> tuple[str, str, str]:
|
||||
@@ -232,7 +263,7 @@ def _until(definition) -> str:
|
||||
def evaluate(definition, windows: list[list[Hour]], ctx: Context) -> Optional[Result]:
|
||||
"""지수 하나를 하루치로 계산한다. 시간대가 여러 개면 가장 좋은 쪽."""
|
||||
best: Optional[Result] = None
|
||||
weights = {a: getattr(definition, f"weight_{a}") for a in AXES}
|
||||
weights = {a: getattr(definition, f"weight_{a}", 0) for a in AXES}
|
||||
rules = definition.factor_rules
|
||||
until = _until(definition)
|
||||
for hours in windows:
|
||||
@@ -243,12 +274,20 @@ def evaluate(definition, windows: list[list[Hour]], ctx: Context) -> Optional[Re
|
||||
raining = any(h.rain_type is not RainType.NONE for h in hours)
|
||||
winds = [h.wind_ms for h in hours if h.wind_ms is not None]
|
||||
feels = mean(h.feels_c for h in hours)
|
||||
uvs = [h.uv for h in hours if h.uv is not None]
|
||||
suns = [h.sunshine_ratio for h in hours if h.sunshine_ratio is not None]
|
||||
views = [h.visibility_km for h in hours if h.visibility_km is not None]
|
||||
gusts = [h.gust_ms for h in hours if h.gust_ms is not None]
|
||||
grounds = [h.ground_c for h in hours if h.ground_c is not None]
|
||||
scored = {
|
||||
"temp": temp_score(rules["temp"], feels),
|
||||
"rain": rain_score(rules["rain"], max_prob, raining, until if max_prob > own_prob else ""),
|
||||
"wind": wind_score(rules["wind"], max(winds) if winds else None),
|
||||
"humidity": humidity_score(rules["humidity"], mean(h.humidity for h in hours)),
|
||||
"air": air_score(ctx.pm25, ctx.air_label),
|
||||
"uv": uv_score(rules["uv"], max(uvs, default=None)) if weights["uv"] else (0, ""),
|
||||
"sun": sun_score(rules["sun"], mean(suns) if suns else None) if weights["sun"] else (0, ""),
|
||||
"view": view_score(rules["view"], min(views, default=None)) if weights["view"] else (0, ""),
|
||||
"time": time_score(rules["time"], ctx),
|
||||
}
|
||||
factors = {a: v for a, (v, _) in scored.items()}
|
||||
@@ -259,6 +298,7 @@ def evaluate(definition, windows: list[list[Hour]], ctx: Context) -> Optional[Re
|
||||
"feels_c": (min(h.feels_c for h in hours), max(h.feels_c for h in hours)),
|
||||
"cloudy_ratio": round(100 * sum(h.sky is Sky.CLOUDY for h in hours) / len(hours)),
|
||||
"warning": "wind" if ctx.wind_warning else None,
|
||||
"gust_ms": max(gusts, default=None), "ground_c": max(grounds, default=None),
|
||||
}
|
||||
reason, cap = _zero(definition.zero_rules, agg)
|
||||
if reason is not None:
|
||||
@@ -277,11 +317,11 @@ def hour_temp(lo: float, hi: float, hour: int) -> float:
|
||||
|
||||
|
||||
def estimate(definition, fc: DayForecast, windows: list[list[int]], ctx: Context, next_fc: Optional[DayForecast] = None) -> Optional[Result]:
|
||||
"""중기예보로 내는 예상 점수. 기온·비는 정의 규칙 그대로, 바람·습도·미세먼지는 정보 없음으로 둔다. 0점 조건은 비 확률만 본다."""
|
||||
"""중기예보로 내는 예상 점수. 기온·비는 정의 규칙 그대로, 바람·습도·미세먼지·자외선·햇빛·가시거리는 정보 없음으로 둔다. 0점 조건은 비 확률만 본다."""
|
||||
if fc.temp_min_c is None or fc.temp_max_c is None:
|
||||
return None
|
||||
best: Optional[Result] = None
|
||||
weights = {a: getattr(definition, f"weight_{a}") for a in AXES}
|
||||
weights = {a: getattr(definition, f"weight_{a}", 0) for a in AXES}
|
||||
rules = definition.factor_rules
|
||||
until = _until(definition)
|
||||
after = next_fc or fc
|
||||
@@ -301,6 +341,7 @@ def estimate(definition, fc: DayForecast, windows: list[list[int]], ctx: Context
|
||||
"wind": wind_score(rules["wind"], None),
|
||||
"humidity": humidity,
|
||||
"air": air_score(None, None),
|
||||
**{a: (_UNKNOWN, f"{_OM_LABEL[a]} 정보가 없어 {_UNKNOWN}점으로 둬요") if weights[a] else (0, "") for a in _OM_LABEL},
|
||||
"time": time_score(rules["time"], ctx),
|
||||
}
|
||||
factors = {a: v for a, (v, _) in scored.items()}
|
||||
|
||||
@@ -1,11 +1,53 @@
|
||||
import math
|
||||
from datetime import datetime, timezone
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
_SYNODIC_DAYS = 29.530588
|
||||
_KNOWN_NEW_MOON = datetime(2000, 1, 6, 18, 14, tzinfo=timezone.utc)
|
||||
|
||||
|
||||
def illumination(at: datetime) -> float:
|
||||
"""달이 밝게 보이는 비율 0(그믐)~1(보름). 평균 삭망월 근사."""
|
||||
phase = ((at - _KNOWN_NEW_MOON).total_seconds() / 86400 % _SYNODIC_DAYS) / _SYNODIC_DAYS
|
||||
return (1 - math.cos(2 * math.pi * phase)) / 2
|
||||
"""달이 밝게 보이는 비율 0(그믐)~1(보름)."""
|
||||
return (1 - math.cos(2 * math.pi * _fraction(at))) / 2
|
||||
|
||||
|
||||
def _fraction(at: datetime) -> float:
|
||||
"""직전 삭에서 다음 삭까지 얼마나 지났는지 0~1. 앞뒤 삭은 실제 시각(nearest)으로 잡는다."""
|
||||
near = nearest(at, False)
|
||||
prev, nxt = (near, nearest(near + timedelta(days=_SYNODIC_DAYS), False)) if near <= at else (nearest(near - timedelta(days=_SYNODIC_DAYS), False), near)
|
||||
return (at - prev) / (nxt - prev)
|
||||
|
||||
|
||||
# 달 모양 이름. 차오르는 비율(0 삭 → 0.5 보름 → 1 삭) 구간마다
|
||||
_NAMES = ((0.03, "삭"), (0.22, "초승달"), (0.28, "상현달"), (0.47, "차오르는 달"), (0.53, "보름달"), (0.72, "기우는 달"), (0.78, "하현달"), (0.97, "그믐달"), (1.0, "삭"))
|
||||
|
||||
|
||||
def phase_name(at: datetime) -> str:
|
||||
"""그 시각 달 모양 이름 (삭·초승달·상현달·차오르는 달·보름달·기우는 달·하현달·그믐달)."""
|
||||
p = _fraction(at)
|
||||
return next(name for limit, name in _NAMES if p < limit)
|
||||
|
||||
|
||||
def _true_phase(k: float, full: bool) -> datetime:
|
||||
"""Meeus 천문 알고리즘 49장. k 는 2000년 1월 기준 몇 번째 삭(보름이면 +0.5). 오차 몇 분."""
|
||||
t = k / 1236.85
|
||||
jde = 2451550.09766 + 29.530588861 * k + 0.00015437 * t**2 - 0.000000150 * t**3 + 0.00000000073 * t**4
|
||||
e = 1 - 0.002516 * t - 0.0000074 * t**2
|
||||
r = math.radians
|
||||
m = r(2.5534 + 29.10535670 * k - 0.0000014 * t**2 - 0.00000011 * t**3)
|
||||
mp = r(201.5643 + 385.81693528 * k + 0.0107582 * t**2 + 0.00001238 * t**3 - 0.000000058 * t**4)
|
||||
f = r(160.7108 + 390.67050284 * k - 0.0016118 * t**2 - 0.00000227 * t**3 + 0.000000011 * t**4)
|
||||
om = r(124.7746 - 1.56375588 * k + 0.0020672 * t**2 + 0.00000215 * t**3)
|
||||
s = math.sin
|
||||
a, b, c, d = (-0.40614, 0.17302, 0.01614, 0.01043) if full else (-0.40720, 0.17241, 0.01608, 0.01039)
|
||||
jde += (a * s(mp) + b * e * s(m) + c * s(2 * mp) + d * s(2 * f) + (0.00734 if full else 0.00739) * e * s(mp - m)
|
||||
- 0.00515 * e * s(mp + m) + (0.00209 if full else 0.00208) * e * e * s(2 * m) - 0.00111 * s(mp - 2 * f)
|
||||
- 0.00057 * s(mp + 2 * f) + 0.00056 * e * s(2 * mp + m) - 0.00042 * s(3 * mp) + 0.00042 * e * s(m + 2 * f)
|
||||
+ 0.00038 * e * s(m - 2 * f) - 0.00024 * e * s(2 * mp - m) - 0.00017 * s(om))
|
||||
return datetime(2000, 1, 1, 12, tzinfo=timezone.utc) + timedelta(days=jde - 2451545.0)
|
||||
|
||||
|
||||
def nearest(at: datetime, full: bool) -> datetime:
|
||||
"""at 에서 가장 가까운 보름(full) 또는 삭의 실제 시각 (UTC)."""
|
||||
offset = 0.5 if full else 0.0
|
||||
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))
|
||||
@@ -2,9 +2,9 @@ import statistics
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
from common.enums import Confidence, SkyGrade, SkyType
|
||||
from common.enums import Confidence, SkyGrade, SkySituation, SkyType
|
||||
|
||||
DISTANCES_KM = (20, 50, 100)
|
||||
DISTANCES_KM = (20, 100)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -14,11 +14,11 @@ class Layers:
|
||||
high: float
|
||||
|
||||
|
||||
def score(near20: Layers, near50: Layers, far100: Layers) -> int:
|
||||
"""머리 위(20·50km)는 중·상층 구름이 알맞게 있어야 물들고, 먼 쪽(100km)이 막히면 햇빛이 못 들어와 전체가 깎인다."""
|
||||
canvas = (max(near20.mid, near20.high) + max(near50.mid, near50.high)) / 2
|
||||
def score(near20: Layers, far100: Layers) -> int:
|
||||
"""머리 위(20km)는 중·상층 구름이 알맞게 있어야 물들고, 먼 쪽(100km)이 막히면 햇빛이 못 들어와 전체가 깎인다."""
|
||||
canvas = max(near20.mid, near20.high)
|
||||
f_canvas = 0.3 if canvas < 10 else max(0.0, 1 - abs(canvas - 50) / 50)
|
||||
f_near = 1 - 0.8 * (near20.low + near50.low) / 200
|
||||
f_near = 1 - 0.8 * near20.low / 100
|
||||
light = 1 - min(far100.low + 0.5 * far100.mid, 100) / 100
|
||||
return round(100 * (0.75 * f_canvas + 0.25 * f_near) * (0.25 + 0.75 * light))
|
||||
|
||||
@@ -49,10 +49,10 @@ def best_times(kind: SkyType, sun_at: datetime, twilight_at: datetime, high_clou
|
||||
return [
|
||||
{"at": sun_at.isoformat(), "kind": "sun", "label": "해 져요"},
|
||||
{"at": (sun_at + timedelta(minutes=peak_min)).isoformat(), "kind": "peak", "label": "가장 붉을 때"},
|
||||
{"at": twilight_at.isoformat(), "kind": "twilight", "label": "보랏빛 하늘"},
|
||||
{"at": twilight_at.isoformat(), "kind": "twilight", "label": "블루아워"},
|
||||
]
|
||||
return [
|
||||
{"at": twilight_at.isoformat(), "kind": "twilight", "label": "푸른 새벽"},
|
||||
{"at": twilight_at.isoformat(), "kind": "twilight", "label": "블루아워"},
|
||||
{"at": (sun_at - timedelta(minutes=peak_min)).isoformat(), "kind": "peak", "label": "가장 붉을 때"},
|
||||
{"at": sun_at.isoformat(), "kind": "sun", "label": "해 떠요"},
|
||||
]
|
||||
@@ -73,13 +73,40 @@ def mean_layers(rows: list[Layers]) -> Layers:
|
||||
return Layers(*(statistics.mean(getattr(r, k) for r in rows) for k in ("low", "mid", "high")))
|
||||
|
||||
|
||||
def reason(near20: Layers, near50: Layers, far100: Layers) -> str:
|
||||
def situation(near20: Layers, far100: Layers) -> SkySituation:
|
||||
"""하늘 상황 하나. reason() 과 같은 순서로 본다: 먼 쪽이 막혔나 → 머리 위 낮은 구름 → 물들 중·높은 구름의 양."""
|
||||
if far100.low + 0.5 * far100.mid >= 60:
|
||||
return SkySituation.COVERED
|
||||
if near20.low >= 60:
|
||||
return SkySituation.LOW_CLOUD
|
||||
canvas = max(near20.mid, near20.high)
|
||||
if canvas < 25:
|
||||
return SkySituation.FEW
|
||||
if canvas > 75:
|
||||
return SkySituation.THICK
|
||||
return SkySituation.GLOW
|
||||
|
||||
|
||||
SITUATION_LINE = {
|
||||
SkySituation.COVERED: "구름에 가려요",
|
||||
SkySituation.LOW_CLOUD: "낮은 구름이 덮어요",
|
||||
SkySituation.FEW: "구름이 적어 짧게 끝나요",
|
||||
SkySituation.GLOW: "하늘이 넓게 물들 수 있어요",
|
||||
SkySituation.THICK: "구름이 두꺼워 색이 약해요",
|
||||
}
|
||||
SITUATION_VERDICT = {
|
||||
SkySituation.COVERED: "rest", SkySituation.LOW_CLOUD: "rest", SkySituation.FEW: "maybe", SkySituation.GLOW: "go", SkySituation.THICK: "maybe",
|
||||
}
|
||||
VERDICT_RANK = {"rest": 0, "maybe": 1, "go": 2}
|
||||
|
||||
|
||||
def reason(near20: Layers, far100: Layers) -> str:
|
||||
"""score() 가 깎는 순서대로 본다: 먼 쪽 빛이 막혔나 → 머리 위 낮은 구름 → 물들 중·높은 구름의 양."""
|
||||
if far100.low + 0.5 * far100.mid >= 60:
|
||||
return "해 지는 쪽 먼 하늘이 구름에 막혀 빛이 못 들어와요"
|
||||
if (near20.low + near50.low) / 2 >= 60:
|
||||
if near20.low >= 60:
|
||||
return "낮은 구름이 머리 위를 덮어 붉은빛을 가려요"
|
||||
canvas = round((max(near20.mid, near20.high) + max(near50.mid, near50.high)) / 2)
|
||||
canvas = round(max(near20.mid, near20.high))
|
||||
if canvas < 10:
|
||||
return "물들 구름이 거의 없어 하늘이 은은하게 끝나요"
|
||||
if canvas > 85:
|
||||
|
||||
+31
-19
@@ -1,22 +1,28 @@
|
||||
import asyncio
|
||||
import html
|
||||
import xml.etree.ElementTree as ET
|
||||
from datetime import date, datetime, timedelta
|
||||
from typing import Optional
|
||||
|
||||
import httpx
|
||||
|
||||
from common.enums import EVENT_ICON, EventKind
|
||||
from config.settings import settings
|
||||
from services.external.data_go_kr import DataGoKrNotConfigured, DataGoKrRequestFailed
|
||||
from services.external.guard import Unreachable, guarded
|
||||
|
||||
# 한국문화정보원 한눈에보는문화정보조회서비스 (분야별 목록). 응답은 XML.
|
||||
REALM_URL = "https://apis.data.go.kr/B553457/cultureinfo/realm2"
|
||||
EXHIBITION = "D000"
|
||||
CONCERT = "B000" # 음악/콘서트
|
||||
_REALM_KIND = {EXHIBITION: EventKind.EXHIBITION, CONCERT: EventKind.CONCERT}
|
||||
# event.source_id 접두어. TourAPI contentid(숫자)와 겹치지 않게 한다.
|
||||
SOURCE_PREFIX = "kcis:"
|
||||
IMAGE_CREDIT = "ⓒ한국문화정보원"
|
||||
_PAGE_SIZE = 100
|
||||
_ATTEMPTS = 3
|
||||
_BACKOFF_SEC = 1.5
|
||||
_BACKOFF_SEC = 1.0
|
||||
_PAGE_GAP_SEC = 1.0 # 쪽을 쉬지 않고 받으면 초당 요청 제한(코드 23)에 걸린다
|
||||
|
||||
# 법정동 시도 코드 앞 두 자리 → 문화정보 API 의 sido 값
|
||||
SIDO_NAME = {
|
||||
@@ -29,6 +35,10 @@ async def _get_page(client: httpx.AsyncClient, params: dict) -> tuple[list[dict]
|
||||
"""한 쪽을 받아 (item 목록, totalCount). 로그·예외에 키를 남기지 않는다."""
|
||||
if not settings.data_go_kr_service_key:
|
||||
raise DataGoKrNotConfigured("DATA_GO_KR_SERVICE_KEY is empty")
|
||||
return await guarded("datagokr:realm2", lambda: _try_page(client, params), DataGoKrRequestFailed)
|
||||
|
||||
|
||||
async def _try_page(client: httpx.AsyncClient, params: dict) -> tuple[list[dict], int]:
|
||||
last = ""
|
||||
for attempt in range(_ATTEMPTS):
|
||||
try:
|
||||
@@ -36,28 +46,28 @@ async def _get_page(client: httpx.AsyncClient, params: dict) -> tuple[list[dict]
|
||||
root = ET.fromstring(res.content)
|
||||
except (httpx.HTTPError, ET.ParseError) as e:
|
||||
last = type(e).__name__
|
||||
else:
|
||||
reason = root.findtext(".//returnReasonCode")
|
||||
if reason:
|
||||
raise DataGoKrRequestFailed(f"realm2 {reason} {root.findtext('.//errMsg')}")
|
||||
code = root.findtext(".//resultCode")
|
||||
if code not in (None, "00", "0000"):
|
||||
raise DataGoKrRequestFailed(f"realm2 {code} {root.findtext('.//resultMsg')}")
|
||||
if res.status_code == 200:
|
||||
items = [{c.tag: (c.text or "").strip() for c in it} for it in root.iter("item")]
|
||||
return items, int(root.findtext(".//totalCount") or 0)
|
||||
last = f"HTTP {res.status_code}"
|
||||
if attempt < _ATTEMPTS - 1:
|
||||
await asyncio.sleep(_BACKOFF_SEC * (attempt + 1))
|
||||
continue
|
||||
reason = root.findtext(".//returnReasonCode")
|
||||
if reason:
|
||||
raise DataGoKrRequestFailed(f"realm2 {reason} {root.findtext('.//errMsg')}")
|
||||
code = root.findtext(".//resultCode")
|
||||
if code not in (None, "00", "0000"):
|
||||
raise DataGoKrRequestFailed(f"realm2 {code} {root.findtext('.//resultMsg')}")
|
||||
if res.status_code == 200:
|
||||
items = [{c.tag: (c.text or "").strip() for c in it} for it in root.iter("item")]
|
||||
return items, int(root.findtext(".//totalCount") or 0)
|
||||
last = f"HTTP {res.status_code}"
|
||||
await asyncio.sleep(_BACKOFF_SEC * (attempt + 1))
|
||||
raise DataGoKrRequestFailed(f"realm2 failed after {_ATTEMPTS} attempts: {last}")
|
||||
raise Unreachable(f"failed after {_ATTEMPTS} attempts: {last}")
|
||||
|
||||
|
||||
async def fetch_exhibitions(client: httpx.AsyncClient, sido_code: str, since: date, days: int) -> list[dict]:
|
||||
"""시도의 전시(미술관·박물관 등) 중 since~since+days 사이에 열리는 것."""
|
||||
async def fetch_exhibitions(client: httpx.AsyncClient, sido_code: str, since: date, days: int, realm: str = EXHIBITION) -> list[dict]:
|
||||
"""시도의 realm 분야(기본 전시) 중 since~since+days 사이에 열리는 것."""
|
||||
sido = SIDO_NAME.get(sido_code)
|
||||
if sido is None:
|
||||
return []
|
||||
params = {"realmCode": EXHIBITION, "sido": sido, "from": since.strftime("%Y%m%d"), "to": (since + timedelta(days=days)).strftime("%Y%m%d")}
|
||||
params = {"realmCode": realm, "sido": sido, "from": since.strftime("%Y%m%d"), "to": (since + timedelta(days=days)).strftime("%Y%m%d")}
|
||||
items: list[dict] = []
|
||||
page = 1
|
||||
while True:
|
||||
@@ -66,6 +76,7 @@ async def fetch_exhibitions(client: httpx.AsyncClient, sido_code: str, since: da
|
||||
if not chunk or len(items) >= total:
|
||||
return items
|
||||
page += 1
|
||||
await asyncio.sleep(_PAGE_GAP_SEC)
|
||||
|
||||
|
||||
def _date(v: Optional[str]) -> Optional[date]:
|
||||
@@ -83,7 +94,7 @@ def _coord(v: Optional[str]) -> Optional[float]:
|
||||
return None
|
||||
|
||||
|
||||
def parse_exhibitions(items: list[dict], sido_code: str, since: date) -> list[dict]:
|
||||
def parse_exhibitions(items: list[dict], sido_code: str, since: date, realm: str = EXHIBITION) -> list[dict]:
|
||||
rows: dict[str, dict] = {}
|
||||
for it in items:
|
||||
start, end = _date(it.get("startDate")), _date(it.get("endDate"))
|
||||
@@ -94,8 +105,9 @@ def parse_exhibitions(items: list[dict], sido_code: str, since: date) -> list[di
|
||||
lat, lon = (y, x) if x is None or y is None or x > y else (x, y)
|
||||
source_id = f"{SOURCE_PREFIX}{it['seq']}"
|
||||
rows.setdefault(source_id, {
|
||||
"source_id": source_id, "sido_code": sido_code, "name": it.get("title", "")[:60], "place_name": (it.get("place") or "")[:60],
|
||||
"source_id": source_id, "sido_code": sido_code, "name": html.unescape(it.get("title", ""))[:60], "place_name": html.unescape(it.get("place") or "")[:60],
|
||||
"start_date": start, "end_date": end, "is_confirmed": True, "source_url": None,
|
||||
"image_url": (it.get("thumbnail") or "").replace("http://", "https://", 1) or None, "lat": lat, "lon": lon,
|
||||
"kind": _REALM_KIND[realm], "icon": EVENT_ICON[_REALM_KIND[realm]],
|
||||
})
|
||||
return list(rows.values())
|
||||
+11
-5
@@ -3,9 +3,10 @@ import asyncio
|
||||
import httpx
|
||||
|
||||
from config.settings import settings
|
||||
from services.external.guard import Unreachable, guarded
|
||||
|
||||
_ATTEMPTS = 3
|
||||
_BACKOFF_SEC = 1.5
|
||||
_BACKOFF_SEC = 1.0
|
||||
|
||||
|
||||
class DataGoKrNotConfigured(RuntimeError):
|
||||
@@ -17,15 +18,20 @@ class DataGoKrRequestFailed(RuntimeError):
|
||||
|
||||
|
||||
async def get_body(client: httpx.AsyncClient, url: str, params: dict) -> dict:
|
||||
"""data.go.kr 공통 호출. 가끔 오는 504(SERVICETIMEOUT)는 다시 시도한다. 로그·예외에 키를 남기지 않는다."""
|
||||
"""data.go.kr 공통 호출. 가끔 오는 504(SERVICETIMEOUT)는 다시 시도하고, 응답이 없으면 잠시 그 API 를 쉰다. 로그·예외에 키를 남기지 않는다."""
|
||||
if not settings.data_go_kr_service_key:
|
||||
raise DataGoKrNotConfigured("DATA_GO_KR_SERVICE_KEY is empty")
|
||||
op = url.rsplit("/", 1)[-1]
|
||||
return await guarded(f"datagokr:{op}", lambda: _get_body(client, url, op, params), DataGoKrRequestFailed)
|
||||
|
||||
|
||||
async def _get_body(client: httpx.AsyncClient, url: str, op: str, params: dict) -> dict:
|
||||
last = ""
|
||||
for attempt in range(_ATTEMPTS):
|
||||
try:
|
||||
res = await client.get(url, params={"serviceKey": settings.data_go_kr_service_key, **params})
|
||||
data = res.json() if res.status_code == 200 else None
|
||||
last = "" if data else f"HTTP {res.status_code}"
|
||||
except (httpx.HTTPError, ValueError) as e:
|
||||
data, last = None, type(e).__name__
|
||||
if data and "response" in data:
|
||||
@@ -33,9 +39,9 @@ async def get_body(client: httpx.AsyncClient, url: str, params: dict) -> dict:
|
||||
if header.get("resultCode", "00") not in ("00", "0000"):
|
||||
raise DataGoKrRequestFailed(f"{op} {header.get('resultCode')} {header.get('resultMsg')}")
|
||||
return data["response"]["body"]
|
||||
last = last or f"HTTP {res.status_code}"
|
||||
await asyncio.sleep(_BACKOFF_SEC * (attempt + 1))
|
||||
raise DataGoKrRequestFailed(f"{op} failed after {_ATTEMPTS} attempts: {last}")
|
||||
if attempt < _ATTEMPTS - 1:
|
||||
await asyncio.sleep(_BACKOFF_SEC * (attempt + 1))
|
||||
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]:
|
||||
|
||||
Vendored
+46
@@ -0,0 +1,46 @@
|
||||
import asyncio
|
||||
from typing import Awaitable, Callable, Optional, TypeVar
|
||||
|
||||
from redis.exceptions import RedisError
|
||||
|
||||
from common.cache.redis_client import REDIS
|
||||
from common.logger import LOG
|
||||
|
||||
T = TypeVar("T")
|
||||
|
||||
BUDGET_SEC = 8.0 # 재시도까지 합쳐 한 번 호출에 기다리는 최대 시간
|
||||
DOWN_SEC = 120 # 응답이 없던 API 는 이 시간 동안 부르지 않고 바로 실패로 돌린다
|
||||
|
||||
|
||||
class Unreachable(Exception):
|
||||
"""재시도해도 응답을 못 받음 (연결 실패·HTTP 오류). API 가 준 오류 코드와 달리 '잠시 쉬기' 대상이다."""
|
||||
|
||||
|
||||
async def _is_down(name: str) -> bool:
|
||||
try:
|
||||
return bool(await REDIS.conn.exists(f"apidown:{name}"))
|
||||
except RedisError as e:
|
||||
LOG.error(f"[api] {name} down check: {e}")
|
||||
return False
|
||||
|
||||
|
||||
async def _mark_down(name: str, reason: str) -> None:
|
||||
LOG.error(f"[api] {name} 응답 없음, {DOWN_SEC}초 동안 부르지 않음: {reason}")
|
||||
try:
|
||||
await REDIS.conn.set(f"apidown:{name}", reason[:200], ex=DOWN_SEC)
|
||||
except RedisError as e:
|
||||
LOG.error(f"[api] {name} mark down: {e}")
|
||||
|
||||
|
||||
async def guarded(name: str, call: Callable[[], Awaitable[T]], fail: type[Exception], budget_sec: Optional[float] = None) -> T:
|
||||
"""외부 API 호출을 budget_sec 안에 끝내고, 응답이 없던 API 는 DOWN_SEC 동안 기다리지 않고 바로 fail 을 던진다."""
|
||||
if await _is_down(name):
|
||||
raise fail(f"{name} skipped: no answer within the last {DOWN_SEC}s")
|
||||
budget_sec = budget_sec or BUDGET_SEC
|
||||
try:
|
||||
async with asyncio.timeout(budget_sec):
|
||||
return await call()
|
||||
except (TimeoutError, Unreachable) as e:
|
||||
reason = str(e) or f"no answer within {budget_sec:.0f}s"
|
||||
await _mark_down(name, reason)
|
||||
raise fail(f"{name} {reason}") from None
|
||||
+85
-7
@@ -1,13 +1,15 @@
|
||||
import asyncio
|
||||
from datetime import datetime, timezone
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
import httpx
|
||||
|
||||
from common.enums import CloudModel
|
||||
from services.external.guard import Unreachable, guarded
|
||||
|
||||
URL = "https://api.open-meteo.com/v1/forecast"
|
||||
MODELS = {"ecmwf_ifs025": CloudModel.ECMWF, "gfs_seamless": CloudModel.GFS, "jma_seamless": CloudModel.JMA, "icon_seamless": CloudModel.ICON}
|
||||
MODELS = {"jma_seamless": CloudModel.JMA, "icon_seamless": CloudModel.ICON}
|
||||
_ATTEMPTS = 3
|
||||
_BUDGET_SEC = 10.0 # 좌표가 많으면 여러 묶음을 동시에 보내 평소보다 조금 더 걸린다
|
||||
|
||||
|
||||
class OpenMeteoRequestFailed(RuntimeError):
|
||||
@@ -15,13 +17,30 @@ class OpenMeteoRequestFailed(RuntimeError):
|
||||
|
||||
|
||||
_CHUNK = 24
|
||||
WEATHER_VARS = (
|
||||
"uv_index", "uv_index_clear_sky", "visibility", "wind_gusts_10m", "pressure_msl",
|
||||
"sunshine_duration", "shortwave_radiation", "soil_temperature_0cm",
|
||||
)
|
||||
SLOT_HOURS = 3
|
||||
# 해가 없는 밤 구간(21~06시 = 끝 시각 KST 0·3·6시)은 햇빛 값(일조·일사·자외선)을 저장하지 않는다.
|
||||
DARK_SLOT_END_KST = (0, 3, 6)
|
||||
_SUN_FIELDS = ("uv_index", "uv_index_clear_sky", "sunshine_s", "shortwave_avg_wm2", "shortwave_max_wm2")
|
||||
_KST_OFFSET = timedelta(hours=9)
|
||||
|
||||
|
||||
def is_dark_slot(end: datetime) -> bool:
|
||||
return (end.astimezone(timezone.utc) + _KST_OFFSET).hour in DARK_SLOT_END_KST
|
||||
|
||||
|
||||
async def fetch_clouds(client: httpx.AsyncClient, points: list[tuple[float, float]], days: int = 3) -> list[dict]:
|
||||
"""좌표마다 시간별 층별 구름을 모델 4개로. 한 요청에 좌표가 많으면 느려서 나눠 동시에 보낸다. 응답 순서는 좌표 순서와 같다."""
|
||||
"""좌표마다 시간별 층별 구름을 모델별로. 한 요청에 좌표가 많으면 느려서 나눠 동시에 보낸다. 응답 순서는 좌표 순서와 같다."""
|
||||
chunks = [points[i:i + _CHUNK] for i in range(0, len(points), _CHUNK)]
|
||||
results = await asyncio.gather(*[_fetch_chunk(client, c, days) for c in chunks])
|
||||
return [d for r in results for d in r]
|
||||
|
||||
async def all_chunks() -> list[dict]:
|
||||
results = await asyncio.gather(*[_fetch_chunk(client, c, days) for c in chunks])
|
||||
return [d for r in results for d in r]
|
||||
|
||||
return await guarded("openmeteo", all_chunks, OpenMeteoRequestFailed, _BUDGET_SEC)
|
||||
|
||||
|
||||
async def _fetch_chunk(client: httpx.AsyncClient, points: list[tuple[float, float]], days: int) -> list[dict]:
|
||||
@@ -31,6 +50,10 @@ async def _fetch_chunk(client: httpx.AsyncClient, points: list[tuple[float, floa
|
||||
"hourly": "cloud_cover_low,cloud_cover_mid,cloud_cover_high",
|
||||
"models": ",".join(MODELS), "past_days": 1, "forecast_days": days, "timezone": "GMT",
|
||||
}
|
||||
return await _get_forecast(client, params, len(points))
|
||||
|
||||
|
||||
async def _get_forecast(client: httpx.AsyncClient, params: dict, point_count: int) -> list[dict]:
|
||||
for attempt in range(_ATTEMPTS):
|
||||
try:
|
||||
res = await client.get(URL, params=params)
|
||||
@@ -39,8 +62,29 @@ async def _fetch_chunk(client: httpx.AsyncClient, points: list[tuple[float, floa
|
||||
return data if isinstance(data, list) else [data]
|
||||
except (httpx.HTTPError, ValueError) as e:
|
||||
last = f"{type(e).__name__} {getattr(getattr(e, 'response', None), 'status_code', '')}".strip()
|
||||
await asyncio.sleep(1.0 * (attempt + 1))
|
||||
raise OpenMeteoRequestFailed(f"forecast {len(points)} points: {last}")
|
||||
if attempt < _ATTEMPTS - 1:
|
||||
await asyncio.sleep(1.0 * (attempt + 1))
|
||||
raise Unreachable(f"forecast {point_count} points: {last}")
|
||||
|
||||
|
||||
async def fetch_weather(client: httpx.AsyncClient, points: list[tuple[float, float]], days: int = 4) -> list[dict]:
|
||||
"""좌표마다 시간별 자외선·가시거리·돌풍·기압·일조·일사·지면온도 (모델 지정 없음). 응답 순서는 좌표 순서와 같다."""
|
||||
chunks = [points[i:i + _CHUNK] for i in range(0, len(points), _CHUNK)]
|
||||
|
||||
async def all_chunks() -> list[dict]:
|
||||
results = await asyncio.gather(*[_fetch_weather_chunk(client, c, days) for c in chunks])
|
||||
return [d for r in results for d in r]
|
||||
|
||||
return await guarded("openmeteo:weather", all_chunks, OpenMeteoRequestFailed, _BUDGET_SEC)
|
||||
|
||||
|
||||
async def _fetch_weather_chunk(client: httpx.AsyncClient, points: list[tuple[float, float]], days: int) -> list[dict]:
|
||||
params = {
|
||||
"latitude": ",".join(f"{lat:.2f}" for lat, _ in points),
|
||||
"longitude": ",".join(f"{lon:.2f}" for _, lon in points),
|
||||
"hourly": ",".join(WEATHER_VARS), "wind_speed_unit": "ms", "forecast_days": days, "timezone": "GMT",
|
||||
}
|
||||
return await _get_forecast(client, params, len(points))
|
||||
|
||||
|
||||
def parse_clouds(point: tuple[float, float], data: dict) -> list[dict]:
|
||||
@@ -55,3 +99,37 @@ def parse_clouds(point: tuple[float, float], data: dict) -> list[dict]:
|
||||
continue
|
||||
rows.append({"lat": lat, "lon": lon, "forecast_at": at, "model": model.value, "cloud_low": low, "cloud_mid": mid, "cloud_high": high})
|
||||
return rows
|
||||
|
||||
|
||||
def _round(v, digits: int = 0):
|
||||
return None if v is None else (round(v, digits) if digits else int(round(v)))
|
||||
|
||||
|
||||
def parse_weather(data: dict) -> list[dict]:
|
||||
"""시간별 응답을 3시간 구간(끝 시각 GMT 0·3·6…)으로 묶는다. 일조는 합, 일사는 평균·최대, 나머지는 끝 시각 값.
|
||||
직전 3시간이 다 있는 구간만 만든다 (응답 맨 앞처럼 일부만 있는 구간은 건너뜀). 밤 구간은 햇빛 값을 비운다."""
|
||||
h = data["hourly"]
|
||||
times = [datetime.fromisoformat(t).replace(tzinfo=timezone.utc) for t in h["time"]]
|
||||
index = {t: i for i, t in enumerate(times)}
|
||||
rows = []
|
||||
for end, i in index.items():
|
||||
if end.hour % SLOT_HOURS:
|
||||
continue
|
||||
span = [index.get(end - timedelta(hours=k)) for k in range(SLOT_HOURS)]
|
||||
if None in span:
|
||||
continue
|
||||
sun = [h["sunshine_duration"][j] for j in span]
|
||||
rad = [h["shortwave_radiation"][j] for j in span]
|
||||
row = {
|
||||
"forecast_at": end,
|
||||
"uv_index": _round(h["uv_index"][i], 2), "uv_index_clear_sky": _round(h["uv_index_clear_sky"][i], 2),
|
||||
"visibility_m": _round(h["visibility"][i]), "wind_gust_ms": _round(h["wind_gusts_10m"][i], 1),
|
||||
"pressure_hpa": _round(h["pressure_msl"][i], 1), "soil_temp_c": _round(h["soil_temperature_0cm"][i], 1),
|
||||
"sunshine_s": None if None in sun else int(round(sum(sun))),
|
||||
"shortwave_avg_wm2": None if None in rad else int(round(sum(rad) / len(rad))),
|
||||
"shortwave_max_wm2": None if None in rad else int(round(max(rad))),
|
||||
}
|
||||
if is_dark_slot(end):
|
||||
row |= dict.fromkeys(_SUN_FIELDS)
|
||||
rows.append(row)
|
||||
return rows
|
||||
Vendored
+107
@@ -0,0 +1,107 @@
|
||||
import asyncio
|
||||
import html
|
||||
import json
|
||||
import re
|
||||
from datetime import date
|
||||
from typing import Optional
|
||||
|
||||
import httpx
|
||||
|
||||
from common.enums import EVENT_ICON, EventKind
|
||||
|
||||
# 팝가(popga.co.kr) 팝업스토어. 공개 API 가 없어 robots.txt 가 허용하는 사이트맵·상세 페이지를 읽는다.
|
||||
SITEMAP_URL = "https://popga.co.kr/sitemap.xml"
|
||||
POPUP_URL = "https://popga.co.kr/popup/{id}"
|
||||
SOURCE_PREFIX = "popga:"
|
||||
STORE = "STORE" # 팝가 분류: STORE=팝업스토어, PERFORMANCE=공연, FESTIVAL=축제
|
||||
REQUEST_GAP_SEC = 0.3
|
||||
|
||||
_LOC = re.compile(r"<loc>\s*([^<\s]+)\s*</loc>")
|
||||
_URL = re.compile(r"<url>(.*?)</url>", re.S)
|
||||
_LASTMOD = re.compile(r"<lastmod>\s*([^<\s]+)\s*</lastmod>")
|
||||
_POPUP_PATH = re.compile(r"^https://popga\.co\.kr/popup/(\d+)$")
|
||||
_LD_JSON = re.compile(r'<script[^>]*application/ld\+json[^>]*>(.*?)</script>', re.S)
|
||||
|
||||
_SIDO = {
|
||||
"서울": "11", "부산": "26", "대구": "27", "인천": "28", "광주": "29", "대전": "30", "울산": "31", "세종": "36", "경기": "41",
|
||||
"충북": "43", "충남": "44", "전남": "46", "경북": "47", "경남": "48", "제주": "50", "강원": "51", "전북": "52",
|
||||
"충청북도": "43", "충청남도": "44", "전라남도": "46", "경상북도": "47", "경상남도": "48", "전라북도": "52",
|
||||
}
|
||||
|
||||
|
||||
async def fetch_popup_index(client: httpx.AsyncClient) -> dict[int, str]:
|
||||
"""사이트맵 전체에서 팝업 상세 페이지 {id: lastmod}."""
|
||||
res = await client.get(SITEMAP_URL)
|
||||
res.raise_for_status()
|
||||
found: dict[int, str] = {}
|
||||
for sitemap in _LOC.findall(res.text):
|
||||
await asyncio.sleep(REQUEST_GAP_SEC)
|
||||
part = await client.get(sitemap)
|
||||
part.raise_for_status()
|
||||
for block in _URL.findall(part.text):
|
||||
loc, mod = _LOC.search(block), _LASTMOD.search(block)
|
||||
m = _POPUP_PATH.match(loc.group(1)) if loc else None
|
||||
if m:
|
||||
found[int(m.group(1))] = mod.group(1) if mod else ""
|
||||
return found
|
||||
|
||||
|
||||
async def fetch_popup_page(client: httpx.AsyncClient, popup_id: int) -> str:
|
||||
res = await client.get(POPUP_URL.format(id=popup_id))
|
||||
res.raise_for_status()
|
||||
return res.text
|
||||
|
||||
|
||||
def sido_of(address: str) -> Optional[str]:
|
||||
"""주소 첫 낱말("서울", "서울특별시", "경상남도")로 시도 코드."""
|
||||
first = (address or "").split(" ", 1)[0]
|
||||
if first in _SIDO:
|
||||
return _SIDO[first]
|
||||
return next((code for name, code in _SIDO.items() if len(name) == 2 and first.startswith(name)), None)
|
||||
|
||||
|
||||
def _event_ld(page: str) -> Optional[dict]:
|
||||
for block in _LD_JSON.findall(page):
|
||||
try:
|
||||
data = json.loads(block)
|
||||
except json.JSONDecodeError:
|
||||
continue
|
||||
if isinstance(data, dict) and data.get("@type") == "Event":
|
||||
return data
|
||||
return None
|
||||
|
||||
|
||||
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_popup(page: str, popup_id: int, since: date) -> Optional[dict]:
|
||||
"""팝업스토어이고 since 이후에 끝나면 event 행, 아니면 None."""
|
||||
kind = re.search(rf'\\?"id\\?":{popup_id},\\?"type\\?":\\?"([A-Z_]+)', page)
|
||||
ld = _event_ld(page)
|
||||
if kind is None or kind.group(1) != STORE or ld is None:
|
||||
return None
|
||||
start, end = _date(ld.get("startDate")), _date(ld.get("endDate"))
|
||||
if start is None or end is None or end < since:
|
||||
return None
|
||||
loc = ld.get("location") or {}
|
||||
sido = sido_of((loc.get("address") or {}).get("streetAddress", ""))
|
||||
if sido is None:
|
||||
return None
|
||||
geo = loc.get("geo") or {}
|
||||
return {
|
||||
"source_id": f"{SOURCE_PREFIX}{popup_id}", "sido_code": sido, "name": html.unescape(ld.get("name") or "")[:60],
|
||||
"place_name": html.unescape(loc.get("name") or "")[:60], "start_date": start, "end_date": end, "is_confirmed": True,
|
||||
"source_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],
|
||||
}
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
import httpx
|
||||
|
||||
from common.logger import LOG
|
||||
from config.settings import settings
|
||||
|
||||
TIMEOUT_SEC = 10.0
|
||||
|
||||
|
||||
def _card(title: str, detail: str) -> dict:
|
||||
"""Adaptive Card 1.2 — Teams Workflows 수신 webhook 이 받는 최소 모양."""
|
||||
return {
|
||||
"type": "message",
|
||||
"attachments": [{
|
||||
"contentType": "application/vnd.microsoft.card.adaptive",
|
||||
"contentUrl": None,
|
||||
"content": {
|
||||
"$schema": "http://adaptivecards.io/schemas/adaptive-card.json",
|
||||
"type": "AdaptiveCard",
|
||||
"version": "1.2",
|
||||
"body": [
|
||||
{"type": "TextBlock", "text": title, "weight": "Bolder", "wrap": True},
|
||||
{"type": "TextBlock", "text": detail, "wrap": True},
|
||||
],
|
||||
},
|
||||
}],
|
||||
}
|
||||
|
||||
|
||||
async def send(title: str, detail: str) -> bool:
|
||||
"""TEAMS_WEBHOOK_URL 이 있을 때만 보낸다. 로그에 주소를 남기지 않는다."""
|
||||
url = settings.teams_webhook_url.strip()
|
||||
if not url:
|
||||
return False
|
||||
if not url.startswith("https://"):
|
||||
LOG.error("[teams] TEAMS_WEBHOOK_URL 이 https 가 아니다")
|
||||
return False
|
||||
try:
|
||||
async with httpx.AsyncClient(timeout=TIMEOUT_SEC, follow_redirects=False) as client:
|
||||
res = await client.post(url, json=_card(title, detail))
|
||||
res.raise_for_status()
|
||||
return True
|
||||
except httpx.HTTPError as e:
|
||||
LOG.error(f"[teams] send failed: {type(e).__name__}")
|
||||
return False
|
||||
+2
-1
@@ -3,6 +3,7 @@ from typing import Optional
|
||||
|
||||
import httpx
|
||||
|
||||
from common.enums import EVENT_ICON, EventKind
|
||||
from services.external.data_go_kr import get_all_items
|
||||
|
||||
FESTIVAL_URL = "https://apis.data.go.kr/B551011/KorService2/searchFestival2"
|
||||
@@ -36,6 +37,6 @@ def parse_festivals(items: list[dict], sido_code: str) -> list[dict]:
|
||||
"source_id": str(it["contentid"]), "sido_code": sido_code, "name": it.get("title", "")[:60],
|
||||
"place_name": (it.get("addr1") or "")[:60], "start_date": start, "end_date": end, "is_confirmed": True,
|
||||
"source_url": None, "image_url": (it.get("firstimage") or "").replace("http://", "https://", 1) or None,
|
||||
"lat": _coord(it.get("mapy")), "lon": _coord(it.get("mapx")),
|
||||
"lat": _coord(it.get("mapy")), "lon": _coord(it.get("mapx")), "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.database.db_session_manager import DB_SESSION_MNG
|
||||
from common.database.model.models import Article, Post, Region, WeatherHourly
|
||||
from common.enums import AirGrade, ArticleCategory, ErrorType, PostType, RefType, SkyGrade, WarningType
|
||||
from common.enums import AirGrade, ArticleCategory, ErrorType, PostType, RefType, Sky, SkyGrade, SkySituation, WarningType
|
||||
from common.logger import LOG
|
||||
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
|
||||
@@ -25,18 +25,20 @@ from router.v1.feed.protocol import (
|
||||
)
|
||||
from services.air_service import GRADE_LABEL as AIR_GRADE_LABEL
|
||||
from services.air_service import pm10_grade, pm25_grade
|
||||
from services.calc.sky_score import GRADE_LABEL
|
||||
from services.calc.moon import illumination, nearest, phase_name
|
||||
from services.calc.sky_score import GRADE_LABEL, SITUATION_LINE
|
||||
from services.calc.sun import sun_times
|
||||
from services.index_service import IndexBoard, IndexItem, IndexService
|
||||
from services.now_service import NowService, NowWeather
|
||||
from services.season_service import SeasonService
|
||||
from services.sky_service import SkyService, SkyView
|
||||
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.week_service import DayPlan, EventItem, WeekService, image_credit
|
||||
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_rank import TripPick, WeekendRank, pick_trip, weekend_days
|
||||
|
||||
# 그날 피드 카드: (번호, 종류, 참조, 지수 순위). 03:00 에 전부 만들고, 볼 때 시간대에 따라 켜고 끄고 순서를 정한다 (docs/피드기획_v2.html).
|
||||
# 그날 피드 카드: (번호, 종류, 참조, 지수 순위). 03:00 에 전부 만들고, 볼 때 시간대에 따라 켜고 끄고 순서를 정한다 (docs/피드_기획.html).
|
||||
LINEUP = [
|
||||
(1, PostType.WEATHER, RefType.NONE, None),
|
||||
(2, PostType.ALERT, RefType.NONE, None),
|
||||
@@ -56,13 +58,14 @@ LINEUP = [
|
||||
(16, PostType.WEEKEND_PLAN, RefType.NONE, 2),
|
||||
(17, PostType.AIR, RefType.NONE, None),
|
||||
(18, PostType.DAY_TRIP, RefType.NONE, None),
|
||||
(19, PostType.MOON, RefType.NONE, None),
|
||||
]
|
||||
# 시간대별 순서. 목록에 없는 종류는 그 시간대에 꺼진다. '오늘 하루 날씨'는 히어로 바로 아래 고정이라 따로 둔다. 행사는 사이사이 무작위.
|
||||
ORDER = {
|
||||
"morning": [PostType.ALERT, PostType.AIR, PostType.GAK, PostType.GAK, PostType.GAK, PostType.SEASON, PostType.SUNSET, PostType.TIP, PostType.WEEK, PostType.WEEKEND_PLAN, PostType.WEEKEND_PLAN, PostType.DAY_TRIP, PostType.QUOTE],
|
||||
"day": [PostType.GAK, PostType.ALERT, PostType.AIR, PostType.GAK, PostType.GAK, PostType.SUNSET, PostType.WEEK, PostType.WEEKEND_PLAN, PostType.SEASON, PostType.WEEKEND_PLAN, PostType.DAY_TRIP, PostType.TIP, 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.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.QUOTE],
|
||||
"morning": [PostType.ALERT, PostType.AIR, 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.GAK, PostType.GAK, PostType.SUNSET, PostType.WEEK, PostType.WEEKEND_PLAN, PostType.SEASON, PostType.WEEKEND_PLAN, PostType.DAY_TRIP, PostType.TIP, PostType.MOON, PostType.QUOTE],
|
||||
"evening": [PostType.SUNSET, PostType.GAK, PostType.ALERT, PostType.GAK, PostType.GAK, PostType.AIR, PostType.TOMORROW, PostType.WEEK, PostType.WEEKEND_PLAN, PostType.SEASON, PostType.WEEKEND_PLAN, PostType.DAY_TRIP, PostType.TIP, PostType.MOON, PostType.QUOTE],
|
||||
"night": [PostType.TOMORROW, PostType.ALERT, PostType.SUNSET, PostType.WEEK, PostType.GAK, PostType.WEEKEND_PLAN, PostType.GAK, PostType.GAK, PostType.WEEKEND_PLAN, PostType.DAY_TRIP, PostType.AIR, PostType.SEASON, PostType.TIP, PostType.MOON, PostType.QUOTE],
|
||||
}
|
||||
_SKY_MODE = {"morning": "morning", "day": "day", "evening": "sunset", "night": "night"}
|
||||
_CATEGORY_META = {ArticleCategory.SEASON.value: "계절 소식", ArticleCategory.TIP.value: "날씨 상식", ArticleCategory.GAK.value: "각 원리", ArticleCategory.QUOTE.value: "한 문장"}
|
||||
@@ -335,7 +338,7 @@ class FeedService:
|
||||
stories=[_top(i) for i in items], posts=arrange(cards, slot, now, sunset_at, has_warning, f"{day}:{region.code}"),
|
||||
bands=Bands(
|
||||
events=[BandEvent(event_id=e.event.event_id, name=e.event.name, status_label=e.status_label, icon=e.event.icon,
|
||||
image=e.event.image_url, image_credit=image_credit(e.event)) for e in 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]],
|
||||
season=[
|
||||
BandArticle(article_id=a.article_id, title=a.title, meta=f"{_CATEGORY_META[a.category]} · {a.read_minutes}분", icon=a.icon)
|
||||
@@ -373,6 +376,7 @@ class FeedService:
|
||||
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,
|
||||
weather_score=board.weather_score if board else None, top1=_top(top) if top else None, bubble=bubble,
|
||||
moon_name=phase_name(_tonight(now)), moon_pct=round(illumination(_tonight(now)) * 100),
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
@@ -411,12 +415,12 @@ class FeedService:
|
||||
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])
|
||||
if t is PostType.EVENT:
|
||||
soon = [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
|
||||
if len(soon) < rank:
|
||||
return None
|
||||
e = soon[rank - 1]
|
||||
rows = ([Row(label="장소", value=e.event.place_name)] if e.event.place_name else []) + [Row(label="기간", value=day_range(e.event.start_date, e.event.end_date))]
|
||||
rows = ([Row(label="장소", value=e.event.place_name, place=e.event.place_name)] if e.event.place_name else []) + [Row(label="기간", value=day_range(e.event.start_date, e.event.end_date))]
|
||||
caption = _event_caption(e)
|
||||
return PostData(**base, title=e.event.name, icon=e.event.icon, caption=caption,
|
||||
slides=[RowsSlide(kind="rows", eyebrow=f"가까운 행사 · {e.status_label}", line=e.event.name, icon=e.event.icon, rows=rows, image=e.event.image_url, image_credit=image_credit(e.event))],
|
||||
@@ -440,8 +444,46 @@ class FeedService:
|
||||
return self._quote(base, c)
|
||||
if t is PostType.DAY_TRIP and c.trip is not None:
|
||||
return self._day_trip(base, *c.trip)
|
||||
if t is PostType.MOON:
|
||||
return self._moon(base, c)
|
||||
return None
|
||||
|
||||
def _moon(self, base: dict, c: "_Ctx") -> PostData:
|
||||
"""오늘 밤(정오~다음 날 정오)에 보름이나 삭이 있으면 그 이야기를, 아니면 달 모양·밝기와 다음 보름. 피드 아래쪽에 둔다."""
|
||||
tonight = _tonight(c.now)
|
||||
start = tonight.replace(hour=12)
|
||||
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)
|
||||
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
|
||||
rows = [Row(label="밤 하늘", value=_MOON_SKY[sky])] if sky is not None else []
|
||||
eyebrow = f"오늘 밤 달 · {c.region.short_name}"
|
||||
if at is None:
|
||||
name, pct = phase_name(tonight), round(illumination(tonight) * 100)
|
||||
nxt = nearest(tonight + timedelta(days=15), True) if full < tonight else full
|
||||
nxt = nxt.astimezone(KST)
|
||||
waxing = name in ("초승달", "상현달", "차오르는 달")
|
||||
caption = ("구름이 많아 달은 숨바꼭질해요." if sky is Sky.CLOUDY
|
||||
else "하루하루 차오르는 중이에요. 보름까지 같이 세어 봐요 🌙" if waxing else "조금씩 기우는 중이에요. 그만큼 별은 더 잘 보여요 ✨")
|
||||
return PostData(**base, title=f"오늘 밤 {name}", icon="moon", caption=caption,
|
||||
slides=[RowsSlide(kind="rows", eyebrow=eyebrow, line=f"오늘 밤은 {name},\n밝기 {pct}%", icon="moon",
|
||||
rows=[*rows, Row(label="다음 보름", value=f"{nxt.month}.{nxt.day:02d} ({_WEEKDAY_KO[nxt.weekday()]})")])],
|
||||
share_messages=[f"오늘 밤은 {name}이래 🌙"])
|
||||
when = f"{'내일 ' if at.date() > tonight.date() else ''}{at:%H:%M}"
|
||||
if is_full:
|
||||
line = f"오늘 밤 보름달,\n{when}에 가장 둥글어요"
|
||||
caption = "구름 사이로 잠깐씩 보일 수 있어요." if sky is Sky.CLOUDY else "소원 빌기 딱 좋은 밤이에요 🌕"
|
||||
return PostData(**base, title="오늘 밤 보름달", icon="moon", caption=caption,
|
||||
slides=[RowsSlide(kind="rows", eyebrow=eyebrow, line=line, icon="moon", rows=[Row(label="달 밝기", value="100%"), *rows])],
|
||||
share_messages=["오늘 밤 보름달이래 🌕 같이 볼래?"])
|
||||
stars = next((i for i in (c.board.items if c.board else []) if i.definition.code == "stars"), None)
|
||||
if stars is not None:
|
||||
rows.append(Row(label="별보기각", value=f"{stars.score.score}점"))
|
||||
caption = "구름이 많아 별은 아쉬워요." if sky is Sky.CLOUDY else "불빛 적은 곳으로 조금만 나가 봐요 ✨"
|
||||
return PostData(**base, title="오늘 밤 달 없는 밤", icon="moon", caption=caption,
|
||||
slides=[RowsSlide(kind="rows", eyebrow=eyebrow, line="달이 숨는 밤,\n별이 제일 잘 보여요", icon="moon", rows=[Row(label="달 밝기", value="0%"), *rows])],
|
||||
share_messages=["오늘 밤 달이 없어서 별 보기 좋대 ✨"])
|
||||
|
||||
def _day_trip(self, base: dict, pick: TripPick, events: list[EventItem]) -> PostData:
|
||||
"""1~2시간 거리 후보 도시 중 이번 주말 나들이 점수 1위. 첫 장은 도시·날씨, 뒤로 그날 그곳 행사 최대 2장."""
|
||||
b = pick.best
|
||||
@@ -453,7 +495,7 @@ class FeedService:
|
||||
rows.append(Row(label="볼거리", value=pick.note))
|
||||
slides = [RowsSlide(kind="rows", eyebrow=f"당일치기 · {when} {short_day(b.day)}", line=f"{when}엔 {pick.label},\n나들이 {b.score}점", icon=b.icon, rows=rows)]
|
||||
for e in events:
|
||||
ev_rows = ([Row(label="장소", value=e.event.place_name)] if e.event.place_name else []) + [Row(label="기간", value=day_range(e.event.start_date, e.event.end_date))]
|
||||
ev_rows = ([Row(label="장소", value=e.event.place_name, place=e.event.place_name)] if e.event.place_name else []) + [Row(label="기간", value=day_range(e.event.start_date, e.event.end_date))]
|
||||
slides.append(RowsSlide(kind="rows", eyebrow=f"{pick.label} 근처 행사 · {e.status_label}", line=e.event.name, icon=e.event.icon, rows=ev_rows,
|
||||
image=e.event.image_url, image_credit=image_credit(e.event)))
|
||||
if pick.runner_up is not None:
|
||||
@@ -526,30 +568,29 @@ class FeedService:
|
||||
share_messages=[f"{c.region.short_name} 지금 미세먼지 {label} {tail}"])
|
||||
|
||||
def _sunset(self, base: dict, c: "_Ctx") -> Optional[PostData]:
|
||||
"""해 지기 전엔 오늘, 진 뒤엔 내일 노을. 60점 미만이면 한 줄 카드."""
|
||||
"""해 지기 전엔 오늘, 진 뒤엔 내일 노을. 하늘 상황으로 말하고, '쉬어요'면 한 줄 카드."""
|
||||
after = c.now >= c.sunset_at
|
||||
target = next((x for x in c.sky.days if x.score_date > c.now.date()), None) if after else c.sky.sunset
|
||||
if target is None:
|
||||
return None
|
||||
when = "내일" if after else "오늘"
|
||||
grade = GRADE_LABEL[SkyGrade(target.grade)]
|
||||
if target.score < _SUNSET_FULL:
|
||||
nxt = None if after else next((x for x in c.sky.days if x.score_date > c.now.date()), None)
|
||||
caption = "구름에 가려요." + (f" 내일 노을 {nxt.score}점이에요." if nxt is not None else "")
|
||||
return PostData(**base, size="line", title=f"{when} 노을은 쉬어요", icon="sunset", caption=caption, slides=[],
|
||||
share_messages=[f"{when} 노을은 구름에 가려요"])
|
||||
peak = next((b for b in target.best_times if b["kind"] == "peak"), target.best_times[0])
|
||||
peak_at = datetime.fromisoformat(peak["at"]).astimezone(KST)
|
||||
side = compass(c.sky.sunset_azimuth)
|
||||
slides = [SunsetSlide(kind="sunset", eyebrow=f"{when} 노을 · {c.region.name}", line=f"{peak_at:%H:%M}, {side}쪽이 가장 붉어요", score=target.score,
|
||||
grade_label=grade, cuts=[Cut(**b) for b in target.best_times])]
|
||||
sit = SkySituation(target.situation) if target.situation else None
|
||||
line = SITUATION_LINE[sit] if sit else GRADE_LABEL[SkyGrade(target.grade)]
|
||||
better = sky_outlook(target, c.sky.days, c.now.date())
|
||||
sun = next((b for b in target.best_times if b["kind"] == "sun"), target.best_times[0])
|
||||
sun_at = datetime.fromisoformat(sun["at"]).astimezone(KST)
|
||||
if day_verdict(target) == "rest":
|
||||
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"]
|
||||
slides = [SunsetSlide(kind="sunset", eyebrow=f"{when} 노을 · {c.region.name}", line=line, score=target.score,
|
||||
grade_label=line, cuts=cuts, situation=sit)]
|
||||
if c.sky.spots:
|
||||
slides.append(RowsSlide(kind="rows", eyebrow="가까운 노을 명소", line=f"해 지는 {side}쪽이 트인 곳", icon="sunset",
|
||||
rows=[Row(label=f"{n + 1} {x.spot.name}", value=f"{x.distance_km}km") for n, x in enumerate(c.sky.spots)]))
|
||||
nxt = next((x for x in c.sky.days if x.score_date > target.score_date), None)
|
||||
caption = f"{'모레' if after else '내일'} 노을은 {nxt.score}점이에요." if nxt is not None else "가장 붉은 때 앞뒤 20분이 골든타임이에요."
|
||||
return PostData(**base, title=f"{when} 노을 {target.score}점", icon="sunset", caption=caption,
|
||||
slides=slides, share_messages=[f"{when} 노을 {target.score}점이래 🌇 {peak_at:%H:%M}에 같이 볼래?"])
|
||||
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)]))
|
||||
caption = better or "보통 해 진 뒤 10~20분이 가장 붉어요."
|
||||
return PostData(**base, title=f"{when} 노을 · {line}", icon="sunset", caption=caption,
|
||||
slides=slides, share_messages=[f"{when} 노을, {line} 🌇 {sun_at:%H:%M}에 해 져요"])
|
||||
|
||||
def _tomorrow(self, base: dict, c: "_Ctx") -> PostData:
|
||||
tomorrow = c.now.date() + timedelta(days=1)
|
||||
@@ -616,6 +657,14 @@ def _event_caption(e: EventItem) -> str:
|
||||
return "일정이 확정됐어요." if e.event.is_confirmed else "올해 정확한 일정은 공식 안내로 확인해 주세요."
|
||||
|
||||
|
||||
_MOON_SKY = {Sky.CLEAR: "맑음, 잘 보여요", Sky.PARTLY: "구름 조금, 사이사이 보여요", Sky.CLOUDY: "흐림, 가려질 수 있어요"}
|
||||
|
||||
|
||||
def _tonight(now: datetime) -> datetime:
|
||||
"""'오늘 밤' 22시. 피드 하루(03:00 시작)와 맞춰, 자정~03시는 전날 밤으로 본다."""
|
||||
return datetime.combine(feed_day(now.astimezone(KST)), time(22), tzinfo=KST)
|
||||
|
||||
|
||||
@dataclass
|
||||
class _Ctx:
|
||||
region: Region
|
||||
|
||||
@@ -7,7 +7,7 @@ from typing import Optional
|
||||
from fastapi import Depends
|
||||
|
||||
from common.database.db_session_manager import DB_SESSION_MNG
|
||||
from common.database.model.models import IndexDefinition, IndexScore, Region, WeatherDaily, WeatherHourly
|
||||
from common.database.model.models import IndexDefinition, IndexScore, OpenMeteoHourly, Region, WeatherDaily, WeatherHourly
|
||||
from common.enums import AirGrade, ErrorType, RainType, Sky, SkyType, WarningType
|
||||
from common.utils.kma_time import KST, kst_midnight, now_kst
|
||||
from crud.index_crud import IndexCRUD
|
||||
@@ -19,6 +19,7 @@ from services.air_service import GRADE_LABEL, AirService
|
||||
from services.calc.index_calc import AXES, Context, DayForecast, Hour, Result, estimate, evaluate
|
||||
from services.calc.moon import illumination
|
||||
from services.calc.sun import sun_times
|
||||
from services.external.open_meteo import is_dark_slot
|
||||
from services.warning_service import WarningService
|
||||
from services.weather_service import WeatherService
|
||||
|
||||
@@ -89,13 +90,48 @@ def window_hours(defn, day: date, region: Region) -> list[list[int]]:
|
||||
return out
|
||||
|
||||
|
||||
def windows_for(defn, day: date, region: Region, by_at: dict[datetime, WeatherHourly]) -> list[list[Hour]]:
|
||||
"""시간대 정의를 그날의 시간별 날씨 목록으로 바꾼다. 24시 이후는 다음 날로 넘어간다."""
|
||||
def _slot_end_hour(h: int) -> int:
|
||||
"""h시~h+1시를 덮는 3시간 구간의 끝 시각. 일조처럼 '직전 3시간 합'인 값에 쓴다 (7시→9시, 12시→15시)."""
|
||||
return (h + 3) // 3 * 3
|
||||
|
||||
|
||||
def _nearest_slot_end_hour(h: int) -> int:
|
||||
"""h시~h+1시의 한가운데에 가장 가까운 3시간 구간 끝 시각. 자외선·가시거리·돌풍·지표면 온도처럼 '끝 시각 순간값'에 쓴다 (9시→9시, 10시→12시)."""
|
||||
return int((h + 0.5) / 3 + 0.5) * 3
|
||||
|
||||
|
||||
def _om_fields(instant: Optional[OpenMeteoHourly], covering: Optional[OpenMeteoHourly]) -> dict:
|
||||
"""3시간 구간 값을 지수 계산 입력으로 바꾼다. 없으면 빈 값(점수에서 '정보 없음'). 밤 구간은 햇빛 값을 받지 않으므로 0으로 본다."""
|
||||
fields = {}
|
||||
if instant is not None:
|
||||
fields |= {
|
||||
"uv": 0.0 if is_dark_slot(instant.forecast_at) else float(instant.uv_index) if instant.uv_index is not None else None,
|
||||
"visibility_km": instant.visibility_m / 1000 if instant.visibility_m is not None else None,
|
||||
"gust_ms": float(instant.wind_gust_ms) if instant.wind_gust_ms is not None else None,
|
||||
"ground_c": float(instant.soil_temp_c) if instant.soil_temp_c is not None else None,
|
||||
}
|
||||
if covering is not None and is_dark_slot(covering.forecast_at):
|
||||
fields["sunshine_ratio"] = 0.0
|
||||
elif covering is not None and covering.sunshine_s is not None:
|
||||
fields["sunshine_ratio"] = min(covering.sunshine_s / 10800, 1.0)
|
||||
return fields
|
||||
|
||||
|
||||
def windows_for(
|
||||
defn, day: date, region: Region, by_at: dict[datetime, WeatherHourly], by_om: Optional[dict[datetime, OpenMeteoHourly]] = None
|
||||
) -> list[list[Hour]]:
|
||||
"""시간대 정의를 그날의 시간별 날씨 목록으로 바꾼다. 24시 이후는 다음 날로 넘어간다. 시간마다 Open-Meteo 3시간 구간 값을 붙인다 (순간값은 가장 가까운 구간, 일조는 덮는 구간)."""
|
||||
by_om = by_om or {}
|
||||
start = kst_midnight(day)
|
||||
out = []
|
||||
for hours in window_hours(defn, day, region):
|
||||
rows = [by_at.get(start + timedelta(hours=h)) for h in hours]
|
||||
out.append([replace(_hour(r), hour=h) for h, r in zip(hours, rows) if r is not None])
|
||||
out.append([
|
||||
replace(_hour(r), hour=h, **_om_fields(
|
||||
by_om.get(start + timedelta(hours=_nearest_slot_end_hour(h))), by_om.get(start + timedelta(hours=_slot_end_hour(h)))
|
||||
))
|
||||
for h, r in zip(hours, rows) if r is not None
|
||||
])
|
||||
return out
|
||||
|
||||
|
||||
@@ -114,10 +150,11 @@ def _lookahead_days(defn) -> int:
|
||||
|
||||
|
||||
def day_result(
|
||||
defn, day: date, region: Region, by_at: dict[datetime, WeatherHourly], daily: dict[date, DayForecast], ctx: Context, short: bool
|
||||
defn, day: date, region: Region, by_at: dict[datetime, WeatherHourly], daily: dict[date, DayForecast], ctx: Context, short: bool,
|
||||
by_om: Optional[dict[datetime, OpenMeteoHourly]] = None,
|
||||
) -> Optional[Result]:
|
||||
"""short(오늘~모레)이거나 시간대가 시간별 예보로 다 채워지면 그대로 계산, 아니면 중기예보로 예상 점수."""
|
||||
windows = windows_for(defn, day, region, by_at)
|
||||
windows = windows_for(defn, day, region, by_at, by_om)
|
||||
if short or all(len(w) == len(h) for w, h in zip(windows, window_hours(defn, day, region))):
|
||||
return evaluate(defn, windows, replace(ctx, lookahead_rain_prob=lookahead_rain(defn, day, by_at)))
|
||||
fc = daily.get(day)
|
||||
@@ -201,6 +238,10 @@ class IndexService:
|
||||
return ErrorType.EXTERNAL_API_ERROR, None
|
||||
_, daily_rows = await DB_SESSION_MNG.execute_lambda(lambda s: self.week.daily(s, region.code, today, days[-1] + timedelta(days=2)))
|
||||
daily = {d.forecast_date: day_forecast(d) for d in daily_rows or []}
|
||||
om_err, om_rows = await DB_SESSION_MNG.execute_lambda(
|
||||
lambda s: self.weather.openmeteo_between(s, region.code, start, start + timedelta(days=DAYS + 2))
|
||||
)
|
||||
by_om = {r.forecast_at: r for r in om_rows} if om_err is ErrorType.SUCCESS else {}
|
||||
air = await self.air_service.nearest(region)
|
||||
by_at = {r.forecast_at: r for r in rows}
|
||||
base_ctx = dict(
|
||||
@@ -209,10 +250,12 @@ class IndexService:
|
||||
wind_warning=any(w.warning_type is WarningType.WIND for w in warnings or []),
|
||||
)
|
||||
today_ctx = Context(day=today, is_holiday=False, moon=0, sunset_score=None, lookahead_rain_prob=0, **base_ctx)
|
||||
weather_result = evaluate(WEATHER_SCORE_DEF, windows_for(WEATHER_SCORE_DEF, today, region, by_at), today_ctx)
|
||||
weather_result = evaluate(WEATHER_SCORE_DEF, windows_for(WEATHER_SCORE_DEF, today, region, by_at, by_om), today_ctx)
|
||||
|
||||
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
|
||||
if by_om:
|
||||
inputs_at = max(inputs_at, max(r.fetched_at for r in by_om.values()))
|
||||
err, computed = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.last_computed(s, region.code, today))
|
||||
_, scored = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.score_dates(s, region.code, today, days[-1]))
|
||||
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)}
|
||||
@@ -232,7 +275,7 @@ class IndexService:
|
||||
sunset_score=sunset.get(day), lookahead_rain_prob=0, **base_ctx,
|
||||
)
|
||||
for d in defs:
|
||||
result = day_result(d, day, region, by_at, daily, ctx, short=day < today + timedelta(days=DAYS))
|
||||
result = day_result(d, day, region, by_at, daily, ctx, short=day < today + timedelta(days=DAYS), by_om=by_om)
|
||||
if result is None:
|
||||
continue
|
||||
out.append({
|
||||
|
||||
@@ -13,14 +13,15 @@ from common.cache.lock import redis_lock
|
||||
from common.cache.redis_client import REDIS
|
||||
from common.database.db_session_manager import DB_SESSION_MNG
|
||||
from common.database.model.models import Region, SkyScore, SunsetSpot
|
||||
from common.enums import ErrorType, SkyGrade, SkyType
|
||||
from common.enums import ErrorType, SkyGrade, SkySituation, SkyType
|
||||
from common.logger import LOG
|
||||
from common.utils.geo import destination, haversine_km
|
||||
from common.utils.geo import bearing_deg, destination, haversine_km
|
||||
from common.utils.kma_time import KST, now_kst
|
||||
from crud.region_crud import RegionCRUD
|
||||
from crud.sky_crud import SkyCRUD
|
||||
from services.calc.sky_score import (
|
||||
DISTANCES_KM, GRADE_LABEL, VERDICT_LINE, Layers, best_times, confidence, grade, mean_layers, reason, score, sunset_timeline, verdict,
|
||||
DISTANCES_KM, GRADE_LABEL, SITUATION_LINE, SITUATION_VERDICT, VERDICT_LINE, VERDICT_RANK, Layers, best_times, confidence, grade, mean_layers,
|
||||
reason, score, situation, sunset_timeline, verdict,
|
||||
)
|
||||
from services.calc.sun import SunTimes, sun_times
|
||||
from services.external.open_meteo import OpenMeteoRequestFailed, fetch_clouds, parse_clouds
|
||||
@@ -37,6 +38,7 @@ _background: set[asyncio.Task] = set()
|
||||
class Spot:
|
||||
spot: SunsetSpot
|
||||
distance_km: float
|
||||
direction: float = 0.0 # 내 구에서 본 방위각
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -49,6 +51,9 @@ class SkyPlan:
|
||||
reason: str
|
||||
score: int
|
||||
grade_label: str
|
||||
situation_label: Optional[str]
|
||||
models_total: Optional[int]
|
||||
models_agree: Optional[int]
|
||||
best_at: Optional[datetime]
|
||||
spot: Optional[Spot]
|
||||
timeline: list[dict]
|
||||
@@ -75,7 +80,8 @@ class RankItem:
|
||||
|
||||
def nearest_spots(lat: float, lon: float, spots: list[SunsetSpot]) -> list[Spot]:
|
||||
"""반경 안에서 해 지는 쪽이 트인 곳(sort_order 0)을 먼저, 그 안에서는 가까운 순."""
|
||||
near = [Spot(spot=p, distance_km=round(haversine_km(lat, lon, float(p.lat), float(p.lon)), 1)) for p in spots]
|
||||
near = [Spot(spot=p, distance_km=round(haversine_km(lat, lon, float(p.lat), float(p.lon)), 1), direction=bearing_deg(lat, lon, float(p.lat), float(p.lon)))
|
||||
for p in spots]
|
||||
near = [x for x in near if x.distance_km <= SPOT_RADIUS_KM]
|
||||
return sorted(near, key=lambda x: (x.spot.sort_order, x.distance_km))[:SPOT_LIMIT]
|
||||
|
||||
@@ -96,21 +102,23 @@ def _subject(word: str) -> str:
|
||||
return f"{word}{'이' if 0 <= last < 11172 and last % 28 else '가'}"
|
||||
|
||||
|
||||
def day_verdict(x: SkyScore) -> str:
|
||||
"""하늘 상황이 있으면 그걸로, 없으면(예전 계산분) 점수로."""
|
||||
return SITUATION_VERDICT[SkySituation(x.situation)] if x.situation else verdict(x.score)
|
||||
|
||||
|
||||
def outlook(target: SkyScore, days: list[SkyScore], today: date) -> str:
|
||||
"""target 다음 날들 중 가장 나은 날과 비교한다. 10점 넘게 차이 나야 낫다고 말한다."""
|
||||
later = [x for x in days if x.score_date > target.score_date]
|
||||
"""뒤의 날 중 결론이 더 좋은 날이 있을 때만 한 줄. 없으면 빈 문자열."""
|
||||
later = [x for x in days if x.score_date > target.score_date and VERDICT_RANK[day_verdict(x)] > VERDICT_RANK[day_verdict(target)]]
|
||||
if not later:
|
||||
return ""
|
||||
best = max(later, key=lambda x: x.score)
|
||||
if best.score - target.score > _OUTLOOK_GAP:
|
||||
return f"{_subject(_word(best.score_date, today))} 더 나아요 — {best.score}점, {VERDICT_LINE[verdict(best.score)]}"
|
||||
if target.score - best.score > _OUTLOOK_GAP:
|
||||
return f"{_subject(_word(target.score_date, today))} 가장 나아요 — 뒤로 갈수록 못해요"
|
||||
return f"{'·'.join(_word(x.score_date, today) for x in later)}도 비슷해요"
|
||||
best = max(later, key=lambda x: (VERDICT_RANK[day_verdict(x)], x.score))
|
||||
line = SITUATION_LINE[SkySituation(best.situation)] if best.situation else VERDICT_LINE[day_verdict(best)]
|
||||
return f"{_subject(_word(best.score_date, today))} 더 나아요 · {line}"
|
||||
|
||||
|
||||
def build_plan(target: SkyScore, st: SunTimes, layers: Optional[list[Layers]], spots: list[Spot], days: list[SkyScore], today: date) -> SkyPlan:
|
||||
v = verdict(target.score)
|
||||
v = day_verdict(target)
|
||||
when = _word(target.score_date, today)
|
||||
peak = next((b for b in target.best_times if b["kind"] == "peak"), None)
|
||||
peak_at = datetime.fromisoformat(peak["at"]) if peak else None
|
||||
@@ -118,8 +126,10 @@ def build_plan(target: SkyScore, st: SunTimes, layers: Optional[list[Layers]], s
|
||||
day=target.score_date, when=when, verdict=v, headline=VERDICT_LINE[v],
|
||||
reason=reason(*layers) if layers else _FALLBACK_REASON[v],
|
||||
score=target.score, grade_label=GRADE_LABEL[SkyGrade(target.grade)],
|
||||
situation_label=SITUATION_LINE[SkySituation(target.situation)] if target.situation else None,
|
||||
models_total=target.models_total, models_agree=target.models_agree,
|
||||
best_at=peak_at, spot=spots[0] if spots and v != "rest" else None,
|
||||
timeline=sunset_timeline(st.golden_start_at.astimezone(KST), st.sunset_at.astimezone(KST), peak_at, st.dusk_end_at.astimezone(KST)),
|
||||
timeline=sunset_timeline(st.golden_start_at.astimezone(KST), st.sunset_at.astimezone(KST), None, st.dusk_end_at.astimezone(KST)),
|
||||
outlook=outlook(target, days, today),
|
||||
)
|
||||
|
||||
@@ -140,35 +150,47 @@ def _nearest_hour(at: datetime) -> datetime:
|
||||
|
||||
|
||||
def _score_rows(region: Region, today: date, clouds: dict, now: datetime) -> list[dict]:
|
||||
first = sun_times(today, float(region.lat), float(region.lon))
|
||||
rows = []
|
||||
for kind, azimuth in ((SkyType.SUNSET, first.sunset_azimuth), (SkyType.SUNRISE, first.sunrise_azimuth)):
|
||||
pts = _points(region, azimuth)
|
||||
for kind in (SkyType.SUNSET, SkyType.SUNRISE):
|
||||
for i in range(DAYS):
|
||||
d = today + timedelta(days=i)
|
||||
st: SunTimes = sun_times(d, float(region.lat), float(region.lon))
|
||||
sun_at, twilight_at = (st.sunset_at, st.dusk_end_at) if kind is SkyType.SUNSET else (st.sunrise_at, st.dawn_start_at)
|
||||
hour = _nearest_hour(sun_at)
|
||||
per_model = []
|
||||
highs = []
|
||||
for model in {k[2] for k in clouds}:
|
||||
layers = [clouds.get((p[0], p[1], model, hour)) for p in pts]
|
||||
per_model, highs, model_layers = [], [], []
|
||||
for model in {k[4] for k in clouds}:
|
||||
layers = [clouds.get((region.code, kind.value, km, hour, model)) for km in DISTANCES_KM]
|
||||
if None in layers:
|
||||
continue
|
||||
per_model.append(score(*layers))
|
||||
highs.append((layers[0].high + layers[1].high) / 2)
|
||||
highs.append(layers[0].high)
|
||||
model_layers.append(layers)
|
||||
if not per_model:
|
||||
continue
|
||||
value = round(statistics.mean(per_model))
|
||||
sit = situation(*(mean_layers([m[k] for m in model_layers]) for k in range(len(DISTANCES_KM))))
|
||||
rows.append({
|
||||
"region_code": region.code, "score_date": d, "sky_type": kind.value, "score": value, "grade": grade(value).value,
|
||||
"confidence": confidence(per_model).value,
|
||||
"best_times": best_times(kind, sun_at.astimezone(KST), twilight_at.astimezone(KST), statistics.mean(highs)),
|
||||
"computed_at": now,
|
||||
"situation": sit.value, "models_total": len(model_layers), "models_agree": sum(situation(*m) is sit for m in model_layers),
|
||||
})
|
||||
return rows
|
||||
|
||||
|
||||
def ranking_summary(items: list["RankItem"]) -> Optional[str]:
|
||||
"""대표 30곳 대부분(70% 이상)이 같은 상황이면 한 줄로. 점수 차이가 작아 순위만으론 뜻이 없는 날."""
|
||||
sits = [x.score.situation for x in items if x.score.situation]
|
||||
if len(sits) < 5:
|
||||
return None
|
||||
for sit, line in ((SkySituation.FEW, "오늘은 전국이 맑아 대부분 짧게 끝나요"), (SkySituation.COVERED, "오늘은 전국 대부분 구름에 가려요"),
|
||||
(SkySituation.LOW_CLOUD, "오늘은 전국 대부분 낮은 구름이 덮어요")):
|
||||
if sits.count(sit.value) >= 0.7 * len(sits):
|
||||
return line
|
||||
return None
|
||||
|
||||
|
||||
class SkyService:
|
||||
def __init__(self, regions: RegionCRUD = Depends(RegionCRUD), crud: SkyCRUD = Depends(SkyCRUD)) -> None:
|
||||
self.regions = regions
|
||||
@@ -198,7 +220,7 @@ class SkyService:
|
||||
LOG.error(f"[sky] spots {region.code}: {err.name}")
|
||||
near = nearest_spots(lat, lon, spots or [])
|
||||
first = sun_times(now.date(), lat, lon)
|
||||
plan = await self._plan(region, first.sunset_azimuth, sunsets, near, now)
|
||||
plan = await self._plan(region, sunsets, near, now)
|
||||
return ErrorType.SUCCESS, SkyView(
|
||||
region=region,
|
||||
sunset_azimuth=first.sunset_azimuth,
|
||||
@@ -209,7 +231,7 @@ class SkyService:
|
||||
plan=plan,
|
||||
)
|
||||
|
||||
async def _plan(self, region: Region, azimuth: int, sunsets: list[SkyScore], spots: list[Spot], now: datetime) -> Optional[SkyPlan]:
|
||||
async def _plan(self, region: Region, sunsets: list[SkyScore], spots: list[Spot], now: datetime) -> Optional[SkyPlan]:
|
||||
"""블루아워가 끝나기 전엔 오늘, 지나면 내일 노을로 결론을 낸다. 구름 층은 점수 계산 때 받은 값을 다시 읽는다."""
|
||||
lat, lon = float(region.lat), float(region.lon)
|
||||
target, st = None, None
|
||||
@@ -220,15 +242,15 @@ class SkyService:
|
||||
break
|
||||
if target is None or st is None:
|
||||
return None
|
||||
pts = _points(region, azimuth)
|
||||
err, rows = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.clouds_at(s, pts, _nearest_hour(st.sunset_at)))
|
||||
err, rows = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.clouds_at(s, region.code, _nearest_hour(st.sunset_at)))
|
||||
if err is not ErrorType.SUCCESS:
|
||||
LOG.error(f"[sky] plan clouds {region.code}: {err.name}")
|
||||
by_point: dict[tuple[float, float], list[Layers]] = {}
|
||||
by_km: dict[int, list[Layers]] = {}
|
||||
for r in rows or []:
|
||||
by_point.setdefault((float(r.lat), float(r.lon)), []).append(Layers(r.cloud_low, r.cloud_mid, r.cloud_high))
|
||||
layers = [mean_layers(by_point[p]) for p in pts if p in by_point]
|
||||
return build_plan(target, st, layers if len(layers) == len(pts) else None, spots, sunsets, now.date())
|
||||
if r.kind == SkyType.SUNSET.value:
|
||||
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]
|
||||
return build_plan(target, st, layers if len(layers) == len(DISTANCES_KM) else None, spots, sunsets, now.date())
|
||||
|
||||
async def ranking(self) -> tuple[ErrorType, list[RankItem]]:
|
||||
err, regions = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.ranking_regions(s))
|
||||
@@ -276,24 +298,32 @@ class SkyService:
|
||||
plan = {}
|
||||
for r in regions:
|
||||
st = sun_times(today, float(r.lat), float(r.lon))
|
||||
plan[r.code] = _points(r, st.sunset_azimuth) + _points(r, st.sunrise_azimuth)
|
||||
points = sorted({p for pts in plan.values() for p in pts})
|
||||
plan[r.code] = {SkyType.SUNSET: _points(r, st.sunset_azimuth), SkyType.SUNRISE: _points(r, st.sunrise_azimuth)}
|
||||
points = sorted({p for kinds in plan.values() for pts in kinds.values() for p in pts})
|
||||
try:
|
||||
async with httpx.AsyncClient(timeout=30) as client:
|
||||
data = await fetch_clouds(client, points, days=DAYS)
|
||||
except OpenMeteoRequestFailed as e:
|
||||
LOG.error(f"[sky] {len(regions)} regions: {e}")
|
||||
return
|
||||
needed_hours = {
|
||||
_nearest_hour(at)
|
||||
for r in regions
|
||||
for i in range(DAYS)
|
||||
for st in [sun_times(today + timedelta(days=i), float(r.lat), float(r.lon))]
|
||||
for at in (st.sunset_at, st.sunrise_at)
|
||||
}
|
||||
cloud_rows = [row for p, d in zip(points, data) for row in parse_clouds(p, d) if row["forecast_at"] in needed_hours]
|
||||
by_point: dict[tuple[float, float], dict[datetime, list[dict]]] = {}
|
||||
for p, d in zip(points, data):
|
||||
for row in parse_clouds(p, d):
|
||||
by_point.setdefault(p, {}).setdefault(row["forecast_at"], []).append(row)
|
||||
cloud_rows = []
|
||||
for r in regions:
|
||||
for kind, pts in plan[r.code].items():
|
||||
for i in range(DAYS):
|
||||
st = sun_times(today + timedelta(days=i), float(r.lat), float(r.lon))
|
||||
hour = _nearest_hour(st.sunset_at if kind is SkyType.SUNSET else st.sunrise_at)
|
||||
for km, p in zip(DISTANCES_KM, pts):
|
||||
cloud_rows += [
|
||||
{"region_code": r.code, "kind": kind.value, "distance_km": km, "forecast_at": hour, "model": row["model"],
|
||||
"cloud_low": row["cloud_low"], "cloud_mid": row["cloud_mid"], "cloud_high": row["cloud_high"]}
|
||||
for row in by_point.get(p, {}).get(hour, [])
|
||||
]
|
||||
clouds = {
|
||||
(float(r["lat"]), float(r["lon"]), r["model"], r["forecast_at"]): Layers(r["cloud_low"], r["cloud_mid"], r["cloud_high"])
|
||||
(r["region_code"], r["kind"], r["distance_km"], r["forecast_at"], r["model"]): Layers(r["cloud_low"], r["cloud_mid"], r["cloud_high"])
|
||||
for r in cloud_rows
|
||||
}
|
||||
score_rows = [row for r in regions for row in _score_rows(r, today, clouds, now)]
|
||||
|
||||
@@ -11,7 +11,7 @@ from common.cache.lock import redis_lock
|
||||
from common.cache.redis_client import REDIS
|
||||
from common.database.db_session_manager import DB_SESSION_MNG
|
||||
from common.database.model.models import Event, Place, Region, WeatherDaily
|
||||
from common.enums import ErrorType, RainType, Sky
|
||||
from common.enums import ErrorType, EventKind, RainType, Sky
|
||||
from common.logger import LOG
|
||||
from common.utils.geo import haversine_km
|
||||
from common.utils.kma_time import KST, kst_midnight, now_kst
|
||||
@@ -22,7 +22,7 @@ from crud.weather_crud import WeatherCRUD
|
||||
from crud.week_crud import WeekCRUD
|
||||
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 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.kasi import fetch_holidays
|
||||
from services.external.tour_api import IMAGE_CREDIT as TOUR_CREDIT
|
||||
@@ -100,6 +100,21 @@ def image_credit(e: Event) -> Optional[str]:
|
||||
return CULTURE_CREDIT if e.source_id.startswith(CULTURE_PREFIX) else TOUR_CREDIT
|
||||
|
||||
|
||||
_MIX_ORDER = (EventKind.FESTIVAL, EventKind.POPUP, EventKind.EXHIBITION, EventKind.CONCERT)
|
||||
|
||||
|
||||
def mix_kinds(items: list[EventItem]) -> list[EventItem]:
|
||||
"""종류(축제→팝업→전시→콘서트)를 돌아가며 하나씩. 같은 종류 안에서는 받은 순서를 지킨다."""
|
||||
queues = [[e for e in items if e.event.kind == k] for k in _MIX_ORDER]
|
||||
queues.append([e for e in items if e.event.kind not in _MIX_ORDER])
|
||||
mixed = []
|
||||
while any(queues):
|
||||
for q in queues:
|
||||
if q:
|
||||
mixed.append(q.pop(0))
|
||||
return mixed
|
||||
|
||||
|
||||
def nearby_sidos(region: Region, regions: list[Region]) -> list[str]:
|
||||
"""반경 안에 걸칠 수 있는 시도들. 자기 시도는 항상 앞에."""
|
||||
lat, lon = float(region.lat), float(region.lon)
|
||||
@@ -131,6 +146,31 @@ def _status(e: Event, today: date) -> tuple[str, str]:
|
||||
return "soon", f"D-{days}"
|
||||
|
||||
|
||||
async def _culture(client: httpx.AsyncClient, sido: str, today: date, realm: str) -> list[dict]:
|
||||
"""문화정보원 전시·콘서트. 실패해도 TourAPI 행사는 그대로 넣게 여기서 로그만 남긴다."""
|
||||
try:
|
||||
return parse_exhibitions(await fetch_exhibitions(client, sido, today, EVENT_DAYS, realm), sido, today, realm)
|
||||
except (DataGoKrNotConfigured, DataGoKrRequestFailed) as e:
|
||||
LOG.error(f"[week] culture {realm} {sido}: {e}")
|
||||
return []
|
||||
|
||||
|
||||
async def collect_events(sido: str, today: date) -> tuple[ErrorType, dict[str, int]]:
|
||||
"""시도 하나의 축제·전시·콘서트를 받아 event 에 넣는다. 종류별 건수를 돌려준다."""
|
||||
try:
|
||||
async with httpx.AsyncClient(timeout=30) as client:
|
||||
festivals = parse_festivals(await fetch_festivals(client, sido, today), sido)
|
||||
exhibitions = await _culture(client, sido, today, EXHIBITION)
|
||||
concerts = await _culture(client, sido, today, CONCERT)
|
||||
except (DataGoKrNotConfigured, DataGoKrRequestFailed) as e:
|
||||
LOG.error(f"[week] events {sido}: {e}")
|
||||
return ErrorType.EXTERNAL_API_ERROR, {}
|
||||
rows = list({r["source_id"]: r for r in festivals + exhibitions + concerts}.values())
|
||||
err = await DB_SESSION_MNG.execute_lambda_run([lambda s: WeekCRUD().upsert_events(s, rows)])
|
||||
LOG.info(f"[week] events {sido} {len(rows)}: {err.name}")
|
||||
return err, {"festival": len(festivals), "exhibition": len(exhibitions), "concert": len(concerts)}
|
||||
|
||||
|
||||
class WeekService:
|
||||
def __init__(
|
||||
self,
|
||||
@@ -214,8 +254,7 @@ class WeekService:
|
||||
return err, []
|
||||
sidos = nearby_sidos(region, regions)
|
||||
await asyncio.gather(
|
||||
*(self._ensure_events(sido, today) for sido in sidos), self.index_service.weather_service.ensure_vilage(region, now),
|
||||
self.index_service.weather_service.ensure_mid(region, now),
|
||||
self.index_service.weather_service.ensure_vilage(region, now), self.index_service.weather_service.ensure_mid(region, now),
|
||||
)
|
||||
err, events = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.events(s, sidos, today, today + timedelta(days=EVENT_DAYS)))
|
||||
_, daily = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.daily(s, region.code, today, today + timedelta(days=DAYS - 1)))
|
||||
@@ -258,29 +297,3 @@ class WeekService:
|
||||
await REDIS.conn.set(key, "1", ex=30 * 86400)
|
||||
except _ERRORS as e:
|
||||
LOG.error(f"[week] holidays {year}: {e}")
|
||||
|
||||
async def _exhibitions(self, client: httpx.AsyncClient, sido: str, today: date) -> list[dict]:
|
||||
"""문화정보원 전시. 실패해도 TourAPI 행사는 그대로 나가게 여기서 로그만 남긴다."""
|
||||
try:
|
||||
return parse_exhibitions(await fetch_exhibitions(client, sido, today, EVENT_DAYS), sido, today)
|
||||
except (DataGoKrNotConfigured, DataGoKrRequestFailed) as e:
|
||||
LOG.error(f"[week] exhibitions {sido}: {e}")
|
||||
return []
|
||||
|
||||
async def _ensure_events(self, sido: str, today: date) -> None:
|
||||
key = f"event:{sido}:{today:%Y%m%d}"
|
||||
try:
|
||||
if await REDIS.conn.exists(key):
|
||||
return
|
||||
async with redis_lock(f"lock:{key}", ttl_sec=60) as acquired:
|
||||
if not acquired:
|
||||
return
|
||||
async with httpx.AsyncClient(timeout=30) as client:
|
||||
rows = parse_festivals(await fetch_festivals(client, sido, today), sido)
|
||||
rows += await self._exhibitions(client, sido, today)
|
||||
err = await DB_SESSION_MNG.execute_lambda_run([lambda s: self.crud.upsert_events(s, rows)])
|
||||
if err is ErrorType.SUCCESS:
|
||||
await REDIS.conn.set(key, "1", ex=86400)
|
||||
LOG.info(f"[week] events {sido} {len(rows)}: {err.name}")
|
||||
except _ERRORS as e:
|
||||
LOG.error(f"[week] events {sido}: {e}")
|
||||
@@ -2,8 +2,9 @@ import asyncio
|
||||
import os
|
||||
|
||||
# 개발 DB·Redis 를 건드리지 않도록 테스트 전용 DB(<이름>_test)와 Redis 15번을 쓴다. 앱 import 전에 정해야 한다.
|
||||
# 여러 작업 폴더에서 동시에 돌릴 땐 TEST_DB_NAME·TEST_REDIS_DB 를 폴더마다 다르게 준다 (시작할 때 DB 를 지우고 Redis 를 비우므로).
|
||||
os.environ["DB_NAME"] = os.environ.get("TEST_DB_NAME", "nalssigak_test")
|
||||
os.environ["REDIS_DB"] = "15"
|
||||
os.environ["REDIS_DB"] = os.environ.get("TEST_REDIS_DB", "15")
|
||||
|
||||
import asyncpg # noqa: E402
|
||||
import pytest # noqa: E402
|
||||
@@ -41,7 +42,7 @@ def anyio_backend():
|
||||
|
||||
|
||||
_VOLATILE = (
|
||||
"weather_hourly", "weather_daily", "cloud_hourly", "air_station", "air_quality", "weather_warning", "sun_time",
|
||||
"weather_hourly", "weather_daily", "cloud_hourly", "openmeteo_hourly", "air_station", "air_quality", "weather_warning", "sun_time",
|
||||
"sky_score", "index_score", "post", "post_like", "post_save", "comment", "comment_like", "holiday", "solar_term", "users",
|
||||
)
|
||||
|
||||
@@ -67,8 +68,9 @@ async def _async(v):
|
||||
@pytest.fixture
|
||||
def offline(monkeypatch):
|
||||
"""외부 API 를 모두 맑고 잔잔한 가짜 값으로 바꾼다."""
|
||||
from datetime import timedelta
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
import scheduler.jobs as jobs
|
||||
import services.air_service as air_service
|
||||
import services.now_service as now_service
|
||||
import services.season_service as season_service
|
||||
@@ -95,6 +97,17 @@ def offline(monkeypatch):
|
||||
h |= {f"cloud_cover_low_{m}": [0] * len(times), f"cloud_cover_mid_{m}": [20] * len(times), f"cloud_cover_high_{m}": [50] * len(times)}
|
||||
return _async([{"hourly": h} for _ in points])
|
||||
|
||||
def openmeteo_weather(client, points, days=4):
|
||||
start = datetime.now(timezone.utc).replace(hour=0, minute=0, second=0, microsecond=0, tzinfo=None)
|
||||
times = [(start + timedelta(hours=h)).strftime("%Y-%m-%dT%H:00") for h in range(24 * days)]
|
||||
n = len(times)
|
||||
h = {
|
||||
"time": times, "uv_index": [3.0] * n, "uv_index_clear_sky": [3.0] * n, "visibility": [20000.0] * n,
|
||||
"wind_gusts_10m": [4.0] * n, "pressure_msl": [1015.0] * n, "sunshine_duration": [3600.0] * n,
|
||||
"shortwave_radiation": [300.0] * n, "soil_temperature_0cm": [18.0] * n,
|
||||
}
|
||||
return _async([{"hourly": h} for _ in points])
|
||||
|
||||
clear = [("TMP", "20"), ("SKY", "1"), ("PTY", "0"), ("POP", "0"), ("PCP", "강수없음"), ("REH", "50"), ("WSD", "1.5")]
|
||||
monkeypatch.setattr(weather_service, "fetch_vilage", lambda *a: _async(hourly(24 * 4, clear)))
|
||||
monkeypatch.setattr(now_service, "fetch_ultra", lambda *a: _async(hourly(24 * 2, [("PTY", "0"), ("RN1", "강수없음"), ("T1H", "20")])))
|
||||
@@ -105,6 +118,7 @@ def offline(monkeypatch):
|
||||
}]))
|
||||
monkeypatch.setattr(warning_service, "fetch_warning_events", lambda *a: _async([]))
|
||||
monkeypatch.setattr(sky_service, "fetch_clouds", clouds)
|
||||
monkeypatch.setattr(jobs, "fetch_weather", openmeteo_weather)
|
||||
monkeypatch.setattr(weather_service, "fetch_mid", lambda *a: _async(({}, {})))
|
||||
monkeypatch.setattr(week_service, "fetch_holidays", lambda *a: _async([]))
|
||||
monkeypatch.setattr(week_service, "fetch_festivals", lambda c, sido, since: _async([{
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
import asyncio
|
||||
import time
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
|
||||
from config.settings import settings
|
||||
from services.external import data_go_kr, guard, open_meteo
|
||||
from services.external.data_go_kr import DataGoKrRequestFailed, get_body
|
||||
from services.external.open_meteo import OpenMeteoRequestFailed, fetch_clouds
|
||||
|
||||
URL = "https://apis.data.go.kr/1360000/VilageFcstInfoService_2.0/getVilageFcst"
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def fast(monkeypatch):
|
||||
monkeypatch.setattr(settings, "data_go_kr_service_key", "fake-key")
|
||||
monkeypatch.setattr(data_go_kr, "_BACKOFF_SEC", 0)
|
||||
monkeypatch.setattr(guard, "BUDGET_SEC", 0.3)
|
||||
|
||||
|
||||
def _client(handler) -> httpx.AsyncClient:
|
||||
return httpx.AsyncClient(transport=httpx.MockTransport(handler))
|
||||
|
||||
|
||||
def _ok(_req: httpx.Request) -> httpx.Response:
|
||||
return httpx.Response(200, json={"response": {"header": {"resultCode": "00"}, "body": {"items": []}}})
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_hanging_api_gives_up_within_budget_then_is_skipped(fast):
|
||||
calls = []
|
||||
|
||||
async def hang(req: httpx.Request) -> httpx.Response:
|
||||
calls.append(1)
|
||||
await asyncio.sleep(5)
|
||||
return _ok(req)
|
||||
|
||||
async with _client(hang) as client:
|
||||
start = time.perf_counter()
|
||||
with pytest.raises(DataGoKrRequestFailed, match="no answer within"):
|
||||
await get_body(client, URL, {})
|
||||
assert time.perf_counter() - start < 1
|
||||
start = time.perf_counter()
|
||||
with pytest.raises(DataGoKrRequestFailed, match="skipped"):
|
||||
await get_body(client, URL, {})
|
||||
assert time.perf_counter() - start < 0.1
|
||||
assert len(calls) == 1
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_refused_connection_is_skipped_but_other_apis_still_called(fast):
|
||||
def handler(req: httpx.Request) -> httpx.Response:
|
||||
if req.url.path.endswith("getVilageFcst"):
|
||||
raise httpx.ConnectError("refused")
|
||||
return _ok(req)
|
||||
|
||||
async with _client(handler) as client:
|
||||
with pytest.raises(DataGoKrRequestFailed, match="failed after 3 attempts: ConnectError"):
|
||||
await get_body(client, URL, {})
|
||||
with pytest.raises(DataGoKrRequestFailed, match="skipped"):
|
||||
await get_body(client, URL, {})
|
||||
assert await get_body(client, URL.replace("getVilageFcst", "getUltraSrtFcst"), {}) == {"items": []}
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_error_code_from_api_does_not_pause_it(fast):
|
||||
calls = []
|
||||
|
||||
def handler(req: httpx.Request) -> httpx.Response:
|
||||
calls.append(1)
|
||||
return httpx.Response(200, json={"response": {"header": {"resultCode": "03", "resultMsg": "NO_DATA"}}})
|
||||
|
||||
async with _client(handler) as client:
|
||||
for _ in range(2):
|
||||
with pytest.raises(DataGoKrRequestFailed, match="03 NO_DATA"):
|
||||
await get_body(client, URL, {})
|
||||
assert len(calls) == 2
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_open_meteo_down_is_skipped(monkeypatch):
|
||||
monkeypatch.setattr(open_meteo, "_BUDGET_SEC", 0.3)
|
||||
calls = []
|
||||
|
||||
async def hang(req: httpx.Request) -> httpx.Response:
|
||||
calls.append(1)
|
||||
await asyncio.sleep(5)
|
||||
return httpx.Response(200, json=[])
|
||||
|
||||
async with _client(hang) as client:
|
||||
for _ in range(2):
|
||||
with pytest.raises(OpenMeteoRequestFailed):
|
||||
await fetch_clouds(client, [(37.5, 127.0)])
|
||||
assert len(calls) == 1
|
||||
@@ -3,9 +3,10 @@ from datetime import date
|
||||
import httpx
|
||||
import pytest
|
||||
|
||||
from common.enums import EventKind
|
||||
from config.settings import settings
|
||||
from services.external import culture_api
|
||||
from services.external.culture_api import fetch_exhibitions, parse_exhibitions
|
||||
from services.external.culture_api import CONCERT, fetch_exhibitions, parse_exhibitions
|
||||
from services.external.data_go_kr import DataGoKrRequestFailed
|
||||
|
||||
_ITEM = """<item><serviceName>공연/전시</serviceName><seq>{seq}</seq><title>{title}</title><startDate>{start}</startDate><endDate>{end}</endDate>
|
||||
@@ -23,6 +24,7 @@ def key(monkeypatch):
|
||||
monkeypatch.setattr(settings, "data_go_kr_service_key", "fake-key")
|
||||
monkeypatch.setattr(culture_api, "_PAGE_SIZE", 2)
|
||||
monkeypatch.setattr(culture_api, "_BACKOFF_SEC", 0)
|
||||
monkeypatch.setattr(culture_api, "_PAGE_GAP_SEC", 0)
|
||||
|
||||
|
||||
def _client(handler) -> httpx.AsyncClient:
|
||||
@@ -45,6 +47,19 @@ async def test_fetch_exhibitions_pages_through_xml(key):
|
||||
assert seen[0]["realmCode"] == "D000" and seen[0]["sido"] == "서울" and seen[0]["from"] == "20261006" and seen[0]["to"] == "20261105"
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_fetch_exhibitions_asks_concert_realm(key):
|
||||
seen = []
|
||||
|
||||
def handler(req: httpx.Request) -> httpx.Response:
|
||||
seen.append(dict(req.url.params))
|
||||
return httpx.Response(200, text=_page([], 0))
|
||||
|
||||
async with _client(handler) as client:
|
||||
assert await fetch_exhibitions(client, "26", date(2026, 10, 6), 30, CONCERT) == []
|
||||
assert seen[0]["realmCode"] == "B000" and seen[0]["sido"] == "부산"
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_fetch_exhibitions_reports_unregistered_key(key):
|
||||
body = ("<OpenAPI_ServiceResponse><cmmMsgHeader><errMsg>SERVICE_KEY_IS_NOT_REGISTERED_ERROR</errMsg>"
|
||||
@@ -76,4 +91,12 @@ def test_parse_exhibitions_maps_fields_and_drops_ended_or_duplicate():
|
||||
assert rows[0]["image_url"] == "https://www.culture.go.kr/upload/a.jpg"
|
||||
assert rows[0]["lat"] == 37.57592 and rows[0]["lon"] == 126.97689
|
||||
assert rows[0]["sido_code"] == "11" and rows[0]["place_name"] == "테스트 미술관"
|
||||
assert rows[0]["kind"] == EventKind.EXHIBITION
|
||||
assert all(len(r["source_id"]) <= 20 for r in rows)
|
||||
|
||||
|
||||
def test_parse_exhibitions_unescapes_title_and_place():
|
||||
items = [{"seq": "601", "title": "테스트 콘서트 <가을밤>", "place": "테스트 홀 & 라운지", "startDate": "20261010", "endDate": "20261010"}]
|
||||
rows = parse_exhibitions(items, "11", date(2026, 10, 6), CONCERT)
|
||||
assert rows[0]["name"] == "테스트 콘서트 <가을밤>" and rows[0]["place_name"] == "테스트 홀 & 라운지"
|
||||
assert rows[0]["kind"] == EventKind.CONCERT and rows[0]["icon"] == "concert"
|
||||
@@ -0,0 +1,83 @@
|
||||
import httpx
|
||||
import pytest
|
||||
|
||||
import scheduler.jobs as jobs
|
||||
from common.cache.redis_client import REDIS
|
||||
from common.enums import ErrorType
|
||||
from config.settings import settings
|
||||
from services.external import teams_webhook
|
||||
|
||||
|
||||
async def _async(v):
|
||||
return v
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def sent(monkeypatch):
|
||||
calls = []
|
||||
|
||||
async def send(title, detail):
|
||||
calls.append((title, detail))
|
||||
return True
|
||||
|
||||
monkeypatch.setattr(jobs.teams_webhook, "send", send)
|
||||
monkeypatch.setattr(jobs, "_SIDO_GAP_SEC", 0)
|
||||
monkeypatch.setattr(jobs, "refresh_popups", lambda: _async(ErrorType.SUCCESS))
|
||||
return calls
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_refresh_events_sums_kinds_and_notifies(sent, monkeypatch):
|
||||
monkeypatch.setattr(jobs, "collect_events", lambda sido, today: _async((ErrorType.SUCCESS, {"festival": 2, "exhibition": 1, "concert": 3})))
|
||||
assert await jobs.refresh_events() is ErrorType.SUCCESS
|
||||
n = len(jobs.SIDO_NAME)
|
||||
assert sent[0][0] == "행사 수집 완료"
|
||||
assert f"축제 {2 * n}, 전시 {n}, 콘서트 {3 * n}, 팝업 0" in sent[0][1]
|
||||
assert await REDIS.conn.exists(jobs.EVENTS_DONE)
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_refresh_events_reports_failed_sido_and_does_not_mark_done(sent, monkeypatch):
|
||||
monkeypatch.setattr(jobs, "collect_events", lambda sido, today: _async(
|
||||
(ErrorType.EXTERNAL_API_ERROR, {}) if sido == "46" else (ErrorType.SUCCESS, {"festival": 1, "exhibition": 0, "concert": 0})))
|
||||
assert await jobs.refresh_events() is ErrorType.EXTERNAL_API_ERROR
|
||||
assert sent[0][0] == "행사 수집 일부 실패" and "실패한 시도: 전남" in sent[0][1]
|
||||
assert not await REDIS.conn.exists(jobs.EVENTS_DONE)
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_refresh_events_skips_when_done_within_7_days(sent, monkeypatch):
|
||||
await REDIS.conn.set(jobs.EVENTS_DONE, "2026-10-05")
|
||||
monkeypatch.setattr(jobs, "collect_events", lambda *a: pytest.fail("수집하면 안 된다"))
|
||||
assert await jobs.refresh_events(only_if_missing=True) is ErrorType.SUCCESS
|
||||
assert sent == []
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_teams_send_posts_adaptive_card_only_when_configured(monkeypatch):
|
||||
posted = []
|
||||
|
||||
class Client:
|
||||
def __init__(self, **_):
|
||||
pass
|
||||
|
||||
async def __aenter__(self):
|
||||
return self
|
||||
|
||||
async def __aexit__(self, *_):
|
||||
return False
|
||||
|
||||
async def post(self, url, json):
|
||||
posted.append((url, json))
|
||||
return httpx.Response(202, request=httpx.Request("POST", url))
|
||||
|
||||
monkeypatch.setattr(teams_webhook.httpx, "AsyncClient", Client)
|
||||
monkeypatch.setattr(settings, "teams_webhook_url", "")
|
||||
assert await teams_webhook.send("t", "d") is False
|
||||
monkeypatch.setattr(settings, "teams_webhook_url", "http://example.test/hook")
|
||||
assert await teams_webhook.send("t", "d") is False
|
||||
monkeypatch.setattr(settings, "teams_webhook_url", "https://example.test/hook")
|
||||
assert await teams_webhook.send("행사 수집 완료", "축제 1") is True
|
||||
card = posted[0][1]["attachments"][0]["content"]
|
||||
assert [b["text"] for b in card["body"]] == ["행사 수집 완료", "축제 1"]
|
||||
assert len(posted) == 1
|
||||
@@ -6,10 +6,12 @@ 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.season_crud import SeasonCRUD
|
||||
from router.router import app
|
||||
from services.feed_service import build_feed_day
|
||||
from services.week_service import collect_events
|
||||
|
||||
REGION = "1114000000"
|
||||
|
||||
@@ -51,6 +53,7 @@ def test_weekends_groups_this_and_next_weekend():
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_feed_assembles_hero_stories_posts_and_bands(offline):
|
||||
await collect_events("11", now_kst().date())
|
||||
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
|
||||
body = (await client.get("/v1/feed", params={"region": REGION})).json()
|
||||
assert body["result"]["success"] is True
|
||||
@@ -160,6 +163,7 @@ async def test_build_day_makes_every_card_at_three():
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_feed_has_quote_and_no_adjacent_same_type(offline):
|
||||
await collect_events("11", now_kst().date())
|
||||
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
|
||||
body = (await client.get("/v1/feed", params={"region": REGION})).json()
|
||||
articles = (await client.get("/v1/season/article/list")).json()
|
||||
@@ -324,6 +328,7 @@ async def test_feed_has_day_trip_card_with_city_event(offline, monkeypatch):
|
||||
"firstimage": "http://tong.visitkorea.or.kr/c.jpg"}] if sido == "51" else []
|
||||
|
||||
monkeypatch.setattr(week_service, "fetch_festivals", festivals)
|
||||
await week_service.collect_events("51", today)
|
||||
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
|
||||
body = (await client.get("/v1/feed", params={"region": "4113500000"})).json()
|
||||
trip = next(p for p in body["posts"] if p["post_type"] == PostType.DAY_TRIP.value)
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
from datetime import date, timedelta
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
from httpx import ASGITransport, AsyncClient
|
||||
@@ -6,9 +7,12 @@ from httpx import ASGITransport, AsyncClient
|
||||
import services.air_service as air_service
|
||||
import services.warning_service as warning_service
|
||||
import services.weather_service as weather_service
|
||||
from common.database.db_session_manager import DB_SESSION_MNG
|
||||
from common.database.model.models import OpenMeteoHourly, WeatherHourly
|
||||
from common.utils.kma_time import kst_midnight, now_kst
|
||||
from crud.weather_crud import WeatherCRUD
|
||||
from router.router import app
|
||||
from services.index_service import slot_days, slot_label
|
||||
from services.index_service import _nearest_slot_end_hour, _slot_end_hour, slot_days, slot_label, windows_for
|
||||
|
||||
REGION = "1141000000"
|
||||
|
||||
@@ -78,3 +82,111 @@ async def test_index_detail_has_six_factors_and_rules(fakes):
|
||||
assert sum(f["weight"] for f in body["factors"]) == 100
|
||||
assert body["zero_rules"] == "비 확률 80% 이상이거나 바람 14m/s 이상이면 0점"
|
||||
assert body["limit"].startswith("모기")
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_index_detail_has_four_score_bands_with_today_marked(fakes):
|
||||
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
|
||||
body = (await client.get("/v1/index/1", params={"region": REGION})).json()
|
||||
bands = body["bands"]
|
||||
assert [(b["low"], b["high"]) for b in bands] == [(0, 29), (30, 59), (60, 79), (80, 100)]
|
||||
assert all(b["text"] for b in bands)
|
||||
current = [b for b in bands if b["current"]]
|
||||
assert len(current) == 1 and current[0]["low"] <= body["index"]["score"] <= current[0]["high"]
|
||||
|
||||
|
||||
def test_every_index_has_four_band_sentences():
|
||||
import json
|
||||
import os
|
||||
seed = json.load(open(os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "seed", "index_definition.json"), encoding="utf-8"))
|
||||
assert all(sorted(d["sentences"], key=int) == ["0", "30", "60", "80"] and all(d["sentences"].values()) for d in seed)
|
||||
|
||||
|
||||
def _om_row(at, **over):
|
||||
row = {
|
||||
"region_code": REGION, "forecast_at": at, "fetched_at": now_kst(), "uv_index": 2.0, "uv_index_clear_sky": 2.0,
|
||||
"visibility_m": 25000, "wind_gust_ms": 5.0, "pressure_hpa": 1015.0, "soil_temp_c": 20.0,
|
||||
"sunshine_s": 10800, "shortwave_avg_wm2": 500, "shortwave_max_wm2": 600,
|
||||
}
|
||||
return row | over
|
||||
|
||||
|
||||
async def _put_om(rows):
|
||||
await DB_SESSION_MNG.execute_lambda_run([lambda s: WeatherCRUD().upsert_openmeteo(s, rows)])
|
||||
|
||||
|
||||
async def _laundry_sun(client):
|
||||
items = (await client.get("/v1/index/list", params={"region": REGION})).json()["items"]
|
||||
index_id = next(i["index_id"] for i in items if i["code"] == "laundry")
|
||||
body = (await client.get(f"/v1/index/{index_id}", params={"region": REGION})).json()
|
||||
return {f["axis"]: f for f in body["factors"]}
|
||||
|
||||
|
||||
def test_slot_end_hours_for_covering_and_nearest_slot():
|
||||
hours = (0, 2, 3, 7, 8, 9, 10, 11, 12, 15, 21, 23, 26)
|
||||
assert [_slot_end_hour(h) for h in hours] == [3, 3, 6, 9, 9, 12, 12, 12, 15, 18, 24, 24, 27]
|
||||
assert [_nearest_slot_end_hour(h) for h in hours] == [0, 3, 3, 9, 9, 9, 12, 12, 12, 15, 21, 24, 27]
|
||||
|
||||
|
||||
def test_windows_attach_instant_values_from_nearest_slot_and_sunshine_from_covering_slot():
|
||||
day = date(2026, 10, 6)
|
||||
start = kst_midnight(day)
|
||||
by_at = {
|
||||
start + timedelta(hours=h): WeatherHourly(
|
||||
forecast_at=start + timedelta(hours=h), feels_c=20, rain_type=1, rain_prob=0, wind_ms=1.0, humidity=50, sky=1
|
||||
)
|
||||
for h in range(7, 16)
|
||||
}
|
||||
by_om = {
|
||||
start + timedelta(hours=end): OpenMeteoHourly(
|
||||
forecast_at=start + timedelta(hours=end), uv_index=uv, sunshine_s=sun, visibility_m=12000, wind_gust_ms=7.5, soil_temp_c=20.0
|
||||
)
|
||||
for end, uv, sun in ((9, 1.0, 1800), (12, 2.0, 5400), (15, 3.0, 9000), (18, 4.0, 10800))
|
||||
}
|
||||
morning, noon = windows_for(SimpleNamespace(windows=[{"from": 7, "to": 9}, {"from": 11, "to": 16}]), day, None, by_at, by_om)
|
||||
assert [h.uv for h in morning] == [1.0, 1.0]
|
||||
assert [h.uv for h in noon] == [2.0, 2.0, 3.0, 3.0, 3.0] # 순간값은 가장 가까운 구간 (11·12시→12시, 13~15시→15시)
|
||||
assert [h.sunshine_ratio for h in noon] == [0.5, 9000 / 10800, 9000 / 10800, 9000 / 10800, 1.0] # 일조는 덮는 구간 (직전 3시간 합)
|
||||
assert morning[0].visibility_km == 12.0 and morning[0].gust_ms == 7.5 and morning[0].ground_c == 20.0
|
||||
no_om = windows_for(SimpleNamespace(windows=[{"from": 7, "to": 9}]), day, None, by_at, None)[0]
|
||||
assert all(h.uv is None and h.sunshine_ratio is None for h in no_om)
|
||||
|
||||
|
||||
def test_dark_slots_count_as_no_sun_not_unknown():
|
||||
day = date(2026, 10, 6)
|
||||
start = kst_midnight(day)
|
||||
by_at = {
|
||||
start + timedelta(hours=h): WeatherHourly(
|
||||
forecast_at=start + timedelta(hours=h), feels_c=20, rain_type=1, rain_prob=0, wind_ms=1.0, humidity=50, sky=1
|
||||
)
|
||||
for h in (22, 23)
|
||||
}
|
||||
by_om = {start + timedelta(hours=24): OpenMeteoHourly(forecast_at=start + timedelta(hours=24), uv_index=None, sunshine_s=None, visibility_m=20000)}
|
||||
hours = windows_for(SimpleNamespace(windows=[{"from": 22, "to": 24}]), day, None, by_at, by_om)[0]
|
||||
assert [(h.uv, h.sunshine_ratio, h.visibility_km) for h in hours] == [(0.0, 0.0, 20.0)] * 2
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_new_axis_shows_only_for_weighted_indices_and_unknown_without_data(fakes):
|
||||
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
|
||||
laundry = await _laundry_sun(client)
|
||||
yajang = (await client.get("/v1/index/1", params={"region": REGION})).json()["factors"]
|
||||
assert laundry["sun"]["weight"] == 25 and laundry["sun"]["value"] == 70 and laundry["sun"]["note"] == "햇빛 정보 없음"
|
||||
assert sum(f["weight"] for f in laundry.values()) == 100
|
||||
assert [f["axis"] for f in yajang] == ["temp", "rain", "wind", "humidity", "air", "time"]
|
||||
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
|
||||
items = (await client.get("/v1/index/list", params={"region": REGION})).json()["items"]
|
||||
stars_id = next(i["index_id"] for i in items if i["code"] == "stars")
|
||||
stars = (await client.get(f"/v1/index/{stars_id}", params={"region": REGION})).json()["factors"]
|
||||
assert {f["axis"]: f["label"] for f in stars}["view"] == "가시거리"
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_openmeteo_data_changes_index_and_triggers_recompute(fakes):
|
||||
today = kst_midnight(now_kst().date())
|
||||
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
|
||||
before = await _laundry_sun(client)
|
||||
assert before["sun"]["value"] == 70
|
||||
await _put_om([_om_row(today + timedelta(hours=h), fetched_at=now_kst() + timedelta(hours=1)) for h in (12, 15, 18)])
|
||||
after = await _laundry_sun(client)
|
||||
assert after["sun"]["value"] == 100 and after["sun"]["note"] == "해 난 비율 100%"
|
||||
@@ -4,8 +4,8 @@ from types import SimpleNamespace
|
||||
|
||||
from common.enums import RainType, Sky
|
||||
from services.calc.index_calc import (
|
||||
OUTING_HOURS, Context, DayForecast, Hour, axis_label, estimate, evaluate, hour_temp, outing, outing_estimate, rain_score, temp_score,
|
||||
zero_rules_text,
|
||||
OUTING_HOURS, Context, DayForecast, Hour, axis_label, estimate, evaluate, hour_temp, outing, outing_estimate, rain_score, sun_score, temp_score,
|
||||
uv_score, view_score, zero_rules_text,
|
||||
)
|
||||
from services.calc.moon import illumination
|
||||
|
||||
@@ -24,8 +24,8 @@ def _defn(**kw):
|
||||
return SimpleNamespace(**{**base, **kw})
|
||||
|
||||
|
||||
def _h(hour, feels=21.0, prob=0, rain=RainType.NONE, wind=1.5, hum=50, sky=Sky.CLEAR):
|
||||
return Hour(hour=hour, feels_c=feels, rain_type=rain, rain_prob=prob, wind_ms=wind, humidity=hum, sky=sky)
|
||||
def _h(hour, feels=21.0, prob=0, rain=RainType.NONE, wind=1.5, hum=50, sky=Sky.CLEAR, **extra):
|
||||
return Hour(hour=hour, feels_c=feels, rain_type=rain, rain_prob=prob, wind_ms=wind, humidity=hum, sky=sky, **extra)
|
||||
|
||||
|
||||
def test_perfect_evening_scores_100():
|
||||
@@ -111,6 +111,52 @@ def test_moon_full_and_new():
|
||||
assert illumination(datetime(2000, 1, 21, 12, tzinfo=timezone.utc)) > 0.95
|
||||
|
||||
|
||||
def test_uv_sun_view_scores_are_linear_and_unknown_is_70():
|
||||
assert uv_score({"zero": 8, "full": 2}, 1)[0] == 100 and uv_score({"zero": 8, "full": 2}, 5)[0] == 50 and uv_score({"zero": 8, "full": 2}, 9)[0] == 0
|
||||
assert sun_score({"zero": 0.2, "full": 0.8}, 0.5)[0] == 50 and sun_score({"zero": 0.2, "full": 0.8}, 1.0)[0] == 100
|
||||
assert view_score({"zero": 5, "full": 20}, 12.5)[0] == 50 and view_score({"zero": 5, "full": 20}, 3)[0] == 0
|
||||
assert (uv_score({"zero": 8, "full": 2}, None)[0], sun_score({"zero": 0.2, "full": 0.8}, None)[0], view_score({"zero": 5, "full": 20}, None)[0]) == (70, 70, 70)
|
||||
assert uv_score({"zero": 8, "full": 2}, 5)[1] == "자외선 5.0"
|
||||
assert view_score({"zero": 5, "full": 20}, 12.5)[1] == "가시거리 12.5km" and view_score({"zero": 5, "full": 20}, None)[1] == "가시거리 정보 없음"
|
||||
|
||||
|
||||
def _uv_defn():
|
||||
rules = _defn().factor_rules | {"uv": {"zero": 8, "full": 2}}
|
||||
return _defn(weight_temp=25, weight_humidity=5, weight_uv=10, factor_rules=rules)
|
||||
|
||||
|
||||
def test_weighted_uv_axis_lowers_score_when_uv_is_high_and_is_unknown_when_missing():
|
||||
low = evaluate(_uv_defn(), [[_h(19, wind=1.0, uv=1.0)]], CTX)
|
||||
high = evaluate(_uv_defn(), [[_h(19, wind=1.0, uv=9.0)]], CTX)
|
||||
missing = evaluate(_uv_defn(), [[_h(19, wind=1.0)]], CTX)
|
||||
assert low.score == 100 and low.factors["uv"] == 100
|
||||
assert high.factors["uv"] == 0 and high.score < 80
|
||||
assert missing.factors["uv"] == 70 and missing.notes["uv"] == "자외선 정보 없음"
|
||||
|
||||
|
||||
def test_unweighted_new_axes_do_not_affect_score_and_use_max_uv_in_window():
|
||||
plain = evaluate(_defn(), [[_h(19, wind=1.0, uv=9.0)]], CTX)
|
||||
assert plain.score == 100 and plain.factors["uv"] == 0
|
||||
window = evaluate(_uv_defn(), [[_h(19, wind=1.0, uv=1.0), _h(20, wind=1.0, uv=9.0)]], CTX)
|
||||
assert window.factors["uv"] == 0
|
||||
|
||||
|
||||
def test_gust_and_ground_temperature_zero_rules():
|
||||
gust = _defn(zero_rules=[{"field": "gust_ms", "op": ">=", "value": 15}])
|
||||
assert evaluate(gust, [[_h(19, wind=1.0, gust_ms=16.0)]], CTX).score == 0
|
||||
assert evaluate(gust, [[_h(19, wind=1.0, gust_ms=10.0)]], CTX).score == 100
|
||||
assert evaluate(gust, [[_h(19, wind=1.0)]], CTX).score == 100 # 값이 없으면 걸리지 않는다
|
||||
ground = [{"field": "ground_c", "op": ">=", "value": 45}]
|
||||
assert zero_rules_text(ground) == "지표면 온도 45° 이상이면 0점"
|
||||
assert evaluate(_defn(zero_rules=ground), [[_h(19, wind=1.0, ground_c=47.0)]], CTX).zero_reason == "지표면 온도 45° 이상이라 0점"
|
||||
|
||||
|
||||
def test_estimate_and_labels_cover_openmeteo_axes():
|
||||
r = estimate(_uv_defn(), _fc(), [[19, 20]], CTX)
|
||||
assert r.factors["uv"] == 70 and r.factors["sun"] == 0 and r.factors["view"] == 0
|
||||
assert [axis_label(a, {}) for a in ("uv", "sun", "view")] == ["자외선", "햇빛", "가시거리"]
|
||||
|
||||
|
||||
def _fc(lo=15.0, hi=23.0, am=0, pm=0, sky=Sky.CLEAR):
|
||||
return DayForecast(temp_min_c=lo, temp_max_c=hi, rain_prob_am=am, rain_prob_pm=pm, sky=sky)
|
||||
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
from datetime import datetime, timezone
|
||||
from types import SimpleNamespace
|
||||
|
||||
from common.enums import PostType
|
||||
from common.utils.kma_time import KST
|
||||
from services.calc.moon import nearest, phase_name
|
||||
from services.feed_service import FeedService, _tonight
|
||||
|
||||
|
||||
def test_true_phases_match_published_times_within_five_minutes():
|
||||
known = [(True, datetime(2024, 4, 23, 23, 49, tzinfo=timezone.utc)), (False, datetime(2024, 4, 8, 18, 21, tzinfo=timezone.utc)),
|
||||
(True, datetime(2025, 10, 7, 3, 47, tzinfo=timezone.utc)), (False, datetime(2017, 8, 21, 18, 30, tzinfo=timezone.utc))]
|
||||
for full, at in known:
|
||||
assert abs((nearest(at, full) - at).total_seconds()) < 300
|
||||
|
||||
|
||||
def test_phase_names():
|
||||
assert phase_name(datetime(2025, 10, 7, 3, 47, tzinfo=timezone.utc)) == "보름달"
|
||||
assert phase_name(datetime(2024, 4, 8, 18, 21, tzinfo=timezone.utc)) == "삭"
|
||||
|
||||
|
||||
def test_tonight_follows_feed_day_starting_at_3am():
|
||||
assert _tonight(datetime(2024, 4, 9, 1, 0, tzinfo=KST)) == datetime(2024, 4, 8, 22, 0, tzinfo=KST)
|
||||
assert _tonight(datetime(2024, 4, 8, 20, 0, tzinfo=KST)) == datetime(2024, 4, 8, 22, 0, tzinfo=KST)
|
||||
assert _tonight(datetime(2024, 4, 9, 9, 0, tzinfo=KST)) == datetime(2024, 4, 9, 22, 0, tzinfo=KST)
|
||||
|
||||
|
||||
def _moon_post(now: datetime):
|
||||
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)
|
||||
return FeedService._moon(None, base, c)
|
||||
|
||||
|
||||
def test_moon_post_every_night_with_full_and_new_moon_stories():
|
||||
full = _moon_post(datetime(2025, 10, 7, 20, 0, tzinfo=KST)) # 보름 10.07 12:47
|
||||
assert full.title == "오늘 밤 보름달" and "12:4" in full.slides[0].line
|
||||
new = _moon_post(datetime(2024, 4, 9, 1, 0, tzinfo=KST)) # 삭 04.09 03:21, 자정 넘긴 새벽에도 그 밤
|
||||
assert new.title == "오늘 밤 달 없는 밤"
|
||||
plain = _moon_post(datetime(2025, 10, 4, 20, 0, tzinfo=KST)) # 보름 사흘 전
|
||||
assert plain.title == "오늘 밤 차오르는 달" and plain.slides[0].rows[-1].label == "다음 보름" and plain.slides[0].rows[-1].value.startswith("10.07")
|
||||
@@ -0,0 +1,113 @@
|
||||
import pytest
|
||||
from sqlalchemy import text
|
||||
|
||||
import scheduler.jobs as jobs
|
||||
from common.database.db_session_manager import DB_SESSION_MNG
|
||||
from common.enums import ErrorType
|
||||
from services.external.open_meteo import OpenMeteoRequestFailed, parse_weather
|
||||
|
||||
SLOTS_PER_REGION = 31 # 96시간 응답에서 직전 3시간이 다 있는 3시간 구간 (끝 시각 03시 ~ 다음다음다음날 21시)
|
||||
|
||||
|
||||
def _hourly(**over):
|
||||
times = [f"2026-10-06T{h:02d}:00" for h in range(9)]
|
||||
base = {
|
||||
"time": times,
|
||||
"uv_index": [round(0.1 * h, 1) for h in range(9)],
|
||||
"uv_index_clear_sky": [round(0.2 * h, 1) for h in range(9)],
|
||||
"visibility": [10000.0 + h for h in range(9)],
|
||||
"wind_gusts_10m": [1.0 + h for h in range(9)],
|
||||
"pressure_msl": [1000.0 + h for h in range(9)],
|
||||
"sunshine_duration": [0, 600, 1200, 1800, 2400, 3000, 3600, 3600, 3600],
|
||||
"shortwave_radiation": [0, 10, 20, 30, 40, 60, 100, 200, 300],
|
||||
"soil_temperature_0cm": [10.0 + h for h in range(9)],
|
||||
}
|
||||
return {"hourly": base | over}
|
||||
|
||||
|
||||
def test_three_hour_slots_sum_sunshine_and_average_radiation():
|
||||
rows = {r["forecast_at"].hour: r for r in parse_weather(_hourly())}
|
||||
assert sorted(rows) == [3, 6] # 00시 구간은 앞 두 시간이 없어 만들지 않는다
|
||||
assert rows[3]["sunshine_s"] == 600 + 1200 + 1800
|
||||
assert rows[3]["shortwave_avg_wm2"] == 20 and rows[3]["shortwave_max_wm2"] == 30
|
||||
assert rows[6]["sunshine_s"] == 2400 + 3000 + 3600
|
||||
assert rows[6]["shortwave_avg_wm2"] == 67 and rows[6]["shortwave_max_wm2"] == 100
|
||||
|
||||
|
||||
def test_other_values_are_taken_at_slot_end():
|
||||
row = {r["forecast_at"].hour: r for r in parse_weather(_hourly())}[6]
|
||||
assert row["uv_index"] == 0.6 and row["uv_index_clear_sky"] == 1.2
|
||||
assert row["visibility_m"] == 10006 and row["wind_gust_ms"] == 7.0
|
||||
assert row["pressure_hpa"] == 1006.0 and row["soil_temp_c"] == 16.0
|
||||
|
||||
|
||||
def test_missing_hour_value_makes_aggregate_none_but_keeps_instant_values():
|
||||
sun = [0, 600, None, 1800, 2400, 3000, 3600, 3600, 3600]
|
||||
rows = {r["forecast_at"].hour: r for r in parse_weather(_hourly(sunshine_duration=sun))}
|
||||
assert rows[3]["sunshine_s"] is None and rows[3]["uv_index"] == 0.3
|
||||
assert rows[6]["sunshine_s"] == 9000
|
||||
|
||||
|
||||
def test_dark_slots_drop_sun_values_but_keep_others():
|
||||
times = [f"2026-10-06T{h:02d}:00" for h in range(24)]
|
||||
full = {k: [1.0] * 24 for k in ("uv_index", "uv_index_clear_sky", "visibility", "wind_gusts_10m", "pressure_msl", "soil_temperature_0cm")}
|
||||
rows = {r["forecast_at"].hour: r for r in parse_weather({"hourly": {"time": times, "sunshine_duration": [600] * 24, "shortwave_radiation": [50] * 24} | full})}
|
||||
dark = {15, 18, 21} # GMT 끝 시각 = KST 0·3·6시 (21~06시). KST 21시 구간(18~21시)은 남긴다
|
||||
assert sorted(rows) == [3, 6, 9, 12, 15, 18, 21]
|
||||
for hour, row in rows.items():
|
||||
sun = (row["uv_index"], row["uv_index_clear_sky"], row["sunshine_s"], row["shortwave_avg_wm2"], row["shortwave_max_wm2"])
|
||||
assert (sun == (None,) * 5) is (hour in dark)
|
||||
assert row["visibility_m"] == 1 and row["soil_temp_c"] == 1.0
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_refresh_stores_every_region_and_is_repeatable(offline):
|
||||
assert await jobs.refresh_openmeteo_weather() is ErrorType.SUCCESS
|
||||
first = await _counts()
|
||||
assert first["regions"] == 256 and first["rows"] == 256 * SLOTS_PER_REGION and first["slots"] == SLOTS_PER_REGION
|
||||
|
||||
assert await jobs.refresh_openmeteo_weather() is ErrorType.SUCCESS
|
||||
assert (await _counts())["rows"] == first["rows"]
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_refresh_failure_returns_error_and_stores_nothing(offline, monkeypatch):
|
||||
async def fail(client, points, days=4):
|
||||
raise OpenMeteoRequestFailed("boom")
|
||||
|
||||
monkeypatch.setattr(jobs, "fetch_weather", fail)
|
||||
assert await jobs.refresh_openmeteo_weather() is ErrorType.EXTERNAL_API_ERROR
|
||||
assert (await _counts())["rows"] == 0
|
||||
|
||||
|
||||
async def _counts() -> dict:
|
||||
err, res = await DB_SESSION_MNG.execute_lambda(
|
||||
lambda s: s.execute(text("SELECT count(*) AS rows, count(DISTINCT region_code) AS regions, count(DISTINCT forecast_at) AS slots FROM openmeteo_hourly"))
|
||||
)
|
||||
return dict(res.one()._mapping)
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_upsert_keeps_previous_value_when_new_value_is_missing():
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
from crud.weather_crud import WeatherCRUD
|
||||
|
||||
at = datetime(2026, 10, 6, 3, tzinfo=timezone.utc)
|
||||
first = {
|
||||
"region_code": "1144000000", "forecast_at": at, "fetched_at": at, "uv_index": 3.0, "uv_index_clear_sky": 3.5,
|
||||
"visibility_m": 20000, "wind_gust_ms": 4.0, "pressure_hpa": 1015.0, "soil_temp_c": 18.0,
|
||||
"sunshine_s": 3600, "shortwave_avg_wm2": 300, "shortwave_max_wm2": 400,
|
||||
}
|
||||
second = first | {"fetched_at": at + timedelta(hours=6), "uv_index": None, "sunshine_s": None, "visibility_m": 15000}
|
||||
|
||||
for row in (first, second):
|
||||
await DB_SESSION_MNG.execute_lambda_run([lambda s, r=row: WeatherCRUD().upsert_openmeteo(s, [r])])
|
||||
|
||||
err, res = await DB_SESSION_MNG.execute_lambda(
|
||||
lambda s: s.execute(text("SELECT uv_index, sunshine_s, visibility_m, fetched_at FROM openmeteo_hourly WHERE region_code = '1144000000'"))
|
||||
)
|
||||
row = res.one()
|
||||
assert float(row.uv_index) == 3.0 and row.sunshine_s == 3600 # 비어 온 값은 이전 값 유지
|
||||
assert row.visibility_m == 15000 # 값이 있으면 덮어씀
|
||||
assert row.fetched_at == second["fetched_at"]
|
||||
@@ -0,0 +1,64 @@
|
||||
import json
|
||||
from datetime import date
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
|
||||
from common.enums import EventKind
|
||||
from services.external import popga
|
||||
from services.external.popga import fetch_popup_index, parse_popup, sido_of
|
||||
|
||||
|
||||
def _page(popup_id: int, kind: str, start: str, end: str, address: str = "서울 성동구 테스트로 1") -> str:
|
||||
ld = {
|
||||
"@context": "https://schema.org", "@type": "Event", "name": "테스트 팝업 & 굿즈", "startDate": start, "endDate": end,
|
||||
"location": {"@type": "Place", "name": "테스트 빌딩 1F", "address": {"@type": "PostalAddress", "streetAddress": address},
|
||||
"geo": {"@type": "GeoCoordinates", "latitude": 37.5446123, "longitude": 127.0557456}},
|
||||
}
|
||||
payload = f'self.__next_f.push([1,"{{\\"data\\":{{\\"id\\":{popup_id},\\"type\\":\\"{kind}\\",\\"source\\":null}}}}"])'
|
||||
return f'<html><script type="application/ld+json">{json.dumps(ld, ensure_ascii=False)}</script><script>{payload}</script></html>'
|
||||
|
||||
|
||||
def test_parse_popup_maps_store():
|
||||
row = parse_popup(_page(501, "STORE", "2026-10-02", "2026-10-11"), 501, date(2026, 10, 1))
|
||||
assert row == {
|
||||
"source_id": "popga:501", "sido_code": "11", "name": "테스트 팝업 & 굿즈", "place_name": "테스트 빌딩 1F",
|
||||
"start_date": date(2026, 10, 2), "end_date": date(2026, 10, 11), "is_confirmed": True,
|
||||
"source_url": "https://popga.co.kr/popup/501", "image_url": None, "lat": 37.54461, "lon": 127.05575, "kind": EventKind.POPUP, "icon": "popup",
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.parametrize("kind,end,address", [
|
||||
("PERFORMANCE", "2026-10-11", "서울 성동구 테스트로 1"),
|
||||
("STORE", "2026-09-30", "서울 성동구 테스트로 1"),
|
||||
("STORE", "2026-10-11", "알 수 없는 주소"),
|
||||
])
|
||||
def test_parse_popup_skips_non_store_ended_or_unknown_sido(kind, end, address):
|
||||
assert parse_popup(_page(502, kind, "2026-09-01", end, address), 502, date(2026, 10, 1)) is None
|
||||
|
||||
|
||||
def test_parse_popup_reads_type_of_its_own_id():
|
||||
page = _page(503, "STORE", "2026-10-02", "2026-10-11").replace('\\"id\\":503,\\"type\\":\\"STORE\\"', '\\"id\\":999,\\"type\\":\\"STORE\\"')
|
||||
assert parse_popup(page, 503, date(2026, 10, 1)) is None
|
||||
|
||||
|
||||
@pytest.mark.parametrize("address,code", [
|
||||
("서울 마포구 테스트로 1", "11"), ("서울특별시 마포구", "11"), ("경기 수원시", "41"), ("경상남도 진주시", "48"),
|
||||
("강원특별자치도 춘천시", "51"), ("전북특별자치도 전주시", "52"), ("", None),
|
||||
])
|
||||
def test_sido_of(address, code):
|
||||
assert sido_of(address) == code
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_fetch_popup_index_reads_popup_pages_only(monkeypatch):
|
||||
monkeypatch.setattr(popga, "REQUEST_GAP_SEC", 0)
|
||||
pages = {
|
||||
"/sitemap.xml": "<sitemapindex><sitemap><loc>https://popga.co.kr/sitemap/2.xml</loc></sitemap>"
|
||||
"<sitemap><loc>https://popga.co.kr/sitemap/5.xml</loc></sitemap></sitemapindex>",
|
||||
"/sitemap/2.xml": "<urlset><url><loc>https://popga.co.kr/popup/12</loc><lastmod>2026-10-06T00:00:00Z</lastmod></url>"
|
||||
"<url><loc>https://popga.co.kr/popup/11</loc></url></urlset>",
|
||||
"/sitemap/5.xml": "<urlset><url><loc>https://popga.co.kr/popup/12/review/3</loc><lastmod>2026-10-06</lastmod></url></urlset>",
|
||||
}
|
||||
async with httpx.AsyncClient(transport=httpx.MockTransport(lambda req: httpx.Response(200, text=pages[req.url.path]))) as client:
|
||||
assert await fetch_popup_index(client) == {12: "2026-10-06T00:00:00Z", 11: ""}
|
||||
@@ -54,8 +54,10 @@ async def test_sky_view_scores_three_days_with_spots(monkeypatch, clean):
|
||||
assert plan["verdict"] == "go" and plan["headline"] == "나가 볼 만해요" and plan["when"] in ("오늘", "내일")
|
||||
assert "알맞게" in plan["reason"]
|
||||
assert plan["spot"]["name"] == "망원한강공원" and plan["best_at"]
|
||||
assert [t["kind"] for t in plan["timeline"]] == ["golden", "sun", "peak", "blue"]
|
||||
assert plan["outlook"].endswith("비슷해요")
|
||||
assert [t["kind"] for t in plan["timeline"]] == ["golden", "sun", "blue"]
|
||||
assert plan["situation_label"] == "하늘이 넓게 물들 수 있어요" and plan["models_agree"] == plan["models_total"] == 2
|
||||
assert plan["outlook"] == ""
|
||||
assert body["sunset"]["verdict"] == "go" and body["spots"][0]["direction"]
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
@@ -104,14 +106,38 @@ def test_nearest_spots_west_first_and_empty_outside_radius():
|
||||
assert sky_service.nearest_spots(33.0, 127.0, spots) == []
|
||||
|
||||
|
||||
def test_outlook_points_to_a_better_day_only_when_clearly_better():
|
||||
def test_outlook_only_when_a_later_day_has_a_better_verdict():
|
||||
from datetime import date, timedelta
|
||||
|
||||
from common.database.model.models import SkyScore
|
||||
from common.enums import SkySituation
|
||||
|
||||
today = date(2026, 10, 6)
|
||||
day = lambda i, v: SkyScore(score_date=today + timedelta(days=i), score=v) # noqa: E731
|
||||
assert sky_service.outlook(day(0, 30), [day(0, 30), day(1, 35), day(2, 72)], today) == "모레가 더 나아요 — 72점, 나가 볼 만해요"
|
||||
assert sky_service.outlook(day(0, 80), [day(0, 80), day(1, 50), day(2, 40)], today).startswith("오늘이 가장 나아요")
|
||||
assert sky_service.outlook(day(0, 50), [day(0, 50), day(1, 55), day(2, 45)], today) == "내일·모레도 비슷해요"
|
||||
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, 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) == ""
|
||||
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
|
||||
async def test_clouds_are_stored_by_region_with_only_needed_hours(monkeypatch, clean):
|
||||
async def fake_fetch(client, points, days=3):
|
||||
return _fake_response(points, days)
|
||||
|
||||
monkeypatch.setattr(sky_service, "fetch_clouds", fake_fetch)
|
||||
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
|
||||
await client.get("/v1/sky", params={"region": "1144000000"})
|
||||
|
||||
err, rows = await DB_SESSION_MNG.execute_lambda(
|
||||
lambda s: s.execute(text("SELECT kind, distance_km, forecast_at, model FROM cloud_hourly WHERE region_code = '1144000000'"))
|
||||
)
|
||||
rows = rows.all()
|
||||
assert len(rows) == 2 * 2 * 3 * 2
|
||||
assert {(r.kind, r.distance_km) for r in rows} == {(1, 20), (1, 100), (2, 20), (2, 100)}
|
||||
assert {r.model for r in rows} == {3, 4}
|
||||
assert len({r.forecast_at for r in rows}) == 6
|
||||
@@ -2,7 +2,7 @@ from datetime import date, datetime, timedelta, timezone
|
||||
|
||||
from common.enums import Confidence, SkyGrade, SkyType
|
||||
from common.utils.geo import destination, haversine_km
|
||||
from services.calc.sky_score import GRADE_LABEL, Layers, best_times, confidence, grade, reason, score, sunset_timeline, verdict
|
||||
from services.calc.sky_score import GRADE_LABEL, Layers, best_times, confidence, grade, reason, score, situation, sunset_timeline, verdict
|
||||
from services.calc.sun import sun_times
|
||||
|
||||
CLEAR = Layers(0, 0, 0)
|
||||
@@ -10,21 +10,21 @@ CLEAR = Layers(0, 0, 0)
|
||||
|
||||
def test_high_clouds_overhead_and_clear_horizon_is_best():
|
||||
canvas = Layers(low=0, mid=20, high=50)
|
||||
assert score(canvas, canvas, CLEAR) == 100
|
||||
assert score(canvas, CLEAR) == 100
|
||||
|
||||
|
||||
def test_clear_sky_is_only_soft():
|
||||
assert grade(score(CLEAR, CLEAR, CLEAR)) is SkyGrade.SOFT
|
||||
assert grade(score(CLEAR, CLEAR)) is SkyGrade.SOFT
|
||||
|
||||
|
||||
def test_low_clouds_toward_sun_block_the_light():
|
||||
canvas = Layers(low=0, mid=20, high=50)
|
||||
assert grade(score(canvas, 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
|
||||
|
||||
|
||||
def test_overcast_low_clouds_is_gray():
|
||||
gray = Layers(low=100, mid=100, high=100)
|
||||
assert grade(score(gray, gray, gray)) is SkyGrade.GRAY
|
||||
assert grade(score(gray, gray)) is SkyGrade.GRAY
|
||||
|
||||
|
||||
def test_confidence_from_model_spread():
|
||||
@@ -43,15 +43,15 @@ def test_sunset_best_times_order():
|
||||
sunset = datetime(2026, 10, 2, 9, 15, tzinfo=timezone.utc)
|
||||
dusk = datetime(2026, 10, 2, 9, 41, tzinfo=timezone.utc)
|
||||
labels = [t["label"] for t in best_times(SkyType.SUNSET, sunset, dusk, 50)]
|
||||
assert labels == ["해 져요", "가장 붉을 때", "보랏빛 하늘"]
|
||||
assert labels == ["해 져요", "가장 붉을 때", "블루아워"]
|
||||
|
||||
|
||||
def test_reason_names_what_decided_the_score():
|
||||
canvas = Layers(low=0, mid=20, high=50)
|
||||
assert "알맞게" in reason(canvas, canvas, CLEAR)
|
||||
assert "먼 하늘" in reason(canvas, canvas, Layers(low=90, mid=50, high=0))
|
||||
assert "낮은 구름" in reason(Layers(100, 0, 0), Layers(80, 0, 0), CLEAR)
|
||||
assert "거의 없어" in reason(CLEAR, CLEAR, CLEAR)
|
||||
assert "알맞게" in reason(canvas, CLEAR)
|
||||
assert "먼 하늘" in reason(canvas, Layers(low=90, mid=50, high=0))
|
||||
assert "낮은 구름" in reason(Layers(100, 0, 0), CLEAR)
|
||||
assert "거의 없어" in reason(CLEAR, CLEAR)
|
||||
|
||||
|
||||
def test_verdict_bands_and_gray_label_is_not_weather_word():
|
||||
@@ -65,3 +65,23 @@ def test_sunset_timeline_runs_golden_to_blue():
|
||||
assert [r["kind"] for r in rows] == ["golden", "sun", "peak", "blue"]
|
||||
ats = [datetime.fromisoformat(r["at"]) for r in rows]
|
||||
assert ats == sorted(ats) and 15 <= (ats[1] - ats[0]).total_seconds() / 60 <= 60
|
||||
|
||||
|
||||
def test_situation_follows_reason_order():
|
||||
from common.enums import SkySituation
|
||||
clear, glow = Layers(0, 0, 0), Layers(0, 40, 50)
|
||||
assert situation(clear, clear) is SkySituation.FEW
|
||||
assert situation(glow, clear) is SkySituation.GLOW
|
||||
assert situation(Layers(0, 90, 95), clear) is SkySituation.THICK
|
||||
assert situation(Layers(80, 0, 0), clear) is SkySituation.LOW_CLOUD
|
||||
assert situation(glow, Layers(70, 0, 0)) is SkySituation.COVERED
|
||||
|
||||
|
||||
def test_ranking_summary_only_when_most_spots_share_a_situation():
|
||||
from types import SimpleNamespace
|
||||
|
||||
from common.enums import SkySituation
|
||||
from services.sky_service import ranking_summary
|
||||
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)] * 5 + [item(SkySituation.GLOW)] * 5) is None
|
||||
+21
-10
@@ -8,12 +8,12 @@ import services.warning_service as warning_service
|
||||
import services.weather_service as weather_service
|
||||
import services.week_service as week_service
|
||||
from common.database.model.models import Event
|
||||
from common.enums import RainType, Sky
|
||||
from common.enums import EventKind, RainType, Sky
|
||||
from common.utils.kma_time import KST, kst_midnight, now_kst
|
||||
from router.router import app
|
||||
from services.external.kma import latest_mid_base, mid_word, parse_mid
|
||||
from services.external.data_go_kr import DataGoKrRequestFailed
|
||||
from services.week_service import _status
|
||||
from services.week_service import EventItem, _status, mix_kinds
|
||||
|
||||
REGION = "1144000000"
|
||||
|
||||
@@ -45,6 +45,15 @@ def test_event_status_labels():
|
||||
assert _status(ev(date(2026, 10, 20), date(2026, 10, 21)), today) == ("soon", "D-18")
|
||||
|
||||
|
||||
def test_mix_kinds_rotates_festival_popup_exhibition_concert():
|
||||
item = lambda name, kind: EventItem(event=Event(name=name, kind=kind), status="soon", status_label="", fit=None) # noqa: E731
|
||||
items = [item("연주회1", EventKind.CONCERT), item("연주회2", EventKind.CONCERT), item("전시1", EventKind.EXHIBITION),
|
||||
item("팝업1", EventKind.POPUP), item("연주회3", EventKind.CONCERT), item("축제1", EventKind.FESTIVAL)]
|
||||
assert [e.event.name for e in mix_kinds(items)] == ["축제1", "팝업1", "전시1", "연주회1", "연주회2", "연주회3"]
|
||||
only = [item(f"연주회{i}", EventKind.CONCERT) for i in range(3)]
|
||||
assert [e.event.name for e in mix_kinds(only)] == ["연주회0", "연주회1", "연주회2"]
|
||||
|
||||
|
||||
async def _async(v):
|
||||
return v
|
||||
|
||||
@@ -67,6 +76,11 @@ def _mid(*_):
|
||||
return land, ta
|
||||
|
||||
|
||||
async def _collect(*sidos):
|
||||
for sido in sidos:
|
||||
await week_service.collect_events(sido, now_kst().date())
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def fakes(monkeypatch):
|
||||
today = now_kst().date()
|
||||
@@ -99,6 +113,7 @@ async def test_week_reaches_mid_forecast_end_with_holiday_and_rain(fakes):
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_events_exclude_long_running_and_add_weather_fit(fakes):
|
||||
await _collect("11")
|
||||
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
|
||||
body = (await client.get("/v1/week/event/list", params={"region": REGION})).json()
|
||||
assert [e["name"] for e in body["events"]] == ["가을 축제"]
|
||||
@@ -114,6 +129,7 @@ async def test_events_include_culture_exhibitions_with_their_credit(fakes, monke
|
||||
"seq": "123", "title": "가을 특별전", "place": "테스트 미술관", "startDate": (today + timedelta(days=1)).strftime("%Y%m%d"),
|
||||
"endDate": (today + timedelta(days=20)).strftime("%Y%m%d"), "thumbnail": "http://www.culture.go.kr/x.jpg", "gpsX": "126.97", "gpsY": "37.57",
|
||||
}]))
|
||||
await _collect("11")
|
||||
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
|
||||
body = (await client.get("/v1/week/event/list", params={"region": REGION})).json()
|
||||
by_name = {e["name"]: e for e in body["events"]}
|
||||
@@ -129,6 +145,7 @@ async def test_events_keep_tour_festivals_when_culture_api_fails(fakes, monkeypa
|
||||
raise DataGoKrRequestFailed("realm2 30 SERVICE_KEY_IS_NOT_REGISTERED_ERROR")
|
||||
|
||||
monkeypatch.setattr(week_service, "fetch_exhibitions", fail)
|
||||
await _collect("11")
|
||||
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
|
||||
body = (await client.get("/v1/week/event/list", params={"region": REGION})).json()
|
||||
assert [e["name"] for e in body["events"]] == ["가을 축제"]
|
||||
@@ -145,16 +162,10 @@ async def test_events_pick_within_30km_across_sido(fakes, monkeypatch):
|
||||
"41": [{"contentid": "41", "title": "연천 축제", "addr1": "경기 연천군", "mapy": "38.0963", "mapx": "127.0750", **span},
|
||||
{"contentid": "42", "title": "좌표 없는 경기 축제", "addr1": "경기", **span}],
|
||||
}
|
||||
asked = []
|
||||
|
||||
def festivals(client, sido, since):
|
||||
asked.append(sido)
|
||||
return _async(by_sido.get(sido, []))
|
||||
|
||||
monkeypatch.setattr(week_service, "fetch_festivals", festivals)
|
||||
monkeypatch.setattr(week_service, "fetch_festivals", lambda client, sido, since: _async(by_sido.get(sido, [])))
|
||||
await _collect("11", "41")
|
||||
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
|
||||
body = (await client.get("/v1/week/event/list", params={"region": "4113500000"})).json()
|
||||
assert {"11", "41"} <= set(asked) and "26" not in asked
|
||||
assert {e["name"] for e in body["events"]} == {"잠실 축제", "좌표 없는 경기 축제"}
|
||||
|
||||
|
||||
|
||||
@@ -5,7 +5,7 @@ from apscheduler.schedulers.asyncio import AsyncIOScheduler
|
||||
|
||||
from common.database.db_session_manager import DB_SESSION_MNG
|
||||
from common.logger import LOG
|
||||
from scheduler.jobs import build_today_feed, cleanup_old_rows, refresh_air_stations, refresh_weekend_rank
|
||||
from scheduler.jobs import build_today_feed, cleanup_old_rows, refresh_air_stations, refresh_events, refresh_openmeteo_weather, refresh_weekend_rank
|
||||
|
||||
|
||||
async def daily() -> None:
|
||||
@@ -20,8 +20,12 @@ async def main() -> None:
|
||||
# 주말 나들이 점수: 단기예보 05·17시 발표와 중기예보 06·18시 발표가 다 나온 뒤. 켤 때 캐시가 없으면 한 번.
|
||||
scheduler.add_job(refresh_weekend_rank, "cron", hour="6,18", minute=40, max_instances=1, coalesce=True)
|
||||
scheduler.add_job(refresh_weekend_rank, kwargs={"only_if_missing": True}, max_instances=1)
|
||||
# 행사(축제·전시·콘서트·팝업): 7일에 한 번, 끝나면 Teams 알림. 켤 때 7일 안에 받은 기록이 없으면 한 번.
|
||||
scheduler.add_job(refresh_events, "cron", day_of_week="mon", hour=4, minute=0, max_instances=1, coalesce=True)
|
||||
scheduler.add_job(refresh_events, kwargs={"only_if_missing": True}, max_instances=1)
|
||||
scheduler.add_job(refresh_openmeteo_weather, "cron", hour="3,9,15,21", minute=10, max_instances=1, coalesce=True)
|
||||
scheduler.start()
|
||||
LOG.info("[worker] started, daily job at 03:00 KST, weekend rank at 06:40·18:40 KST")
|
||||
LOG.info("[worker] started, daily job at 03:00 KST, weekend rank at 06:40·18:40 KST, events on Mon 04:00 KST, openmeteo job at 03·09·15·21:10 KST")
|
||||
|
||||
stop = asyncio.Event()
|
||||
loop = asyncio.get_running_loop()
|
||||
|
||||
+7
-4
@@ -6,8 +6,11 @@ services:
|
||||
build:
|
||||
context: ./frontend
|
||||
target: prod
|
||||
args:
|
||||
# 비우면 같은 주소의 /v1 로 부르고 nginx 가 backend 로 넘긴다
|
||||
VITE_API_BASE_URL: ${VITE_API_BASE_URL:-}
|
||||
ports:
|
||||
- "8080:80"
|
||||
- "${FRONT_PORT:-8080}:80"
|
||||
restart: unless-stopped
|
||||
|
||||
# 개발형: docker compose --profile dev up --build frontend-dev → http://localhost:5173
|
||||
@@ -36,7 +39,7 @@ services:
|
||||
REDIS_HOST: redis
|
||||
REDIS_PORT: "6379"
|
||||
ports:
|
||||
- "9810:9800"
|
||||
- "${API_BIND:-9810}:9800"
|
||||
depends_on:
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
@@ -70,7 +73,7 @@ services:
|
||||
POSTGRES_PASSWORD: ${DB_PASSWORD}
|
||||
POSTGRES_DB: ${DB_NAME}
|
||||
ports:
|
||||
- "5440:5432"
|
||||
- "${PG_BIND:-5440}:5432"
|
||||
volumes:
|
||||
- pgdata:/var/lib/postgresql/data
|
||||
- ./backend/postgres-init:/docker-entrypoint-initdb.d:ro
|
||||
@@ -85,7 +88,7 @@ services:
|
||||
image: redis:7-alpine
|
||||
command: ["redis-server", "--appendonly", "yes"]
|
||||
ports:
|
||||
- "6390:6379"
|
||||
- "${REDIS_BIND:-6390}:6379"
|
||||
volumes:
|
||||
- redisdata:/data
|
||||
healthcheck:
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
#!/usr/bin/env bash
|
||||
# 킹서버 배포. 서버의 저장소 폴더에서 실행한다.
|
||||
# ./deploy.sh main 받아서 다시 빌드·재시작
|
||||
# ./deploy.sh --restore-db 덤프.dump 위 작업 후 DB 를 덤프로 덮어쓴다 (pg_dump -Fc 형식)
|
||||
# DB 구조는 배포마다 init.sql 을 다시 돌려 맞춘다. 그래서 init.sql 은 여러 번 돌려도 안전하게 쓴다
|
||||
# (CREATE ... IF NOT EXISTS, ALTER TABLE ... ADD COLUMN IF NOT EXISTS). 칸 이름·타입 변경과 삭제는 이 방식으로 안 되니 따로 SQL 을 돌린다.
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")"
|
||||
|
||||
[ -f .env ] || { echo ".env 가 없습니다. .env.example 을 보고 만드세요." >&2; exit 1; }
|
||||
set -a; . ./.env; set +a
|
||||
|
||||
# 받은 뒤 새 스크립트로 다시 시작한다 (실행 중인 셸은 옛 내용을 읽고 있어서, 새로 추가된 단계가 그 회차에 빠진다)
|
||||
if [ -z "${DEPLOY_PULLED:-}" ]; then
|
||||
git pull --ff-only origin main
|
||||
DEPLOY_PULLED=1 exec "$0" "$@"
|
||||
fi
|
||||
docker compose up -d --wait postgres redis
|
||||
docker compose exec -T postgres psql -q -v ON_ERROR_STOP=1 -U "$DB_USER" -d "$DB_NAME" < backend/postgres-init/init.sql
|
||||
docker compose up -d --build backend worker frontend
|
||||
docker compose exec -T backend python scripts/load_seed.py
|
||||
|
||||
if [ "${1:-}" = "--restore-db" ]; then
|
||||
dump="${2:?덤프 파일 경로가 필요합니다}"
|
||||
[ -f "$dump" ] || { echo "덤프 파일이 없습니다: $dump" >&2; exit 1; }
|
||||
docker compose stop backend worker
|
||||
docker compose exec -T postgres pg_restore -U "$DB_USER" -d "$DB_NAME" --clean --if-exists --no-owner < "$dump"
|
||||
docker compose exec -T redis redis-cli FLUSHDB
|
||||
docker compose start backend worker
|
||||
fi
|
||||
|
||||
docker compose ps
|
||||
@@ -1,4 +1,4 @@
|
||||
# 2026-10-06 회의 — 날씨각
|
||||
# 2026-10-02(금) 회의 — 날씨각
|
||||
|
||||
## 수정
|
||||
- 각 점수 하향. 100점은 "기온 22도·습도 30%·미풍" 같은 완벽한 조건에만 준다 (결정)
|
||||
@@ -59,6 +59,11 @@
|
||||
- 시간·요일 10%: 요일별 점수: 금 100, 토 100, 일 85, 그 외 78
|
||||
- 점수 깎이는 조건: 비 확률 80% 이상이면 0점, 바람 14m/s 이상이면 0점
|
||||
- 반영 못 하는 것: 모기, 가게 영업 여부, 자리 경쟁은 반영하지 못해요
|
||||
- 점수 구간별 설명 (상세 창에 나옴):
|
||||
- 0~29점: 비 오거나 바람이 쌩쌩, 오늘 야장은 접어요. 실내 포차로 피신!
|
||||
- 30~59점: 앉을 순 있는데 춥거나 덥거나 눅눅해요. 겉옷이나 부채 필수!
|
||||
- 60~79점: 꽤 괜찮은 저녁! 바람만 살랑 불어 주면 딱이에요.
|
||||
- 80~100점: 18~24°에 바람 살랑, 비 걱정 없음! 오늘은 무조건 바깥 자리 🍻
|
||||
|
||||
### 피크닉각 (`picnic`)
|
||||
|
||||
@@ -74,6 +79,11 @@
|
||||
- 시간·요일 10%: 요일별 점수: 토 100, 일 100, 공휴일 100, 그 외 60
|
||||
- 점수 깎이는 조건: 비 확률 60% 이상이면 0점
|
||||
- 반영 못 하는 것: 잔디 상태, 공원 혼잡도는 반영하지 못해요
|
||||
- 점수 구간별 설명 (상세 창에 나옴):
|
||||
- 0~29점: 비 소식이 있어요. 돗자리는 집에 고이 두기!
|
||||
- 30~59점: 햇볕이 뜨겁거나 바람이 쌀쌀해요. 그늘이나 담요 챙기면 버틸 만!
|
||||
- 60~79점: 돗자리 펴기 괜찮은 날! 바람막이 하나면 완벽해요.
|
||||
- 80~100점: 20~26°에 바람 잔잔, 김밥 싸서 당장 출발! 🧺
|
||||
|
||||
### 치맥각 (`chimaek`)
|
||||
|
||||
@@ -89,6 +99,11 @@
|
||||
- 시간·요일 10%: 요일별 점수: 금 100, 토 100, 그 외 74
|
||||
- 점수 깎이는 조건: 체감 10° 미만이면 0점, 비 확률 80% 이상이면 0점
|
||||
- 반영 못 하는 것: 야구 경기 같은 이벤트는 아직 반영하지 못해요
|
||||
- 점수 구간별 설명 (상세 창에 나옴):
|
||||
- 0~29점: 체감 10° 아래거나 비가 와요. 치킨은 배달, 맥주는 집에서!
|
||||
- 30~59점: 바깥은 좀 쌀쌀하거나 후덥지근해요. 가게 안쪽 자리 추천!
|
||||
- 60~79점: 바깥 테이블 괜찮아요! 얇은 겉옷 하나만 챙겨요.
|
||||
- 80~100점: 20~27°의 선선한 저녁, 치킨에 맥주 부르는 날 🍗
|
||||
|
||||
### 산책각 (`walk`)
|
||||
|
||||
@@ -104,6 +119,11 @@
|
||||
- 시간·요일 5%: 고정 55점
|
||||
- 점수 깎이는 조건: 비 확률 90% 이상이면 0점, 초미세먼지 75㎍/㎥ 이상이면 0점
|
||||
- 반영 못 하는 것: 길 공사, 조명은 반영하지 못해요
|
||||
- 점수 구간별 설명 (상세 창에 나옴):
|
||||
- 0~29점: 비가 쏟아지거나 초미세먼지가 매우 나빠요. 오늘은 실내 걷기로!
|
||||
- 30~59점: 걸을 순 있는데 춥거나 덥거나 공기가 탁해요. 짧게 한 바퀴만!
|
||||
- 60~79점: 한 바퀴 돌기 좋은 저녁! 이어폰 챙겨서 가볍게 나가요.
|
||||
- 80~100점: 15~23°에 공기 맑고 바람 살랑, 동네 한 바퀴 무조건 🚶
|
||||
|
||||
### 환기각 (`vent`)
|
||||
|
||||
@@ -119,6 +139,11 @@
|
||||
- 시간·요일 5%: 고정 100점
|
||||
- 점수 깎이는 조건: 초미세먼지 75㎍/㎥ 이상이면 0점
|
||||
- 반영 못 하는 것: 집 방향과 주변 공사 먼지는 반영하지 못해요
|
||||
- 점수 구간별 설명 (상세 창에 나옴):
|
||||
- 0~29점: 초미세먼지가 매우 나빠요. 창문 꼭 닫고 공기청정기 ON!
|
||||
- 30~59점: 공기가 탁하거나 비가 와요. 5분만 짧게 열고 닫기!
|
||||
- 60~79점: 열어도 괜찮아요. 맞바람 나게 10분이면 충분!
|
||||
- 80~100점: 공기 맑고 바람도 적당, 창문 활짝 열 시간 🌬️
|
||||
|
||||
### 등산각 (`hiking`)
|
||||
|
||||
@@ -134,6 +159,11 @@
|
||||
- 시간·요일 5%: 요일별 점수: 토 100, 일 100, 공휴일 100, 그 외 50
|
||||
- 점수 깎이는 조건: 비 확률 70% 이상이면 0점, wind 특보가 있으면
|
||||
- 반영 못 하는 것: 등산로 통제, 낙석 정보는 산림청 안내를 확인하세요
|
||||
- 점수 구간별 설명 (상세 창에 나옴):
|
||||
- 0~29점: 비 소식이나 강풍 특보가 있어요. 오늘 산은 쉬어요!
|
||||
- 30~59점: 산 위는 꽤 춥거나 더워요(6° 낮게 쳐요). 옷차림 단단히!
|
||||
- 60~79점: 오를 만해요! 바람막이 챙기고 일찍 출발해요.
|
||||
- 80~100점: 산 위도 선선하고 바람 잔잔, 정상 인증각 ⛰️
|
||||
|
||||
### 세차각 (`carwash`)
|
||||
|
||||
@@ -149,6 +179,11 @@
|
||||
- 시간·요일 5%: 고정 100점
|
||||
- 점수 깎이는 조건: 비 확률 70% 이상이면 최대 20점
|
||||
- 반영 못 하는 것: 황사·꽃가루 같은 하늘 먼지는 일부만 반영해요
|
||||
- 점수 구간별 설명 (상세 창에 나옴):
|
||||
- 0~29점: 곧 비가 와요. 지금 세차하면 물 낭비!
|
||||
- 30~59점: 비 기운이 남아 있어요. 하루쯤 미루는 게 이득!
|
||||
- 60~79점: 세차해도 괜찮아요. 먼지는 좀 붙을 수 있어요.
|
||||
- 80~100점: 비 걱정 없고 공기도 맑아요. 반짝반짝 오래가는 날 ✨
|
||||
|
||||
### 캠핑각 (`camping`)
|
||||
|
||||
@@ -164,6 +199,11 @@
|
||||
- 시간·요일 5%: 요일별 점수: 금 100, 토 100, 그 외 60
|
||||
- 점수 깎이는 조건: 비 확률 60% 이상이면 0점, 바람 14m/s 이상이면 0점
|
||||
- 반영 못 하는 것: 캠핑장 예약 상황은 반영하지 못해요
|
||||
- 점수 구간별 설명 (상세 창에 나옴):
|
||||
- 0~29점: 비가 오거나 바람이 너무 세요. 텐트 날아가요!
|
||||
- 30~59점: 밤에 춥거나 습해요. 침낭은 두꺼운 걸로!
|
||||
- 60~79점: 하룻밤 괜찮아요. 새벽엔 쌀쌀하니 담요 챙기기!
|
||||
- 80~100점: 밤새 12~22°에 바람 잔잔, 불멍하기 딱 좋은 밤 🔥
|
||||
|
||||
### 러닝각 (`running`)
|
||||
|
||||
@@ -179,6 +219,11 @@
|
||||
- 시간·요일 5%: 고정 100점
|
||||
- 점수 깎이는 조건: 체감 35° 이상이면 0점, 비 확률 90% 이상이면 0점
|
||||
- 반영 못 하는 것: 노면 상태는 반영하지 못해요
|
||||
- 점수 구간별 설명 (상세 창에 나옴):
|
||||
- 0~29점: 체감 35° 넘거나 비가 쏟아져요. 오늘은 러닝머신으로!
|
||||
- 30~59점: 덥거나 눅눅해서 금방 지쳐요. 거리 줄이고 물 꼭!
|
||||
- 60~79점: 뛸 만해요! 아침·저녁 중 시원한 쪽 고르기.
|
||||
- 80~100점: 8~18°에 공기 보송, 기록 갱신각 🏃
|
||||
|
||||
### 별보기각 (`stars`)
|
||||
|
||||
@@ -194,6 +239,11 @@
|
||||
- 시간·요일 45%: 달이 어두울수록 좋음 (보름 20점 → 그믐 100점)
|
||||
- 점수 깎이는 조건: 흐린 시간 비율 80% 이상이면 0점
|
||||
- 반영 못 하는 것: 도시 불빛은 지역 평균으로만 반영해요
|
||||
- 점수 구간별 설명 (상세 창에 나옴):
|
||||
- 0~29점: 구름이 하늘을 꽉 덮었어요. 별은 다음 기회에!
|
||||
- 30~59점: 달이 밝거나 하늘이 뿌예서 큰 별 몇 개만 보여요.
|
||||
- 60~79점: 꽤 보여요! 불빛 적은 곳으로 조금만 나가요.
|
||||
- 80~100점: 달은 어둡고 공기는 맑아요. 은하수 노려볼 만한 밤 ✨
|
||||
|
||||
### 짬뽕각 (`jjamppong`)
|
||||
|
||||
@@ -209,6 +259,11 @@
|
||||
- 시간·요일 5%: 고정 100점
|
||||
- 점수 깎이는 조건: 없음
|
||||
- 반영 못 하는 것: 실제 주문량으로 검증하기 전이에요
|
||||
- 점수 구간별 설명 (상세 창에 나옴):
|
||||
- 0~29점: 25° 넘게 더워요. 국물보다 냉면이 당길 날!
|
||||
- 30~59점: 국물이 살짝 생각나는 정도예요.
|
||||
- 60~79점: 쌀쌀하거나 비 와서 국물 각 잡혀요!
|
||||
- 80~100점: 춥고 비까지! 얼큰한 짬뽕 한 그릇 무조건 🍜
|
||||
|
||||
### 막걸리각 (`makgeolli`)
|
||||
|
||||
@@ -224,6 +279,11 @@
|
||||
- 시간·요일 5%: 요일별 점수: 금 100, 토 100, 그 외 50
|
||||
- 점수 깎이는 조건: 없음
|
||||
- 반영 못 하는 것: 실제 판매량으로 검증하기 전이에요
|
||||
- 점수 구간별 설명 (상세 창에 나옴):
|
||||
- 0~29점: 비 소식이 없어요. 파전은 비 오는 날을 기다려요!
|
||||
- 30~59점: 하늘이 꾸물꾸물, 막걸리 생각이 살짝 나요.
|
||||
- 60~79점: 비 기운이 있어요. 파전 반죽 준비각!
|
||||
- 80~100점: 비 오고 선선한 저녁, 파전에 막걸리 확정 🍶
|
||||
|
||||
### 뜨아각 (`iced_hot`)
|
||||
|
||||
@@ -239,6 +299,11 @@
|
||||
- 시간·요일 10%: 고정 100점
|
||||
- 점수 깎이는 조건: 없음
|
||||
- 반영 못 하는 것: 사람마다 달라서 재미로 봐 주세요
|
||||
- 점수 구간별 설명 (상세 창에 나옴):
|
||||
- 0~29점: 아침부터 22° 넘어요. 아직은 아아의 계절!
|
||||
- 30~59점: 아침이 살짝 선선해요. 아아 들다 손 시릴 수도?
|
||||
- 60~79점: 아침 공기가 차요. 오늘은 뜨아로 갈아탈 때!
|
||||
- 80~100점: 아침이 한 자릿수, 따뜻한 커피 없인 못 버텨요 ☕
|
||||
|
||||
### 빨래각 (`laundry`)
|
||||
|
||||
@@ -254,6 +319,11 @@
|
||||
- 시간·요일 5%: 고정 100점
|
||||
- 점수 깎이는 조건: 비 확률 60% 이상이면 0점
|
||||
- 반영 못 하는 것: 집 일조량은 반영하지 못해요
|
||||
- 점수 구간별 설명 (상세 창에 나옴):
|
||||
- 0~29점: 비 소식이 있어요. 오늘 빨래는 실내 건조로!
|
||||
- 30~59점: 눅눅하거나 쌀쌀해서 잘 안 말라요. 얇은 것만 널어요.
|
||||
- 60~79점: 잘 마르는 편이에요. 두꺼운 건 오후까지 두기!
|
||||
- 80~100점: 따뜻하고 보송한데 바람까지 솔솔, 이불 빨래 가능한 날 ☀️
|
||||
|
||||
### 자전거각 (`bike`)
|
||||
|
||||
@@ -269,6 +339,11 @@
|
||||
- 시간·요일 5%: 요일별 점수: 토 100, 일 100, 공휴일 100, 그 외 70
|
||||
- 점수 깎이는 조건: 비 확률 70% 이상이면 0점, 바람 10m/s 이상이면 0점
|
||||
- 반영 못 하는 것: 자전거 도로 공사는 반영하지 못해요
|
||||
- 점수 구간별 설명 (상세 창에 나옴):
|
||||
- 0~29점: 비가 오거나 바람이 10m/s 넘어요. 자전거는 쉬어요!
|
||||
- 30~59점: 맞바람이 세거나 기온이 애매해요. 짧은 코스만!
|
||||
- 60~79점: 탈 만해요! 강변은 바람 좀 부니 바람막이 챙기기.
|
||||
- 80~100점: 15~24°에 바람 잔잔, 멀리 달려도 좋은 날 🚲
|
||||
|
||||
### 멍뭉산책각 (`dog`)
|
||||
|
||||
@@ -284,6 +359,11 @@
|
||||
- 시간·요일 5%: 고정 100점
|
||||
- 점수 깎이는 조건: 체감 33° 이상이면 0점, 초미세먼지 75㎍/㎥ 이상이면 0점
|
||||
- 반영 못 하는 것: 노면 온도는 실측하지 못해요
|
||||
- 점수 구간별 설명 (상세 창에 나옴):
|
||||
- 0~29점: 체감 33° 넘거나 초미세먼지가 매우 나빠요. 발바닥도 폐도 위험, 실내 놀이로!
|
||||
- 30~59점: 덥거나 공기가 탁해요. 짧게 볼일만 보고 들어와요.
|
||||
- 60~79점: 산책 괜찮아요! 그늘 많은 길로 가요.
|
||||
- 80~100점: 5~22°에 공기 맑음, 멍멍이 신나는 날 🐶
|
||||
|
||||
### 김서림각 (`glasses`)
|
||||
|
||||
@@ -299,6 +379,11 @@
|
||||
- 시간·요일 5%: 고정 100점
|
||||
- 점수 깎이는 조건: 없음
|
||||
- 반영 못 하는 것: 실내 온도는 반영하지 못해요
|
||||
- 점수 구간별 설명 (상세 창에 나옴):
|
||||
- 0~29점: 아침이 15° 넘게 따뜻해요. 안경 김 걱정 없어요!
|
||||
- 30~59점: 실내 들어갈 때 살짝 뿌예질 수 있어요.
|
||||
- 60~79점: 출근길 안경에 김 서려요. 닦을 천 챙기기!
|
||||
- 80~100점: 영하권 아침에 습하기까지, 문 열자마자 앞이 하얘져요 👓
|
||||
|
||||
### 화장붕괴각 (`makeup`)
|
||||
|
||||
@@ -314,6 +399,11 @@
|
||||
- 시간·요일 5%: 고정 100점
|
||||
- 점수 깎이는 조건: 없음
|
||||
- 반영 못 하는 것: 피부 타입은 반영하지 못해요
|
||||
- 점수 구간별 설명 (상세 창에 나옴):
|
||||
- 0~29점: 선선하고 보송해요. 화장 하루 종일 버텨요!
|
||||
- 30~59점: 오후쯤 살짝 번들거릴 수 있어요.
|
||||
- 60~79점: 덥고 습해서 무너지기 쉬워요. 픽서 챙기기!
|
||||
- 80~100점: 30° 넘는 찜통에 습도까지, 기름종이 필수 🫠
|
||||
|
||||
### 냉면각 (`naengmyeon`)
|
||||
|
||||
@@ -329,6 +419,11 @@
|
||||
- 시간·요일 5%: 고정 100점
|
||||
- 점수 깎이는 조건: 없음
|
||||
- 반영 못 하는 것: 실제 주문량으로 검증하기 전이에요
|
||||
- 점수 구간별 설명 (상세 창에 나옴):
|
||||
- 0~29점: 점심이 18° 아래로 선선해요. 냉면보다 국밥!
|
||||
- 30~59점: 시원한 게 살짝 당기는 정도예요.
|
||||
- 60~79점: 점심에 덥네요. 냉면 한 그릇 생각나요!
|
||||
- 80~100점: 30° 넘는 한낮, 살얼음 동동 냉면 확정 🥶
|
||||
|
||||
### 택시대란각 (`taxi`)
|
||||
|
||||
@@ -344,6 +439,11 @@
|
||||
- 시간·요일 15%: 요일별 점수: 금 100, 토 100, 그 외 40
|
||||
- 점수 깎이는 조건: 없음
|
||||
- 반영 못 하는 것: 행사·공연 종료 시간은 반영하지 못해요
|
||||
- 점수 구간별 설명 (상세 창에 나옴):
|
||||
- 0~29점: 맑고 포근한 밤, 택시 금방 잡혀요.
|
||||
- 30~59점: 조금 기다릴 수 있어요. 앱 미리 켜두기!
|
||||
- 60~79점: 비나 추위로 택시 잡기 힘들어요. 막차 시간 확인!
|
||||
- 80~100점: 비 오는 추운 밤, 택시 전쟁이에요. 막차 타세요 🚕
|
||||
|
||||
### 배달폭주각 (`delivery`)
|
||||
|
||||
@@ -359,6 +459,11 @@
|
||||
- 시간·요일 10%: 요일별 점수: 금 100, 토 100, 일 100, 그 외 60
|
||||
- 점수 깎이는 조건: 없음
|
||||
- 반영 못 하는 것: 실제 배달 앱 지표로 검증하기 전이에요
|
||||
- 점수 구간별 설명 (상세 창에 나옴):
|
||||
- 0~29점: 날씨 멀쩡해요. 배달 평소처럼 와요.
|
||||
- 30~59점: 살짝 늦을 수 있어요.
|
||||
- 60~79점: 비나 추위로 주문이 몰려요. 일찍 시키기!
|
||||
- 80~100점: 비 오는 추운 저녁, 배달 한참 걸려요. 지금 바로 주문! 🛵
|
||||
|
||||
### 가드닝각 (`garden`)
|
||||
|
||||
@@ -374,6 +479,11 @@
|
||||
- 시간·요일 5%: 고정 100점
|
||||
- 점수 깎이는 조건: 비 확률 70% 이상이면 0점
|
||||
- 반영 못 하는 것: 식물 종류는 반영하지 못해요
|
||||
- 점수 구간별 설명 (상세 창에 나옴):
|
||||
- 0~29점: 비 소식이 있어요. 물 주기는 하늘에 맡겨요!
|
||||
- 30~59점: 춥거나 더워요. 화분은 안으로, 물은 조금만.
|
||||
- 60~79점: 화분 돌보기 괜찮아요. 아침에 물 듬뿍!
|
||||
- 80~100점: 12~25°의 보송한 아침, 분갈이까지 해도 되는 날 🌱
|
||||
|
||||
### 사진산책각 (`photo`)
|
||||
|
||||
@@ -389,6 +499,11 @@
|
||||
- 시간·요일 30%: 그날 노을 점수를 그대로 씀
|
||||
- 점수 깎이는 조건: 비 확률 80% 이상이면 0점
|
||||
- 반영 못 하는 것: 장소 혼잡도는 반영하지 못해요
|
||||
- 점수 구간별 설명 (상세 창에 나옴):
|
||||
- 0~29점: 비가 와요. 카메라는 쉬어요!
|
||||
- 30~59점: 노을이 약하거나 하늘이 흐려요. 골목 사진 위주로!
|
||||
- 60~79점: 노을이 꽤 기대돼요. 해 지기 30분 전에 나가요.
|
||||
- 80~100점: 노을 점수 높고 공기 맑음, 인생샷 각 📸
|
||||
|
||||
### 야구각 (`baseball`)
|
||||
|
||||
@@ -404,6 +519,11 @@
|
||||
- 시간·요일 10%: 요일별 점수: 월 10, 그 외 100
|
||||
- 점수 깎이는 조건: 비 확률 70% 이상이면 0점
|
||||
- 반영 못 하는 것: 경기 일정과 시즌(3~10월)은 반영하지 못해요
|
||||
- 점수 구간별 설명 (상세 창에 나옴):
|
||||
- 0~29점: 비 70% 넘어요. 우천 취소 각!
|
||||
- 30~59점: 쌀쌀하거나 비 기운이 있어요. 담요랑 우비 챙겨요.
|
||||
- 60~79점: 직관 괜찮아요! 밤엔 선선하니 겉옷 하나.
|
||||
- 80~100점: 15~25°에 비 걱정 없음, 응원가 목청껏 부르는 날 ⚾
|
||||
|
||||
### 공부각 (`study`)
|
||||
|
||||
@@ -419,6 +539,11 @@
|
||||
- 시간·요일 10%: 요일별 점수: 토 50, 일 50, 공휴일 50, 그 외 100
|
||||
- 점수 깎이는 조건: 없음
|
||||
- 반영 못 하는 것: 사람마다 달라서 재미로 봐 주세요
|
||||
- 점수 구간별 설명 (상세 창에 나옴):
|
||||
- 0~29점: 밖이 너무 좋아요. 공부는… 내일의 내가 할게요!
|
||||
- 30~59점: 나가고 싶은 마음 반, 공부 반이에요.
|
||||
- 60~79점: 밖이 애매해서 책상에 앉을 만해요.
|
||||
- 80~100점: 비 오고 춥거나 더워서 나갈 맛이 안 나요. 집중각 📚
|
||||
|
||||
### 넷플릭스각 (`netflix`)
|
||||
|
||||
@@ -434,6 +559,11 @@
|
||||
- 시간·요일 15%: 요일별 점수: 금 100, 토 100, 그 외 60
|
||||
- 점수 깎이는 조건: 없음
|
||||
- 반영 못 하는 것: 재미로 보는 지수예요
|
||||
- 점수 구간별 설명 (상세 창에 나옴):
|
||||
- 0~29점: 밤 공기가 좋아서 밖이 더 끌려요.
|
||||
- 30~59점: 한 편 정도 볼 만해요.
|
||||
- 60~79점: 비 오거나 쌀쌀한 밤, 이불 속이 최고!
|
||||
- 80~100점: 비 오는 주말 앞 밤, 정주행 시작각 🍿
|
||||
|
||||
### 군밤각 (`chestnut`)
|
||||
|
||||
@@ -449,4 +579,9 @@
|
||||
- 시간·요일 5%: 고정 100점
|
||||
- 점수 깎이는 조건: 없음
|
||||
- 반영 못 하는 것: 군밤 노점이 있는지는 반영하지 못해요
|
||||
- 점수 구간별 설명 (상세 창에 나옴):
|
||||
- 0~29점: 아직 18° 넘어요. 군밤은 조금 더 추워지면!
|
||||
- 30~59점: 저녁이 선선해졌어요. 군밤 노점이 슬슬 생각나요.
|
||||
- 60~79점: 손이 시려요. 따끈한 군밤 한 봉지!
|
||||
- 80~100점: 영하 가까운 저녁, 군밤 품고 걷는 날 🌰
|
||||
|
||||
@@ -146,7 +146,7 @@ code{font-family:var(--mono);font-size:12.5px;background:var(--soft-db);padding:
|
||||
<div style="--c:var(--kma)"><dt>중기예보</dt><dd>4~10일 뒤 오전·오후 날씨(맑음·구름·흐림·비)와 최저·최고기온</dd></div>
|
||||
<div style="--c:var(--kma)"><dt>기상특보</dt><dd>최근 7일 구역별 특보 종류(강풍·호우 등)와 단계</dd></div>
|
||||
<div style="--c:var(--air)"><dt>미세먼지</dt><dd>전국 측정소별 PM10·PM2.5 농도와 등급</dd></div>
|
||||
<div style="--c:var(--om)"><dt>층별 구름</dt><dd>3일치 낮은·중간·높은 구름 양(%), 예보 모델 4개(ECMWF·GFS·JMA·ICON)</dd></div>
|
||||
<div style="--c:var(--om)"><dt>층별 구름</dt><dd>3일치 낮은·중간·높은 구름 양(%), 해 지는·뜨는 쪽 20·100km 지점, 예보 모델 2개(일본 JMA·독일 ICON)</dd></div>
|
||||
<div style="--c:var(--tour)"><dt>축제·행사</dt><dd>행사 이름·장소·시작일·종료일</dd></div>
|
||||
<div style="--c:var(--kasi)"><dt>공휴일·절기</dt><dd>그해 공휴일과 24절기의 날짜·이름</dd></div>
|
||||
</dl>
|
||||
@@ -174,6 +174,7 @@ code{font-family:var(--mono);font-size:12.5px;background:var(--soft-db);padding:
|
||||
<tr><td>미세먼지</td><td><span class="chip" style="--c:var(--air)">에어코리아 실시간</span></td><td>전국</td><td>매시 <span class="mono">:20</span></td><td><code>air_quality</code></td><td><code>air:tried</code> 10분</td></tr>
|
||||
<tr><td>측정소 위치</td><td><span class="chip" style="--c:var(--air)">에어코리아 측정소</span></td><td>전국</td><td>처음 + 매일 03:00</td><td><code>air_station</code></td><td>—</td></tr>
|
||||
<tr><td>층별 구름 (노을·일출)</td><td><span class="chip" style="--c:var(--om)">Open-Meteo</span></td><td>좌표 24개씩</td><td>오전 · 13시 · 21시 시간대마다 1번</td><td><code>cloud_hourly</code></td><td><code>sky:</code> 표시 24시간</td></tr>
|
||||
<tr><td>자외선·가시거리·일조 등</td><td><span class="chip" style="--c:var(--om)">Open-Meteo</span></td><td>전국 256곳</td><td>6시간마다 03·09·15·21시 10분 (worker)</td><td><code>openmeteo_hourly</code></td><td>—</td></tr>
|
||||
<tr><td>축제·행사</td><td><span class="chip" style="--c:var(--tour)">TourAPI</span></td><td>시도 1곳</td><td>그 시도 하루 1번</td><td><code>event</code></td><td><code>event:</code> 표시 24시간</td></tr>
|
||||
<tr><td>공휴일 · 24절기</td><td><span class="chip" style="--c:var(--kasi)">천문연</span></td><td>1년치</td><td>그해 값이 없을 때</td><td><code>holiday</code> <code>solar_term</code></td><td>표시 30일</td></tr>
|
||||
<tr><td>해 뜨고 지는 시각</td><td><span class="chip" style="--c:var(--kasi)">서버 계산</span></td><td>구 1곳</td><td>그날 값이 없을 때</td><td><code>sun_time</code></td><td>—</td></tr>
|
||||
@@ -211,22 +212,14 @@ code{font-family:var(--mono);font-size:12.5px;background:var(--soft-db);padding:
|
||||
|
||||
<h2 style="margin-top:22px">이렇게 나눠서 감수하는 것</h2>
|
||||
<div class="warns">
|
||||
<div class="warn"><div class="tag doc">장애</div><p>외부 기관 5곳(기상청·에어코리아·Open-Meteo·TourAPI·천문연)에 기대므로 어느 한 곳이 멈추면 그 칸이 빠집니다. 별개로, 지금은 응답 없는 API를 너무 오래 기다려서 기상청이 멈추면 피드를 연 사람 일부가 100초 가까이 기다립니다. 이건 출처 수가 아니라 기다리는 방식의 문제라, Open-Meteo 하나로 바꿔도 똑같이 생깁니다. 출시 전에 "빨리 포기하고 저장된 값 보여주기"로 고칠 예정입니다(운영 점검 보고서 참고).</p></div>
|
||||
<div class="warn"><div class="tag doc">장애</div><p>외부 기관 5곳(기상청·에어코리아·Open-Meteo·TourAPI·천문연)에 기대므로 어느 한 곳이 멈추면 그 칸이 빠집니다. 기관이 멈추면 8초까지만 기다린 뒤 저장해 둔 값을 보여주고, 그 기관은 2분 동안 다시 부르지 않습니다. 그래서 멈춘 동안 기다리는 사람은 기관마다 2분에 한 명꼴입니다.</p></div>
|
||||
<div class="warn"><div class="tag doc">먼 날짜</div><p>4~10일 뒤는 중기예보라 도 단위·오전/오후로만 나옵니다. 그래서 주말까지 4일 넘게 남은 월·화요일에는 주말 플랜에 "15~19시 비" 같은 시간대를 넣을 수 없습니다. Open-Meteo는 이 기간도 1시간 단위로 주는데, 그걸 포기한 셈입니다.</p></div>
|
||||
<div class="warn"><div class="tag doc">유료 결정</div><p>노을 구름 때문에 출시 전에 Open-Meteo 유료 여부를 정해야 합니다.</p></div>
|
||||
</div>
|
||||
<p class="hit"><b>다시 볼 때</b>: 정확도 비교(TODO)에서 Open-Meteo가 뚜렷하게 더 맞는다고 나오면 다시 검토합니다. 그래도 1번 이유(특보와 엇갈림)는 남기 때문에 통일보다는 4~10일 뒤만 Open-Meteo로 받는 방식이 먼저 후보입니다.</p>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<h2>확인이 필요한 것</h2>
|
||||
<p class="sub">코드를 읽다가 발견한 점입니다. 고치지는 않았습니다.</p>
|
||||
<div class="warns">
|
||||
<div class="warn"><div class="tag doc">문서 차이</div><p><code>data-pipeline.md</code>와 코드가 다른 곳: 실패 시 5분 캐시와 <code>rank:sunset</code> 키는 코드에 없고, 각 점수는 저장 직후가 아니라 조회할 때 계산합니다. 중기예보 신선도는 DB가 아니라 Redis 표시로 판단합니다.</p></div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<p class="foot">기준: backend 코드 (services/, scheduler/jobs.py, router/v1/), 2026-10-06.</p>
|
||||
<p class="foot">기준: backend 코드 (services/, scheduler/jobs.py, router/v1/), 2026-10-07.</p>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
File renamed without changes.
@@ -242,7 +242,7 @@
|
||||
|
||||
## 8. 피드 묶기 (2026-10-02 다시 기획, 확정)
|
||||
|
||||
자세한 기획: `docs/피드기획_v2.html`. 백엔드 동작: `backend/docs/data-pipeline.md` "그날 피드".
|
||||
자세한 기획: `docs/피드_기획.html`. 백엔드 동작: `docs/데이터_흐름.html`.
|
||||
|
||||
| 단계 | 로직 |
|
||||
|---|---|
|
||||
File renamed without changes.
@@ -2,7 +2,7 @@
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com">
|
||||
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=IBM+Plex+Sans+KR:wght@400;500;700&family=IBM+Plex+Mono:wght@400;500&display=swap">
|
||||
<style>
|
||||
/* 레이아웃: 요약 표 → 타입별 카드(켜지는 조건 · 본문 · 슬라이드 · 데이터 · 문제). 데이터흐름.html 과 같은 토큰. */
|
||||
/* 레이아웃: 요약 표 → 타입별 카드(켜지는 조건 · 본문 · 슬라이드 · 데이터 · 문제). 데이터_흐름.html 과 같은 토큰. */
|
||||
:root{
|
||||
--bg:#f5f7f9; --panel:#ffffff; --fg:#17212b; --muted:#5d6b78; --line:#d9e0e6; --grid:#e9eef2;
|
||||
--accent:#2f6fd6; --warn:#a4400f; --soft-warn:#fdefe6; --soft:#eef3fb;
|
||||
@@ -60,7 +60,7 @@ ul{margin:0;padding-left:18px}
|
||||
<tr><td>2 각</td><td>항상 3장 (1~3위)</td><td>내일 점수와 오늘 대비 (없으면 하기 좋은 시간)</td><td>각 그림·점수·설명</td><td>새 정보</td></tr>
|
||||
<tr><td>3 노을</td><td>노을 점수가 있을 때</td><td>다음 날 노을 점수</td><td>노을 점수·시각 + 가까운 명소</td><td>새 정보</td></tr>
|
||||
<tr><td>4 계절 소식</td><td>그날 고른 글이 있을 때</td><td>글 둘째 문단</td><td>글 첫 문단</td><td>괜찮음</td></tr>
|
||||
<tr><td>5 축제·행사</td><td>30km 안, 7일 안에 열리는 행사 1~3위</td><td>"지금 진행 중 · 여기서 12km · 토요일 맑음 22°"</td><td>사진 + 장소·기간</td><td>새 정보</td></tr>
|
||||
<tr><td>5 축제·행사</td><td>30km 안, 7일 안에 열리는 행사 3장 (축제→팝업→전시→콘서트 차례로 섞음)</td><td>"지금 진행 중 · 여기서 12km · 토요일 맑음 22°"</td><td>사진 + 장소·기간</td><td>새 정보</td></tr>
|
||||
<tr><td>6 날씨 상식</td><td>그날 고른 글이 있을 때</td><td>글 둘째 문단</td><td>글 첫 문단</td><td>괜찮음</td></tr>
|
||||
<tr><td>7 주말 예보</td><td>주말 예보가 있을 때</td><td>"이번 주말은 ○○만 챙기면 돼요…"</td><td>토·일 비교 + 옷차림·우산 팁</td><td>괜찮음</td></tr>
|
||||
<tr><td>8 생활 알림</td><td>비 40% 이상 또는 특보</td><td>특보 종류별 할 일 / 비는 우산 크기</td><td>특보·비 시각 표</td><td>새 정보</td></tr>
|
||||
@@ -80,10 +80,10 @@ ul{margin:0;padding-left:18px}
|
||||
<article class="type">
|
||||
<header><span class="no">5 EVENT</span><h3>축제·행사</h3></header>
|
||||
<dl>
|
||||
<dt>켜지는 조건</dt><dd>내 지역 중심에서 30km 안(시도 상관없음, 좌표 없는 행사는 같은 시도)에서 오늘부터 7일 안에 열려 있는 행사가 순위만큼 있을 때. 피드에 최대 3장이 무작위 자리에 끼워집니다 (<code>feed_service.py:353</code>).</dd>
|
||||
<dt>슬라이드</dt><dd>행사 사진(없으면 아이콘), 머리말 "가까운 행사 · 진행 중/곧 시작", 행사 이름, 표(장소 — 비어 있으면 뺌, 기간 <code>10.5~10.11</code>).</dd>
|
||||
<dt>켜지는 조건</dt><dd>내 지역 중심에서 30km 안(시도 상관없음, 좌표 없는 행사는 같은 시도)에서 오늘부터 7일 안에 열려 있는 행사가 순위만큼 있을 때. 축제→팝업→전시→콘서트 차례로 한 장씩 돌아가며 고르고(같은 종류 안에서는 시작일이 가까운 순, 없는 종류는 건너뜀), 피드에 최대 3장이 무작위 자리에 끼워집니다 (<code>week_service.py</code> <code>mix_kinds</code>). 띠의 행사 4개도 같은 방식.</dd>
|
||||
<dt>슬라이드</dt><dd>행사 사진(없으면 종류별 아이콘: 축제 불꽃·팝업 쇼핑백·전시 액자·콘서트 마이크), 머리말 "가까운 행사 · 진행 중/곧 시작", 행사 이름, 표(장소 — 비어 있으면 뺌, 기간 <code>10.5~10.11</code>).</dd>
|
||||
<dt>본문</dt><dd>진행 상태·거리(<code>distance_km</code>)·그날 날씨(<code>fit</code>) 중 있는 것을 이어 붙임: "지금 진행 중 · 여기서 12km · 토요일 맑음 22°". 진행 중이 아니고 거리·날씨가 다 없으면 "일정이 확정됐어요." 또는 "올해 정확한 일정은 공식 안내로 확인해 주세요." (<code>feed_service.py</code> <code>_event_caption</code>)</dd>
|
||||
<dt>데이터</dt><dd>TourAPI 행사·문화정보원 전시(<code>event</code> 테이블): 이름·장소·시작일·종료일·사진·좌표·일정 확정 여부. 시도 단위로 받으므로 반경에 걸칠 수 있는 주변 시도(구 중심 50km 안)까지 같이 받습니다 (<code>week_service.py</code> <code>nearby_sidos</code>). 그날 날씨는 기상청 중기예보.</dd>
|
||||
<dt>데이터</dt><dd><code>event</code> 테이블(<code>kind</code> 1=축제 2=전시 3=콘서트 4=팝업): TourAPI 축제, 문화정보원 전시·음악/콘서트, 팝가(popga.co.kr) 팝업스토어. 이름·장소·시작일·종료일·사진(팝업은 없음)·좌표. 워커가 7일마다(월 04:00) 전국 17개 시도를 받아 두고, 끝나면 Teams 로 알립니다 (<code>scheduler/jobs.py</code> <code>refresh_events</code>). 화면을 열 때는 받지 않습니다. 반경에 걸칠 수 있는 주변 시도(구 중심 50km 안)까지 같이 봅니다 (<code>nearby_sidos</code>). 그날 날씨는 기상청 중기예보.</dd>
|
||||
</dl>
|
||||
<div class="issue"><b>남은 것:</b> 행사 소개글은 <code>event</code> 테이블에 칸이 없어서 지금은 보여 줄 수 없습니다. TourAPI 상세 조회에는 소개글이 있습니다.</div>
|
||||
</article>
|
||||
@@ -112,7 +112,7 @@ td .note{display:block;color:var(--muted);font-size:12px;margin-top:3px;line-hei
|
||||
|
||||
<article class="card">
|
||||
<header><h3>오늘의 각 1·2·3위</h3><span class="kind">핵심 콘텐츠 · 3장</span><span class="state always">항상</span></header>
|
||||
<dl><dt>보여 주는 것</dt><dd>그날 하루 기준 순위(확정). 100점은 완벽한 조건(예: 기온 22°·습도 30%·미풍)에만 주고, 편한 범위 안이라도 최적값에서 멀면 깎이며 가장 나쁜 요인이 전체를 끌어내립니다(확정, 10/6). 점수, 하기 좋은 시간, 이유 한 줄, 보낼 문구("치맥 한잔 할래?").</dd></dl>
|
||||
<dl><dt>보여 주는 것</dt><dd>그날 하루 기준 순위(확정). 100점은 완벽한 조건(예: 기온 22°·습도 30%·미풍)에만 주고, 편한 범위 안이라도 최적값에서 멀면 깎이며 가장 나쁜 요인이 전체를 끌어내립니다(확정, 10/2). 점수, 하기 좋은 시간, 이유 한 줄, 보낼 문구("치맥 한잔 할래?").</dd></dl>
|
||||
<dl><dt>① 유저</dt><dd>날씨 숫자 대신 "오늘 뭐 하면 좋은지"를 받습니다.</dd></dl>
|
||||
<dl><dt>② 운영</dt><dd>다른 날씨 서비스에 없는 우리만의 콘텐츠. 각마다 상세 페이지가 검색에 걸립니다.</dd></dl>
|
||||
</article>
|
||||
@@ -133,7 +133,7 @@ td .note{display:block;color:var(--muted);font-size:12px;margin-top:3px;line-hei
|
||||
|
||||
<article class="card">
|
||||
<header><h3>주말 예보</h3><span class="kind">계획</span><span class="state always">매일</span></header>
|
||||
<dl><dt>켜지는 때</dt><dd>평일에도 매일(확정, 10/6). 첫 장은 이번 주말, 다음 주말은 예보가 닿는 날(오늘+10일, 수요일쯤)부터 두 번째 장으로 붙습니다. 토·일 최저→최고 기온, 비 확률, 일교차를 나란히 비교하고 "토·일 둘 다 맑음! 나들이 확정각"처럼 한 줄로 정리합니다. 아래에 옷차림·우산 팁 하나(비 > 더위 > 추위 > 일교차 순으로 하나만, 10/6 변경).</dd></dl>
|
||||
<dl><dt>켜지는 때</dt><dd>평일에도 매일(확정, 10/2). 첫 장은 이번 주말, 다음 주말은 예보가 닿는 날(오늘+10일, 수요일쯤)부터 두 번째 장으로 붙습니다. 토·일 최저→최고 기온, 비 확률, 일교차를 나란히 비교하고 "토·일 둘 다 맑음! 나들이 확정각"처럼 한 줄로 정리합니다. 아래에 옷차림·우산 팁 하나(비 > 더위 > 추위 > 일교차 순으로 하나만, 10/6 변경).</dd></dl>
|
||||
<dl><dt>① 유저</dt><dd>주말 약속 날을 정하는 근거가 됩니다.</dd></dl>
|
||||
<dl><dt>② 운영</dt><dd>단톡방에 공유되는 카드. 목·금 방문이 늘어납니다.</dd></dl>
|
||||
</article>
|
||||
@@ -147,7 +147,7 @@ td .note{display:block;color:var(--muted);font-size:12px;margin-top:3px;line-hei
|
||||
|
||||
<article class="card">
|
||||
<header><h3>행사·축제</h3><span class="kind">나들이 · 최대 3장</span><span class="state cond">조건부</span></header>
|
||||
<dl><dt>켜지는 때</dt><dd>그 시도에서 7일 안에 열리는 행사가 있을 때. 가까운 순으로 최대 3장을 각각 독립 카드로, 다른 카드 사이사이 무작위 자리에 넣습니다. 자리는 하루 동안 그대로입니다(확정, 10/6). 그날 날씨와 같이 보여 줍니다("토요일 맑음, 갈 만해요").</dd></dl>
|
||||
<dl><dt>켜지는 때</dt><dd>30km 안에서 7일 안에 열리는 행사(축제·팝업·전시·콘서트)가 있을 때. 종류를 축제→팝업→전시→콘서트 차례로 섞어(같은 종류 안에서는 가까운 순) 최대 3장을 각각 독립 카드로, 다른 카드 사이사이 무작위 자리에 넣습니다. 자리는 하루 동안 그대로입니다(확정, 10/2). 그날 날씨와 같이 보여 줍니다("토요일 맑음, 갈 만해요").</dd></dl>
|
||||
<dl><dt>① 유저</dt><dd>날씨 좋은 날 갈 곳을 얻습니다.</dd></dl>
|
||||
<dl><dt>② 운영</dt><dd>"○○ 축제 날씨" 검색 유입.</dd></dl>
|
||||
</article>
|
||||
@@ -213,10 +213,10 @@ td .note{display:block;color:var(--muted);font-size:12px;margin-top:3px;line-hei
|
||||
<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">6</span><p>카드마다 보낼 문구가 있고, 보내면 카드 그대로 이미지+링크로 갑니다(확정).</p></div>
|
||||
<div><span class="n">7</span><p>UI는 따로 고민하지 않고 인스타그램·페이스북 방식을 그대로 따릅니다(확정, 10/6).</p></div>
|
||||
<div><span class="n">8</span><p>지역은 날씨를 가져오는 시군구 단위 그대로입니다. 수원시 장안구 같은 일반구도 따로 봅니다(확정, 10/6, 256곳).</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>
|
||||
</section>
|
||||
|
||||
<p class="foot">근거: docs/콘텐츠설계서.md, docs/콘텐츠구현기획.md 8장, 2026-09-30·2026-10-06 회의 확정 사항(docs/meetings/2026-10-06.md). 버전 v2.3, 2026-10-06. 카드 10종으로 진행, 추가 카드는 나중에.</p>
|
||||
<p class="foot">근거: docs/콘텐츠_설계서.md, docs/콘텐츠_구현기획.md 8장, 2026-09-30·2026-10-02 회의 확정 사항(docs/meetings/2026-10-02.md). 버전 v2.3, 2026-10-06. 카드 10종으로 진행, 추가 카드는 나중에.</p>
|
||||
</div>
|
||||
+141
@@ -0,0 +1,141 @@
|
||||
# 피드 동작 방식: 만들기 · 순서 · 갱신
|
||||
|
||||
기준: `backend/services/feed_service.py`, `backend/services/index_service.py`, `backend/scheduler/jobs.py`, `backend/router/v1/feed/feed.py` (2026-10-07)
|
||||
|
||||
## 한 줄 요약
|
||||
|
||||
새벽 3시에 **전국 공통 틀(칸 19개)**을 DB에 만들고, 누가 피드를 열 때 **그 구의 데이터로 칸을 채워** Redis에 잠깐 둔다. 좋아요·댓글 수는 매번 DB에서 새로 읽어 덮어쓴다.
|
||||
|
||||
```
|
||||
[03:00 worker] ── 틀 19칸 → PostgreSQL post
|
||||
└─ Redis feed:* 전부 삭제
|
||||
|
||||
[사용자가 /v1/feed?region=구]
|
||||
① Redis feed:{구}:{시간대} 있음? ── 있으면 ⑤로
|
||||
② 틀이 없으면 지금 만든다 (03:00 작업을 놓쳤을 때 대비)
|
||||
③ 재료 7가지를 동시에 모은다 (오래됐으면 외부 API로 갱신)
|
||||
④ 칸마다 채우고, 시간대 순서로 놓는다 → Redis에 저장
|
||||
⑤ 좋아요·댓글 수, 내가 누른 표시를 DB에서 읽어 덮어쓴다 → 응답
|
||||
```
|
||||
|
||||
## 1. 틀 만들기 (하루 한 번, 전국 공통)
|
||||
|
||||
- **언제**: 매일 03:00 worker가 `build_feed_day`를 돌린다. 하루는 03:00에 시작해 다음 날 03:00에 끝난다.
|
||||
피드 요청이 올 때마다 같은 함수가 한 번 더 돈다. 이미 있는 칸은 그대로 두고, 빠진 칸(03:00 작업을 놓쳤거나 배포로 새 종류가 생긴 경우)만 더한다.
|
||||
- **어디에**: PostgreSQL `post` 테이블에 하루 19줄.
|
||||
- **한 줄에 들어가는 것**: 글 번호, 날짜, 칸 번호, 종류, 같은 종류 중 몇 번째인지, 유효 시간, 좋아요·댓글 수.
|
||||
계절 소식·날씨 상식 칸만 그날 보여줄 글 번호를 미리 정해 둔다(날짜마다 돌아가며).
|
||||
- **들어가지 않는 것**: 점수, 문장, 숫자 같은 내용. 내용은 구마다 다르므로 열 때 채운다.
|
||||
|
||||
| 칸 | 종류 | 몇 번째 | 켜지는 조건 (채울 때 판단) |
|
||||
|---|---|---|---|
|
||||
| 1 | 오늘·내일 날씨 | | 오늘 예보가 있으면 |
|
||||
| 2 | 생활 알림(특보) | | 그 구에 특보가 있을 때 |
|
||||
| 3~5 | 오늘의 각 | 1·2·3위 | 각 점수가 있으면 |
|
||||
| 6 | 노을 | | 노을 계산이 있으면. 하늘 상황으로 말하고, 결론이 '쉬어요'(구름에 가려요·낮은 구름이 덮어요)면 한 줄 카드 |
|
||||
| 7 | 내일 미리보기 | | 저녁·밤에만 |
|
||||
| 8 | 주말 예보 | | 주말 예보가 있으면 |
|
||||
| 9, 13, 14 | 가까운 행사 | 1·2·3번째 | 7일 안에 열리는 행사가 그만큼 있으면 |
|
||||
| 10 | 계절 소식 | | 그날 고른 글 |
|
||||
| 11 | 날씨 상식 | | 그날 고른 글 |
|
||||
| 12 | 한 문장 | | 그날 날씨에 맞는 글 |
|
||||
| 15·16 | 주말 플랜 | 토·일 | 주말 예보가 있으면 |
|
||||
| 17 | 미세먼지 | | 측정값이 3시간 안이면 |
|
||||
| 18 | 당일치기 | | 1~2시간 거리 후보 도시 1위가 있으면 |
|
||||
| 19 | 오늘 밤 달 | | 늘 켜짐. 보름·삭인 밤이면 그 이야기, 아니면 달 모양·밝기·다음 보름 |
|
||||
|
||||
## 2. 칸 채우기 (누가 열 때, 구마다)
|
||||
|
||||
### 재료 모으기
|
||||
아래 7가지를 동시에 모은다. 각 재료는 먼저 DB를 보고, 오래됐을 때만 외부 API를 부른다(외부 API가 멈추면 8초까지만 기다리고 저장된 값으로 간다).
|
||||
|
||||
| 재료 | 가져오는 곳 (DB) | 외부 출처 |
|
||||
|---|---|---|
|
||||
| 오늘·내일 3시간 칸 | `weather_hourly` | 기상청 단기예보 |
|
||||
| 지금 날씨(2시간 비·출퇴근·미세먼지·특보) | Redis `ultra:{구}`, `air_quality`, `weather_warning` | 기상청 초단기·특보, 에어코리아 |
|
||||
| 노을 | `sky_score` | Open-Meteo 구름 |
|
||||
| 각 점수 27개 | `index_score` | (위 재료로 계산) |
|
||||
| 열흘 날씨 | `weather_daily` | 기상청 단기·중기 |
|
||||
| 행사 | `event` | TourAPI, 문화정보 |
|
||||
| 당일치기 | 후보 도시들의 위 재료 | 같음 |
|
||||
|
||||
그 밖에 주말 일몰 시각(`sun_time`, 서버 계산), 앞으로 이틀 시간별 예보(`weather_hourly`), 오늘의 틀(`post`), 글(`article`)을 읽는다.
|
||||
|
||||
### 칸마다 채우기
|
||||
틀의 19칸을 하나씩 보며, 종류에 맞는 재료로 제목·캡션·슬라이드를 만든다. **채울 재료가 없거나 켜지는 조건이 아니면 그 칸은 빠진다.**
|
||||
예) 분당구 10/7 아침: 19칸 중 17개가 채워졌다. 특보(없음)와 내일 미리보기(저녁부터)가 빠졌다.
|
||||
|
||||
### 순서 정하기 (언제 순위가 바뀌나)
|
||||
|
||||
**시간대 4개** (구마다 그날 일몰 시각으로 나눈다)
|
||||
|
||||
| 시간대 | 시각 | 예: 분당구 10/7 (일몰 18:05) |
|
||||
|---|---|---|
|
||||
| 아침 | 05:00~11:00 | 05:00~11:00 |
|
||||
| 낮 | 11:00~일몰 2시간 전 | 11:00~16:05 |
|
||||
| 저녁 | 일몰 2시간 전~21:00 | 16:05~21:00 |
|
||||
| 밤 | 21:00~다음 날 05:00 | 21:00~05:00 |
|
||||
|
||||
시간대가 바뀌면 캐시 키(`feed:{구}:{시간대}`)가 달라져서 그 순간 새 순서로 다시 만들어진다.
|
||||
|
||||
**시간대별 기본 순서** (`ORDER`). 목록에 없는 종류는 그 시간대에 꺼진다.
|
||||
|
||||
| 시간대 | 순서 (히어로 아래 '오늘·내일 날씨' 다음부터) |
|
||||
|---|---|
|
||||
| 아침 | 특보 → 미세먼지 → 각 1·2·3 → 계절 소식 → 노을 → 날씨 상식 → 주말 예보 → 주말 플랜(토) → 주말 플랜(일) → 당일치기 → 달 → 한 문장 |
|
||||
| 낮 | 각 → 특보 → 미세먼지 → 각 → 각 → 노을 → 주말 예보 → 주말 플랜 → 계절 소식 → 주말 플랜 → 당일치기 → 날씨 상식 → 달 → 한 문장 |
|
||||
| 저녁 | 노을 → 각 → 특보 → 각 → 각 → 미세먼지 → 내일 미리보기 → 주말 예보 → 주말 플랜 → 계절 소식 → 주말 플랜 → 당일치기 → 날씨 상식 → 달 → 한 문장 |
|
||||
| 밤 | 내일 미리보기 → 특보 → 노을 → 주말 예보 → 각 → 주말 플랜 → 각 → 각 → 주말 플랜 → 당일치기 → 미세먼지 → 계절 소식 → 날씨 상식 → 달 → 한 문장 |
|
||||
|
||||
뜻: 아침엔 "나가기 전에 볼 것"(특보·공기·오늘 각), 낮엔 각을 맨 위로, 저녁엔 노을을 맨 위로, 밤엔 내일 준비(내일 미리보기)와 주말 계획을 앞으로. 내일 미리보기는 저녁·밤에만 나온다.
|
||||
|
||||
**기본 순서 위에 덧붙는 규칙**
|
||||
1. **특보가 있으면** 맨 위(히어로 바로 아래), 그다음 오늘·내일 날씨. 특보가 없으면 날씨가 맨 위.
|
||||
2. **금요일 저녁**엔 주말 예보를 노을 바로 다음(2번째)으로 올린다.
|
||||
3. **저녁에 해가 진 뒤**엔 노을 카드가 내일 노을로 바뀌고, 맨 위에서 세 번째로 내려간다.
|
||||
4. **밤**엔 한 문장을 맨 끝으로.
|
||||
5. **같은 종류가 붙으면** 뒤에서 다른 종류를 당겨 끼운다(각·각·각이 연달아 나오지 않게).
|
||||
6. **행사 카드(최대 3장)**는 위 순서와 따로, "날짜+구"를 씨앗으로 고른 자리에 끼운다. 같은 날 같은 구는 시간대가 바뀌어도 늘 같은 몇 번째 자리에 들어간다.
|
||||
7. 켜지는 조건이 안 맞는 칸(특보 없음, 행사 없음 등)은 빠지고 뒤 칸이 당겨진다.
|
||||
|
||||
**각 카드 3장의 순서**
|
||||
- 어떤 각이 들어가나: 그 구의 오늘 점수 1·2·3위(점수 높은 순, `index_service`).
|
||||
- 셋끼리 순서: "지금 시각에서 하기 좋은 시간대가 가장 가까운 각"이 먼저. 하기 좋은 시간이 오늘 이미 지난 각은 뒤로. 예) 오후 3시면 저녁 6시부터인 야장각이 아침 7시까지인 뜨아각보다 앞.
|
||||
- 각 점수와 순위 자체는 새 예보·미세먼지가 들어올 때 다시 계산되므로(하루 8번 예보 + 매시 미세먼지), 그때 캐시가 끝나면 1·2·3위가 바뀔 수 있다.
|
||||
|
||||
**히어로·띠의 순서**
|
||||
- 오늘의 각 줄(27개)과 띠의 각 순위(5개): 오늘 점수 높은 순.
|
||||
- 히어로 1위 각: 오늘 점수 1위.
|
||||
- 띠의 행사: 30km 안 행사 중 시작일이 오늘과 가까운 순(같으면 가까운 거리 순) 4개. 계절 소식: 이번 주 글.
|
||||
|
||||
### 같이 만드는 것
|
||||
- 히어로: 지금 기온·체감, 불쾌지수, 날씨 점수, 1위 각, 말풍선, 오늘 밤 달 모양·밝기
|
||||
- 오늘의 각 줄: 27개 이름·점수·순위
|
||||
- 띠: 행사 4개, 각 순위 5개, 계절 소식
|
||||
|
||||
## 3. 저장과 갱신
|
||||
|
||||
### Redis에 저장 (완성본)
|
||||
- 키: `feed:{구 코드}:{시간대}` (예: `feed:4113500000:morning`)
|
||||
- DB에는 완성본을 저장하지 않는다. Redis가 비어도 DB의 틀과 재료로 다시 만든다.
|
||||
- **얼마나 두나**: 다음에 내용이 바뀌는 시각까지, 최대 1시간.
|
||||
바뀌는 시각 = 03:00, 05시, 11시, 일몰 2시간 전, 일몰, 21시, 다음 단기예보 제공 시각, 매시 20분(미세먼지)
|
||||
- **재료 중 하나라도 못 가져왔으면 60초**만 둔다. 다음 요청이 다시 채우게 하려고.
|
||||
|
||||
### 언제 새로 만들어지나
|
||||
| 상황 | 어떻게 |
|
||||
|---|---|
|
||||
| 캐시 시간이 끝남 | 다음 요청이 ③④를 다시 해서 새 완성본을 만든다 |
|
||||
| 시간대가 바뀜 | 키가 달라지므로(`morning` → `day`) 새로 만든다 |
|
||||
| 03:00 | worker가 새 날 틀을 만들고 `feed:*`를 전부 지운다 |
|
||||
| 배포로 새 종류의 칸이 생김 | 다음 요청 때 빠진 칸만 그날 틀에 더해진다(이미 있는 칸은 그대로). 캐시가 끝난 뒤부터 보인다 |
|
||||
| 예보·미세먼지가 새로 들어옴 | 캐시가 끝나는 시각(예보 제공 시각·매시 20분)에 맞춰 다시 만들어져 각 점수·순위·문장이 바뀐다 |
|
||||
|
||||
### 매번 새로 읽는 것
|
||||
좋아요·댓글 수와 "내가 눌렀는지"는 캐시된 완성본을 쓰더라도 응답 직전에 DB에서 읽어 덮어쓴다(`router/v1/feed/feed.py`). 그래서 좋아요는 바로 반영된다.
|
||||
|
||||
## 4. 알아 둘 점
|
||||
|
||||
- **좋아요·댓글은 전국이 같은 글에 쌓인다.** 글 번호가 전국 공통이라, 분당구의 "각 1위(환기각)"와 마포구의 "각 1위(야장각)"가 같은 글 번호를 쓴다.
|
||||
- **공유 링크(`/v1/feed/post/{id}`)는 지금 그 구의 피드에서 글을 찾는다.** 어제 글이나 지금 꺼진 글은 "없는 글"이 된다. 공유한 글을 다시 보여줄 계획이 생기면 그때 공유한 글만 따로 저장한다.
|
||||
- **아무도 안 여는 구는 만들지 않는다.** 외부 API 호출도 그 구를 누가 열 때만 일어난다.
|
||||
@@ -147,5 +147,5 @@ code{font-family:var(--mono);font-size:12.5px;background:var(--soft);padding:1px
|
||||
<p>좋아요·댓글·프로필은 사용자가 만든 실제 값입니다.</p>
|
||||
</section>
|
||||
|
||||
<p class="foot">기준: main a7220b2, 2026-10-06. 상세 흐름은 docs/데이터흐름.html.</p>
|
||||
<p class="foot">기준: main a7220b2, 2026-10-06. 상세 흐름은 docs/데이터_흐름.html.</p>
|
||||
</div>
|
||||
@@ -1,17 +0,0 @@
|
||||
{
|
||||
"detector": {
|
||||
"ignoreRules": [],
|
||||
"ignoreFiles": [],
|
||||
"ignoreValues": [
|
||||
{
|
||||
"rule": "side-tab",
|
||||
"value": "*",
|
||||
"files": [
|
||||
"src/a/APages.tsx"
|
||||
],
|
||||
"createdAt": "2026-09-29T13:18:15.447Z",
|
||||
"reason": "model triage: border-r-4 border-black are cell dividers of the A poster-grid wall (user-chosen A 포스터 그리드), not colored side accents"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -1 +0,0 @@
|
||||
{"version":1,"sessions":{"8dca1a79-a5f0-4a96-a6a0-46a1ea37b382":{"updatedAt":1790727492068,"files":{"/Users/minachoi/orca/workspaces/o2o-weather/main-2/frontend/src/a/APages.tsx":{"editCount":2,"findings":[],"stopBaseline":{"version":1,"engine":"0.1.5","counts":{}},"cleanAcked":true}},"footerShown":true},"9c398292-16d6-4b79-a132-a0f1dcfae041":{"updatedAt":1790905454036,"files":{"/Users/minachoi/orca/workspaces/o2o-weather/main-2/frontend/src/b/b.css":{"editCount":1,"findings":[],"stopBaseline":{"version":1,"engine":"0.1.5","counts":{}},"cleanAcked":true},"/Users/minachoi/orca/workspaces/o2o-weather/main-2/frontend/src/b/ui.tsx":{"editCount":1,"findings":[],"stopBaseline":{"version":1,"engine":"0.1.5","counts":{}},"cleanAcked":true},"/Users/minachoi/orca/workspaces/o2o-weather/main-2/frontend/src/b/mock/feed.ts":{"editCount":1,"findings":[],"stopBaseline":{"version":1,"engine":"0.1.5","counts":{}}},"/Users/minachoi/orca/workspaces/o2o-weather/main-2/frontend/src/b/mock/week.ts":{"editCount":1,"findings":[],"stopBaseline":{"version":1,"engine":"0.1.5","counts":{}}},"/Users/minachoi/orca/workspaces/o2o-weather/main-2/frontend/src/b/mock/season.ts":{"editCount":1,"findings":[],"stopBaseline":{"version":1,"engine":"0.1.5","counts":{}}},"/Users/minachoi/orca/workspaces/o2o-weather/main-2/frontend/src/b/data.ts":{"editCount":1,"findings":[],"stopBaseline":{"version":1,"engine":"0.1.5","counts":{}}},"/Users/minachoi/orca/workspaces/o2o-weather/main-2/frontend/src/b/Sheets.tsx":{"editCount":1,"findings":[],"stopBaseline":{"version":1,"engine":"0.1.5","counts":{}},"cleanAcked":true},"/Users/minachoi/orca/workspaces/o2o-weather/main-2/frontend/src/b/svg.tsx":{"editCount":1,"findings":[],"stopBaseline":{"version":1,"engine":"0.1.5","counts":{}},"cleanAcked":true},"/Users/minachoi/orca/workspaces/o2o-weather/main-2/frontend/src/b/BLayout.tsx":{"editCount":1,"findings":[],"stopBaseline":{"version":1,"engine":"0.1.5","counts":{}},"cleanAcked":true},"/Users/minachoi/orca/workspaces/o2o-weather/main-2/frontend/src/b/Post.tsx":{"editCount":1,"findings":[],"stopBaseline":{"version":1,"engine":"0.1.5","counts":{}},"cleanAcked":true},"/Users/minachoi/orca/workspaces/o2o-weather/main-2/frontend/src/b/realPosts.ts":{"editCount":1,"findings":[],"stopBaseline":{"version":1,"engine":"0.1.5","counts":{}}},"/Users/minachoi/orca/workspaces/o2o-weather/main-2/frontend/src/b/TodayPage.tsx":{"editCount":1,"findings":[],"stopBaseline":{"version":1,"engine":"0.1.5","counts":{}},"cleanAcked":true},"/Users/minachoi/orca/workspaces/o2o-weather/main-2/frontend/src/b/GakPage.tsx":{"editCount":1,"findings":[],"stopBaseline":{"version":1,"engine":"0.1.5","counts":{}},"cleanAcked":true},"/Users/minachoi/orca/workspaces/o2o-weather/main-2/frontend/src/b/SkyPage.tsx":{"editCount":1,"findings":[],"stopBaseline":{"version":1,"engine":"0.1.5","counts":{}},"cleanAcked":true},"/Users/minachoi/orca/workspaces/o2o-weather/main-2/frontend/src/b/WeekPage.tsx":{"editCount":1,"findings":[],"stopBaseline":{"version":1,"engine":"0.1.5","counts":{}},"cleanAcked":true},"/Users/minachoi/orca/workspaces/o2o-weather/main-2/frontend/src/b/SeasonPage.tsx":{"editCount":2,"findings":[],"stopBaseline":{"version":1,"engine":"0.1.5","counts":{}},"cleanAcked":true},"/Users/minachoi/orca/workspaces/o2o-weather/main-2/frontend/src/api/mutator/custom-fetch.ts":{"editCount":1,"findings":[],"stopBaseline":{"version":1,"engine":"0.1.5","counts":{}}}}},"aaff183a-d0d1-42b6-860a-c2c2b6ccc89a":{"updatedAt":1791268588092,"files":{"/Users/minachoi/orca/workspaces/o2o-weather/main-2/frontend/src/b/GakPage.tsx":{"editCount":3,"findings":[],"stopBaseline":{"version":1,"engine":"0.1.5","counts":{}},"cleanAcked":true},"/Users/minachoi/orca/workspaces/o2o-weather/main-2/frontend/src/b/Post.tsx":{"editCount":2,"findings":[],"stopBaseline":{"version":1,"engine":"0.1.5","counts":{}},"cleanAcked":true},"/Users/minachoi/orca/workspaces/o2o-weather/main-2/frontend/src/b/SkyPage.tsx":{"editCount":1,"findings":[],"stopBaseline":{"version":1,"engine":"0.1.5","counts":{}},"cleanAcked":true},"/Users/minachoi/orca/workspaces/o2o-weather/main-2/frontend/src/b/Sheets.tsx":{"editCount":1,"findings":[],"stopBaseline":{"version":1,"engine":"0.1.5","counts":{}},"cleanAcked":true},"/Users/minachoi/orca/workspaces/o2o-weather/main-2/frontend/src/b/ui.tsx":{"editCount":1,"findings":[],"stopBaseline":{"version":1,"engine":"0.1.5","counts":{}},"cleanAcked":true}}}}}
|
||||
@@ -14,6 +14,8 @@ CMD ["npm", "run", "dev", "--", "--host", "0.0.0.0", "--port", "5173"]
|
||||
|
||||
# ---- build: 타입체크 후 정적 파일 생성 ----
|
||||
FROM deps AS build
|
||||
ARG VITE_API_BASE_URL=""
|
||||
ENV VITE_API_BASE_URL=$VITE_API_BASE_URL
|
||||
COPY . .
|
||||
RUN npm run build
|
||||
|
||||
|
||||
@@ -20,6 +20,17 @@ server {
|
||||
try_files $uri =404;
|
||||
}
|
||||
|
||||
# API 는 같은 주소로 받아 backend 컨테이너로 넘긴다
|
||||
location /v1/ {
|
||||
# 백엔드 컨테이너가 다시 뜨면 IP 가 바뀌므로 docker DNS 로 매번 다시 찾는다
|
||||
resolver 127.0.0.11 valid=10s ipv6=off;
|
||||
set $api http://backend:9800;
|
||||
proxy_pass $api;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
}
|
||||
|
||||
# SPA: /indices, /sky 같은 주소로 새로고침해도 index.html을 돌려준다
|
||||
location / {
|
||||
add_header Cache-Control "no-cache";
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 16 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 24 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 18 KiB |
@@ -3,8 +3,8 @@
|
||||
import { type DefaultError, type InfiniteData, infiniteQueryOptions, queryOptions, type UseMutationOptions } from '@tanstack/react-query';
|
||||
|
||||
import { client } from '../client.gen';
|
||||
import { addComment, deleteComment, getArticle, getFeed, getIndex, getPost, getSeasonWeek, getSky, getSkyRanking, 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';
|
||||
import type { AddCommentData, AddCommentError, AddCommentResponse, DeleteCommentData, DeleteCommentError, DeleteCommentResponse, GetArticleData, GetArticleError, GetArticleResponse, GetFeedData, GetFeedError, GetFeedResponse, GetIndexData, GetIndexError, GetIndexResponse, GetPostData, GetPostError, GetPostResponse, GetSeasonWeekData, GetSeasonWeekResponse, GetSkyData, GetSkyError, GetSkyRankingData, GetSkyRankingResponse, GetSkyResponse, GetWeatherNowData, GetWeatherNowError, GetWeatherNowResponse, GetWeatherTodayData, GetWeatherTodayError, GetWeatherTodayResponse, GetWeekData, GetWeekError, GetWeekRankingData, GetWeekRankingResponse, GetWeekResponse, HealthzHealthzGetData, HealthzHealthzGetResponse, LikeCommentData, LikeCommentError, LikeCommentResponse, LikePostData, LikePostError, LikePostResponse, ListArticlesData, ListArticlesError, ListArticlesResponse, ListCommentsData, ListCommentsError, ListCommentsResponse, ListEventsData, ListEventsError, ListEventsResponse, ListIndicesData, ListIndicesError, ListIndicesResponse, ListPlacesData, ListPlacesError, ListPlacesResponse, ListRegionsData, ListRegionsError, ListRegionsResponse, ListSavedData, ListSavedError, ListSavedResponse, LoginData, LoginError, LoginResponse, LogoutData, LogoutError, LogoutResponse, MeData, MeError, MeResponse, NearestRegionData, NearestRegionError, NearestRegionResponse, RefreshData, RefreshError, RefreshResponse, SavePostData, SavePostError, SavePostResponse, SignupData, SignupError, SignupResponse, UnlikeCommentData, UnlikeCommentError, UnlikeCommentResponse, UnlikePostData, UnlikePostError, UnlikePostResponse, UnsavePostData, UnsavePostError, UnsavePostResponse, UpdateMeData, UpdateMeError, UpdateMeResponse } from '../types.gen';
|
||||
import { addComment, deleteComment, getArticle, getFeed, 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';
|
||||
import type { AddCommentData, AddCommentError, AddCommentResponse, DeleteCommentData, DeleteCommentError, DeleteCommentResponse, GetArticleData, GetArticleError, GetArticleResponse, GetFeedData, GetFeedError, GetFeedResponse, GetIndexData, GetIndexError, GetIndexResponse, GetPostData, GetPostError, GetPostResponse, GetSeasonWeekData, GetSeasonWeekResponse, GetSkyData, GetSkyError, GetSkyRankingData, GetSkyRankingResponse, GetSkyResponse, GetWatchSummaryData, GetWatchSummaryError, GetWatchSummaryResponse, GetWeatherNowData, GetWeatherNowError, GetWeatherNowResponse, GetWeatherTodayData, GetWeatherTodayError, GetWeatherTodayResponse, GetWeekData, GetWeekError, GetWeekRankingData, GetWeekRankingResponse, GetWeekResponse, HealthzHealthzGetData, HealthzHealthzGetResponse, LikeCommentData, LikeCommentError, LikeCommentResponse, LikePostData, LikePostError, LikePostResponse, ListArticlesData, ListArticlesError, ListArticlesResponse, ListCommentsData, ListCommentsError, ListCommentsResponse, ListEventsData, ListEventsError, ListEventsResponse, ListIndicesData, ListIndicesError, ListIndicesResponse, ListPlacesData, ListPlacesError, ListPlacesResponse, ListRegionsData, ListRegionsError, ListRegionsResponse, ListSavedData, ListSavedError, ListSavedResponse, LoginData, LoginError, LoginResponse, LogoutData, LogoutError, LogoutResponse, MeData, MeError, MeResponse, NearestRegionData, NearestRegionError, NearestRegionResponse, RefreshData, RefreshError, RefreshResponse, SavePostData, SavePostError, SavePostResponse, SignupData, SignupError, SignupResponse, UnlikeCommentData, UnlikeCommentError, UnlikeCommentResponse, UnlikePostData, UnlikePostError, UnlikePostResponse, UnsavePostData, UnsavePostError, UnsavePostResponse, UpdateMeData, UpdateMeError, UpdateMeResponse } from '../types.gen';
|
||||
|
||||
export type QueryKey<TOptions extends Options> = [
|
||||
Pick<TOptions, 'baseUrl' | 'body' | 'headers' | 'path' | 'query'> & {
|
||||
@@ -709,6 +709,24 @@ export const likeCommentMutation = (options?: Partial<Options<LikeCommentData>>)
|
||||
return mutationOptions;
|
||||
};
|
||||
|
||||
export const getWatchSummaryQueryKey = (options: Options<GetWatchSummaryData>) => createQueryKey('getWatchSummary', options);
|
||||
|
||||
/**
|
||||
* 워치 한 번에: 지금 날씨, 각 1~7위·내 각, 노을, 남은 3시간 칸, 컴플리케이션 시간표
|
||||
*/
|
||||
export const getWatchSummaryOptions = (options: Options<GetWatchSummaryData>) => queryOptions<GetWatchSummaryResponse, GetWatchSummaryError, GetWatchSummaryResponse, ReturnType<typeof getWatchSummaryQueryKey>>({
|
||||
queryFn: async ({ queryKey, signal }) => {
|
||||
const { data } = await getWatchSummary({
|
||||
...options,
|
||||
...queryKey[0],
|
||||
signal,
|
||||
throwOnError: true
|
||||
});
|
||||
return data;
|
||||
},
|
||||
queryKey: getWatchSummaryQueryKey(options)
|
||||
});
|
||||
|
||||
export const healthzHealthzGetQueryKey = (options?: Options<HealthzHealthzGetData>) => createQueryKey('healthzHealthzGet', options);
|
||||
|
||||
/**
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
// This file is auto-generated by @hey-api/openapi-ts
|
||||
|
||||
export { addComment, deleteComment, getArticle, getFeed, getIndex, getPost, getSeasonWeek, getSky, getSkyRanking, 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 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 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 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 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 SignupData, type SignupError, type SignupErrors, type SignupResponse, type SignupResponses, Sky, SkyGrade, type SkyPlanData, type SkyScoreData, SkyType, SlotTone, type SpotData, type SunsetSlide, type TermData, type Tomorrow, type TopIndex, type TrendPoint, type UnlikeCommentData, type UnlikeCommentError, type UnlikeCommentErrors, type UnlikeCommentResponse, type UnlikeCommentResponses, type UnlikePostData, type UnlikePostError, type UnlikePostErrors, type UnlikePostResponse, type UnlikePostResponses, type UnsavePostData, type UnsavePostError, type UnsavePostErrors, type UnsavePostResponse, type UnsavePostResponsLine truncated
|
||||
export { addComment, deleteComment, getArticle, getFeed, 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 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 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 UnlikeCommentErrors, type UnlikeCommentResponse, type UnlikeCommentResponses, type UnlikePostData, type UnlikePostLine truncated
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
import type { Client, ClientMeta, Options as Options2, RequestResult, TDataShape } from './client';
|
||||
import { client } from './client.gen';
|
||||
import type { AddCommentData, AddCommentErrors, AddCommentResponses, DeleteCommentData, DeleteCommentErrors, DeleteCommentResponses, GetArticleData, GetArticleErrors, GetArticleResponses, GetFeedData, GetFeedErrors, GetFeedResponses, GetIndexData, GetIndexErrors, GetIndexResponses, GetPostData, GetPostErrors, GetPostResponses, GetSeasonWeekData, GetSeasonWeekResponses, GetSkyData, GetSkyErrors, GetSkyRankingData, GetSkyRankingResponses, GetSkyResponses, GetWeatherNowData, GetWeatherNowErrors, GetWeatherNowResponses, GetWeatherTodayData, GetWeatherTodayErrors, GetWeatherTodayResponses, GetWeekData, GetWeekErrors, GetWeekRankingData, GetWeekRankingResponses, GetWeekResponses, HealthzHealthzGetData, HealthzHealthzGetResponses, LikeCommentData, LikeCommentErrors, LikeCommentResponses, LikePostData, LikePostErrors, LikePostResponses, ListArticlesData, ListArticlesErrors, ListArticlesResponses, ListCommentsData, ListCommentsErrors, ListCommentsResponses, ListEventsData, ListEventsErrors, ListEventsResponses, ListIndicesData, ListIndicesErrors, ListIndicesResponses, ListPlacesData, ListPlacesErrors, ListPlacesResponses, ListRegionsData, ListRegionsErrors, ListRegionsResponses, ListSavedData, ListSavedErrors, ListSavedResponses, LoginData, LoginErrors, LoginResponses, LogoutData, LogoutErrors, LogoutResponses, MeData, MeErrors, MeResponses, NearestRegionData, NearestRegionErrors, NearestRegionResponses, RefreshData, RefreshErrors, RefreshResponses, SavePostData, SavePostErrors, SavePostResponses, SignupData, SignupErrors, SignupResponses, UnlikeCommentData, UnlikeCommentErrors, UnlikeCommentResponses, UnlikePostData, UnlikePostErrors, UnlikePostResponses, UnsavePostData, UnsavePostErrors, UnsavePostResponses, UpdateMeData, UpdateMeErrors, UpdateMeResponses } from './types.gen';
|
||||
import type { AddCommentData, AddCommentErrors, AddCommentResponses, DeleteCommentData, DeleteCommentErrors, DeleteCommentResponses, GetArticleData, GetArticleErrors, GetArticleResponses, GetFeedData, GetFeedErrors, GetFeedResponses, GetIndexData, GetIndexErrors, GetIndexResponses, GetPostData, GetPostErrors, GetPostResponses, GetSeasonWeekData, GetSeasonWeekResponses, GetSkyData, GetSkyErrors, GetSkyRankingData, GetSkyRankingResponses, GetSkyResponses, GetWatchSummaryData, GetWatchSummaryErrors, GetWatchSummaryResponses, GetWeatherNowData, GetWeatherNowErrors, GetWeatherNowResponses, GetWeatherTodayData, GetWeatherTodayErrors, GetWeatherTodayResponses, GetWeekData, GetWeekErrors, GetWeekRankingData, GetWeekRankingResponses, GetWeekResponses, HealthzHealthzGetData, HealthzHealthzGetResponses, LikeCommentData, LikeCommentErrors, LikeCommentResponses, LikePostData, LikePostErrors, LikePostResponses, ListArticlesData, ListArticlesErrors, ListArticlesResponses, ListCommentsData, ListCommentsErrors, ListCommentsResponses, ListEventsData, ListEventsErrors, ListEventsResponses, ListIndicesData, ListIndicesErrors, ListIndicesResponses, ListPlacesData, ListPlacesErrors, ListPlacesResponses, ListRegionsData, ListRegionsErrors, ListRegionsResponses, ListSavedData, ListSavedErrors, ListSavedResponses, LoginData, LoginErrors, LoginResponses, LogoutData, LogoutErrors, LogoutResponses, MeData, MeErrors, MeResponses, NearestRegionData, NearestRegionErrors, NearestRegionResponses, RefreshData, RefreshErrors, RefreshResponses, SavePostData, SavePostErrors, SavePostResponses, SignupData, SignupErrors, SignupResponses, UnlikeCommentData, UnlikeCommentErrors, UnlikeCommentResponses, UnlikePostData, UnlikePostErrors, UnlikePostResponses, UnsavePostData, UnsavePostErrors, UnsavePostResponses, UpdateMeData, UpdateMeErrors, UpdateMeResponses } from './types.gen';
|
||||
|
||||
export type Options<TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown> = Options2<TData, ThrowOnError, TResponse> & {
|
||||
/**
|
||||
@@ -218,6 +218,11 @@ export const unlikeComment = <ThrowOnError extends boolean = true>(options: Opti
|
||||
*/
|
||||
export const likeComment = <ThrowOnError extends boolean = true>(options: Options<LikeCommentData, ThrowOnError>): RequestResult<LikeCommentResponses, LikeCommentErrors, ThrowOnError> => (options.client ?? client).post<LikeCommentResponses, LikeCommentErrors, ThrowOnError>({ url: '/v1/reaction/comment/{comment_id}/like', ...options });
|
||||
|
||||
/**
|
||||
* 워치 한 번에: 지금 날씨, 각 1~7위·내 각, 노을, 남은 3시간 칸, 컴플리케이션 시간표
|
||||
*/
|
||||
export const getWatchSummary = <ThrowOnError extends boolean = true>(options: Options<GetWatchSummaryData, ThrowOnError>): RequestResult<GetWatchSummaryResponses, GetWatchSummaryErrors, ThrowOnError> => (options.client ?? client).get<GetWatchSummaryResponses, GetWatchSummaryErrors, ThrowOnError>({ url: '/v1/watch/summary', ...options });
|
||||
|
||||
/**
|
||||
* 헬스체크
|
||||
*/
|
||||
|
||||
@@ -570,6 +570,18 @@ export type Hero = {
|
||||
* Bubble
|
||||
*/
|
||||
bubble?: string | null;
|
||||
/**
|
||||
* Moon Name
|
||||
*
|
||||
* 오늘 밤 달 모양: 삭·초승달·상현달·차오르는 달·보름달·기우는 달·하현달·그믐달
|
||||
*/
|
||||
moon_name?: string | null;
|
||||
/**
|
||||
* Moon Pct
|
||||
*
|
||||
* 달이 밝게 보이는 비율 0~100
|
||||
*/
|
||||
moon_pct?: number | null;
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -930,7 +942,11 @@ export const PostType = {
|
||||
/**
|
||||
* DAY_TRIP
|
||||
*/
|
||||
DAY_TRIP: 13
|
||||
DAY_TRIP: 13,
|
||||
/**
|
||||
* MOON
|
||||
*/
|
||||
MOON: 14
|
||||
} as const;
|
||||
|
||||
/**
|
||||
@@ -1027,6 +1043,10 @@ export type RankData = {
|
||||
*/
|
||||
score: number;
|
||||
grade: SkyGrade;
|
||||
/**
|
||||
* Situation Label
|
||||
*/
|
||||
situation_label?: string | null;
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -1331,6 +1351,12 @@ export type ResIndexDetail = {
|
||||
* Limit
|
||||
*/
|
||||
limit?: string | null;
|
||||
/**
|
||||
* Bands
|
||||
*
|
||||
* 점수 구간별 설명 (0~29, 30~59, 60~79, 80~100)
|
||||
*/
|
||||
bands?: Array<ScoreBand>;
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -1594,12 +1620,71 @@ export type ResSkyRanking = {
|
||||
* Day
|
||||
*/
|
||||
day?: string | null;
|
||||
/**
|
||||
* Summary
|
||||
*
|
||||
* 대부분 같은 하늘 상황인 날 한 줄 (예: 오늘은 전국이 맑아 대부분 짧게 끝나요)
|
||||
*/
|
||||
summary?: string | null;
|
||||
/**
|
||||
* Items
|
||||
*/
|
||||
items?: Array<RankData>;
|
||||
};
|
||||
|
||||
/**
|
||||
* Res_WatchSummary
|
||||
*/
|
||||
export type ResWatchSummary = {
|
||||
result?: ErrorInfo;
|
||||
/**
|
||||
* Msg
|
||||
*/
|
||||
msg?: string | null;
|
||||
/**
|
||||
* Region Code
|
||||
*/
|
||||
region_code?: string | null;
|
||||
/**
|
||||
* Region Name
|
||||
*/
|
||||
region_name?: string | null;
|
||||
/**
|
||||
* Issued At
|
||||
*/
|
||||
issued_at?: string | null;
|
||||
/**
|
||||
* Refresh At
|
||||
*/
|
||||
refresh_at?: string | null;
|
||||
/**
|
||||
* Mode
|
||||
*/
|
||||
mode?: 'morning' | 'day' | 'evening' | 'night' | null;
|
||||
now?: WatchNow | null;
|
||||
/**
|
||||
* Warning
|
||||
*/
|
||||
warning?: string | null;
|
||||
/**
|
||||
* Top
|
||||
*/
|
||||
top?: Array<TopIndex>;
|
||||
/**
|
||||
* Picks
|
||||
*/
|
||||
picks?: Array<TopIndex>;
|
||||
sunset?: WatchSunset | null;
|
||||
/**
|
||||
* Slots
|
||||
*/
|
||||
slots?: Array<WatchSlot>;
|
||||
/**
|
||||
* Timeline
|
||||
*/
|
||||
timeline?: Array<WatchTimeline>;
|
||||
};
|
||||
|
||||
/**
|
||||
* Res_WeatherNow
|
||||
*/
|
||||
@@ -1714,6 +1799,12 @@ export type Row = {
|
||||
* Value
|
||||
*/
|
||||
value: string;
|
||||
/**
|
||||
* Place
|
||||
*
|
||||
* 위치가 정해진 장소면 지도에서 찾을 이름 (앱이 네이버 지도 링크를 건다)
|
||||
*/
|
||||
place?: string | null;
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -1771,6 +1862,32 @@ export type SavedPost = {
|
||||
saved_at: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* ScoreBand
|
||||
*/
|
||||
export type ScoreBand = {
|
||||
/**
|
||||
* Low
|
||||
*/
|
||||
low: number;
|
||||
/**
|
||||
* High
|
||||
*/
|
||||
high: number;
|
||||
/**
|
||||
* Text
|
||||
*
|
||||
* 이 점수 구간이면 어떤 날인지, 통통 튀는 말투 한 문장
|
||||
*/
|
||||
text: string;
|
||||
/**
|
||||
* Current
|
||||
*
|
||||
* 오늘 점수가 이 구간에 있음
|
||||
*/
|
||||
current: boolean;
|
||||
};
|
||||
|
||||
/**
|
||||
* Sky
|
||||
*/
|
||||
@@ -1853,6 +1970,22 @@ export type SkyPlanData = {
|
||||
* Grade Label
|
||||
*/
|
||||
grade_label: string;
|
||||
/**
|
||||
* Situation Label
|
||||
*/
|
||||
situation_label?: string | null;
|
||||
/**
|
||||
* Models Total
|
||||
*
|
||||
* 계산에 쓴 예보 모델 수
|
||||
*/
|
||||
models_total?: number | null;
|
||||
/**
|
||||
* Models Agree
|
||||
*
|
||||
* 그중 같은 하늘 상황을 낸 모델 수
|
||||
*/
|
||||
models_agree?: number | null;
|
||||
/**
|
||||
* Best At
|
||||
*/
|
||||
@@ -1891,8 +2024,54 @@ export type SkyScoreData = {
|
||||
* Best Times
|
||||
*/
|
||||
best_times?: Array<BestTime>;
|
||||
situation?: SkySituation | null;
|
||||
/**
|
||||
* Situation Label
|
||||
*
|
||||
* 하늘 상황 한 줄: 구름에 가려요 / 구름이 적어 짧게 끝나요 / 하늘이 넓게 물들 수 있어요 등
|
||||
*/
|
||||
situation_label?: string | null;
|
||||
/**
|
||||
* Verdict
|
||||
*/
|
||||
verdict?: 'go' | 'maybe' | 'rest' | null;
|
||||
};
|
||||
|
||||
/**
|
||||
* SkySituation
|
||||
*
|
||||
* 노을·일출 하늘 상황. 구름 층으로 고른다 (sky_score.situation).
|
||||
*/
|
||||
export const SkySituation = {
|
||||
/**
|
||||
* COVERED
|
||||
*/
|
||||
COVERED: 1,
|
||||
/**
|
||||
* LOW_CLOUD
|
||||
*/
|
||||
LOW_CLOUD: 2,
|
||||
/**
|
||||
* FEW
|
||||
*/
|
||||
FEW: 3,
|
||||
/**
|
||||
* GLOW
|
||||
*/
|
||||
GLOW: 4,
|
||||
/**
|
||||
* THICK
|
||||
*/
|
||||
THICK: 5
|
||||
} as const;
|
||||
|
||||
/**
|
||||
* SkySituation
|
||||
*
|
||||
* 노을·일출 하늘 상황. 구름 층으로 고른다 (sky_score.situation).
|
||||
*/
|
||||
export type SkySituation = typeof SkySituation[keyof typeof SkySituation];
|
||||
|
||||
/**
|
||||
* SkyType
|
||||
*/
|
||||
@@ -1960,6 +2139,12 @@ export type SpotData = {
|
||||
* Distance Km
|
||||
*/
|
||||
distance_km: number;
|
||||
/**
|
||||
* Direction
|
||||
*
|
||||
* 내 구에서 본 방향 (16방위, 예: 북서)
|
||||
*/
|
||||
direction?: string;
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -1990,6 +2175,10 @@ export type SunsetSlide = {
|
||||
* Cuts
|
||||
*/
|
||||
cuts: Array<Cut>;
|
||||
/**
|
||||
* 하늘 상황. 앱이 카드 하늘 색을 고른다
|
||||
*/
|
||||
situation?: SkySituation | null;
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -2202,6 +2391,90 @@ export const WarningType = {
|
||||
*/
|
||||
export type WarningType = typeof WarningType[keyof typeof WarningType];
|
||||
|
||||
/**
|
||||
* WatchNow
|
||||
*/
|
||||
export type WatchNow = {
|
||||
/**
|
||||
* Temp C
|
||||
*/
|
||||
temp_c?: number | null;
|
||||
/**
|
||||
* Icon
|
||||
*/
|
||||
icon?: string | null;
|
||||
/**
|
||||
* Rain 2H
|
||||
*/
|
||||
rain_2h?: boolean | null;
|
||||
/**
|
||||
* Text
|
||||
*/
|
||||
text?: string | null;
|
||||
};
|
||||
|
||||
/**
|
||||
* WatchSlot
|
||||
*/
|
||||
export type WatchSlot = {
|
||||
/**
|
||||
* At
|
||||
*/
|
||||
at: string;
|
||||
/**
|
||||
* Icon
|
||||
*/
|
||||
icon: string;
|
||||
/**
|
||||
* Temp C
|
||||
*/
|
||||
temp_c?: number | null;
|
||||
/**
|
||||
* Rain Prob
|
||||
*/
|
||||
rain_prob?: number | null;
|
||||
};
|
||||
|
||||
/**
|
||||
* WatchSunset
|
||||
*/
|
||||
export type WatchSunset = {
|
||||
/**
|
||||
* Is Today
|
||||
*/
|
||||
is_today: boolean;
|
||||
/**
|
||||
* Score
|
||||
*/
|
||||
score: number;
|
||||
/**
|
||||
* Grade Label
|
||||
*/
|
||||
grade_label: string;
|
||||
/**
|
||||
* Sunset At
|
||||
*/
|
||||
sunset_at: string;
|
||||
/**
|
||||
* Best At
|
||||
*/
|
||||
best_at: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* WatchTimeline
|
||||
*/
|
||||
export type WatchTimeline = {
|
||||
/**
|
||||
* Start At
|
||||
*/
|
||||
start_at: string;
|
||||
/**
|
||||
* Kind
|
||||
*/
|
||||
kind: 'gak' | 'sunset';
|
||||
};
|
||||
|
||||
/**
|
||||
* WeatherSlot
|
||||
*/
|
||||
@@ -3426,6 +3699,44 @@ export type LikeCommentResponses = {
|
||||
|
||||
export type LikeCommentResponse = LikeCommentResponses[keyof LikeCommentResponses];
|
||||
|
||||
export type GetWatchSummaryData = {
|
||||
body?: never;
|
||||
path?: never;
|
||||
query: {
|
||||
/**
|
||||
* Region
|
||||
*
|
||||
* 구 행정코드
|
||||
*/
|
||||
region: string;
|
||||
/**
|
||||
* Pick
|
||||
*
|
||||
* 내 각 코드, 쉼표로 최대 3개 (예: running,laundry)
|
||||
*/
|
||||
pick?: string | null;
|
||||
};
|
||||
url: '/v1/watch/summary';
|
||||
};
|
||||
|
||||
export type GetWatchSummaryErrors = {
|
||||
/**
|
||||
* Validation Error
|
||||
*/
|
||||
422: HttpValidationError;
|
||||
};
|
||||
|
||||
export type GetWatchSummaryError = GetWatchSummaryErrors[keyof GetWatchSummaryErrors];
|
||||
|
||||
export type GetWatchSummaryResponses = {
|
||||
/**
|
||||
* Successful Response
|
||||
*/
|
||||
200: ResWatchSummary;
|
||||
};
|
||||
|
||||
export type GetWatchSummaryResponse = GetWatchSummaryResponses[keyof GetWatchSummaryResponses];
|
||||
|
||||
export type HealthzHealthzGetData = {
|
||||
body?: never;
|
||||
path?: never;
|
||||
|
||||
@@ -26,12 +26,13 @@ const ACCOUNTS: Record<PostType, readonly [string, string]> = {
|
||||
[PostType.WEEKEND_PLAN]: ['주말 플랜', 'calendar'],
|
||||
[PostType.AIR]: ['미세먼지', 'vent'],
|
||||
[PostType.DAY_TRIP]: ['당일치기', 'picnic'],
|
||||
[PostType.MOON]: ['오늘 밤 달', 'moon'],
|
||||
}
|
||||
|
||||
type Slide = HoursSlide | RowsSlide | GakSlide | SunsetSlide | WeekSlide | PlanSlide
|
||||
|
||||
const GAK_BG: SlideBg[] = ['butter', 'peach', 'lilac']
|
||||
const ROW_ICON_BG: Record<string, SlideBg> = { umbrella: 'lilac', vent: 'mint', sunset: 'peach', thermo: 'sky', maple: 'peach' }
|
||||
const ROW_ICON_BG: Record<string, SlideBg> = { umbrella: 'lilac', vent: 'mint', sunset: 'peach', thermo: 'sky', maple: 'peach', moon: 'lilac' }
|
||||
|
||||
/** 배경색은 API에 없어 글 종류·아이콘으로 고른다 */
|
||||
function slideBg(post: PostData, slide: Slide): SlideBg {
|
||||
@@ -125,12 +126,12 @@ function SlideView({ slide, bg }: { slide: Slide; bg: SlideBg }) {
|
||||
)
|
||||
if (slide.kind === 'sunset')
|
||||
return (
|
||||
<div className={cx(slideBase, 'b-bg-dusk')}>
|
||||
<div className={cx(slideBase, slide.situation ? `b-sit-${slide.situation}` : 'b-bg-dusk')}>
|
||||
<Eyebrow>{slide.eyebrow}</Eyebrow>
|
||||
<Big>
|
||||
<Lines text={slide.line} />
|
||||
</Big>
|
||||
<b className="mt-2 font-bagel text-[62px] leading-[0.9] font-normal">{slide.score}</b>
|
||||
<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">
|
||||
{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)}`)}>
|
||||
|
||||
@@ -51,6 +51,7 @@ const TITLES = { article: '읽을거리', seasonWeek: '이번 주 특집', share
|
||||
/** 아래에서 올라오는 창: 네이티브 <dialog>라 ESC·포커스 가두기·포커스 되돌리기가 기본으로 된다 */
|
||||
function SheetHost({ state, onClose }: { state: SheetState; onClose: () => void }) {
|
||||
const ref = useRef<HTMLDialogElement>(null)
|
||||
const { kind } = useSky()
|
||||
const [gakTitle, setGakTitle] = useState('')
|
||||
const [articleTitle, setArticleTitle] = useState('')
|
||||
|
||||
@@ -79,6 +80,7 @@ function SheetHost({ state, onClose }: { state: SheetState; onClose: () => void
|
||||
<dialog
|
||||
ref={ref}
|
||||
aria-label={title}
|
||||
data-t={kind}
|
||||
onClose={onClose}
|
||||
onClick={(e) => {
|
||||
if (e.target === e.currentTarget) onClose()
|
||||
@@ -88,7 +90,7 @@ function SheetHost({ state, onClose }: { state: SheetState; onClose: () => void
|
||||
{state && (
|
||||
<div className="b-sheet flex max-h-[86dvh] flex-col rounded-t-[22px] bg-white">
|
||||
<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-[#d5dce7]" 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>
|
||||
<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)">
|
||||
×
|
||||
@@ -301,6 +303,8 @@ function GakSheet({ indexId, onTitle }: { indexId: number; onTitle: (t: string)
|
||||
const load = loadOf(q)
|
||||
if (!g) return <Body>{load === 'loading' ? <GakSkel /> : <StateBox load={load} onRetry={() => q.refetch()} empty="이 각의 계산 근거가 아직 없어요." hold={<GakSkel />} className="inset-0" />}</Body>
|
||||
const factors = d.factors ?? []
|
||||
const bands = d.bands ?? []
|
||||
const now = bands.find((b) => b.current)
|
||||
return (
|
||||
<Body>
|
||||
<div className="flex items-center gap-3">
|
||||
@@ -311,6 +315,12 @@ function GakSheet({ indexId, onTitle }: { indexId: number; onTitle: (t: string)
|
||||
</div>
|
||||
<b className="ml-auto font-bagel text-[42px] font-normal text-(--orange)">{g.score}</b>
|
||||
</div>
|
||||
{now && (
|
||||
<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>
|
||||
{now.text}
|
||||
</p>
|
||||
)}
|
||||
{factors.length > 2 && <Radar name={g.name} factors={factors} />}
|
||||
{g.trend && g.trend.length > 0 && (
|
||||
<div className="mt-2.5 grid grid-cols-4 gap-1.5">
|
||||
@@ -323,6 +333,18 @@ function GakSheet({ indexId, onTitle }: { indexId: number; onTitle: (t: string)
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
{bands.length > 0 && (
|
||||
<ol className="mt-3.5 flex flex-col gap-1.5" aria-label="점수 구간별 설명">
|
||||
{bands.map((b) => (
|
||||
<li key={b.low} className={cx('grid grid-cols-[62px_1fr] items-start gap-2 text-[13px] font-semibold', !b.current && 'opacity-45')}>
|
||||
<span className={cx('rounded-full py-px text-center font-jua text-xs text-white tabular-nums', b.current ? 'bg-(--orange)' : 'bg-(--ink3)')}>
|
||||
{b.low}~{b.high}
|
||||
</span>
|
||||
<span>{b.text}</span>
|
||||
</li>
|
||||
))}
|
||||
</ol>
|
||||
)}
|
||||
<div className="mt-3.5 flex flex-col gap-2.5">
|
||||
{factors.map((f) => (
|
||||
<div key={f.axis} className="grid grid-cols-[84px_1fr_52px] items-center gap-x-2.5 text-[13.5px] font-bold">
|
||||
@@ -564,6 +586,7 @@ function ShareSheet({ share }: { share: SharePayload }) {
|
||||
}
|
||||
|
||||
/* ---------- 댓글 ---------- */
|
||||
const NOT_FOUND = 3001 // 서버 ErrorType.NOT_FOUND
|
||||
const EMOJIS = ['☀️', '🌂', '🍻', '🌇', '😍', '👍']
|
||||
|
||||
function CommentRow({ c, postId }: { c: CommentData; postId: number }) {
|
||||
@@ -577,28 +600,36 @@ function CommentRow({ c, postId }: { c: CommentData; postId: number }) {
|
||||
const unlike = useMutation(unlikeCommentMutation())
|
||||
const remove = useMutation(deleteCommentMutation())
|
||||
const [removeFailed, setRemoveFailed] = useState(false)
|
||||
const [likeFailed, setLikeFailed] = useState(false)
|
||||
|
||||
const toggle = () => {
|
||||
if (!loggedIn) return open({ type: 'login' })
|
||||
if (like.isPending || unlike.isPending) return
|
||||
const next = !liked
|
||||
setLikeFailed(false)
|
||||
setLiked(next)
|
||||
setCount((n) => n + (next ? 1 : -1))
|
||||
const revert = () => {
|
||||
setLiked(!next)
|
||||
setCount(c.like_count)
|
||||
}
|
||||
;(next ? like : unlike).mutate(
|
||||
{ path: { comment_id: c.comment_id } },
|
||||
{
|
||||
onSuccess: (res) => {
|
||||
if (!res.result?.success) {
|
||||
setLiked(!next)
|
||||
setCount(c.like_count)
|
||||
if (res.result?.success) {
|
||||
setLiked(!!res.liked)
|
||||
if (res.like_count != null) setCount(res.like_count)
|
||||
return
|
||||
}
|
||||
setLiked(!!res.liked)
|
||||
if (res.like_count != null) setCount(res.like_count)
|
||||
revert()
|
||||
// 그 사이 지워진 댓글이면 알림 없이 목록을 다시 받아 사라지게 한다
|
||||
if (res.result?.code === NOT_FOUND) queryClient.invalidateQueries({ queryKey: listCommentsInfiniteQueryKey({ path: { post_id: postId } }) })
|
||||
else setLikeFailed(true)
|
||||
},
|
||||
onError: () => {
|
||||
setLiked(!next)
|
||||
setCount(c.like_count)
|
||||
revert()
|
||||
setLikeFailed(true)
|
||||
},
|
||||
},
|
||||
)
|
||||
@@ -634,7 +665,7 @@ function CommentRow({ c, postId }: { c: CommentData; postId: number }) {
|
||||
{c.body}
|
||||
</p>
|
||||
<small className="mt-0.5 block text-xs font-bold text-(--ink3)">
|
||||
{ago(c.created_at)} · 좋아요 {count}개
|
||||
{ago(c.created_at)} · {likeFailed ? <span className="text-(--heart)" role="alert">좋아요를 못 했어요. 잠시 뒤에 다시 눌러 주세요</span> : `좋아요 ${count}개`}
|
||||
{c.mine && (
|
||||
<>
|
||||
{' · '}
|
||||
|
||||
+65
-159
@@ -1,72 +1,11 @@
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import type { ReactNode } from 'react'
|
||||
import { getSkyOptions, getSkyRankingOptions } from '../api/client/@tanstack/react-query.gen'
|
||||
import type { BestTime, RegionData, SkyPlanData, SpotData } from '../api/client/types.gen'
|
||||
import type { BestTime, SkyPlanData } from '../api/client/types.gen'
|
||||
import { cx } from '../lib/utils'
|
||||
import { clockShort, compass, dayLabel, loadOf } from './lib'
|
||||
import { clockShort, loadOf } from './lib'
|
||||
import { useRegion } from './regionContext'
|
||||
import { Sec, Skel, StateBox } from './ui'
|
||||
|
||||
const W = 400
|
||||
const H = 260
|
||||
const BLOCKS = [
|
||||
[20, 20, 90, 60],
|
||||
[130, 18, 100, 52],
|
||||
[262, 22, 110, 48],
|
||||
[24, 190, 110, 54],
|
||||
[170, 196, 90, 50],
|
||||
[290, 180, 92, 62],
|
||||
]
|
||||
|
||||
/** 내 구 중심을 기준으로 명소를 km 단위로 놓고, 해 지는 방향을 그린다 */
|
||||
function SpotMap({ region, spots, azimuth }: { region: RegionData; spots: SpotData[]; azimuth: number | null | undefined }) {
|
||||
const kx = 111 * Math.cos((region.lat * Math.PI) / 180)
|
||||
const pts = spots.map((s) => ({ no: s.no, x: (s.lon - region.lon) * kx, y: (s.lat - region.lat) * 111 }))
|
||||
const maxX = Math.max(0.5, ...pts.map((p) => Math.abs(p.x)))
|
||||
const maxY = Math.max(0.5, ...pts.map((p) => Math.abs(p.y)))
|
||||
const scale = Math.min(160 / maxX, 95 / maxY)
|
||||
const cx0 = W / 2
|
||||
const cy0 = H / 2
|
||||
const az = ((azimuth ?? 270) * Math.PI) / 180
|
||||
const dir = (len: number, turn = 0) => [cx0 + Math.sin(az + turn) * len, cy0 - Math.cos(az + turn) * len] as const
|
||||
const tip = dir(190)
|
||||
const label = dir(120)
|
||||
|
||||
return (
|
||||
<div className="mx-3 mt-3 overflow-hidden rounded-[26px] bg-[#eef2e8] shadow-[inset_0_0_0_2px_#e1e7da]">
|
||||
<svg viewBox={`0 0 ${W} ${H}`} role="img" aria-label={`${region.name} 주변 노을 명소 지도`} className="block h-auto w-full">
|
||||
<rect width={W} height={H} fill="#eef2e8" />
|
||||
{BLOCKS.map(([x, y, w, h]) => (
|
||||
<rect key={`${x}-${y}`} x={x} y={y} width={w} height={h} rx="10" fill="#e1e7da" />
|
||||
))}
|
||||
<path d={`M${W / 2 - 10} 0 L${W / 2 + 4} ${H}`} stroke="#fff" strokeWidth="9" />
|
||||
<path d={`M0 ${H / 2 - 30} H${W}`} stroke="#fff" strokeWidth="10" />
|
||||
{azimuth != null && (
|
||||
<>
|
||||
<path d={`M${cx0} ${cy0} L${dir(260, -0.3).join(' ')} L${dir(260, 0.3).join(' ')} Z`} fill="#ff8e4e" opacity=".18" />
|
||||
<path d={`M${cx0} ${cy0} L${tip.join(' ')}`} stroke="#ff7a45" strokeWidth="3" strokeDasharray="7 6" />
|
||||
<text x={Math.min(W - 110, Math.max(8, label[0] - 50))} y={label[1] + 26} fontFamily="Jua,sans-serif" fontSize="14" fill="#d4552a">
|
||||
해 지는 {compass(azimuth)}쪽
|
||||
</text>
|
||||
</>
|
||||
)}
|
||||
<circle cx={cx0} cy={cy0} r="13" fill="#4f97e3" opacity=".25" />
|
||||
<circle cx={cx0} cy={cy0} r="6" fill="#4f97e3" stroke="#fff" strokeWidth="2" />
|
||||
<text x={cx0 + 14} y={cy0 + 18} fontFamily="Pretendard Variable,sans-serif" fontWeight="800" fontSize="11" fill="#2f6fb7">
|
||||
지금 여기
|
||||
</text>
|
||||
{pts.map((p) => (
|
||||
<g key={p.no}>
|
||||
<circle cx={cx0 + p.x * scale} cy={cy0 - p.y * scale} r="13" fill="#ff7a45" stroke="#fff" strokeWidth="3" />
|
||||
<text x={cx0 + p.x * scale} y={cy0 - p.y * scale + 5} textAnchor="middle" fontFamily="Bagel Fat One,sans-serif" fontSize="14" fill="#fff">
|
||||
{p.no}
|
||||
</text>
|
||||
</g>
|
||||
))}
|
||||
</svg>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
import { MapLink, Sec, Skel, StateBox } from './ui'
|
||||
|
||||
function LiSkel({ ghost = false }: { ghost?: boolean }) {
|
||||
return (
|
||||
@@ -89,54 +28,58 @@ function LiSkel({ ghost = false }: { ghost?: boolean }) {
|
||||
)
|
||||
}
|
||||
|
||||
const HERO = 'relative mx-3 mt-1 min-h-[350px] overflow-hidden rounded-[32px] bg-[linear-gradient(180deg,#7e6fe6,#f08aa2_58%,#ffc28a)] px-5 pt-5 pb-16 text-white'
|
||||
// 다른 탭 히어로보다 짧게. 배경은 하늘 상황별 색(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 THREE = [0, 1, 2]
|
||||
const FOUR = [0, 1, 2, 3]
|
||||
const RANK_SKELS = Array.from({ length: 8 }, (_, i) => i)
|
||||
|
||||
/** 결론 → 왜 → 몇 시에 어디로 → 점수(보조). 글자 줄 수를 고정해 스켈레톤과 크기가 같다 */
|
||||
function HeroBody({ plan }: { plan?: SkyPlanData }) {
|
||||
/** 히어로엔 해 지는 시각과 하늘 상황 한 줄만. 결론·이유는 아래 카드로 */
|
||||
function HeroBody({ plan, sunset }: { plan?: SkyPlanData; sunset?: string }) {
|
||||
const v = (node: ReactNode, w: string) => (plan ? node : <Skel className={w} />)
|
||||
const place = plan && (plan.spot ? `${plan.spot.name} · ${plan.spot.distance_km}km` : plan.verdict === 'rest' ? '오늘은 나가지 않아도 돼요' : '30km 안에 등록된 명소가 없어요')
|
||||
return (
|
||||
<div aria-hidden={plan ? undefined : true}>
|
||||
<p className="relative m-0 mt-1.5 font-jua text-[38px] leading-[1.1]">{v(plan?.headline, 'w-[200px]')}</p>
|
||||
<div className="relative z-[1] mt-3 rounded-[20px] bg-[rgb(45_36_64/0.55)] px-4 py-3">
|
||||
<p className="m-0 line-clamp-2 h-[2lh] text-[14.5px] leading-snug font-bold">{v(plan?.reason, 'w-[250px]')}</p>
|
||||
<div className="mt-2.5 grid grid-cols-[auto_1fr] items-center gap-x-3 border-t border-white/25 pt-2.5">
|
||||
<b className="row-span-2 font-bagel text-[30px] leading-none font-normal">{v(plan?.best_at && clockShort(plan.best_at), 'w-[76px]')}</b>
|
||||
<span className="text-[13px] font-extrabold">{v(plan && '가장 붉을 때', 'w-20')}</span>
|
||||
<span className="truncate text-[13px] font-bold">{v(place, 'w-36')}</span>
|
||||
</div>
|
||||
<p className="m-0 mt-2.5 border-t border-white/25 pt-2 text-[12.5px] leading-snug font-bold">
|
||||
{v(plan && `노을 점수 ${plan.score}점 · ${plan.grade_label}`, 'w-32')}
|
||||
<small className="block text-[12px] font-semibold">{v(plan && '해 지는 쪽 구름 높이·양으로 매겨요. 60점부터 나가 볼 만해요', 'w-56')}</small>
|
||||
</p>
|
||||
</div>
|
||||
<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 mt-1.5 font-jua text-[21px]">{v(plan?.situation_label ?? plan?.headline, 'w-[190px]')}</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/** 일몰 전 골든아워 → 해 짐 → 가장 붉을 때 → 블루아워, 한 줄 */
|
||||
/** 결론과 이유, 예보 모델이 얼마나 같은 예보를 냈는지, 점수(작게) */
|
||||
function Verdict({ plan }: { plan?: SkyPlanData }) {
|
||||
const v = (node: ReactNode, w: string) => (plan ? node : <Skel className={w} />)
|
||||
const agree = plan?.models_total ? `예보 모델 ${plan.models_total}개 중 ${plan.models_agree}개가 같은 예보` : ''
|
||||
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}>
|
||||
<p className="m-0">
|
||||
<b className="mr-1.5 font-jua text-[17px] font-normal">{v(plan?.headline, 'w-20')}</b>
|
||||
{v(plan?.reason, 'w-[220px]')}
|
||||
</p>
|
||||
<small className="mt-1 block text-[12px] font-bold text-(--ink2)">{v(plan && [agree, `노을 점수 ${plan.score}`].filter(Boolean).join(' · '), 'w-48')}</small>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/** 골든아워 → 해 짐 → 블루아워 */
|
||||
function Timeline({ rows }: { rows?: BestTime[] }) {
|
||||
return (
|
||||
<ol className="relative mx-3 mt-3 grid grid-cols-4 rounded-[22px] bg-white px-2 pt-4 pb-3 shadow-[inset_0_-5px_0_var(--shade)]" aria-hidden={rows ? undefined : true}>
|
||||
<span className="absolute inset-x-[12.5%] top-[22px] h-0.5 bg-(--line)" aria-hidden="true" />
|
||||
{(rows ?? FOUR.map(() => undefined)).map((t, i) => (
|
||||
<li key={t?.kind ?? i} className="relative flex flex-col items-center text-center">
|
||||
<span className={cx('size-3 rounded-full border-2 border-(--line) bg-white', t?.kind === 'peak' && 'border-[#d6457a] bg-[#d6457a]')} />
|
||||
<b className={cx('mt-1.5 font-bagel text-lg leading-tight font-normal', t?.kind === 'peak' && 'text-[#d6457a]')}>{t ? clockShort(t.at) : <Skel className="w-12" />}</b>
|
||||
<span className="text-[12px] font-bold text-(--ink2)">{t ? t.label : <Skel className="w-11" />}</span>
|
||||
</li>
|
||||
))}
|
||||
</ol>
|
||||
<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}>
|
||||
<ol className="relative grid grid-cols-3">
|
||||
<span className="absolute inset-x-[16.6%] top-[6px] h-0.5 bg-(--line)" aria-hidden="true" />
|
||||
{(rows ?? THREE.map(() => undefined)).map((t, i) => (
|
||||
<li key={t?.kind ?? i} className="relative flex flex-col items-center text-center">
|
||||
<span className={cx('size-3 rounded-full border-2 border-(--line) bg-white', t?.kind === 'sun' && 'border-(--orange) bg-(--orange)')} />
|
||||
<b className="mt-1.5 font-bagel text-lg leading-tight font-normal">{t ? clockShort(t.at) : <Skel className="w-12" />}</b>
|
||||
<span className="text-[12px] font-bold text-(--ink2)">{t ? t.label : <Skel className="w-11" />}</span>
|
||||
</li>
|
||||
))}
|
||||
</ol>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function SpotsSkel() {
|
||||
return (
|
||||
<>
|
||||
<Skel shape className="mx-3 mt-3 aspect-[400/260] rounded-[26px]" />
|
||||
<ul className="mx-3 mt-1.5 flex flex-col">
|
||||
{THREE.map((i) => (
|
||||
<LiSkel key={i} />
|
||||
@@ -146,26 +89,6 @@ function SpotsSkel() {
|
||||
)
|
||||
}
|
||||
|
||||
function DaysSkel() {
|
||||
return (
|
||||
<div className="grid grid-cols-3 gap-2 p-3" aria-hidden="true">
|
||||
{THREE.map((i) => (
|
||||
<div key={i} className="rounded-[20px] bg-white p-3 text-center shadow-[inset_0_-5px_0_var(--shade)]">
|
||||
<small className="block text-[12.5px] font-extrabold">
|
||||
<Skel className="w-10" />
|
||||
</small>
|
||||
<b className="block font-bagel text-[30px] font-normal">
|
||||
<Skel className="w-10" />
|
||||
</b>
|
||||
<span className="block text-xs font-bold">
|
||||
<Skel className="w-12" />
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function RankSkel() {
|
||||
return (
|
||||
<ul className="mx-3 mt-1.5 flex flex-col" aria-hidden="true">
|
||||
@@ -176,13 +99,13 @@ function RankSkel() {
|
||||
)
|
||||
}
|
||||
|
||||
function Li({ no, title, sub, right, mine = false }: { no: number; title: string; sub?: string | null; right: string; mine?: boolean }) {
|
||||
function Li({ no, title, sub, right, mine = false, place }: { no: number; title: string; sub?: string | null; right: string; mine?: boolean; place?: string }) {
|
||||
return (
|
||||
<li className={cx('grid grid-cols-[34px_1fr_auto] items-center gap-2.5 border-b-[1.5px] border-(--line) px-1 py-3 last:border-b-0', mine && 'rounded-2xl bg-white')}>
|
||||
<span className="text-center font-bagel text-xl text-(--orange)">{no}</span>
|
||||
<span className="min-w-0">
|
||||
<b className="block font-jua text-[17px] font-normal">
|
||||
{title}
|
||||
{place ? <MapLink place={place}>{title}</MapLink> : title}
|
||||
{mine && <small className="ml-1.5 font-sans text-xs font-extrabold text-(--rain)">내 지역</small>}
|
||||
</b>
|
||||
<small className="block truncate text-[12.5px] font-semibold text-(--ink2)">{sub || '\u00a0'}</small>
|
||||
@@ -200,74 +123,57 @@ export function SkyPage() {
|
||||
const rankLoad = loadOf(ranking)
|
||||
const plan = sky.data?.plan ?? undefined
|
||||
const spots = (sky.data?.spots ?? []).slice(0, 3)
|
||||
const days = sky.data?.days ?? []
|
||||
const items = (ranking.data?.items ?? []).slice(0, 8)
|
||||
const target = Math.max(0, days.findIndex((d) => d.day === plan?.day))
|
||||
const best = days.reduce<number>((b, d, i) => (d.score > days[b].score ? i : b), target)
|
||||
// 서버 outlook 과 같은 기준: 10점 넘게 나을 때만 더 나은 날로 표시
|
||||
const better = days.length > 0 && days[best].score - days[target].score > 10 ? best : -1
|
||||
const target = sky.data?.days?.find((d) => d.day === plan?.day)
|
||||
const sunset = plan?.timeline?.find((t) => t.kind === 'sun')?.at
|
||||
|
||||
return (
|
||||
<section aria-label="노을" aria-busy={load === 'loading'} className={cx('transition-opacity', sky.isPlaceholderData && 'opacity-60')}>
|
||||
{/* 히어로 상자는 불러오는 중·실패·빈 값 모두 같은 크기 */}
|
||||
<div className={HERO}>
|
||||
<div className="b-skyline pointer-events-none absolute inset-0 [--sky-h:16%]" aria-hidden="true" />
|
||||
<p className="relative m-0 text-[13px] font-extrabold">
|
||||
<div className={cx(HERO, `b-sit-${target?.situation ?? 3}`)}>
|
||||
<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" />
|
||||
{/* 하늘 위 흰 글씨 대비가 모자라 어두운 바탕을 깐다 */}
|
||||
<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' ? (
|
||||
<HeroBody plan={plan} />
|
||||
<HeroBody plan={plan} sunset={sunset} />
|
||||
) : (
|
||||
<StateBox load={load} onRetry={() => sky.refetch()} empty="오늘 노을 정보가 없어요." hold={<HeroBody />} className="inset-x-0 top-1.5 bottom-0" />
|
||||
)}
|
||||
</div>
|
||||
<Sec title="언제 보면 좋을까" sub={plan ? `${plan.when} 해 지는 시간 기준` : '\u00a0'} />
|
||||
{(plan || load === 'loading') && <Verdict plan={plan} />}
|
||||
<Sec title="언제 보면 좋을까" sub="보통 해 진 뒤 10~20분이 가장 붉어요" />
|
||||
{plan?.timeline?.length || load === 'loading' ? (
|
||||
<Timeline rows={plan?.timeline} />
|
||||
) : (
|
||||
<StateBox load="ready" empty={load === 'ready' ? '노을 시간 정보가 없어요.' : '노을 시간을 불러오지 못했어요.'} hold={<Timeline />} className="inset-x-3 top-3 bottom-0" />
|
||||
)}
|
||||
<Sec title="내일·모레가 더 나을까" sub={plan?.outlook || '\u00a0'} />
|
||||
{days.length > 0 ? (
|
||||
<div className="grid grid-cols-3 gap-2 p-3">
|
||||
{days.map((d, i) => (
|
||||
<div key={d.day} className={cx('rounded-[20px] bg-white p-3 text-center shadow-[inset_0_-5px_0_var(--shade)]', i === better && 'ring-2 ring-[#d6457a] ring-inset')}>
|
||||
<small className="block text-[12.5px] font-extrabold text-(--ink2)">{dayLabel(d.day, i)}</small>
|
||||
<b className={cx('block font-bagel text-[30px] font-normal', d.score < 60 ? 'text-(--ink2)' : 'text-[#d6457a]')}>{d.score}</b>
|
||||
<span className="block text-xs font-bold text-(--ink2)">{d.grade_label}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
) : load === 'loading' ? (
|
||||
<DaysSkel />
|
||||
) : (
|
||||
<StateBox load="ready" empty={load === 'ready' ? '앞으로 3일 노을 정보가 없어요.' : '앞으로 3일 노을을 불러오지 못했어요.'} hold={<DaysSkel />} className="inset-3" />
|
||||
)}
|
||||
<Sec title="가까운 노을 명소" sub={sky.data?.sunset_azimuth != null ? `해 지는 ${compass(sky.data.sunset_azimuth)}쪽이 트인 곳, 가까운 순` : '서쪽이 트인 곳, 가까운 순'} />
|
||||
{/* 더 나은 날이 있을 때만 */}
|
||||
{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>}
|
||||
<Sec title="가까운 노을 명소" sub="가까운 순 · 방향은 내 동네에서 본 쪽" />
|
||||
{spots.length ? (
|
||||
<>
|
||||
<SpotMap region={region} spots={spots} azimuth={sky.data?.sunset_azimuth} />
|
||||
<ul className="mx-3 mt-1.5 flex flex-col">
|
||||
{spots.map((p) => (
|
||||
<Li key={p.no} no={p.no} title={p.name} sub={p.description} right={`${p.distance_km}km`} />
|
||||
))}
|
||||
{/* 3곳이 안 되면 빈 줄로 스켈레톤 높이를 지켜 아래 순위가 밀리지 않게 */}
|
||||
{THREE.slice(spots.length).map((i) => (
|
||||
<LiSkel key={`ghost-${i}`} ghost />
|
||||
))}
|
||||
</ul>
|
||||
</>
|
||||
<ul className="mx-3 mt-1.5 flex flex-col">
|
||||
{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} />
|
||||
))}
|
||||
{/* 3곳이 안 되면 빈 줄로 스켈레톤 높이를 지켜 아래 순위가 밀리지 않게 */}
|
||||
{THREE.slice(spots.length).map((i) => (
|
||||
<LiSkel key={`ghost-${i}`} ghost />
|
||||
))}
|
||||
</ul>
|
||||
) : load === 'loading' ? (
|
||||
<SpotsSkel />
|
||||
) : (
|
||||
// 실패 안내·다시 시도는 위 히어로에 한 번만. 여기는 지도·목록 자리만 지킨다
|
||||
// 실패 안내·다시 시도는 위 히어로에 한 번만. 여기는 목록 자리만 지킨다
|
||||
<StateBox load="ready" empty={load === 'ready' ? '근처에 등록된 노을 명소가 없어요.' : '명소 정보를 불러오지 못했어요.'} hold={<SpotsSkel />} className="inset-x-3 top-3 bottom-0" />
|
||||
)}
|
||||
<Sec title="전국 노을 순위" sub="오늘 기준" />
|
||||
<Sec title="전국 노을 순위" sub={ranking.data?.summary ?? '오늘 기준'} />
|
||||
{items.length ? (
|
||||
<ul className="mx-3 mt-1.5 flex flex-col">
|
||||
{items.map((r) => (
|
||||
<Li key={r.region_code} no={r.rank} title={r.name} sub={r.note} right={`${r.score}점`} mine={r.region_code === region.code} />
|
||||
<Li key={r.region_code} no={r.rank} title={r.name} sub={[r.note, r.situation_label].filter(Boolean).join(' · ')} right={`${r.score}점`} mine={r.region_code === region.code} />
|
||||
))}
|
||||
</ul>
|
||||
) : rankLoad === 'loading' ? (
|
||||
|
||||
+108
-55
@@ -4,7 +4,7 @@ import { useQuery } from '@tanstack/react-query'
|
||||
import { getFeedOptions, getWeatherTodayOptions } from '../api/client/@tanstack/react-query.gen'
|
||||
import type { BandArticle, BandEvent, Hero as HeroData, ResWeatherToday, TopIndex } from '../api/client/types.gen'
|
||||
import { cx } from '../lib/utils'
|
||||
import { cardBg, 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 { useRegion } from './regionContext'
|
||||
import { useSheet } from './sheetContext'
|
||||
@@ -15,7 +15,7 @@ import { deg, skyText, slotAt } from './weatherText'
|
||||
type Mode = 'now' | TimeKind
|
||||
|
||||
const MODES: [Mode, string][] = [
|
||||
['now', '지금'],
|
||||
['now', '지금 시간'],
|
||||
['morning', '아침'],
|
||||
['day', '낮'],
|
||||
['sunset', '저녁'],
|
||||
@@ -30,8 +30,14 @@ const PREVIEW: Record<TimeKind, { label: string; clock: string; hour: number }>
|
||||
night: { label: '밤', clock: '22:10', hour: 22 },
|
||||
}
|
||||
|
||||
// 불쾌지수는 6~9월에만 뜻이 있고, 그 밖엔 늘 '쾌적'이라 하루 최저·최고(일교차)를 보여 준다
|
||||
const isMuggySeason = (month: number) => month >= 6 && month <= 9
|
||||
const STARS = Array.from({ length: 26 }, (_, i) => ({ left: `${(i * 37) % 100}%`, top: `${(i * 53) % 60}%`, opacity: 0.4 + ((i * 7) % 6) / 10 }))
|
||||
// 별똥별 셋: 위치·길이·주기를 엇갈려 하나씩 떨어지게
|
||||
const SHOOTS = [
|
||||
{ top: '6%', left: '80%', '--len': '90px', '--dur': '7s', '--dl': '1.5s' },
|
||||
{ top: '20%', left: '52%', '--len': '70px', '--dur': '9s', '--dl': '4s' },
|
||||
{ top: '34%', left: '94%', '--len': '80px', '--dur': '11s', '--dl': '6.5s' },
|
||||
]
|
||||
const ORB_POS = { left: '66%', top: '6px', d: '.5s', f: '4.4s' }
|
||||
|
||||
function useNow(ms = 20000) {
|
||||
const [now, setNow] = useState(() => new Date())
|
||||
@@ -60,6 +66,8 @@ function heroVal(load: Load, v: ReactNode, skel: string) {
|
||||
)
|
||||
}
|
||||
|
||||
const failed = (load: Load) => load === 'error' || load === 'retrying'
|
||||
|
||||
type HeroProps = { hero?: HeroData | null; today?: ResWeatherToday; feedLoad: Load; todayLoad: Load }
|
||||
|
||||
function Hero({ hero, today, feedLoad, todayLoad }: HeroProps) {
|
||||
@@ -79,82 +87,122 @@ function Hero({ hero, today, feedLoad, todayLoad }: HeroProps) {
|
||||
const temp = mode === 'now' && hero ? hero.temp_c : slot?.temp_c
|
||||
const feels = mode === 'now' && hero ? hero.feels_c : slot?.feels_c
|
||||
const top1 = hero?.top1
|
||||
const who = kind === 'night' ? 'bear' : 'rabbit'
|
||||
// 저녁(노을)부터는 가운데 동그라미가 오늘 밤 달 모양이 된다
|
||||
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 temps = slots.flatMap((s) => (s.temp_c == null ? [] : [s.temp_c]))
|
||||
const muggy = isMuggySeason(t.mo)
|
||||
const feelsLine = temp != null ? `체감 ${deg(feels)}${slot ? ` · ${skyText(slot)}` : ''}` : tempLoad === 'loading' ? null : '체감 ?°'
|
||||
// 1위 각 이름·점수는 바로 아래 '오늘의 각' 줄에 있으니 히어로는 결론 한 줄만
|
||||
const gakLine = hero?.bubble ?? (hero ? '오늘은 쉬어 가요' : null)
|
||||
const feelsLine = temp != null ? `체감 ${deg(feels)}${slot ? ` · ${skyText(slot)}` : ''}` : failed(tempLoad) ? '날씨를 못 불러왔어요' : tempLoad === 'ready' ? '체감 ?°' : null
|
||||
const bubble = hero ? (hero.bubble ?? '오늘은 쉬어 가요') : failed(feedLoad) ? '앗, 날씨를 못 불러왔어요' : null
|
||||
|
||||
// 글자 크기는 64(기온)·40(점수)·16(값)·13(라벨) 네 단계. 모든 값은 한 줄이라 로딩·완료·실패 높이가 같다
|
||||
// 아래 값은 모두 로딩·완료·실패 사이 높이가 같다: 글자 자리 스켈레톤, 비 칸은 두 줄 높이로 고정
|
||||
return (
|
||||
<div className="b-hero mx-3 mt-1 rounded-[28px] px-4 pt-3.5 pb-4" data-t={kind}>
|
||||
<div className="b-seg flex rounded-full p-[3px]" role="group" aria-label="시간대 배경 미리보기">
|
||||
<div className="b-hero relative mx-3 mt-1 overflow-hidden rounded-[32px] px-[18px] pt-4 pb-[18px]" data-t={kind}>
|
||||
<div className="b-stars pointer-events-none absolute inset-0" aria-hidden="true">
|
||||
{STARS.map((s, i) => (
|
||||
<i key={i} className="absolute size-[3px] rounded-full shadow-[0_0_6px_#fff]" style={s} />
|
||||
))}
|
||||
{SHOOTS.map((s, i) => (
|
||||
<span key={i} className="b-shoot" style={s} />
|
||||
))}
|
||||
</div>
|
||||
<div className="relative z-[3] flex flex-wrap gap-1.5" role="group" aria-label="시간대 배경 미리보기">
|
||||
{MODES.map(([m, l]) => (
|
||||
<button key={m} type="button" aria-pressed={mode === m} onClick={() => setMode(m)} className="flex-1 cursor-pointer rounded-full py-1 text-[13px] font-bold">
|
||||
<button key={m} type="button" aria-pressed={mode === m} onClick={() => setMode(m)} className={cx('cursor-pointer rounded-full px-2.5 py-[5px] text-xs font-bold', mode === m ? 'bg-(--ink) text-white' : 'bg-white/55 text-(--ink)')}>
|
||||
{l}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<div className="mt-4 flex items-center justify-between gap-3 px-1">
|
||||
<div className="min-w-0">
|
||||
<p className="text-[13px] font-bold">
|
||||
{t.mo}월 {t.d}일 {WEEKDAYS[t.wd]}요일 · {mode === 'now' ? `${String(t.h).padStart(2, '0')}:${String(t.mi).padStart(2, '0')}` : `${PREVIEW[mode].label} ${PREVIEW[mode].clock} 예보`}
|
||||
<div className="relative z-[3] mt-3 flex items-end justify-between">
|
||||
<div>
|
||||
<p className="mb-1 text-[13.5px] font-bold opacity-85">
|
||||
{t.mo}월 {t.d}일 {WEEKDAYS[t.wd]}요일 · {mode === 'now' ? '지금' : `${PREVIEW[mode].label} 미리보기`}
|
||||
</p>
|
||||
<b className="block font-bagel text-[64px] leading-[1.1] font-normal">{heroVal(tempLoad, temp != null ? deg(temp) : null, 'w-[112px]')}</b>
|
||||
<p className="truncate font-jua text-base">{feelsLine ?? <Skel className="w-[112px]" />}</p>
|
||||
<div className="font-bagel text-[60px] leading-none">{mode === 'now' ? `${String(t.h).padStart(2, '0')}:${String(t.mi).padStart(2, '0')}` : PREVIEW[mode].clock}</div>
|
||||
</div>
|
||||
<div className="b-sun b-bob grid size-[112px] shrink-0 place-items-center rounded-full text-center">
|
||||
<span>
|
||||
<b className="block font-bagel text-[40px] leading-[1.1] font-normal">{heroVal(feedLoad, hero?.weather_score, 'w-[52px]')}</b>
|
||||
<small className="block text-[13px] font-bold">날씨 점수</small>
|
||||
</span>
|
||||
<div className="text-right">
|
||||
<b className="block font-bagel text-[42px] leading-none font-normal">{heroVal(tempLoad, temp != null ? deg(temp) : null, 'w-[72px]')}</b>
|
||||
<span className="block text-[12.5px] font-bold opacity-85">{feelsLine ?? <Skel className="w-[118px]" />}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div className="b-stat mt-4 grid grid-cols-2 rounded-[20px]">
|
||||
<HeroStat icon="umbrella" label="앞으로 2시간">
|
||||
{heroVal(feedLoad, hero?.will_rain_2h == null ? null : hero.will_rain_2h ? '비, 우산 챙겨요' : '비 안 와요', 'w-[72px]')}
|
||||
<div className="relative z-[3] mt-3 grid grid-cols-2 gap-2.5">
|
||||
<HeroStat icon="thermo" label="불쾌지수">
|
||||
{heroVal(feedLoad, hero?.discomfort != null ? `${hero.discomfort} · ${hero.discomfort_label ?? ''}` : null, 'w-16')}
|
||||
</HeroStat>
|
||||
<HeroStat icon="thermo" label={muggy ? '불쾌지수' : '오늘 최저·최고'} className="border-l border-current/10">
|
||||
{muggy
|
||||
? heroVal(feedLoad, hero?.discomfort != null ? `${hero.discomfort} · ${hero.discomfort_label ?? ''}` : null, 'w-[72px]')
|
||||
: heroVal(todayLoad, temps.length ? `${deg(Math.min(...temps))} ~ ${deg(Math.max(...temps))}` : null, 'w-[72px]')}
|
||||
<HeroStat icon="umbrella" label="지금 비">
|
||||
{heroVal(feedLoad, hero?.will_rain_2h == null ? null : hero.will_rain_2h ? '2시간 안에 와요' : '2시간 동안 안 와요', 'w-16')}
|
||||
</HeroStat>
|
||||
</div>
|
||||
<div className="relative mt-5 h-[286px]">
|
||||
<span className="b-cloud b-fall top-6 left-[6%] h-[30px] w-[84px]" style={fall('.1s', '6s')} aria-hidden="true" />
|
||||
<div className="b-sun b-fall absolute top-10 left-1/2 -ml-[82px] grid aspect-square w-[164px] place-items-center rounded-full text-center" style={fall('0s', '5.6s', '8px')}>
|
||||
{/* 안 보이는 쪽을 덮어 오늘 밤 달 모양으로 */}
|
||||
{moon && (
|
||||
<svg viewBox="-1 -1 2 2" className="pointer-events-none absolute inset-0 size-full" aria-hidden="true">
|
||||
<path d={moonPath(moon.pct, 1, false)} fill={kind === 'sunset' ? 'rgb(96 40 86 / .55)' : 'rgb(34 30 86 / .62)'} transform={moon.waning ? 'scale(-1,1)' : undefined} />
|
||||
</svg>
|
||||
)}
|
||||
<span className={cx('relative', moon && '[text-shadow:0_0_6px_#fff,0_0_12px_#fff]')}>
|
||||
<b className="block font-bagel text-[56px] leading-[0.9] font-normal">{heroVal(feedLoad, hero?.weather_score, 'w-[84px]')}</b>
|
||||
<small className="mt-0.5 block font-jua text-[14.5px]">{failed(feedLoad) ? '점수를 못 불러왔어요' : '오늘 날씨 점수'}</small>
|
||||
</span>
|
||||
</div>
|
||||
<span className="b-cloud b-fall top-[188px] left-[54%] h-10 w-[118px]" style={fall('.25s', '6.4s')} aria-hidden="true" />
|
||||
{top1 ? (
|
||||
<button type="button" onClick={() => open({ type: 'gak', indexId: top1.index_id })} aria-label={`오늘의 1위 ${top1.name} ${top1.score}점, 계산 근거 보기`} className="col-span-2 flex cursor-pointer items-center gap-2 border-t border-current/10 px-3.5 py-2.5 text-left">
|
||||
<HeroGak line={gakLine} load={feedLoad} />
|
||||
<span className="shrink-0 text-[13px] font-bold opacity-75" aria-hidden="true">
|
||||
근거 보기 ›
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => open({ type: 'gak', indexId: top1.index_id })}
|
||||
aria-label={`1위 ${top1.name} ${top1.score}점, 계산 근거 보기`}
|
||||
className="b-fall absolute z-[2] flex w-24 cursor-pointer flex-col items-center"
|
||||
style={{ left: ORB_POS.left, top: ORB_POS.top, ...fall(ORB_POS.d, ORB_POS.f) }}
|
||||
>
|
||||
<span className="relative w-[78px]">
|
||||
<Ic name={top1.icon} className="w-full drop-shadow-[0_10px_12px_rgb(40_48_74/0.16)]" />
|
||||
<Ic name={MEDALS[0]} className="absolute -top-2 -left-3.5 w-[30px]" />
|
||||
</span>
|
||||
<span className="b-orb-label font-jua text-sm whitespace-nowrap">
|
||||
1위 {top1.name} <em className="font-bagel text-(--orange) not-italic">{top1.score}</em>
|
||||
</span>
|
||||
</button>
|
||||
) : (
|
||||
<div className="col-span-2 flex items-center gap-2 border-t border-current/10 px-3.5 py-2.5">
|
||||
<HeroGak line={gakLine} load={feedLoad} />
|
||||
</div>
|
||||
feedLoad === 'loading' && (
|
||||
<span className="absolute z-[2] flex w-24 flex-col items-center gap-1" style={{ left: ORB_POS.left, top: ORB_POS.top }} aria-hidden="true">
|
||||
<Skel shape className="size-[78px] rounded-full" />
|
||||
<span className="font-jua text-sm">
|
||||
<Skel className="w-[72px]" />
|
||||
</span>
|
||||
</span>
|
||||
)
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function HeroStat({ icon, label, className, children }: { icon: string; label: string; className?: string; children: ReactNode }) {
|
||||
return (
|
||||
<div className={cx('flex min-w-0 items-center gap-2.5 px-3.5 py-2.5', className)}>
|
||||
<Ic name={icon} className="w-7 shrink-0" />
|
||||
<div className="min-w-0">
|
||||
<small className="block text-[13px] font-bold opacity-75">{label}</small>
|
||||
<b className="block truncate font-jua text-base font-normal">{children}</b>
|
||||
<div className="relative z-[3] flex items-end gap-2">
|
||||
<Ic name={who} alt={who === 'rabbit' ? '토끼' : '곰'} className="w-[50px] drop-shadow-[0_8px_10px_rgb(40_48_74/0.15)]" />
|
||||
<span className="mb-3 rounded-[20px_20px_20px_6px] bg-white px-3.5 py-[9px] font-jua text-base text-(--ink) shadow-[0_8px_16px_rgb(40_48_74/0.1)]">{bubble ?? <Skel className="w-[120px]" />}</span>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function HeroGak({ line, load }: { line: string | null; load: Load }) {
|
||||
const WANING = ['기우는 달', '하현달', '그믐달']
|
||||
|
||||
/**
|
||||
* 반지름 r 인 달에서 밝은 쪽(lit) 또는 어두운 쪽 경로. 차오르는 달 기준(오른쪽이 밝음), 기우는 달은 좌우를 뒤집어 쓴다.
|
||||
* 바깥 반원과 명암 경계(가로 반지름 r·|1-2k| 인 타원 호)로 이루어진다.
|
||||
*/
|
||||
function moonPath(pct: number, r: number, lit: boolean) {
|
||||
const k = pct / 100
|
||||
const edge = `A${r * Math.abs(1 - 2 * k)},${r} 0 0 ${k < 0.5 ? 0 : 1} 0,${-r}`
|
||||
return `M0,${-r} A${r},${r} 0 0 ${lit ? 1 : 0} 0,${r} ${edge}`
|
||||
}
|
||||
|
||||
function HeroStat({ icon, label, children }: { icon: string; label: string; children: ReactNode }) {
|
||||
return (
|
||||
<span className="min-w-0 flex-1">
|
||||
<small className="block text-[13px] font-bold opacity-75">오늘의 각</small>
|
||||
<b className="block truncate font-jua text-base font-normal">{heroVal(load, line, 'w-[128px]')}</b>
|
||||
</span>
|
||||
<div className="b-stat flex min-h-[90px] items-center gap-2.5 rounded-[20px] px-3 py-[9px]">
|
||||
<Ic name={icon} className="w-9 shrink-0" />
|
||||
<div className="min-w-0">
|
||||
<small className="block text-xs font-bold opacity-80">{label}</small>
|
||||
<b className="block font-jua text-lg font-normal">{children}</b>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -287,6 +335,10 @@ export function TodayPage() {
|
||||
const nowAt = f?.hero?.now_at
|
||||
const load = loadOf(feed)
|
||||
|
||||
useEffect(() => {
|
||||
window.scrollTo({ top: 0 })
|
||||
}, [region.code])
|
||||
|
||||
// 디자인대로 3·6·9번째 글 뒤에 띠를 넣고, 글이 모자라면 남은 띠는 맨 뒤에 붙인다
|
||||
const bandAt: [number, ReactNode][] = [
|
||||
[3, bands?.events?.length ? <EventsBand key="events" events={bands.events} /> : null],
|
||||
@@ -295,7 +347,8 @@ export function TodayPage() {
|
||||
]
|
||||
|
||||
return (
|
||||
<section 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)} />
|
||||
<Sec title="오늘의 각" sub="누르면 계산 근거를 보여 줘요" more={{ to: '/gak' }} />
|
||||
{/* 실패 안내는 여기 한 번만, 각 줄 스켈레톤과 같은 크기로 */}
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
import { useState } from 'react'
|
||||
import { useState, type ReactNode } from 'react'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { getWeekOptions, getWeekRankingOptions, listEventsOptions, listPlacesOptions } from '../api/client/@tanstack/react-query.gen'
|
||||
import { cx } from '../lib/utils'
|
||||
import { cardBg, dateRange, loadOf, shortDay, sidoOf } from './lib'
|
||||
import { useRegion } from './regionContext'
|
||||
import { useSheet } from './sheetContext'
|
||||
import { Chips, Ic, Rail, Sec, Skel, SkelRail, StateBox, Thumb } from './ui'
|
||||
import { Arrows, Chips, Ic, MapLink, Rail, Sec, Skel, SkelRail, StateBox, Thumb } from './ui'
|
||||
import { useCarousel } from './carousel'
|
||||
|
||||
const TEN = Array.from({ length: 10 }, (_, i) => i)
|
||||
const THREE = [0, 1, 2]
|
||||
@@ -173,7 +174,7 @@ export function WeekPage() {
|
||||
<section aria-label="주말·행사" aria-busy={weekLoad === 'loading'}>
|
||||
<Sec title="열흘 날씨" sub="날짜를 누르면 그날 추천이 바뀌어요" />
|
||||
{days.length ? (
|
||||
<div className={cx('flex snap-x gap-1 overflow-x-auto px-3 pt-3 transition-opacity [scrollbar-width:none]', week.isPlaceholderData && 'opacity-60')} role="group" aria-label="날짜 고르기">
|
||||
<DayStrip dim={week.isPlaceholderData}>
|
||||
{days.map((d) => {
|
||||
const on = d.day === sel?.day
|
||||
const weekend = d.weekday === '토' || d.weekday === '일' || !!d.holiday
|
||||
@@ -192,7 +193,7 @@ export function WeekPage() {
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</DayStrip>
|
||||
) : weekLoad === 'loading' ? (
|
||||
<>
|
||||
<DaysSkel />
|
||||
@@ -247,7 +248,9 @@ export function WeekPage() {
|
||||
<span className="text-[11.5px] font-extrabold text-(--ink3)">
|
||||
{p.area} · {p.is_outdoor ? '야외' : '실내'}
|
||||
</span>
|
||||
<b className="block font-jua text-[16.5px] font-normal">{p.name}</b>
|
||||
<b className="block font-jua text-[16.5px] font-normal">
|
||||
<MapLink place={p.name}>{p.name}</MapLink>
|
||||
</b>
|
||||
<small className="block text-[12.5px] leading-snug font-semibold text-(--ink2)">
|
||||
{p.reason}
|
||||
<br />
|
||||
@@ -313,7 +316,13 @@ export function WeekPage() {
|
||||
{e.name}
|
||||
</b>
|
||||
<small className="block truncate text-[12.5px] font-semibold text-(--ink2)">
|
||||
{[dateRange(e.start_date, e.end_date), e.place_name].filter(Boolean).join(' · ')}
|
||||
{dateRange(e.start_date, e.end_date)}
|
||||
{e.place_name && (
|
||||
<>
|
||||
{' · '}
|
||||
<MapLink place={e.place_name}>{e.place_name}</MapLink>
|
||||
</>
|
||||
)}
|
||||
{!e.is_confirmed && ' · 일정 확인 필요'}
|
||||
</small>
|
||||
<span className={cx('mt-[5px] block h-[1lh] text-xs font-extrabold', e.fit?.includes('비') ? 'text-[#d6457a]' : 'text-[#1f9d62]')}>{e.fit}</span>
|
||||
@@ -334,3 +343,18 @@ export function WeekPage() {
|
||||
</section>
|
||||
)
|
||||
}
|
||||
|
||||
const DAY_STRIP = { align: 'start', dragFree: true, containScroll: 'trimSnaps' } as const
|
||||
|
||||
/** 열흘 날짜 줄: 손가락·마우스로 끌어 넘기고, PC 에선 화살표도 */
|
||||
function DayStrip({ children, dim }: { children: ReactNode; dim: boolean }) {
|
||||
const { ref, api, prev, next } = useCarousel(DAY_STRIP)
|
||||
return (
|
||||
<div className="relative" role="group" aria-label="날짜 고르기">
|
||||
<div ref={ref} className="overflow-hidden">
|
||||
<div className={cx('flex gap-1 px-3 pt-3 transition-opacity *:shrink-0', dim && 'opacity-60')}>{children}</div>
|
||||
</div>
|
||||
<Arrows api={api} prev={prev} next={next} />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
+82
-39
@@ -142,80 +142,114 @@
|
||||
}
|
||||
}
|
||||
|
||||
/* 히어로 시간대 배경 (글자 대비 AA: 저녁은 위쪽을 깊은 보라로) */
|
||||
/* 히어로 시간대 배경 (저녁은 흰 글자 대비 AA 4.5:1 이상이 되게 깊은 보라로) */
|
||||
.b-hero {
|
||||
transition: background 0.6s;
|
||||
}
|
||||
.b-hero[data-t='morning'] {
|
||||
background: linear-gradient(180deg, #ffd9b8, #ffe9d4 45%, #dff0ff);
|
||||
background: linear-gradient(180deg, #ffd9b8, #ffe9d4 40%, #dff0ff);
|
||||
}
|
||||
.b-hero[data-t='day'] {
|
||||
background: linear-gradient(180deg, #9fd3ff, #cfe9ff 55%, #f1f8ff);
|
||||
}
|
||||
.b-hero[data-t='sunset'] {
|
||||
background: linear-gradient(180deg, #5d4fc4, #8b56b8 50%, #e27a8f);
|
||||
background: linear-gradient(180deg, #4c42b0, #6a48b0 45%, #9a4a88);
|
||||
color: #fff;
|
||||
}
|
||||
.b-hero[data-t='night'] {
|
||||
background: linear-gradient(180deg, #141b3d, #27306a 60%, #3d3f86);
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
/* 시간대 미리보기: 한 줄 트랙, 고른 칸만 흰 알약 */
|
||||
.b-seg {
|
||||
background: rgb(255 255 255 / 0.45);
|
||||
.b-hero .b-stars {
|
||||
opacity: 0;
|
||||
transition: opacity 0.6s;
|
||||
}
|
||||
.b-hero:is([data-t='sunset'], [data-t='night']) .b-seg {
|
||||
background: rgb(0 0 0 / 0.2);
|
||||
.b-hero[data-t='night'] .b-stars {
|
||||
opacity: 1;
|
||||
}
|
||||
.b-seg [aria-pressed='true'] {
|
||||
.b-stars i {
|
||||
background: #fff;
|
||||
color: #28304a;
|
||||
box-shadow: 0 1px 4px rgb(40 48 74 / 0.16);
|
||||
}
|
||||
|
||||
/* 비·기온·오늘의 각 카드: 저녁도 밝은 카드라 진한 글자 */
|
||||
.b-stat {
|
||||
background: rgb(255 255 255 / 0.72);
|
||||
color: #28304a;
|
||||
box-shadow: inset 0 -4px 0 rgb(217 229 244 / 0.9);
|
||||
color: var(--ink);
|
||||
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-stat {
|
||||
background: rgb(255 255 255 / 0.18);
|
||||
color: #fff;
|
||||
box-shadow: inset 0 -5px 0 rgb(255 255 255 / 0.12);
|
||||
}
|
||||
.b-hero[data-t='sunset'] .b-stat {
|
||||
background: rgb(255 255 255 / 0.88);
|
||||
box-shadow: inset 0 -4px 0 rgb(255 255 255 / 0.4);
|
||||
background: rgb(30 16 80 / 0.2);
|
||||
}
|
||||
.b-hero[data-t='night'] .b-stat {
|
||||
background: rgb(255 255 255 / 0.12);
|
||||
color: #fff;
|
||||
box-shadow: inset 0 -4px 0 rgb(255 255 255 / 0.08);
|
||||
.b-orb-label {
|
||||
text-shadow: 0 2px 0 rgb(255 255 255 / 0.7);
|
||||
}
|
||||
.b-hero[data-t='night'] .b-orb-label,
|
||||
.b-hero[data-t='sunset'] .b-orb-label {
|
||||
text-shadow: 0 2px 0 rgb(0 0 0 / 0.2);
|
||||
}
|
||||
|
||||
/* 히어로에서 유일하게 강조하는 장식: 점수를 담은 해(밤엔 달) */
|
||||
.b-sun {
|
||||
background: radial-gradient(circle at 34% 30%, #fff5cf, #ffc86e 34%, #ff9a58 72%, #f07a45);
|
||||
background: radial-gradient(circle at 34% 30%, #fff5cf, #ffc86e 30%, #ff8e4e 68%, #ee6436);
|
||||
box-shadow:
|
||||
inset -12px -16px 28px rgb(170 50 20 / 0.28),
|
||||
inset 10px 12px 20px rgb(255 255 255 / 0.55),
|
||||
0 16px 36px rgb(240 106 58 / 0.3);
|
||||
color: #28304a;
|
||||
inset -18px -24px 40px rgb(170 50 20 / 0.34),
|
||||
inset 16px 18px 28px rgb(255 255 255 / 0.55),
|
||||
0 30px 56px rgb(240 106 58 / 0.32);
|
||||
color: #5c1f08; /* 흰 글씨는 주황 위에서 대비가 모자람 */
|
||||
}
|
||||
/* 저녁(노을)부터는 해 대신 달. 저녁엔 노을빛, 밤엔 차가운 달빛 */
|
||||
.b-hero[data-t='sunset'] .b-sun {
|
||||
background: radial-gradient(circle at 34% 30%, #fff4e6, #ffd9b8 32%, #f7a991 68%, #e07a8f);
|
||||
color: #4a2442;
|
||||
box-shadow:
|
||||
inset -18px -24px 40px rgb(150 50 90 / 0.3),
|
||||
inset 16px 18px 28px rgb(255 255 255 / 0.55),
|
||||
0 0 60px rgb(255 150 110 / 0.5);
|
||||
}
|
||||
.b-hero[data-t='night'] .b-sun {
|
||||
background: radial-gradient(circle at 34% 30%, #fff, #e7e3ff 35%, #b9b0f2 72%, #8f86d9);
|
||||
color: #2b2a5c;
|
||||
box-shadow:
|
||||
inset -12px -16px 28px rgb(60 50 140 / 0.26),
|
||||
inset 10px 12px 20px rgb(255 255 255 / 0.6),
|
||||
0 0 44px rgb(190 180 255 / 0.4);
|
||||
inset -18px -24px 40px rgb(60 50 140 / 0.3),
|
||||
inset 16px 18px 28px rgb(255 255 255 / 0.6),
|
||||
0 0 60px rgb(190 180 255 / 0.45);
|
||||
}
|
||||
.b-bob {
|
||||
--amp: 4px;
|
||||
--tilt: 0deg;
|
||||
animation: b-float 6s ease-in-out infinite;
|
||||
|
||||
.b-cloud {
|
||||
position: absolute;
|
||||
border-radius: 999px;
|
||||
background: #fff;
|
||||
box-shadow:
|
||||
inset 0 -12px 18px rgb(160 190 230 / 0.45),
|
||||
0 16px 28px rgb(40 70 120 / 0.13);
|
||||
}
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.b-bob {
|
||||
animation: none;
|
||||
}
|
||||
.b-cloud::before,
|
||||
.b-cloud::after {
|
||||
content: '';
|
||||
position: absolute;
|
||||
border-radius: 999px;
|
||||
background: #fff;
|
||||
box-shadow: inset 0 -10px 16px rgb(160 190 230 / 0.35);
|
||||
}
|
||||
.b-cloud::before {
|
||||
left: 16%;
|
||||
top: -58%;
|
||||
width: 46%;
|
||||
aspect-ratio: 1;
|
||||
}
|
||||
.b-cloud::after {
|
||||
left: 50%;
|
||||
top: -36%;
|
||||
width: 36%;
|
||||
aspect-ratio: 1;
|
||||
}
|
||||
.b-hero[data-t='night'] .b-cloud,
|
||||
.b-hero[data-t='night'] .b-cloud::before,
|
||||
.b-hero[data-t='night'] .b-cloud::after {
|
||||
background: #c9cdf0;
|
||||
}
|
||||
|
||||
/* 이야기 고리 */
|
||||
@@ -249,6 +283,15 @@
|
||||
}
|
||||
|
||||
/* 건물 실루엣 */
|
||||
/* 노을 탭 히어로: 하늘 상황(SkySituation)별 하늘 색. 1 가려짐 2 낮은 구름 3 물들 구름 적음 4 넓게 물듦 5 두꺼움 */
|
||||
.b-sit-1 { background: linear-gradient(180deg, #6f7690, #9aa0b4 55%, #b9b4c0); }
|
||||
.b-sit-2 { background: linear-gradient(180deg, #7a7f9c, #a7a3bb 55%, #c9b8b8); }
|
||||
.b-sit-3 { background: linear-gradient(180deg, #4b5aa8 0%, #7f86c6 38%, #e9b9a8 68%, #ffb27a 86%, #ff8a4c 100%); }
|
||||
.b-sit-4 { background: linear-gradient(180deg, #5b3f9e 0%, #c2559a 40%, #ff7a6a 68%, #ffb35c 100%); }
|
||||
.b-sit-5 { background: linear-gradient(180deg, #6a6aa0, #a98fb4 55%, #e3b1a0); }
|
||||
.b-sit-sun { background: radial-gradient(circle, #fff6dd 0%, #ffd08f 38%, rgb(255 160 90 / 0) 70%); }
|
||||
.b-sit-1 .b-sit-sun, .b-sit-2 .b-sit-sun { opacity: 0.25; }
|
||||
.b-sit-5 .b-sit-sun { opacity: 0.55; }
|
||||
.b-skyline::after {
|
||||
content: '';
|
||||
position: absolute;
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
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'])
|
||||
const OWN = new Set(['fireworks', 'bulb', 'calendar', 'thermo', 'sheaf'])
|
||||
const OWN = new Set(['fireworks', 'bulb', 'calendar', 'thermo', 'sheaf', 'popup', 'exhibition', 'concert'])
|
||||
|
||||
/** 아이콘 이름 → 파일 경로 (공용 public/icons, B 전용 public/b/icons). 'none'(데이터 없는 칸)은 그림 없음 */
|
||||
export function iconSrc(name: string) {
|
||||
@@ -63,6 +63,9 @@ export function clockShort(iso: string) {
|
||||
const COMPASS = ['북', '북북동', '북동', '동북동', '동', '동남동', '남동', '남남동', '남', '남남서', '남서', '서남서', '서', '서북서', '북서', '북북서']
|
||||
|
||||
/** 방위각 → 16방위 이름. 263 → "서" */
|
||||
/** 네이버 지도에서 장소 이름(또는 주소)으로 찾기 */
|
||||
export const naverMap = (query: string) => `https://map.naver.com/p/search/${encodeURIComponent(query)}`
|
||||
|
||||
export const compass = (deg: number) => COMPASS[Math.round(deg / 22.5) % 16]
|
||||
|
||||
/** 18:30 → "6시 반", 18:25 → "6시 25분" */
|
||||
@@ -111,7 +114,7 @@ export function dateRange(start: string, end: string) {
|
||||
}
|
||||
|
||||
const CARD_BG = ['night', 'butter', 'lilac', 'mint', 'peach', 'sky'] as const
|
||||
const ICON_BG: Record<string, (typeof CARD_BG)[number] | 'dusk'> = { picnic: 'mint', walk: 'mint', sunset: 'dusk', chimaek: 'peach', photo: 'butter', fireworks: 'night', sheaf: 'butter', rain: 'sky', calendar: 'sky', bulb: 'lilac', maple: 'peach', snow: 'sky', thermo: 'sky', umbrella: 'lilac' }
|
||||
const ICON_BG: Record<string, (typeof CARD_BG)[number] | 'dusk'> = { picnic: 'mint', walk: 'mint', sunset: 'dusk', chimaek: 'peach', photo: 'butter', fireworks: 'night', popup: 'peach', exhibition: 'lilac', concert: 'night', sheaf: 'butter', rain: 'sky', calendar: 'sky', bulb: 'lilac', maple: 'peach', snow: 'sky', thermo: 'sky', umbrella: 'lilac' }
|
||||
|
||||
/** API에 배경색이 없어 아이콘·순서로 카드 배경을 고른다 */
|
||||
export function cardBg(icon: string, index: number) {
|
||||
|
||||
+12
-3
@@ -2,7 +2,7 @@ import { useState, type CSSProperties, type ReactNode } from 'react'
|
||||
import { Link } from 'react-router'
|
||||
import { cx } from '../lib/utils'
|
||||
import { useCarousel, type Carousel } from './carousel'
|
||||
import { AVATAR_COLORS, iconSrc, moodEmoji, type Load } from './lib'
|
||||
import { AVATAR_COLORS, iconSrc, moodEmoji, naverMap, type Load } from './lib'
|
||||
|
||||
type IcProps = { name: string; className?: string; alt?: string; style?: CSSProperties }
|
||||
|
||||
@@ -193,13 +193,22 @@ export function StateBox({ load, onRetry, empty, className, hold }: StateProps)
|
||||
}
|
||||
|
||||
/** 줄 목록 (라벨 · 값) */
|
||||
export function Rows({ rows, dark = false }: { rows: { label: string; value: string }[]; dark?: boolean }) {
|
||||
/** 위치가 정해진 장소 이름. 누르면 네이버 지도가 새 탭으로 열린다 */
|
||||
export function MapLink({ place, children, className }: { place: string; children: ReactNode; className?: string }) {
|
||||
return (
|
||||
<a href={naverMap(place)} target="_blank" rel="noopener noreferrer" aria-label={`${place}, 네이버 지도에서 보기`} className={cx('underline decoration-dotted decoration-1 underline-offset-[3px]', className)}>
|
||||
{children}
|
||||
</a>
|
||||
)
|
||||
}
|
||||
|
||||
export function Rows({ rows, dark = false }: { rows: { label: string; value: string; place?: string | null }[]; dark?: boolean }) {
|
||||
return (
|
||||
<div className="mt-auto flex flex-col">
|
||||
{rows.map((r) => (
|
||||
<div key={r.label} className={cx('flex justify-between gap-2.5 border-b-2 py-2.5 font-bold last:border-b-0', dark ? 'border-white/18' : 'border-[rgb(40_48_74/0.08)]')}>
|
||||
<span>{r.label}</span>
|
||||
<b className="text-right font-jua text-[17px] font-normal">{r.value}</b>
|
||||
<b className="text-right font-jua text-[17px] font-normal">{r.place ? <MapLink place={r.place}>{r.value}</MapLink> : r.value}</b>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
@@ -19,6 +19,14 @@
|
||||
}
|
||||
body {
|
||||
@apply bg-page font-sans text-ink antialiased;
|
||||
/* 앱처럼: 끌어도 글자가 선택되지 않게. 입력칸은 아래에서 다시 허용 */
|
||||
user-select: none;
|
||||
-webkit-user-select: none;
|
||||
-webkit-touch-callout: none;
|
||||
}
|
||||
:is(input, textarea, [contenteditable='true']) {
|
||||
user-select: text;
|
||||
-webkit-user-select: text;
|
||||
}
|
||||
:focus-visible {
|
||||
outline: 3px solid var(--color-rain);
|
||||
|
||||
Reference in new issue
Block a user