diff --git a/.env.example b/.env.example
index 61e94f4..8c89672 100644
--- a/.env.example
+++ b/.env.example
@@ -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
diff --git a/TODO.md b/TODO.md
index aa54ceb..4ea5bf6 100644
--- a/TODO.md
+++ b/TODO.md
@@ -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`) |
diff --git a/backend/common/database/model/models.py b/backend/common/database/model/models.py
index c9e8712..512ec36 100644
--- a/backend/common/database/model/models.py
+++ b/backend/common/database/model/models.py
@@ -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):
diff --git a/backend/common/enums.py b/backend/common/enums.py
index 650cfe3..b2f0426 100644
--- a/backend/common/enums.py
+++ b/backend/common/enums.py
@@ -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):
diff --git a/backend/common/utils/geo.py b/backend/common/utils/geo.py
index f9496a9..f366822 100644
--- a/backend/common/utils/geo.py
+++ b/backend/common/utils/geo.py
@@ -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
diff --git a/backend/config/settings.py b/backend/config/settings.py
index 956b7fd..eb717d4 100644
--- a/backend/config/settings.py
+++ b/backend/config/settings.py
@@ -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 = ""
diff --git a/backend/crud/sky_crud.py b/backend/crud/sky_crud.py
index 4267c0d..d64a287 100644
--- a/backend/crud/sky_crud.py
+++ b/backend/crud/sky_crud.py
@@ -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]:
diff --git a/backend/crud/week_crud.py b/backend/crud/week_crud.py
index 443e34e..787fc2b 100644
--- a/backend/crud/week_crud.py
+++ b/backend/crud/week_crud.py
@@ -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:
diff --git a/backend/docs/README.md b/backend/docs/README.md
index 38079b5..7e0ac2a 100644
--- a/backend/docs/README.md
+++ b/backend/docs/README.md
@@ -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 |
diff --git a/backend/docs/data-pipeline.html b/backend/docs/data-pipeline.html
deleted file mode 100644
index d464828..0000000
--- a/backend/docs/data-pipeline.html
+++ /dev/null
@@ -1,83 +0,0 @@
-
날씨각 데이터 흐름
-
-
-
-
날씨각 데이터 흐름
-
기준 화면: 시안 B 피드. 무엇을, 언제, 어디서 받아서, 어디에 저장하고, 얼마나 캐시하는지.
-
-
원칙
-
외부 API는 첫 사용자가 볼 때 받는다. 캐시가 오래됐을 때만 부르고, 나머지 사용자는 그 값을 같이 쓴다.
받자마자 우리 형식으로 바꿔 PostgreSQL에 저장한다. 원본 응답은 저장하지 않는다.
계산(체감기온, 지수, 노을 점수)은 데이터가 들어올 때 한 번 하고 저장한다.
그날 카드는 처음부터 다 보인다. 매일 03:00 스케줄러가 그날 카드(post)를 만들고, 카드 안의 숫자·문장은 볼 때 그 구 데이터로 채운다. 시각별로 카드를 하나씩 공개하지 않는다. 순서는 시간대(아침·낮·저녁·밤)에 따라 바뀌고, 조건이 맞는 카드만 켜진다.
Redis는 지워져도 되는 것만 담는다. 비면 PostgreSQL로 다시 만든다.
스케줄은 하루 1번(매일 03:00, worker)만 돈다.
-
-
한눈에
-
데이터
출처
언제 받나
저장 (DB)
캐시 (Redis)
시간별·하루 날씨
기상청 단기예보
새 발표(02·05·08·11·14·17·20·23시 +10분) 후 그 구를 처음 볼 때
weather_hourlyweather_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년치
holidaysolar_term
—
지수·노을 점수
위 값으로 계산
재료가 새로 들어온 직후
index_scoresky_score
피드 완성본에 포함
그날 피드 카드
스케줄러
매일 03:00
post
—
피드 완성본
위 테이블 조립
캐시가 없을 때 (시간대마다 따로)
—
feed:{구}:{시간대}
-
-
저장하는 곳
-
곳
담는 것
지워지면
PostgreSQL
받아 온 값(우리 형식), 계산 결과, 포스트, 사람이 쓴 내용
볼륨에 둬서 지워지지 않음. 원본은 여기
Redis
피드 완성본, 초단기예보, 전국 노을 순위, 동시 호출 잠금
문제없음. 다음 요청 때 PostgreSQL로 다시 만듦
시드 파일 (저장소)
구 목록, 지수 정의·문장 틀, 명소, 절기, 계절 책, 읽을거리
git에 있음. 배포할 때 PostgreSQL로 불러옴
-
-
화면 요청 하나가 처리되는 순서
-
예: 17:20에 마포구 메인 피드를 연다.
-
Redis feed:마포구:저녁 확인. (10월 17:20은 일몰 2시간 전이 지나 저녁 시간대) 있으면 그대로 돌려준다. 대부분 여기서 끝난다.
없으면 재료가 최신인지 확인.
단기예보: DB에 17시 발표가 있나 (17:10부터 받을 수 있음)
초단기예보: Redis ultra:마포구가 있나
미세먼지·특보: 이번 시각 갱신분이 DB에 있나 (전국 공용이라 한 사람이 받으면 모두 같이 씀)
해 시각: 없으면 계산한다
오래된 것만 외부에서 받는다.
여러 API는 동시에 부른다 (가장 느린 하나만큼만 걸림).
Redis 잠금 lock:{API}:{구}를 잡아, 같은 구를 여러 명이 동시에 열어도 호출은 1번.
DB에 직전 값이 있으면 그 값으로 먼저 응답하고, 새 값은 받는 대로 저장해 다음 요청부터 반영한다.
받은 값을 우리 형식으로 바꿔 DB에 저장. 체감기온·불쾌지수도 이때 계산.
재료가 바뀌었으면 계산. 지수 24개 × 오늘·내일·모레 → index_score.
피드 완성본 조립. 오늘 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시간
좌표 여러 개, 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).
-
-
diff --git a/backend/docs/data-pipeline.md b/backend/docs/data-pipeline.md
deleted file mode 100644
index 75ec129..0000000
--- a/backend/docs/data-pipeline.md
+++ /dev/null
@@ -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`).
diff --git a/backend/docs/load-estimate.md b/backend/docs/load-estimate.md
index d20a2d6..c3b5821 100644
--- a/backend/docs/load-estimate.md
+++ b/backend/docs/load-estimate.md
@@ -1,6 +1,6 @@
# 날씨각 호출량·DB 크기 추정
-2026-10-02 기준 코드와 개발 DB 실측으로 계산했다. 동작 방식은 `data-pipeline.md` 참고.
+2026-10-02 기준 코드와 개발 DB 실측으로 계산했다. 동작 방식은 `../../docs/데이터_흐름.html` 참고.
## 핵심
diff --git a/backend/postgres-init/init.sql b/backend/postgres-init/init.sql
index 22985d4..e8f8d2a 100644
--- a/backend/postgres-init/init.sql
+++ b/backend/postgres-init/init.sql
@@ -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 (
diff --git a/backend/router/v1/feed/protocol.py b/backend/router/v1/feed/protocol.py
index 601120a..5ab6b0f 100644
--- a/backend/router/v1/feed/protocol.py
+++ b/backend/router/v1/feed/protocol.py
@@ -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):
diff --git a/backend/router/v1/index/index.py b/backend/router/v1/index/index.py
index deafa58..543bc03 100644
--- a/backend/router/v1/index/index.py
+++ b/backend/router/v1/index/index.py
@@ -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)]
diff --git a/backend/router/v1/index/protocol.py b/backend/router/v1/index/protocol.py
index d67a594..ae5cdba 100644
--- a/backend/router/v1/index/protocol.py
+++ b/backend/router/v1/index/protocol.py
@@ -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)")
diff --git a/backend/router/v1/sky/protocol.py b/backend/router/v1/sky/protocol.py
index bb20d99..b718566 100644
--- a/backend/router/v1/sky/protocol.py
+++ b/backend/router/v1/sky/protocol.py
@@ -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] = []
diff --git a/backend/router/v1/sky/sky.py b/backend/router/v1/sky/sky.py
index dbf02c8..e73945c 100644
--- a/backend/router/v1/sky/sky.py
+++ b/backend/router/v1/sky/sky.py
@@ -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
],
)
diff --git a/backend/scheduler/jobs.py b/backend/scheduler/jobs.py
index 1d2250b..4a51a10 100644
--- a/backend/scheduler/jobs.py
+++ b/backend/scheduler/jobs.py
@@ -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
diff --git a/backend/scripts/gen_gak_doc.py b/backend/scripts/gen_gak_doc.py
index 4e46a2a..a2e84b0 100644
--- a/backend/scripts/gen_gak_doc.py
+++ b/backend/scripts/gen_gak_doc.py
@@ -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")
diff --git a/backend/seed/index_definition.json b/backend/seed/index_definition.json
index dda01fe..41c4cf3 100644
--- a/backend/seed/index_definition.json
+++ b/backend/seed/index_definition.json
@@ -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
}
]
\ No newline at end of file
diff --git a/backend/services/calc/moon.py b/backend/services/calc/moon.py
index 638b5a4..84e9d12 100644
--- a/backend/services/calc/moon.py
+++ b/backend/services/calc/moon.py
@@ -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))
diff --git a/backend/services/calc/sky_score.py b/backend/services/calc/sky_score.py
index b7af6c1..7bf2c79 100644
--- a/backend/services/calc/sky_score.py
+++ b/backend/services/calc/sky_score.py
@@ -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:
diff --git a/backend/services/external/culture_api.py b/backend/services/external/culture_api.py
index 9596aa8..d2d0d87 100644
--- a/backend/services/external/culture_api.py
+++ b/backend/services/external/culture_api.py
@@ -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())
diff --git a/backend/services/external/data_go_kr.py b/backend/services/external/data_go_kr.py
index b7350cb..b4d9b73 100644
--- a/backend/services/external/data_go_kr.py
+++ b/backend/services/external/data_go_kr.py
@@ -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]:
diff --git a/backend/services/external/guard.py b/backend/services/external/guard.py
new file mode 100644
index 0000000..3fa59a4
--- /dev/null
+++ b/backend/services/external/guard.py
@@ -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
diff --git a/backend/services/external/open_meteo.py b/backend/services/external/open_meteo.py
index 87e7adc..f0249bc 100644
--- a/backend/services/external/open_meteo.py
+++ b/backend/services/external/open_meteo.py
@@ -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]:
diff --git a/backend/services/external/popga.py b/backend/services/external/popga.py
new file mode 100644
index 0000000..3f213a1
--- /dev/null
+++ b/backend/services/external/popga.py
@@ -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"\s*([^<\s]+)\s*")
+_URL = re.compile(r"(.*?)", re.S)
+_LASTMOD = re.compile(r"\s*([^<\s]+)\s*")
+_POPUP_PATH = re.compile(r"^https://popga\.co\.kr/popup/(\d+)$")
+_LD_JSON = re.compile(r'', 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],
+ }
diff --git a/backend/services/external/teams_webhook.py b/backend/services/external/teams_webhook.py
new file mode 100644
index 0000000..226d844
--- /dev/null
+++ b/backend/services/external/teams_webhook.py
@@ -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
diff --git a/backend/services/external/tour_api.py b/backend/services/external/tour_api.py
index 127695d..72016d3 100644
--- a/backend/services/external/tour_api.py
+++ b/backend/services/external/tour_api.py
@@ -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
diff --git a/backend/services/feed_service.py b/backend/services/feed_service.py
index 32cac59..a48a432 100644
--- a/backend/services/feed_service.py
+++ b/backend/services/feed_service.py
@@ -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
diff --git a/backend/services/sky_service.py b/backend/services/sky_service.py
index 4cae2a0..4bfe329 100644
--- a/backend/services/sky_service.py
+++ b/backend/services/sky_service.py
@@ -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
diff --git a/backend/services/week_service.py b/backend/services/week_service.py
index fc1841d..acff137 100644
--- a/backend/services/week_service.py
+++ b/backend/services/week_service.py
@@ -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}")
diff --git a/backend/tests/conftest.py b/backend/tests/conftest.py
index c91a791..d02bf82 100644
--- a/backend/tests/conftest.py
+++ b/backend/tests/conftest.py
@@ -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
diff --git a/backend/tests/test_api_guard.py b/backend/tests/test_api_guard.py
new file mode 100644
index 0000000..ba1aafc
--- /dev/null
+++ b/backend/tests/test_api_guard.py
@@ -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
diff --git a/backend/tests/test_culture_api.py b/backend/tests/test_culture_api.py
index 2a62ee9..7a0ca75 100644
--- a/backend/tests/test_culture_api.py
+++ b/backend/tests/test_culture_api.py
@@ -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 = """공연/전시{seq}{title}{start}{end}
@@ -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 = ("SERVICE_KEY_IS_NOT_REGISTERED_ERROR"
@@ -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"
diff --git a/backend/tests/test_event_job.py b/backend/tests/test_event_job.py
new file mode 100644
index 0000000..a46e15c
--- /dev/null
+++ b/backend/tests/test_event_job.py
@@ -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
diff --git a/backend/tests/test_feed.py b/backend/tests/test_feed.py
index 136e5ee..a98db4d 100644
--- a/backend/tests/test_feed.py
+++ b/backend/tests/test_feed.py
@@ -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)
diff --git a/backend/tests/test_index_api.py b/backend/tests/test_index_api.py
index a9f2f35..be47100 100644
--- a/backend/tests/test_index_api.py
+++ b/backend/tests/test_index_api.py
@@ -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)
diff --git a/backend/tests/test_moon.py b/backend/tests/test_moon.py
new file mode 100644
index 0000000..a686495
--- /dev/null
+++ b/backend/tests/test_moon.py
@@ -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")
diff --git a/backend/tests/test_popga.py b/backend/tests/test_popga.py
new file mode 100644
index 0000000..d6622ec
--- /dev/null
+++ b/backend/tests/test_popga.py
@@ -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''
+
+
+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": "https://popga.co.kr/sitemap/2.xml"
+ "https://popga.co.kr/sitemap/5.xml",
+ "/sitemap/2.xml": "https://popga.co.kr/popup/122026-10-06T00:00:00Z"
+ "https://popga.co.kr/popup/11",
+ "/sitemap/5.xml": "https://popga.co.kr/popup/12/review/32026-10-06",
+ }
+ 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: ""}
diff --git a/backend/tests/test_sky_api.py b/backend/tests/test_sky_api.py
index 902e1d4..e008733 100644
--- a/backend/tests/test_sky_api.py
+++ b/backend/tests/test_sky_api.py
@@ -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) == ""
diff --git a/backend/tests/test_sky_score.py b/backend/tests/test_sky_score.py
index 364b5b2..ee617ed 100644
--- a/backend/tests/test_sky_score.py
+++ b/backend/tests/test_sky_score.py
@@ -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
diff --git a/backend/tests/test_week.py b/backend/tests/test_week.py
index 9a60398..d821e0d 100644
--- a/backend/tests/test_week.py
+++ b/backend/tests/test_week.py
@@ -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"]} == {"잠실 축제", "좌표 없는 경기 축제"}
diff --git a/backend/worker_main.py b/backend/worker_main.py
index 97918af..5309779 100644
--- a/backend/worker_main.py
+++ b/backend/worker_main.py
@@ -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()
diff --git a/deploy.sh b/deploy.sh
index d4d40ec..4cf84f6 100755
--- a/deploy.sh
+++ b/deploy.sh
@@ -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:?덤프 파일 경로가 필요합니다}"
diff --git a/docs/각_데이터.md b/docs/각_계산기준.md
similarity index 71%
rename from docs/각_데이터.md
rename to docs/각_계산기준.md
index 08d9d34..1049d70 100644
--- a/docs/각_데이터.md
+++ b/docs/각_계산기준.md
@@ -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점: 영하 가까운 저녁, 군밤 품고 걷는 날 🌰
diff --git a/docs/데이터흐름.html b/docs/데이터_흐름.html
similarity index 96%
rename from docs/데이터흐름.html
rename to docs/데이터_흐름.html
index 65772c6..4655df1 100644
--- a/docs/데이터흐름.html
+++ b/docs/데이터_흐름.html
@@ -211,22 +211,14 @@ code{font-family:var(--mono);font-size:12.5px;background:var(--soft-db);padding:
이렇게 나눠서 감수하는 것
-
장애
외부 기관 5곳(기상청·에어코리아·Open-Meteo·TourAPI·천문연)에 기대므로 어느 한 곳이 멈추면 그 칸이 빠집니다. 별개로, 지금은 응답 없는 API를 너무 오래 기다려서 기상청이 멈추면 피드를 연 사람 일부가 100초 가까이 기다립니다. 이건 출처 수가 아니라 기다리는 방식의 문제라, Open-Meteo 하나로 바꿔도 똑같이 생깁니다. 출시 전에 "빨리 포기하고 저장된 값 보여주기"로 고칠 예정입니다(운영 점검 보고서 참고).
+
장애
외부 기관 5곳(기상청·에어코리아·Open-Meteo·TourAPI·천문연)에 기대므로 어느 한 곳이 멈추면 그 칸이 빠집니다. 기관이 멈추면 8초까지만 기다린 뒤 저장해 둔 값을 보여주고, 그 기관은 2분 동안 다시 부르지 않습니다. 그래서 멈춘 동안 기다리는 사람은 기관마다 2분에 한 명꼴입니다.
먼 날짜
4~10일 뒤는 중기예보라 도 단위·오전/오후로만 나옵니다. 그래서 주말까지 4일 넘게 남은 월·화요일에는 주말 플랜에 "15~19시 비" 같은 시간대를 넣을 수 없습니다. Open-Meteo는 이 기간도 1시간 단위로 주는데, 그걸 포기한 셈입니다.
유료 결정
노을 구름 때문에 출시 전에 Open-Meteo 유료 여부를 정해야 합니다.
다시 볼 때: 정확도 비교(TODO)에서 Open-Meteo가 뚜렷하게 더 맞는다고 나오면 다시 검토합니다. 그래도 1번 이유(특보와 엇갈림)는 남기 때문에 통일보다는 4~10일 뒤만 Open-Meteo로 받는 방식이 먼저 후보입니다.
-
-
확인이 필요한 것
-
코드를 읽다가 발견한 점입니다. 고치지는 않았습니다.
-
-
문서 차이
data-pipeline.md와 코드가 다른 곳: 실패 시 5분 캐시와 rank:sunset 키는 코드에 없고, 각 점수는 저장 직후가 아니라 조회할 때 계산합니다. 중기예보 신선도는 DB가 아니라 Redis 표시로 판단합니다.
-
-
-
-
기준: backend 코드 (services/, scheduler/jobs.py, router/v1/), 2026-10-06.
+
기준: backend 코드 (services/, scheduler/jobs.py, router/v1/), 2026-10-07.