feat: 축제·전시·콘서트·팝업 7일마다 수집, 피드 행사 종류 섞기
- 행사 수집을 화면 요청에서 빼고 worker 가 월 04:00(켤 때 7일 기록 없으면 한 번) 전국 17개 시도를 받는다 - 문화정보원 음악/콘서트(B000) 추가, 쪽·시도 사이 1초 간격으로 초당 요청 제한 회피 - 팝가(popga.co.kr) 팝업스토어 수집: 사이트맵 + 상세 JSON-LD, 바뀐 페이지만 다시 읽음 - 수집이 끝나면 Teams Workflows webhook 으로 종류별 건수 알림 (TEAMS_WEBHOOK_URL) - event.kind(1=축제 2=전시 3=콘서트 4=팝업) 칸과 종류별 아이콘 추가 - 피드 행사 카드·띠를 축제→팝업→전시→콘서트 차례로 섞음 - 포스트 종류별 내용·피드 기획 문서 갱신 같은 작업 폴더의 다른 작업(외부 API 가드, 노을·달 계산, 각 API, 문서 파일 이름 정리 등)도 함께 담김.
This commit is contained in:
1 parent
b61ed92c54
commit
997a366e76
70 files changed
+2083
-649
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
|
||||
|
||||
@@ -25,13 +25,13 @@
|
||||
| [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/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,11 +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`) |
|
||||
| [ ] | **[결정 필요]** 히어로 시안 A/B/C 중 선택 — 지금은 이전 히어로로 롤백 | 히어로 다듬기 | `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` |
|
||||
| [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` |
|
||||
| [ ] | 낮 히어로 해 안 흰 글씨 "오늘 날씨 점수"가 주황 위라 대비 부족 | 히어로 롤백 중 발견 | `frontend/src/b/b.css` |
|
||||
| [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`) |
|
||||
@@ -121,6 +121,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):
|
||||
@@ -220,6 +223,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 = ""
|
||||
|
||||
@@ -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]:
|
||||
|
||||
@@ -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,7 @@
|
||||
|
||||
| 문서 | 내용 | 아티팩트 |
|
||||
|---|---|---|
|
||||
| `../../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 |
|
||||
| `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` 참고.
|
||||
|
||||
## 핵심
|
||||
|
||||
|
||||
@@ -100,6 +100,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 (
|
||||
@@ -287,11 +290,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,6 +1,10 @@
|
||||
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
|
||||
@@ -8,11 +12,22 @@ from common.utils.kma_time import now_kst
|
||||
from crud.air_crud import AirCRUD
|
||||
from crud.feed_crud import FeedCRUD
|
||||
from crud.season_crud import SeasonCRUD
|
||||
from crud.week_crud import WeekCRUD
|
||||
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.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",
|
||||
@@ -55,3 +70,88 @@ 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")
|
||||
|
||||
@@ -61,7 +61,12 @@
|
||||
}
|
||||
],
|
||||
"limit_description": "모기, 가게 영업 여부, 자리 경쟁은 반영하지 못해요",
|
||||
"sentences": {},
|
||||
"sentences": {
|
||||
"0": "비 오거나 바람이 쌩쌩, 오늘 야장은 접어요. 실내 포차로 피신!",
|
||||
"30": "앉을 순 있는데 춥거나 덥거나 눅눅해요. 겉옷이나 부채 필수!",
|
||||
"60": "꽤 괜찮은 저녁! 바람만 살랑 불어 주면 딱이에요.",
|
||||
"80": "18~24°에 바람 살랑, 비 걱정 없음! 오늘은 무조건 바깥 자리 🍻"
|
||||
},
|
||||
"sort_order": 1
|
||||
},
|
||||
{
|
||||
@@ -121,7 +126,12 @@
|
||||
}
|
||||
],
|
||||
"limit_description": "잔디 상태, 공원 혼잡도는 반영하지 못해요",
|
||||
"sentences": {},
|
||||
"sentences": {
|
||||
"0": "비 소식이 있어요. 돗자리는 집에 고이 두기!",
|
||||
"30": "햇볕이 뜨겁거나 바람이 쌀쌀해요. 그늘이나 담요 챙기면 버틸 만!",
|
||||
"60": "돗자리 펴기 괜찮은 날! 바람막이 하나면 완벽해요.",
|
||||
"80": "20~26°에 바람 잔잔, 김밥 싸서 당장 출발! 🧺"
|
||||
},
|
||||
"sort_order": 2
|
||||
},
|
||||
{
|
||||
@@ -185,7 +195,12 @@
|
||||
}
|
||||
],
|
||||
"limit_description": "야구 경기 같은 이벤트는 아직 반영하지 못해요",
|
||||
"sentences": {},
|
||||
"sentences": {
|
||||
"0": "체감 10° 아래거나 비가 와요. 치킨은 배달, 맥주는 집에서!",
|
||||
"30": "바깥은 좀 쌀쌀하거나 후덥지근해요. 가게 안쪽 자리 추천!",
|
||||
"60": "바깥 테이블 괜찮아요! 얇은 겉옷 하나만 챙겨요.",
|
||||
"80": "20~27°의 선선한 저녁, 치킨에 맥주 부르는 날 🍗"
|
||||
},
|
||||
"sort_order": 3
|
||||
},
|
||||
{
|
||||
@@ -247,7 +262,12 @@
|
||||
}
|
||||
],
|
||||
"limit_description": "길 공사, 조명은 반영하지 못해요",
|
||||
"sentences": {},
|
||||
"sentences": {
|
||||
"0": "비가 쏟아지거나 초미세먼지가 매우 나빠요. 오늘은 실내 걷기로!",
|
||||
"30": "걸을 순 있는데 춥거나 덥거나 공기가 탁해요. 짧게 한 바퀴만!",
|
||||
"60": "한 바퀴 돌기 좋은 저녁! 이어폰 챙겨서 가볍게 나가요.",
|
||||
"80": "15~23°에 공기 맑고 바람 살랑, 동네 한 바퀴 무조건 🚶"
|
||||
},
|
||||
"sort_order": 4
|
||||
},
|
||||
{
|
||||
@@ -314,7 +334,12 @@
|
||||
}
|
||||
],
|
||||
"limit_description": "집 방향과 주변 공사 먼지는 반영하지 못해요",
|
||||
"sentences": {},
|
||||
"sentences": {
|
||||
"0": "초미세먼지가 매우 나빠요. 창문 꼭 닫고 공기청정기 ON!",
|
||||
"30": "공기가 탁하거나 비가 와요. 5분만 짧게 열고 닫기!",
|
||||
"60": "열어도 괜찮아요. 맞바람 나게 10분이면 충분!",
|
||||
"80": "공기 맑고 바람도 적당, 창문 활짝 열 시간 🌬️"
|
||||
},
|
||||
"sort_order": 5
|
||||
},
|
||||
{
|
||||
@@ -380,7 +405,12 @@
|
||||
}
|
||||
],
|
||||
"limit_description": "등산로 통제, 낙석 정보는 산림청 안내를 확인하세요",
|
||||
"sentences": {},
|
||||
"sentences": {
|
||||
"0": "비 소식이나 강풍 특보가 있어요. 오늘 산은 쉬어요!",
|
||||
"30": "산 위는 꽤 춥거나 더워요(6° 낮게 쳐요). 옷차림 단단히!",
|
||||
"60": "오를 만해요! 바람막이 챙기고 일찍 출발해요.",
|
||||
"80": "산 위도 선선하고 바람 잔잔, 정상 인증각 ⛰️"
|
||||
},
|
||||
"sort_order": 6
|
||||
},
|
||||
{
|
||||
@@ -436,7 +466,12 @@
|
||||
}
|
||||
],
|
||||
"limit_description": "황사·꽃가루 같은 하늘 먼지는 일부만 반영해요",
|
||||
"sentences": {},
|
||||
"sentences": {
|
||||
"0": "곧 비가 와요. 지금 세차하면 물 낭비!",
|
||||
"30": "비 기운이 남아 있어요. 하루쯤 미루는 게 이득!",
|
||||
"60": "세차해도 괜찮아요. 먼지는 좀 붙을 수 있어요.",
|
||||
"80": "비 걱정 없고 공기도 맑아요. 반짝반짝 오래가는 날 ✨"
|
||||
},
|
||||
"sort_order": 7
|
||||
},
|
||||
{
|
||||
@@ -497,7 +532,12 @@
|
||||
}
|
||||
],
|
||||
"limit_description": "캠핑장 예약 상황은 반영하지 못해요",
|
||||
"sentences": {},
|
||||
"sentences": {
|
||||
"0": "비가 오거나 바람이 너무 세요. 텐트 날아가요!",
|
||||
"30": "밤에 춥거나 습해요. 침낭은 두꺼운 걸로!",
|
||||
"60": "하룻밤 괜찮아요. 새벽엔 쌀쌀하니 담요 챙기기!",
|
||||
"80": "밤새 12~22°에 바람 잔잔, 불멍하기 딱 좋은 밤 🔥"
|
||||
},
|
||||
"sort_order": 8
|
||||
},
|
||||
{
|
||||
@@ -560,7 +600,12 @@
|
||||
}
|
||||
],
|
||||
"limit_description": "노면 상태는 반영하지 못해요",
|
||||
"sentences": {},
|
||||
"sentences": {
|
||||
"0": "체감 35° 넘거나 비가 쏟아져요. 오늘은 러닝머신으로!",
|
||||
"30": "덥거나 눅눅해서 금방 지쳐요. 거리 줄이고 물 꼭!",
|
||||
"60": "뛸 만해요! 아침·저녁 중 시원한 쪽 고르기.",
|
||||
"80": "8~18°에 공기 보송, 기록 갱신각 🏃"
|
||||
},
|
||||
"sort_order": 9
|
||||
},
|
||||
{
|
||||
@@ -613,7 +658,12 @@
|
||||
}
|
||||
],
|
||||
"limit_description": "도시 불빛은 지역 평균으로만 반영해요",
|
||||
"sentences": {},
|
||||
"sentences": {
|
||||
"0": "구름이 하늘을 꽉 덮었어요. 별은 다음 기회에!",
|
||||
"30": "달이 밝거나 하늘이 뿌예서 큰 별 몇 개만 보여요.",
|
||||
"60": "꽤 보여요! 불빛 적은 곳으로 조금만 나가요.",
|
||||
"80": "달은 어둡고 공기는 맑아요. 은하수 노려볼 만한 밤 ✨"
|
||||
},
|
||||
"sort_order": 10
|
||||
},
|
||||
{
|
||||
@@ -663,7 +713,12 @@
|
||||
},
|
||||
"zero_rules": [],
|
||||
"limit_description": "실제 주문량으로 검증하기 전이에요",
|
||||
"sentences": {},
|
||||
"sentences": {
|
||||
"0": "25° 넘게 더워요. 국물보다 냉면이 당길 날!",
|
||||
"30": "국물이 살짝 생각나는 정도예요.",
|
||||
"60": "쌀쌀하거나 비 와서 국물 각 잡혀요!",
|
||||
"80": "춥고 비까지! 얼큰한 짬뽕 한 그릇 무조건 🍜"
|
||||
},
|
||||
"sort_order": 11
|
||||
},
|
||||
{
|
||||
@@ -711,7 +766,12 @@
|
||||
},
|
||||
"zero_rules": [],
|
||||
"limit_description": "실제 판매량으로 검증하기 전이에요",
|
||||
"sentences": {},
|
||||
"sentences": {
|
||||
"0": "비 소식이 없어요. 파전은 비 오는 날을 기다려요!",
|
||||
"30": "하늘이 꾸물꾸물, 막걸리 생각이 살짝 나요.",
|
||||
"60": "비 기운이 있어요. 파전 반죽 준비각!",
|
||||
"80": "비 오고 선선한 저녁, 파전에 막걸리 확정 🍶"
|
||||
},
|
||||
"sort_order": 12
|
||||
},
|
||||
{
|
||||
@@ -757,7 +817,12 @@
|
||||
},
|
||||
"zero_rules": [],
|
||||
"limit_description": "사람마다 달라서 재미로 봐 주세요",
|
||||
"sentences": {},
|
||||
"sentences": {
|
||||
"0": "아침부터 22° 넘어요. 아직은 아아의 계절!",
|
||||
"30": "아침이 살짝 선선해요. 아아 들다 손 시릴 수도?",
|
||||
"60": "아침 공기가 차요. 오늘은 뜨아로 갈아탈 때!",
|
||||
"80": "아침이 한 자릿수, 따뜻한 커피 없인 못 버텨요 ☕"
|
||||
},
|
||||
"sort_order": 13
|
||||
},
|
||||
{
|
||||
@@ -809,7 +874,12 @@
|
||||
}
|
||||
],
|
||||
"limit_description": "집 일조량은 반영하지 못해요",
|
||||
"sentences": {},
|
||||
"sentences": {
|
||||
"0": "비 소식이 있어요. 오늘 빨래는 실내 건조로!",
|
||||
"30": "눅눅하거나 쌀쌀해서 잘 안 말라요. 얇은 것만 널어요.",
|
||||
"60": "잘 마르는 편이에요. 두꺼운 건 오후까지 두기!",
|
||||
"80": "따뜻하고 보송한데 바람까지 솔솔, 이불 빨래 가능한 날 ☀️"
|
||||
},
|
||||
"sort_order": 14
|
||||
},
|
||||
{
|
||||
@@ -874,7 +944,12 @@
|
||||
}
|
||||
],
|
||||
"limit_description": "자전거 도로 공사는 반영하지 못해요",
|
||||
"sentences": {},
|
||||
"sentences": {
|
||||
"0": "비가 오거나 바람이 10m/s 넘어요. 자전거는 쉬어요!",
|
||||
"30": "맞바람이 세거나 기온이 애매해요. 짧은 코스만!",
|
||||
"60": "탈 만해요! 강변은 바람 좀 부니 바람막이 챙기기.",
|
||||
"80": "15~24°에 바람 잔잔, 멀리 달려도 좋은 날 🚲"
|
||||
},
|
||||
"sort_order": 15
|
||||
},
|
||||
{
|
||||
@@ -940,7 +1015,12 @@
|
||||
}
|
||||
],
|
||||
"limit_description": "노면 온도는 실측하지 못해요",
|
||||
"sentences": {},
|
||||
"sentences": {
|
||||
"0": "체감 33° 넘거나 초미세먼지가 매우 나빠요. 발바닥도 폐도 위험, 실내 놀이로!",
|
||||
"30": "덥거나 공기가 탁해요. 짧게 볼일만 보고 들어와요.",
|
||||
"60": "산책 괜찮아요! 그늘 많은 길로 가요.",
|
||||
"80": "5~22°에 공기 맑음, 멍멍이 신나는 날 🐶"
|
||||
},
|
||||
"sort_order": 16
|
||||
},
|
||||
{
|
||||
@@ -986,7 +1066,12 @@
|
||||
},
|
||||
"zero_rules": [],
|
||||
"limit_description": "실내 온도는 반영하지 못해요",
|
||||
"sentences": {},
|
||||
"sentences": {
|
||||
"0": "아침이 15° 넘게 따뜻해요. 안경 김 걱정 없어요!",
|
||||
"30": "실내 들어갈 때 살짝 뿌예질 수 있어요.",
|
||||
"60": "출근길 안경에 김 서려요. 닦을 천 챙기기!",
|
||||
"80": "영하권 아침에 습하기까지, 문 열자마자 앞이 하얘져요 👓"
|
||||
},
|
||||
"sort_order": 17
|
||||
},
|
||||
{
|
||||
@@ -1032,7 +1117,12 @@
|
||||
},
|
||||
"zero_rules": [],
|
||||
"limit_description": "피부 타입은 반영하지 못해요",
|
||||
"sentences": {},
|
||||
"sentences": {
|
||||
"0": "선선하고 보송해요. 화장 하루 종일 버텨요!",
|
||||
"30": "오후쯤 살짝 번들거릴 수 있어요.",
|
||||
"60": "덥고 습해서 무너지기 쉬워요. 픽서 챙기기!",
|
||||
"80": "30° 넘는 찜통에 습도까지, 기름종이 필수 🫠"
|
||||
},
|
||||
"sort_order": 18
|
||||
},
|
||||
{
|
||||
@@ -1080,7 +1170,12 @@
|
||||
},
|
||||
"zero_rules": [],
|
||||
"limit_description": "실제 주문량으로 검증하기 전이에요",
|
||||
"sentences": {},
|
||||
"sentences": {
|
||||
"0": "점심이 18° 아래로 선선해요. 냉면보다 국밥!",
|
||||
"30": "시원한 게 살짝 당기는 정도예요.",
|
||||
"60": "점심에 덥네요. 냉면 한 그릇 생각나요!",
|
||||
"80": "30° 넘는 한낮, 살얼음 동동 냉면 확정 🥶"
|
||||
},
|
||||
"sort_order": 19
|
||||
},
|
||||
{
|
||||
@@ -1128,7 +1223,12 @@
|
||||
},
|
||||
"zero_rules": [],
|
||||
"limit_description": "행사·공연 종료 시간은 반영하지 못해요",
|
||||
"sentences": {},
|
||||
"sentences": {
|
||||
"0": "맑고 포근한 밤, 택시 금방 잡혀요.",
|
||||
"30": "조금 기다릴 수 있어요. 앱 미리 켜두기!",
|
||||
"60": "비나 추위로 택시 잡기 힘들어요. 막차 시간 확인!",
|
||||
"80": "비 오는 추운 밤, 택시 전쟁이에요. 막차 타세요 🚕"
|
||||
},
|
||||
"sort_order": 20
|
||||
},
|
||||
{
|
||||
@@ -1177,7 +1277,12 @@
|
||||
},
|
||||
"zero_rules": [],
|
||||
"limit_description": "실제 배달 앱 지표로 검증하기 전이에요",
|
||||
"sentences": {},
|
||||
"sentences": {
|
||||
"0": "날씨 멀쩡해요. 배달 평소처럼 와요.",
|
||||
"30": "살짝 늦을 수 있어요.",
|
||||
"60": "비나 추위로 주문이 몰려요. 일찍 시키기!",
|
||||
"80": "비 오는 추운 저녁, 배달 한참 걸려요. 지금 바로 주문! 🛵"
|
||||
},
|
||||
"sort_order": 21
|
||||
},
|
||||
{
|
||||
@@ -1234,7 +1339,12 @@
|
||||
}
|
||||
],
|
||||
"limit_description": "식물 종류는 반영하지 못해요",
|
||||
"sentences": {},
|
||||
"sentences": {
|
||||
"0": "비 소식이 있어요. 물 주기는 하늘에 맡겨요!",
|
||||
"30": "춥거나 더워요. 화분은 안으로, 물은 조금만.",
|
||||
"60": "화분 돌보기 괜찮아요. 아침에 물 듬뿍!",
|
||||
"80": "12~25°의 보송한 아침, 분갈이까지 해도 되는 날 🌱"
|
||||
},
|
||||
"sort_order": 22
|
||||
},
|
||||
{
|
||||
@@ -1290,7 +1400,12 @@
|
||||
}
|
||||
],
|
||||
"limit_description": "장소 혼잡도는 반영하지 못해요",
|
||||
"sentences": {},
|
||||
"sentences": {
|
||||
"0": "비가 와요. 카메라는 쉬어요!",
|
||||
"30": "노을이 약하거나 하늘이 흐려요. 골목 사진 위주로!",
|
||||
"60": "노을이 꽤 기대돼요. 해 지기 30분 전에 나가요.",
|
||||
"80": "노을 점수 높고 공기 맑음, 인생샷 각 📸"
|
||||
},
|
||||
"sort_order": 23
|
||||
},
|
||||
{
|
||||
@@ -1348,7 +1463,12 @@
|
||||
}
|
||||
],
|
||||
"limit_description": "경기 일정과 시즌(3~10월)은 반영하지 못해요",
|
||||
"sentences": {},
|
||||
"sentences": {
|
||||
"0": "비 70% 넘어요. 우천 취소 각!",
|
||||
"30": "쌀쌀하거나 비 기운이 있어요. 담요랑 우비 챙겨요.",
|
||||
"60": "직관 괜찮아요! 밤엔 선선하니 겉옷 하나.",
|
||||
"80": "15~25°에 비 걱정 없음, 응원가 목청껏 부르는 날 ⚾"
|
||||
},
|
||||
"sort_order": 24
|
||||
},
|
||||
{
|
||||
@@ -1397,7 +1517,12 @@
|
||||
},
|
||||
"zero_rules": [],
|
||||
"limit_description": "사람마다 달라서 재미로 봐 주세요",
|
||||
"sentences": {},
|
||||
"sentences": {
|
||||
"0": "밖이 너무 좋아요. 공부는… 내일의 내가 할게요!",
|
||||
"30": "나가고 싶은 마음 반, 공부 반이에요.",
|
||||
"60": "밖이 애매해서 책상에 앉을 만해요.",
|
||||
"80": "비 오고 춥거나 더워서 나갈 맛이 안 나요. 집중각 📚"
|
||||
},
|
||||
"sort_order": 25
|
||||
},
|
||||
{
|
||||
@@ -1445,7 +1570,12 @@
|
||||
},
|
||||
"zero_rules": [],
|
||||
"limit_description": "재미로 보는 지수예요",
|
||||
"sentences": {},
|
||||
"sentences": {
|
||||
"0": "밤 공기가 좋아서 밖이 더 끌려요.",
|
||||
"30": "한 편 정도 볼 만해요.",
|
||||
"60": "비 오거나 쌀쌀한 밤, 이불 속이 최고!",
|
||||
"80": "비 오는 주말 앞 밤, 정주행 시작각 🍿"
|
||||
},
|
||||
"sort_order": 26
|
||||
},
|
||||
{
|
||||
@@ -1491,7 +1621,12 @@
|
||||
},
|
||||
"zero_rules": [],
|
||||
"limit_description": "군밤 노점이 있는지는 반영하지 못해요",
|
||||
"sentences": {},
|
||||
"sentences": {
|
||||
"0": "아직 18° 넘어요. 군밤은 조금 더 추워지면!",
|
||||
"30": "저녁이 선선해졌어요. 군밤 노점이 슬슬 생각나요.",
|
||||
"60": "손이 시려요. 따끈한 군밤 한 봉지!",
|
||||
"80": "영하 가까운 저녁, 군밤 품고 걷는 날 🌰"
|
||||
},
|
||||
"sort_order": 27
|
||||
}
|
||||
]
|
||||
@@ -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,7 +2,7 @@ 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)
|
||||
|
||||
@@ -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,6 +73,33 @@ 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 situation(near20: Layers, near50: Layers, far100: Layers) -> SkySituation:
|
||||
"""하늘 상황 하나. reason() 과 같은 순서로 본다: 먼 쪽이 막혔나 → 머리 위 낮은 구름 → 물들 중·높은 구름의 양."""
|
||||
if far100.low + 0.5 * far100.mid >= 60:
|
||||
return SkySituation.COVERED
|
||||
if (near20.low + near50.low) / 2 >= 60:
|
||||
return SkySituation.LOW_CLOUD
|
||||
canvas = (max(near20.mid, near20.high) + max(near50.mid, near50.high)) / 2
|
||||
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, near50: Layers, far100: Layers) -> str:
|
||||
"""score() 가 깎는 순서대로 본다: 먼 쪽 빛이 막혔나 → 머리 위 낮은 구름 → 물들 중·높은 구름의 양."""
|
||||
if far100.low + 0.5 * far100.mid >= 60:
|
||||
|
||||
+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
|
||||
+11
-4
@@ -4,10 +4,12 @@ from datetime import datetime, 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}
|
||||
_ATTEMPTS = 3
|
||||
_BUDGET_SEC = 10.0 # 좌표가 많으면 여러 묶음을 동시에 보내 평소보다 조금 더 걸린다
|
||||
|
||||
|
||||
class OpenMeteoRequestFailed(RuntimeError):
|
||||
@@ -20,8 +22,12 @@ _CHUNK = 24
|
||||
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]:
|
||||
@@ -39,8 +45,9 @@ 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 {len(points)} points: {last}")
|
||||
|
||||
|
||||
def parse_clouds(point: tuple[float, float], data: dict) -> list[dict]:
|
||||
|
||||
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
|
||||
|
||||
@@ -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),
|
||||
)
|
||||
|
||||
@@ -149,26 +159,40 @@ def _score_rows(region: Region, today: date, clouds: dict, now: datetime) -> lis
|
||||
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 = []
|
||||
per_model, highs, model_layers = [], [], []
|
||||
for model in {k[2] for k in clouds}:
|
||||
layers = [clouds.get((p[0], p[1], model, hour)) for p in pts]
|
||||
if None in layers:
|
||||
continue
|
||||
per_model.append(score(*layers))
|
||||
highs.append((layers[0].high + layers[1].high) / 2)
|
||||
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(3)))
|
||||
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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -78,3 +78,21 @@ 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)
|
||||
@@ -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,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"] == 4
|
||||
assert plan["outlook"] == ""
|
||||
assert body["sunset"]["verdict"] == "go" and body["spots"][0]["direction"]
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
@@ -104,14 +106,19 @@ 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) == ""
|
||||
@@ -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)
|
||||
@@ -43,7 +43,7 @@ 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():
|
||||
@@ -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, clear) is SkySituation.FEW
|
||||
assert situation(glow, glow, clear) is SkySituation.GLOW
|
||||
assert situation(Layers(0, 90, 95), Layers(0, 90, 95), clear) is SkySituation.THICK
|
||||
assert situation(Layers(80, 0, 0), Layers(70, 0, 0), clear) is SkySituation.LOW_CLOUD
|
||||
assert situation(glow, 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_weekend_rank
|
||||
|
||||
|
||||
async def daily() -> None:
|
||||
@@ -20,8 +20,11 @@ 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.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")
|
||||
|
||||
stop = asyncio.Event()
|
||||
loop = asyncio.get_running_loop()
|
||||
|
||||
@@ -2,6 +2,8 @@
|
||||
# 킹서버 배포. 서버의 저장소 폴더에서 실행한다.
|
||||
# ./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")"
|
||||
|
||||
@@ -9,7 +11,10 @@ cd "$(dirname "$0")"
|
||||
set -a; . ./.env; set +a
|
||||
|
||||
git pull --ff-only origin main
|
||||
docker compose up -d --build postgres redis backend worker frontend
|
||||
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:?덤프 파일 경로가 필요합니다}"
|
||||
|
||||
@@ -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점: 영하 가까운 저녁, 군밤 품고 걷는 날 🌰
|
||||
|
||||
@@ -211,22 +211,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>
|
||||
@@ -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/2). 그날 날씨와 같이 보여 줍니다("토요일 맑음, 갈 만해요").</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>
|
||||
@@ -218,5 +218,5 @@ td .note{display:block;color:var(--muted);font-size:12px;margin-top:3px;line-hei
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<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>
|
||||
<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>
|
||||
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)}`)}>
|
||||
|
||||
@@ -303,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">
|
||||
@@ -313,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">
|
||||
@@ -325,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">
|
||||
@@ -566,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 }) {
|
||||
@@ -579,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)
|
||||
},
|
||||
},
|
||||
)
|
||||
@@ -636,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' ? (
|
||||
|
||||
@@ -88,6 +88,8 @@ function Hero({ hero, today, feedLoad, todayLoad }: HeroProps) {
|
||||
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 feelsLine = temp != null ? `체감 ${deg(feels)}${slot ? ` · ${skyText(slot)}` : ''}` : failed(tempLoad) ? '날씨를 못 불러왔어요' : tempLoad === 'ready' ? '체감 ?°' : null
|
||||
const bubble = hero ? (hero.bubble ?? '오늘은 쉬어 가요') : failed(feedLoad) ? '앗, 날씨를 못 불러왔어요' : null
|
||||
@@ -133,7 +135,13 @@ function Hero({ hero, today, feedLoad, todayLoad }: HeroProps) {
|
||||
<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')}>
|
||||
<span>
|
||||
{/* 안 보이는 쪽을 덮어 오늘 밤 달 모양으로 */}
|
||||
{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>
|
||||
@@ -174,6 +182,18 @@ function Hero({ hero, today, feedLoad, todayLoad }: HeroProps) {
|
||||
)
|
||||
}
|
||||
|
||||
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 (
|
||||
<div className="b-stat flex min-h-[90px] items-center gap-2.5 rounded-[20px] px-3 py-[9px]">
|
||||
@@ -315,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],
|
||||
@@ -323,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' }} />
|
||||
{/* 실패 안내는 여기 한 번만, 각 줄 스켈레톤과 같은 크기로 */}
|
||||
|
||||
@@ -5,7 +5,7 @@ import { cx } from '../lib/utils'
|
||||
import { cardBg, dateRange, loadOf, shortDay, sidoOf } from './lib'
|
||||
import { useRegion } from './regionContext'
|
||||
import { useSheet } from './sheetContext'
|
||||
import { Arrows, 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)
|
||||
@@ -248,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 />
|
||||
@@ -314,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>
|
||||
|
||||
+19
-1
@@ -198,7 +198,16 @@
|
||||
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: #fff;
|
||||
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);
|
||||
@@ -274,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>
|
||||
|
||||
Reference in new issue
Block a user