Merge branch 'main' into feat/open-meteo
# Conflicts: # backend/router/v1/index/index.py # backend/services/calc/index_calc.py # backend/services/index_service.py # backend/tests/conftest.py # backend/tests/test_index_api.py # backend/tests/test_index_calc.py # backend/tests/test_sky_api.py # backend/worker_main.py
No files matched your search
@@ -19,3 +19,11 @@ PORT=9810
|
||||
# 생성: python -c "import secrets; print(secrets.token_urlsafe(48))"
|
||||
JWT_ACCESS_SECRET=
|
||||
JWT_REFRESH_SECRET=
|
||||
|
||||
# ── 배포(compose): 비우면 로컬 기본값. 킹서버 예: FRONT_PORT=30040, API_BIND=127.0.0.1:9810, PG_BIND=127.0.0.1:5440, REDIS_BIND=127.0.0.1:6390
|
||||
FRONT_PORT=
|
||||
API_BIND=
|
||||
PG_BIND=
|
||||
REDIS_BIND=
|
||||
# 프론트가 부를 API 주소. 비우면 같은 주소의 /v1 (nginx 가 backend 로 넘김)
|
||||
VITE_API_BASE_URL=
|
||||
@@ -1,18 +1,84 @@
|
||||
# TODO
|
||||
|
||||
## 진행 순서
|
||||
|
||||
결정이 필요 없는 것부터, 사용자 눈에 틀린 정보가 보이는 것 → 기능 → 다듬기 순.
|
||||
|
||||
1. 진행 중: 로딩 스켈레톤, 행사 사진·미술관 전시, 각 점수 오늘/내일/토/일
|
||||
2. 틀린 정보 바로잡기: 아이콘 오용 → 뜻 모를 표시 → 빈 데이터 표시 → 포스트 본문 반복
|
||||
3. 데이터 확인: 지역 격자 2곳, 서울·경기 반영 범위
|
||||
4. 기능: 토·일 플랜 행사 거리 30km → 미세먼지 따로 포스트 → 댓글·좋아요 대기 표시 → 노을 명소 지역별 → 주말 전국 랭킹 → 당일치기 포스트
|
||||
5. 다듬기: 노을 탭 재정리 → 히어로 UI → 각 점수 구간별 설명
|
||||
6. 사용자 결정 후: [결정 필요] 표시 행, 가중치 재검토, 닉네임, 커뮤니티, LLM 두 건
|
||||
7. 확인 받고: 서버 배포(운영 영향), Open-Meteo 정확도 비교(비 오는 날 필요)
|
||||
|
||||
| 상태 | 할 일 | 이유 | 관련 파일 |
|
||||
|---|---|---|---|
|
||||
| [ ] | 서버 배포 + 공유 링크 | 10/6 회의 핵심 업무 | `compose.yaml` |
|
||||
| [x] | 각 점수 하향, 100점은 완벽 조건만 | 10/6 회의 결정 | `backend/services/calc/index_calc.py`, `backend/seed/index_definition.json` |
|
||||
| [ ] | 가중치 재검토 | 10/6 회의 | `backend/seed/index_definition.json` |
|
||||
| [ ] | 서버 배포 + 공유 링크 | 10/2 회의 핵심 업무 | `compose.yaml` |
|
||||
| [x] | 각 점수 하향, 100점은 완벽 조건만 | 10/2 회의 결정 | `backend/services/calc/index_calc.py`, `backend/seed/index_definition.json` |
|
||||
| [ ] | 가중치 재검토 | 10/2 회의 | `backend/seed/index_definition.json` |
|
||||
| [x] | 댓글·좋아요·로그인 API 테스트 (화면 확인은 아직) | 시연 때 미검증 | `backend/services/reaction_service.py`, `backend/services/auth_service.py` |
|
||||
| [x] | 주말 날씨 평일 상시 노출 + 다음 주 주말까지 (예보 닿는 +10일부터) | 10/6 회의 | `backend/services/week_service.py` |
|
||||
| [x] | 행사 독립 카드 최대 3장, 피드 무작위 노출 (하루 같은 자리) | 10/6 회의 | `backend/services/feed_service.py` |
|
||||
| [x] | 계절 소식 제철 7개 추가 (햇밤·햇땅콩·은행·고구마·귤·부사·김장) — 피드백 대기 | 10/6 회의 | `backend/seed/article.json` |
|
||||
| [x] | 새 각 추가 (야구·공부·넷플릭스·군밤) | 10/6 회의 | `backend/seed/index_definition.json` |
|
||||
| [ ] | 주말 전국 지역 랭킹 | 10/6 회의 최종 그림 | `backend/services/week_service.py` |
|
||||
| [ ] | 노을 명소 지역별 목록 연결 | 10/6 회의 (추후) | `backend/seed/sunset_spot.csv` |
|
||||
| [ ] | 서울·경기 반영 범위 확인 | 10/6 회의 확인 필요 | `backend/seed/region.csv` |
|
||||
| [x] | 습도 편한 범위 30~60%, 최적 35% | 10/6 회의 예시 "습도 30%" | `backend/seed/index_definition.json` |
|
||||
| [ ] | 지역 격자(nx/ny)가 좌표와 안 맞는 2곳 확인 (4775000000, 4812900000) | 지역 데이터 점검 중 발견 | `backend/seed/region.csv` |
|
||||
| [x] | 주말 날씨 평일 상시 노출 + 다음 주 주말까지 (예보 닿는 +10일부터) | 10/2 회의 | `backend/services/week_service.py` |
|
||||
| [x] | 행사 독립 카드 최대 3장, 피드 무작위 노출 (하루 같은 자리) | 10/2 회의 | `backend/services/feed_service.py` |
|
||||
| [x] | 계절 소식 제철 7개 추가 (햇밤·햇땅콩·은행·고구마·귤·부사·김장) — 피드백 대기 | 10/2 회의 | `backend/seed/article.json` |
|
||||
| [x] | 새 각 추가 (야구·공부·넷플릭스·군밤) | 10/2 회의 | `backend/seed/index_definition.json` |
|
||||
| [x] | 주말 전국 지역 랭킹 — 노을 순위 대표 30곳의 토·일 '나들이 날씨 점수'(낮 10~17시 비 40·기온 35·하늘 15·바람 10, 비 60%↑면 최대 30점) 순위. `GET /v1/week/ranking`, 주말 화면 '이번 주말 전국 날씨 순위'(토/일 탭, 10위까지). 워커가 06:40·18:40에 계산해 Redis에 13시간 저장, 없으면 API가 그 자리에서 계산 | 10/2 회의 최종 그림 | `backend/services/weekend_rank.py`, `backend/services/calc/index_calc.py` (`outing`), `frontend/src/b/WeekPage.tsx` |
|
||||
| [x] | 노을 명소 지역별 목록 연결 — 지금 명소 데이터가 서울 마포구 3곳뿐이고 구 코드로만 찾아서 분당구 등은 하나도 안 나옴 | 10/2 회의 (추후), 사용자 지적 | `backend/seed/sunset_spot.csv`, `backend/services/sky_service.py` |
|
||||
| [ ] | 노을 명소 30km 안에 하나도 없는 구 89/256 — 광주·대전·세종·충북·강원·경북 내륙·전북 내륙 등. TourAPI 키워드로는 안 잡혀 직접 추가하거나 반경을 넓힐지 결정 필요 | 명소 확충 결과 | `backend/seed/sunset_spot.csv`, `backend/services/sky_service.py` |
|
||||
| [ ] | 명소 '서쪽이 트임'(west_open)·설명 꼬리말은 TourAPI 개요를 보고 사람이 붙인 값 — 현장 확인 안 됨. 분당구는 가장 가까운 곳이 17~18km(일자산·반포·광나루)라 수도권 동남부 명소 보강 필요 | 명소 확충 결과 | `backend/seed/sunset_spot.csv` |
|
||||
| [ ] | 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] | 히어로 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` |
|
||||
| [ ] | 커뮤니티: 유저가 자기만의 각을 올리고, 좋아요 많이 받은 순으로 노출 — 검토 필요 (신고·숨김, 작성 양식, 노출 위치) | 사용자 아이디어 | `backend/services/reaction_service.py`, `backend/services/feed_service.py` |
|
||||
| [x] | 노을 탭이 무슨 의미인지 안 읽힘 — 점수·3컷·3일 예보가 '오늘 나가 볼 만한가'로 이어지게 보여줄 내용 재정리 | 사용자 지적 | `frontend/src/b/SkyPage.tsx`, `backend/services/sky_service.py` |
|
||||
| [ ] | 스케줄 포스트 생성에 LLM 입히기 — 날씨·행사·일몰 같은 재료를 넣어 문구·일정 제안을 풍부하게 (고정 문구 반복 탈피). 모델·비용·캐시·실패 시 기존 문구로 대체 방식 결정 필요 | 사용자 요청 | `backend/scheduler/`, `backend/services/feed_service.py`, `backend/services/week_service.py` |
|
||||
| [x] | 데이터 불러오는 동안 오늘 날씨 점수가 '-'로 보임 — 로딩 중임을 제대로 표현하기 (스켈레톤 등), 실패와 구분 | 사용자 지적 | `frontend/src/b/TodayPage.tsx` |
|
||||
| [ ] | 포스트 말고도 LLM을 적용할 곳 찾아보기 — 예: 히어로의 '오늘의 날씨 한마디', 각 계산 근거 설명, 알림 문구 등. 화면별로 고정 문구가 반복되는 자리를 모아 후보 목록 만들기 | 사용자 요청 | `backend/services/feed_service.py`, `backend/services/now_service.py`, `frontend/src/b/TodayPage.tsx` |
|
||||
| [x] | 토·일 플랜 행사를 시도 경계 대신 거리(30km, 서울·인천 포함)로 고르기 — 행사 띠·행사 포스트·주말 플랜·주말 화면 모두 `WeekService.events` 한 곳에서 고름. 구 중심 50km 안 시도들을 함께 받고, 좌표 없는 행사는 같은 시도만. 문구 "서울 행사" → "가까운 행사" | 사용자 결정 — 지금은 경기도 안만 봐서 잠실·성수는 빠지고 연천은 들어옴 | `backend/services/week_service.py`, `backend/services/weekend_plan.py`, `backend/services/external/tour_api.py` |
|
||||
| [x] | 당일치기 포스트 — 1~2시간 거리 후보 도시 중 주말 날씨가 제일 좋은 곳 + 그곳 행사. `PostType.DAY_TRIP`(13), 주말 플랜 뒤. 후보 도시는 `seed/trip_city.csv`(DB 아님, 서버가 바로 읽음 — 줄만 더하면 늘어남) | 사용자 결정 | `backend/services/feed_service.py` (`_day_trip`), `backend/services/weekend_rank.py`, `backend/seed/trip_city.csv`, `frontend/src/b/Post.tsx` |
|
||||
| [ ] | **[결정 필요]** 당일치기 후보 범위 — 지금은 내 지역에서 직선 20~200km 안 후보만, 1위가 50점 미만이면 카드를 끔. 부산·제주 등은 10곳이 다 200km 밖이라 카드가 안 나옴. 거리 기준·지역별 후보 추가 여부 | 당일치기 작업 중 정함 | `backend/services/weekend_rank.py` (`TRIP_MIN_KM`, `TRIP_MAX_KM`, `TRIP_MIN_SCORE`), `backend/seed/trip_city.csv` |
|
||||
| [ ] | 주말이 단기예보 밖(월~수)이면 나들이 점수가 중기예보(오전·오후 비 확률, 최저·최고 기온, 하늘)로만 나와 지역 간 차이가 작음 (10/6 토요일 1~10위 85~82점). 바람 정보 없음 70점 고정 | 주말 랭킹 확인 중 발견 | `backend/services/calc/index_calc.py` (`outing_estimate`) |
|
||||
| [ ] | 월요일 0시~06:40엔 새 주말 점수가 아직 없어 당일치기 카드가 꺼짐 (주말 화면 순위는 그 자리에서 계산해 채움). 필요하면 03:00 작업에도 계산 추가 | 당일치기 작업 중 발견 | `backend/worker_main.py`, `backend/scheduler/jobs.py` |
|
||||
| [ ] | 주말 점수 계산이 대표 지역·후보 도시 34곳 예보를 받음 — 1회 기상청 단기 최대 34(처음엔 68)·중기 68건, 하루 2회 ≈ 200건. 당일치기 도시 행사는 그 도시 주변 시도 TourAPI·문화정보(시도별 하루 1회 캐시). 운영 배포 때 일일 한도와 함께 확인 | 주말 랭킹 작업 | `backend/services/weekend_rank.py`, `backend/docs/load-estimate.md` |
|
||||
| [ ] | 기상청 vs Open-Meteo 정확도 비교 — 두 예보를 3일 모아 기상청 실황과 맞춰 봄 (비 오는 날 포함). 10/6 비교는 전국 맑음이라 비 판단 근거가 약함 | 운영적합성 점검 | `backend/scripts/compare_open_meteo.py` |
|
||||
| [ ] | **[결정 필요]** 각 순위에 중요도 반영 — 점수만으로 정해 환기·세차각이 상위권. 안: `index_definition.priority`(상/중/하) 추가, 정렬은 점수×가중치(상 1.0·중 0.85·하 0.7), 표시 점수는 그대로. 정할 것: 등급 배정(초안 — 상: 빨래·산책·피크닉·등산·캠핑·러닝·자전거 / 중: 야장·치맥·별보기·멍뭉산책·사진산책·김서림·화장붕괴·택시대란·배달폭주 / 하: 환기·세차·가드닝·야구·짬뽕·막걸리·뜨아·냉면·공부·넷플릭스·군밤), 가중치 값, 로컬·운영 DB `ALTER TABLE index_definition ADD COLUMN priority SMALLINT NOT NULL DEFAULT 2` 실행 | 사용자 지적 | `backend/services/index_service.py:119`, `backend/common/database/model/models.py`, `backend/postgres-init/init.sql`, `backend/seed/index_definition.json` |
|
||||
| [x] | 각 상세 창 점수 칸을 오늘/내일/토/일로 — 단기예보(시간별)는 약 4일 뒤까지라 월~수엔 주말 점수를 같은 방식으로 못 냄. 안: 범위 밖 주말은 중기예보(기온·비 확률)로 대략 점수 + "예상" 표시, 오늘·내일이 주말이면 다음 주말 표시 | 사용자 요청 | `backend/services/index_service.py` (`DAYS = 3`), `frontend/src/b/Sheets.tsx` |
|
||||
| [ ] | **[결정 필요]** 그날 밤 달 모양(초승·상현·보름·하현·그믐) 보여 줄 화면 정하기 — 계산은 `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` |
|
||||
| [x] | 아이콘 오용 — 밤 '한 문장' 카드에 망원경(`stars`), 폭염·한파 특보에도 우산 아이콘·"☔ 우산 챙겨!", 흐린 날 노을 시간대 칸에 노을 그림, 데이터 없는 칸에 해·구름 그림, 흐려도 "맑음"·해 그림(주말 플랜·주말 화면), 행사 아이콘 `calendar`/`fireworks` 혼용 | 전체 검수 | `backend/seed/article.json:103,117`, `backend/services/feed_service.py:420`, `backend/services/weather_service.py:85,94`, `backend/services/weekend_plan.py:52,95,116`, `frontend/src/b/WeekPage.tsx:85` |
|
||||
| [x] | 뜻 모를 표시 — "출처: 날씨각 (검수 전 예시)" 노출, "41번째 주", "해 지는 쪽 263°", 점수 뒤 "점" 없음, "추천: 피크닉각 추천", 노을 시각 18:12/6:12 이중 표기, 날짜 "10.04"/"10.4" 혼용, "구름많음"/"구름 많음" 혼용 | 전체 검수 | `backend/seed/article.json`, `frontend/src/b/SeasonPage.tsx:32`, `frontend/src/b/SkyPage.tsx`, `frontend/src/b/WeekPage.tsx:69` |
|
||||
| [x] | 빈 데이터 표시 — 절기 당일 "한로 지나 0일째", 장소 빈 행사 "10.2 ~ 10.11 · ", 공유 창 빈 메시지 " — 제목", 주말 플랜 공유 문구가 쉼표로 끝남, 바람 정보 없을 때 요약이 "맑음" | 전체 검수 | `backend/services/season_service.py:55`, `backend/services/external/tour_api.py:35`, `frontend/src/b/Sheets.tsx:283`, `backend/services/feed_service.py:399`, `backend/services/calc/index_calc.py` (`_summary`) |
|
||||
| [ ] | **[결정 필요]** 중복·쓸모없을 수 있는 UI — 각 상세 창 이름 두 번, 읽을거리 창 분류 두 번, 시트 손잡이(끌어 닫기 없음), 글 시각 항상 "오늘", 피드 노을 슬라이드 큰 점수에 설명 없음(`Post.tsx`, 노을 탭엔 설명 넣음), 각 화면 '전체'에서 1~3위 두 번, 지역 창에도 로그아웃 | UI 점검 | `frontend/src/b/Sheets.tsx`, `frontend/src/b/Post.tsx`, `frontend/src/b/TodayPage.tsx`, `frontend/src/b/GakPage.tsx` |
|
||||
| [ ] | 아이콘 겹침 — `moon`이 날씨·'내일 미리보기' 계정·캐릭터 '달님'에, `rabbit`이 '오늘의 각' 계정·사용자 캐릭터에 같이 쓰여 공식 계정과 사용자가 헷갈림 | 전체 검수 | `frontend/src/b/Post.tsx:18,25`, `frontend/src/b/lib.ts` |
|
||||
| [x] | 댓글 올리기·지우기 대기 표시 없음, 좋아요 실패 시 알림 없음 (로그인·내 정보 저장 대기 문구 포함) | 로딩 검수 | `frontend/src/b/Sheets.tsx` (`CommentsSheet`, `CommentRow`), `frontend/src/b/Post.tsx` (`FullCard`) |
|
||||
| [x] | 행사 사진 연결 — 오늘 행사 띠·주말 행사 카드·행사 포스트·주말 플랜에 사진 + 출처(ⓒ한국관광공사 / ⓒ한국문화정보원), 사진 없거나 깨지면 아이콘 | 사용자 요청 | `frontend/src/b/ui.tsx` (`Thumb`, `Credit`), `backend/services/week_service.py` (`image_credit`) |
|
||||
| [x] | 미술관·박물관 전시 추가 — 문화정보 API(`kcis:` 접두어) 연결, 실패해도 TourAPI 행사는 그대로 | 사용자 요청 | `backend/services/external/culture_api.py`, `backend/services/week_service.py` |
|
||||
| [ ] | 문화정보 API 승인 후 실제 응답 확인 — 지금 `SERVICE_KEY_IS_NOT_REGISTERED_ERROR`(403). 날짜 형식, `gpsX`/`gpsY` 순서, 썸네일 https 여부 확인. 승인 직후 바로 보려면 Redis `event:{sido}:{날짜}` 키 삭제 | 전시 연결 중 발견 | `backend/services/external/culture_api.py` |
|
||||
| [ ] | **[결정 필요]** 두 달 넘는 전시가 `MAX_EVENT_DAYS = 60` 필터에 걸려 빠짐 — 전시는 기준을 따로 둘지 | 전시 연결 중 발견 | `backend/services/week_service.py` |
|
||||
| [ ] | 전시 썸네일 저작권 확인 — 데이터셋은 '이용허락범위 제한 없음'이나 원저작권이 주최 기관에 있을 수 있음 | 전시 연결 중 발견 | `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` |
|
||||
| [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` |
|
||||
| [ ] | 미세먼지 포스트에 오늘 시간대별 예보 추가 — 지금은 실시간 측정값만. 에어코리아 예보 API(`getMinuDustFrcstDspth`, 권역별 오늘·내일 등급) 연결 필요 | 미세먼지 포스트 작업 중 발견 | `backend/services/external/airkorea.py`, `backend/services/feed_service.py` (`_air`) |
|
||||
| [ ] | 마스크 아이콘 없음 — 미세먼지 포스트가 좋음·보통은 `vent`, 나쁨 이상은 `cloud`를 씀 | 미세먼지 포스트 작업 중 발견 | `frontend/public/icons/`, `backend/services/feed_service.py` (`_air`) |
|
||||
| [ ] | **[결정 필요]** 주말 화면 '데이트 명소'는 아직 시도 기준(`places`) — 행사처럼 거리 기준으로 바꿀지. 지금 명소 데이터는 10곳뿐 | 행사 거리 기준 작업 중 발견 | `backend/services/week_service.py` (`places`), `frontend/src/b/WeekPage.tsx` |
|
||||
| [ ] | 행사 수집이 사용자 한 명당 주변 시도 2~4곳으로 늘어 TourAPI·문화정보 API 호출이 시도 수만큼 늘어남(시도별 하루 1회 캐시) — 운영 배포 때 일일 호출 한도 확인 | 행사 거리 기준 작업 중 발견 | `backend/services/week_service.py` (`_ensure_events`), `backend/docs/load-estimate.md` |
|
||||
| [ ] | 다른 문서의 포스트 종류 목록·행사 시도 기준 설명 갱신 (`PostType` 12 미세먼지, 30km 행사) — `docs/포스트타입별_내용.html`만 고침 | 문서 점검 | `backend/docs/`, `docs/화면별_데이터출처.html`, `docs/데이터흐름.html`, `docs/콘텐츠설계서.md` |
|
||||
| [ ] | **[결정 필요]** 스켈레톤 작업에서 바뀐 디자인 — 댓글 없음 안내가 글자 두 줄 → 상자(스켈레톤 3줄 크기) | 스켈레톤 작업 중 발견 | `frontend/src/b/Sheets.tsx` (`CommentsSheet`) |
|
||||
| [ ] | **[결정 필요]** 히어로 시안 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` |
|
||||
| [ ] | 오늘 화면 불러오기 실패 → 다시 불러온 뒤 글 목록 첫 블록이 14px 내려감 (y881→895) | 히어로 롤백 측정 중 발견 | `frontend/src/b/TodayPage.tsx` |
|
||||
| [ ] | 낮 히어로 해 안 흰 글씨 "오늘 날씨 점수"가 주황 위라 대비 부족 | 히어로 롤백 중 발견 | `frontend/src/b/b.css` |
|
||||
@@ -56,6 +56,8 @@ class WeatherDaily(Base):
|
||||
sky: Mapped[int] = mapped_column(SmallInteger)
|
||||
rain_type: Mapped[int] = mapped_column(SmallInteger)
|
||||
rain_prob: Mapped[int] = mapped_column(SmallInteger)
|
||||
rain_prob_am: Mapped[Optional[int]] = mapped_column(SmallInteger, nullable=True)
|
||||
rain_prob_pm: Mapped[Optional[int]] = mapped_column(SmallInteger, nullable=True)
|
||||
issued_at: Mapped[datetime] = mapped_column(DateTime(timezone=True))
|
||||
|
||||
|
||||
@@ -199,6 +201,7 @@ class IndexScore(Base):
|
||||
time_score: Mapped[int] = mapped_column(SmallInteger)
|
||||
zero_reason: Mapped[Optional[str]] = mapped_column(String(100), nullable=True)
|
||||
notes: Mapped[dict] = mapped_column(JSONB)
|
||||
estimated: Mapped[bool] = mapped_column(Boolean, default=False)
|
||||
computed_at: Mapped[datetime] = mapped_column(DateTime(timezone=True))
|
||||
|
||||
|
||||
@@ -233,11 +236,14 @@ class Event(Base):
|
||||
area: Mapped[Optional[str]] = mapped_column(String(20), nullable=True)
|
||||
name: Mapped[str] = mapped_column(String(60))
|
||||
place_name: Mapped[str] = mapped_column(String(60))
|
||||
icon: Mapped[str] = mapped_column(String(30), default="calendar")
|
||||
icon: Mapped[str] = mapped_column(String(30), default="fireworks")
|
||||
start_date: Mapped[date] = mapped_column(Date)
|
||||
end_date: Mapped[date] = mapped_column(Date)
|
||||
is_confirmed: Mapped[bool] = mapped_column(Boolean, default=False)
|
||||
source_url: Mapped[Optional[str]] = mapped_column(String(500), nullable=True)
|
||||
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)
|
||||
|
||||
|
||||
class SolarTerm(Base):
|
||||
|
||||
@@ -122,6 +122,9 @@ class PostType(CodeEnum):
|
||||
ALERT = 8
|
||||
TOMORROW = 9
|
||||
QUOTE = 10
|
||||
WEEKEND_PLAN = 11
|
||||
AIR = 12
|
||||
DAY_TRIP = 13 # 당일치기: 1~2시간 거리 후보 도시 중 주말 날씨 1위 + 그곳 행사
|
||||
|
||||
|
||||
class RefType(CodeEnum):
|
||||
|
||||
@@ -17,3 +17,21 @@ def ieyo(word: str) -> str:
|
||||
|
||||
def month_day(d) -> str:
|
||||
return f"{d.month}월 {d.day}일"
|
||||
|
||||
|
||||
def short_day(d) -> str:
|
||||
"""2026-10-04 → "10.4" """
|
||||
return f"{d.month}.{d.day}"
|
||||
|
||||
|
||||
def day_range(start, end) -> str:
|
||||
""""10.4~10.11", 하루짜리는 "10.4" """
|
||||
return short_day(start) if start == end else f"{short_day(start)}~{short_day(end)}"
|
||||
|
||||
|
||||
_COMPASS = ("북", "북북동", "북동", "동북동", "동", "동남동", "남동", "남남동", "남", "남남서", "남서", "서남서", "서", "서북서", "북서", "북북서")
|
||||
|
||||
|
||||
def compass(deg: float) -> str:
|
||||
"""방위각 → 16방위 이름. 263 → "서" """
|
||||
return _COMPASS[round(deg / 22.5) % 16]
|
||||
@@ -13,8 +13,9 @@ class FeedCRUD:
|
||||
stmt = select(Post).where(Post.feed_date == day, Post.deleted.is_(False)).order_by(Post.position)
|
||||
return list((await s.scalars(stmt)).all())
|
||||
|
||||
async def has_day(self, s: AsyncSession, day: date) -> bool:
|
||||
return await s.scalar(select(Post.post_id).where(Post.feed_date == day, Post.deleted.is_(False)).limit(1)) is not None
|
||||
async def positions(self, s: AsyncSession, day: date) -> set[int]:
|
||||
"""그날 이미 만든 카드 번호. 지운 카드도 넣어 다시 만들지 않게 한다."""
|
||||
return set((await s.scalars(select(Post.position).where(Post.feed_date == day))).all())
|
||||
|
||||
async def insert_day(self, s: AsyncSession, rows: list[dict]) -> None:
|
||||
if rows:
|
||||
|
||||
@@ -24,6 +24,12 @@ class IndexCRUD:
|
||||
)
|
||||
return list((await s.scalars(stmt)).all())
|
||||
|
||||
async def score_dates(self, s: AsyncSession, region_code: str, since: date, until: date) -> set[date]:
|
||||
stmt = select(IndexScore.score_date).distinct().where(
|
||||
IndexScore.region_code == region_code, IndexScore.score_date >= since, IndexScore.score_date <= until
|
||||
)
|
||||
return set((await s.scalars(stmt)).all())
|
||||
|
||||
async def last_computed(self, s: AsyncSession, region_code: str, day: date):
|
||||
stmt = select(func.min(IndexScore.computed_at)).where(IndexScore.region_code == region_code, IndexScore.score_date == day)
|
||||
return await s.scalar(stmt)
|
||||
|
||||
@@ -35,8 +35,8 @@ class SkyCRUD:
|
||||
stmt = select(SkyScore).where(SkyScore.region_code.in_(region_codes), SkyScore.score_date >= since)
|
||||
return list((await s.scalars(stmt.order_by(SkyScore.score_date))).all())
|
||||
|
||||
async def spots(self, s: AsyncSession, region_code: str) -> list[SunsetSpot]:
|
||||
stmt = select(SunsetSpot).where(SunsetSpot.region_code == region_code).order_by(SunsetSpot.sort_order)
|
||||
async def spots_in_box(self, s: AsyncSession, lat: float, lon: float, dlat: float, dlon: float) -> list[SunsetSpot]:
|
||||
stmt = select(SunsetSpot).where(SunsetSpot.lat.between(lat - dlat, lat + dlat), SunsetSpot.lon.between(lon - dlon, lon + dlon))
|
||||
return list((await s.scalars(stmt)).all())
|
||||
|
||||
async def replace_spots(self, s: AsyncSession, rows: list[dict]) -> None:
|
||||
|
||||
@@ -35,8 +35,8 @@ class WeekCRUD:
|
||||
if rows:
|
||||
await s.execute(insert(Place).values(rows))
|
||||
|
||||
async def events(self, s: AsyncSession, sido_code: str, since: date, until: date) -> list[Event]:
|
||||
stmt = select(Event).where(Event.sido_code == sido_code, Event.end_date >= since, Event.start_date <= until)
|
||||
async def events(self, s: AsyncSession, sido_codes: list[str], since: date, until: date) -> list[Event]:
|
||||
stmt = select(Event).where(Event.sido_code.in_(sido_codes), Event.end_date >= since, Event.start_date <= until)
|
||||
return list((await s.scalars(stmt.order_by(Event.start_date))).all())
|
||||
|
||||
async def upsert_events(self, s: AsyncSession, rows: list[dict]) -> None:
|
||||
@@ -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")},
|
||||
set_={k: stmt.excluded[k] for k in ("name", "place_name", "start_date", "end_date", "is_confirmed", "image_url", "lat", "lon")},
|
||||
))
|
||||
|
||||
async def replace_manual_events(self, s: AsyncSession, rows: list[dict]) -> None:
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
| 문서 | 내용 | 아티팩트 |
|
||||
|---|---|---|
|
||||
| `../../docs/데이터지도.html` | 데이터 지도: 피드 하나를 열면 무엇을 언제 받아 어디에 두는지, 하루 시계, 화면별 데이터 | https://claude.ai/artifact/CcdToNRntavNvo3XKNokqJ |
|
||||
| `../../docs/데이터흐름.html` | 데이터 흐름: 어디서 받는지와 그 이유, 피드 하나를 열면 무엇을 언제 받아 어디에 두는지, 하루 시계, 화면별 데이터 | https://claude.ai/artifact/CcdToNRntavNvo3XKNokqJ |
|
||||
| `data-pipeline.md` (`.html` 은 같은 내용) | 외부 API를 언제 받아 어디에 저장·캐시하는지, 피드 칸, 하루 1번 스케줄, 테스트 DB | https://claude.ai/artifact/A4cE22L5aPnMfU53mKCSps |
|
||||
| `openmeteo-data.md` | Open-Meteo로 받는 구름(JMA·ICON, 20·100km)과 보조값(자외선·가시거리·돌풍·기압·일조·일사·지면온도)의 변수, 3시간 집계, 저장·갱신, 호출량, 지수 활용 후보, DB 적용 SQL | - |
|
||||
| `api.html` | API 목록, 응답 예시, 프론트 연결(Hey API) | https://claude.ai/artifact/LjVYpLzomBTrkMxjDvAoDD |
|
||||
|
||||
@@ -122,7 +122,8 @@ light = 1 - min(low100 + 0.5×mid100, 100) / 100
|
||||
| `view` 가시거리 | `visibility_m` **최소**(km) | 20km 이상 100점, 5km 이하 0점, 사이는 선형 | `weight_view`, `view_score` |
|
||||
|
||||
- 값이 없으면(수집 전, 구간 없음) 미세먼지처럼 **70점(정보 없음)**.
|
||||
- 비중이 0인 지수에서는 점수에 영향이 없고, 상세 API(`/v1/index/{id}`)에도 나오지 않는다 (기존 6개 축은 항상 나옴).
|
||||
- 비중이 0인 지수에서는 점수에 영향이 없고, 상세 API(`/v1/index/{id}`)에도 나오지 않는다. 기존 6개 축도 같은 규칙으로, 비중이 0이면 나오지 않는다.
|
||||
- 중기예보로 내는 예상 점수(`estimate`)에서는 값이 없으므로 비중이 있으면 70점(정보 없음)이다.
|
||||
- 0점 조건에 쓰는 필드 2개가 늘었다: `gust_ms`(돌풍 최대), `ground_c`(지표면 온도 최대).
|
||||
|
||||
### 지수별 적용
|
||||
|
||||
@@ -33,6 +33,8 @@ CREATE TABLE IF NOT EXISTS public.weather_daily (
|
||||
sky SMALLINT NOT NULL, -- 그날 대표 하늘 (Sky)
|
||||
rain_type SMALLINT NOT NULL, -- 그날 대표 강수 (RainType)
|
||||
rain_prob SMALLINT NOT NULL, -- 그날 최대 비 확률 %
|
||||
rain_prob_am SMALLINT NULL, -- 오전 비 확률 % (중기예보 8일 뒤부터는 하루 값만 있어 rain_prob 과 같음)
|
||||
rain_prob_pm SMALLINT NULL, -- 오후 비 확률 %
|
||||
issued_at TIMESTAMPTZ NOT NULL,
|
||||
PRIMARY KEY (region_code, forecast_date)
|
||||
);
|
||||
@@ -119,7 +121,7 @@ CREATE TABLE IF NOT EXISTS public.sky_score (
|
||||
PRIMARY KEY (region_code, score_date, sky_type)
|
||||
);
|
||||
|
||||
-- 구별 지수 점수. 오늘·내일·모레를 날짜별 줄로 둔다 (각 화면의 막대 3개).
|
||||
-- 구별 지수 점수. 오늘·내일·모레와 이번 주말을 날짜별 줄로 둔다 (각 상세 창 칸: 오늘·내일·토·일).
|
||||
CREATE TABLE IF NOT EXISTS public.index_score (
|
||||
region_code VARCHAR(10) NOT NULL,
|
||||
score_date DATE NOT NULL,
|
||||
@@ -137,6 +139,7 @@ CREATE TABLE IF NOT EXISTS public.index_score (
|
||||
time_score SMALLINT NOT NULL,
|
||||
zero_reason VARCHAR(100) NULL, -- 0점이 된 이유 (걸리지 않았으면 NULL)
|
||||
notes JSONB NOT NULL, -- 요소별 근거 문장 {"temp": "체감 21°, 편한 범위 18~24° 안", ...}
|
||||
estimated BOOLEAN NOT NULL DEFAULT false, -- 시간별 예보가 없어 중기예보로 낸 예상 점수
|
||||
computed_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
PRIMARY KEY (region_code, score_date, index_id)
|
||||
);
|
||||
@@ -146,7 +149,7 @@ CREATE TABLE IF NOT EXISTS public.post (
|
||||
post_id BIGSERIAL PRIMARY KEY,
|
||||
feed_date DATE NOT NULL,
|
||||
position SMALLINT NOT NULL, -- 그날 카드 번호 (1부터). 화면 순서는 시간대마다 따로 정한다
|
||||
post_type SMALLINT NOT NULL, -- PostType: 1=오늘날씨 2=지수 3=노을 4=계절소식 5=행사 6=상식 7=주말추천 8=우산·특보 9=내일미리보기 10=한문장
|
||||
post_type SMALLINT NOT NULL, -- PostType: 1=오늘날씨 2=지수 3=노을 4=계절소식 5=행사 6=상식 7=주말예보 8=우산·특보 9=내일미리보기 10=한문장 11=주말플랜 12=미세먼지
|
||||
ref_type SMALLINT NOT NULL DEFAULT 1, -- RefType: 1=없음(그 구 데이터로 채움) 2=index_definition 3=article 4=event
|
||||
ref_id BIGINT NULL, -- ref_type 이 가리키는 테이블의 id
|
||||
index_rank SMALLINT NULL, -- 지수 포스트가 "그 구의 N위 지수"일 때 N
|
||||
@@ -278,7 +281,7 @@ CREATE TABLE IF NOT EXISTS public.sunset_spot (
|
||||
description VARCHAR(100) NOT NULL, -- "강 건너 서쪽이 넓게 트임 · 자전거 7분"
|
||||
lat NUMERIC(8,5) NOT NULL,
|
||||
lon NUMERIC(8,5) NOT NULL,
|
||||
sort_order SMALLINT NOT NULL DEFAULT 0
|
||||
sort_order SMALLINT NOT NULL DEFAULT 0 -- 0 해 지는 쪽이 트인 곳(먼저), 1 그 밖
|
||||
);
|
||||
|
||||
-- 날씨 맞춤 데이트 명소 (주말·행사 탭).
|
||||
@@ -303,12 +306,18 @@ CREATE TABLE IF NOT EXISTS public.event (
|
||||
area VARCHAR(20) NULL, -- place.area 와 같은 묶음, NULL = 전체
|
||||
name VARCHAR(60) NOT NULL,
|
||||
place_name VARCHAR(60) NOT NULL, -- "여의도 한강공원"
|
||||
icon VARCHAR(30) NOT NULL DEFAULT 'calendar', -- TourAPI 는 아이콘이 없어 기본값
|
||||
icon VARCHAR(30) NOT NULL DEFAULT 'fireworks', -- TourAPI 는 아이콘이 없어 기본값
|
||||
start_date DATE NOT NULL,
|
||||
end_date DATE NOT NULL,
|
||||
is_confirmed BOOLEAN NOT NULL DEFAULT FALSE, -- FALSE = 예년 기준 일정 (화면에 "확인 필요" 표시)
|
||||
source_url VARCHAR(500) NULL
|
||||
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
|
||||
);
|
||||
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;
|
||||
|
||||
-- 공휴일 (주말·행사 탭의 "개천절").
|
||||
CREATE TABLE IF NOT EXISTS public.holiday (
|
||||
|
||||
@@ -34,6 +34,8 @@ class RowsSlide(WebPacketProtocol):
|
||||
line: str
|
||||
icon: str
|
||||
rows: list[Row] = []
|
||||
image: Optional[str] = None # 있으면 아이콘 대신 카드 전체에 사진
|
||||
image_credit: Optional[str] = None # 사진 출처 표기 ("ⓒ한국관광공사")
|
||||
|
||||
|
||||
class GakSlide(WebPacketProtocol):
|
||||
@@ -67,16 +69,40 @@ class WeekDay(WebPacketProtocol):
|
||||
weekday: str
|
||||
icon: str
|
||||
text: str
|
||||
temp_min_c: Optional[float] = None
|
||||
temp_max_c: Optional[float] = None
|
||||
rain_prob: Optional[int] = None
|
||||
|
||||
|
||||
class WeekSlide(WebPacketProtocol):
|
||||
"""주말 예보: 토·일 비교 + 옷차림·우산 팁."""
|
||||
|
||||
kind: Literal["week"]
|
||||
eyebrow: str
|
||||
line: str
|
||||
days: list[WeekDay]
|
||||
tip: Optional[str] = None
|
||||
|
||||
|
||||
Slide = Annotated[Union[HoursSlide, RowsSlide, GakSlide, SunsetSlide, WeekSlide], Field(discriminator="kind")]
|
||||
class PlanStep(WebPacketProtocol):
|
||||
time: str
|
||||
icon: str
|
||||
title: str
|
||||
sub: str
|
||||
image: Optional[str] = None # 행사 사진
|
||||
image_credit: Optional[str] = None
|
||||
|
||||
|
||||
class PlanSlide(WebPacketProtocol):
|
||||
"""주말 플랜: 그날 시간대별 동선."""
|
||||
|
||||
kind: Literal["plan"]
|
||||
eyebrow: str
|
||||
line: str
|
||||
steps: list[PlanStep]
|
||||
|
||||
|
||||
Slide = Annotated[Union[HoursSlide, RowsSlide, GakSlide, SunsetSlide, WeekSlide, PlanSlide], Field(discriminator="kind")]
|
||||
|
||||
|
||||
class PostData(WebPacketProtocol):
|
||||
@@ -124,6 +150,8 @@ class BandEvent(WebPacketProtocol):
|
||||
name: str
|
||||
status_label: str
|
||||
icon: str
|
||||
image: Optional[str] = None
|
||||
image_credit: Optional[str] = None
|
||||
|
||||
|
||||
class BandArticle(WebPacketProtocol):
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
from datetime import date
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import APIRouter, Depends, Path, Query
|
||||
@@ -5,20 +6,18 @@ 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 services.calc.index_calc import AXES, BASE_AXES, zero_rules_text
|
||||
from services.index_service import IndexItem, IndexService
|
||||
from services.calc.index_calc import AXES, axis_label, zero_rules_text
|
||||
from services.index_service import IndexItem, IndexService, slot_label
|
||||
|
||||
router = APIRouter(prefix="/v1/index", tags=["index"])
|
||||
|
||||
_AXIS_LABEL = {"temp": "기온", "rain": "비", "wind": "바람", "humidity": "습도", "air": "공기", "uv": "자외선", "sun": "햇빛", "view": "가시거리", "time": "시간대"}
|
||||
|
||||
|
||||
def _summary(i: IndexItem) -> IndexSummary:
|
||||
def _summary(i: IndexItem, today: date) -> IndexSummary:
|
||||
d = i.definition
|
||||
return IndexSummary(
|
||||
index_id=d.index_id, code=d.code, name=d.name, icon=d.icon, category=IndexCategory(d.category), is_fun=d.is_fun,
|
||||
is_core=d.is_core, score=i.score.score, rank=i.rank, summary=i.score.summary,
|
||||
trend=[TrendPoint(day=t.score_date, score=t.score) for t in i.trend],
|
||||
trend=[TrendPoint(day=t.score_date, label=slot_label(t.score_date, today), score=t.score, estimated=t.estimated) for t in i.trend],
|
||||
)
|
||||
|
||||
|
||||
@@ -32,7 +31,7 @@ async def list_indices(
|
||||
err, board = await service.board(region)
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return Res_IndexList(result=error_info(err))
|
||||
items = [_summary(i) for i in board.items]
|
||||
items = [_summary(i, board.day) for i in board.items]
|
||||
filtered = [x for x in items if (category is None or x.category is category) and (not core or x.is_core)]
|
||||
return Res_IndexList(region_code=board.region.code, day=board.day, weather_score=board.weather_score, top3=items[:3], items=filtered)
|
||||
|
||||
@@ -47,10 +46,11 @@ async def get_index(index_id: int = Path(...), region: str = Query(..., descript
|
||||
return Res_IndexDetail(result=error_info(ErrorType.NOT_FOUND))
|
||||
d, s = item.definition, item.score
|
||||
return Res_IndexDetail(
|
||||
index=_summary(item), description=d.description,
|
||||
index=_summary(item, board.day), description=d.description,
|
||||
factors=[
|
||||
Factor(axis=a, label=_AXIS_LABEL[a], value=getattr(s, f"{a}_score"), weight=getattr(d, f"weight_{a}"), note=s.notes.get(a, ""))
|
||||
for a in AXES if a in BASE_AXES or getattr(d, f"weight_{a}") > 0
|
||||
Factor(axis=a, label=axis_label(a, d.factor_rules), value=getattr(s, f"{a}_score"), weight=getattr(d, f"weight_{a}"), note=s.notes.get(a, ""))
|
||||
for a in AXES
|
||||
if getattr(d, f"weight_{a}")
|
||||
],
|
||||
zero_rules=zero_rules_text(d.zero_rules), zero_reason=s.zero_reason, limit=d.limit_description,
|
||||
)
|
||||
@@ -1,13 +1,17 @@
|
||||
from datetime import date
|
||||
from typing import Optional
|
||||
|
||||
from pydantic import Field
|
||||
|
||||
from common.enums import IndexCategory
|
||||
from common.models.gmodel import Res_WebPacketProtocol, WebPacketProtocol
|
||||
|
||||
|
||||
class TrendPoint(WebPacketProtocol):
|
||||
day: date
|
||||
label: str = Field(description="칸 이름: 오늘 / 내일 / 토 10.10")
|
||||
score: int
|
||||
estimated: bool = Field(description="시간별 예보가 없어 중기예보로 낸 예상 점수")
|
||||
|
||||
|
||||
class IndexSummary(WebPacketProtocol):
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
from datetime import date, datetime
|
||||
from typing import Optional
|
||||
from typing import Literal, Optional
|
||||
|
||||
from common.enums import Confidence, SkyGrade, SkyType
|
||||
from common.models.gmodel import Res_WebPacketProtocol, WebPacketProtocol
|
||||
@@ -30,6 +30,25 @@ class SpotData(WebPacketProtocol):
|
||||
distance_km: float
|
||||
|
||||
|
||||
class PlanSpot(WebPacketProtocol):
|
||||
name: str
|
||||
distance_km: float
|
||||
|
||||
|
||||
class SkyPlanData(WebPacketProtocol):
|
||||
day: date
|
||||
when: str
|
||||
verdict: Literal["go", "maybe", "rest"]
|
||||
headline: str
|
||||
reason: str
|
||||
score: int
|
||||
grade_label: str
|
||||
best_at: Optional[datetime] = None
|
||||
spot: Optional[PlanSpot] = None
|
||||
timeline: list[BestTime] = []
|
||||
outlook: str = ""
|
||||
|
||||
|
||||
class Res_Sky(Res_WebPacketProtocol):
|
||||
region_code: Optional[str] = None
|
||||
sunset_azimuth: Optional[int] = None
|
||||
@@ -37,6 +56,7 @@ class Res_Sky(Res_WebPacketProtocol):
|
||||
sunrise: Optional[SkyScoreData] = None
|
||||
days: list[SkyScoreData] = []
|
||||
spots: list[SpotData] = []
|
||||
plan: Optional[SkyPlanData] = None
|
||||
|
||||
|
||||
class RankData(WebPacketProtocol):
|
||||
|
||||
@@ -4,9 +4,9 @@ from common.database.model.models import SkyScore
|
||||
from common.enums import Confidence, ErrorType, SkyGrade, SkyType
|
||||
from common.models.errors import error_info
|
||||
from common.utils.kma_time import now_kst
|
||||
from router.v1.sky.protocol import BestTime, RankData, Res_Sky, Res_SkyRanking, SkyScoreData, SpotData
|
||||
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 SkyService
|
||||
from services.sky_service import SkyPlan, SkyService
|
||||
|
||||
router = APIRouter(prefix="/v1/sky", tags=["sky"])
|
||||
|
||||
@@ -18,7 +18,15 @@ def _score(x: SkyScore) -> SkyScoreData:
|
||||
)
|
||||
|
||||
|
||||
@router.get("", response_model=Res_Sky, response_model_exclude_none=True, summary="노을·일출 점수, 3컷, 가까운 명소, 앞으로 3일")
|
||||
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,
|
||||
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,
|
||||
)
|
||||
|
||||
|
||||
@router.get("", response_model=Res_Sky, response_model_exclude_none=True, summary="노을 결론(나가 볼 만한지·왜·언제 어디로), 시간표, 앞으로 3일, 가까운 명소")
|
||||
async def get_sky(region: str = Query(..., description="구 행정코드"), service: SkyService = Depends()) -> Res_Sky:
|
||||
err, view = await service.view(region)
|
||||
if err is not ErrorType.SUCCESS:
|
||||
@@ -31,6 +39,7 @@ async def get_sky(region: str = Query(..., description="구 행정코드"), serv
|
||||
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)
|
||||
for i, s in enumerate(view.spots)
|
||||
],
|
||||
plan=_plan(view.plan) if view.plan else None,
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -51,7 +51,32 @@ class EventData(WebPacketProtocol):
|
||||
status: str
|
||||
status_label: str
|
||||
fit: Optional[str] = None
|
||||
image: Optional[str] = None
|
||||
image_credit: Optional[str] = None # 사진 출처 표기 ("ⓒ한국관광공사")
|
||||
|
||||
|
||||
class Res_EventList(Res_WebPacketProtocol):
|
||||
events: list[EventData] = []
|
||||
|
||||
|
||||
class WeekRankItem(WebPacketProtocol):
|
||||
rank: int
|
||||
region_code: str
|
||||
name: str
|
||||
score: int # 나들이 날씨 점수 (낮 10~17시)
|
||||
reason: str # 근거 한 줄 ("비 10% · 체감 21° · 맑음")
|
||||
icon: str
|
||||
temp_min_c: Optional[float] = None
|
||||
temp_max_c: Optional[float] = None
|
||||
rain_prob: int
|
||||
estimated: bool # 단기예보 밖이라 중기예보로 어림한 점수
|
||||
|
||||
|
||||
class WeekRankDay(WebPacketProtocol):
|
||||
day: date
|
||||
weekday: str
|
||||
items: list[WeekRankItem] = []
|
||||
|
||||
|
||||
class Res_WeekRanking(Res_WebPacketProtocol):
|
||||
days: list[WeekRankDay] = []
|
||||
@@ -6,10 +6,14 @@ from fastapi import APIRouter, Depends, Query
|
||||
from common.enums import ErrorType
|
||||
from common.models.errors import error_info
|
||||
from common.utils.kma_time import now_kst
|
||||
from router.v1.week.protocol import DayData, EventData, PlaceData, Res_EventList, Res_PlaceList, Res_Week
|
||||
from services.week_service import WeekService
|
||||
from router.v1.week.protocol import (
|
||||
DayData, EventData, PlaceData, Res_EventList, Res_PlaceList, Res_Week, Res_WeekRanking, WeekRankDay, WeekRankItem,
|
||||
)
|
||||
from services.week_service import WeekService, image_credit
|
||||
from services.weekend_rank import WeekendRank, rank_days, weekend_days
|
||||
|
||||
router = APIRouter(prefix="/v1/week", tags=["week"])
|
||||
_WEEKDAY_KO = ("월", "화", "수", "목", "금", "토", "일")
|
||||
|
||||
|
||||
@router.get("", response_model=Res_Week, response_model_exclude_none=True, summary="7일 날씨와 그날 추천")
|
||||
@@ -22,6 +26,25 @@ async def get_week(region: str = Query(..., description="구 행정코드"), ser
|
||||
])
|
||||
|
||||
|
||||
@router.get("/ranking", response_model=Res_WeekRanking, response_model_exclude_none=True, summary="이번 주말 전국 나들이 날씨 순위 (대표 30곳)")
|
||||
async def get_week_ranking() -> Res_WeekRanking:
|
||||
service = WeekendRank()
|
||||
err, scores = await service.scores()
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return Res_WeekRanking(result=error_info(err))
|
||||
err, regions, _ = await service.targets()
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return Res_WeekRanking(result=error_info(err))
|
||||
by_code = {r.code: r for r in regions}
|
||||
return Res_WeekRanking(days=[
|
||||
WeekRankDay(day=d, weekday=_WEEKDAY_KO[d.weekday()], items=[
|
||||
WeekRankItem(rank=i + 1, name=by_code[x.region_code].name, **{k: v for k, v in x.__dict__.items() if k != "day"})
|
||||
for i, x in enumerate(items)
|
||||
])
|
||||
for d, items in rank_days(scores, set(by_code), weekend_days(now_kst().date()))
|
||||
])
|
||||
|
||||
|
||||
@router.get("/place/list", response_model=Res_PlaceList, response_model_exclude_none=True, summary="날씨 맞춤 데이트 명소")
|
||||
async def list_places(
|
||||
region: str = Query(...), day: Optional[date] = Query(None, description="기본은 오늘"), area: Optional[str] = Query(None),
|
||||
@@ -50,6 +73,7 @@ async def list_events(region: str = Query(...), area: Optional[str] = Query(None
|
||||
EventData(
|
||||
event_id=i.event.event_id, name=i.event.name, place_name=i.event.place_name, icon=i.event.icon, start_date=i.event.start_date,
|
||||
end_date=i.event.end_date, is_confirmed=i.event.is_confirmed, status=i.status, status_label=i.status_label, fit=i.fit,
|
||||
image=i.event.image_url, image_credit=image_credit(i.event),
|
||||
)
|
||||
for i in items
|
||||
])
|
||||
@@ -14,6 +14,7 @@ from services.external.airkorea import fetch_stations, parse_stations
|
||||
from services.external.data_go_kr import DataGoKrNotConfigured, DataGoKrRequestFailed
|
||||
from services.external.open_meteo import OpenMeteoRequestFailed, fetch_weather, parse_weather
|
||||
from services.feed_service import build_feed_day, clear_feed_cache
|
||||
from services.weekend_rank import WeekendRank
|
||||
|
||||
_CLEANUP_SQL = [
|
||||
"DELETE FROM public.weather_hourly WHERE forecast_at < now() - interval '7 days'",
|
||||
@@ -46,6 +47,13 @@ async def refresh_air_stations() -> ErrorType:
|
||||
return err
|
||||
|
||||
|
||||
async def refresh_weekend_rank(only_if_missing: bool = False) -> ErrorType:
|
||||
"""주말 전국 순위·당일치기용 나들이 점수를 미리 계산해 Redis 에 둔다. only_if_missing 이면 캐시가 있을 때 건너뛴다."""
|
||||
rank = WeekendRank()
|
||||
err, _ = await (rank.scores() if only_if_missing else rank.refresh())
|
||||
LOG.info(f"[scheduler] refresh_weekend_rank: {err.name}")
|
||||
return err
|
||||
|
||||
|
||||
async def refresh_openmeteo_weather() -> ErrorType:
|
||||
"""전국 구 중심 좌표의 자외선·가시거리·돌풍·기압·일조·일사·지면온도를 3시간 구간으로 묶어 저장한다."""
|
||||
|
||||
@@ -0,0 +1,127 @@
|
||||
"""기상청·에어코리아와 Open-Meteo 를 같은 지역·같은 시각으로 비교한다 (응답 시간, 성공률, 값 차이). 예: python scripts/compare_open_meteo.py --regions 20"""
|
||||
import argparse
|
||||
import asyncio
|
||||
import csv
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
import statistics
|
||||
import time
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
import httpx
|
||||
|
||||
from common.enums import RainType
|
||||
from common.utils.kma_time import KST, latest_vilage_base, now_kst
|
||||
from services.external.airkorea import fetch_realtime, fetch_stations, parse_realtime, parse_stations
|
||||
from services.external.data_go_kr import DataGoKrRequestFailed
|
||||
from services.external.kma import fetch_vilage, parse_vilage
|
||||
|
||||
OM_URL = "https://api.open-meteo.com/v1/forecast"
|
||||
OM_AIR_URL = "https://air-quality-api.open-meteo.com/v1/air-quality"
|
||||
OM_MODELS = ("best_match", "kma_seamless")
|
||||
SEED = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "seed", "region.csv")
|
||||
|
||||
|
||||
def _regions(n: int) -> list[dict]:
|
||||
rows = list(csv.DictReader(open(SEED, encoding="utf-8")))
|
||||
step = max(1, len(rows) // n)
|
||||
return rows[::step][:n]
|
||||
|
||||
|
||||
def _grade_pm25(v: float) -> int:
|
||||
return 1 if v <= 15 else 2 if v <= 35 else 3 if v <= 75 else 4
|
||||
|
||||
|
||||
def _grade_pm10(v: float) -> int:
|
||||
return 1 if v <= 30 else 2 if v <= 80 else 3 if v <= 150 else 4
|
||||
|
||||
|
||||
async def _timed(coro):
|
||||
start = time.perf_counter()
|
||||
try:
|
||||
return await coro, time.perf_counter() - start, None
|
||||
except (DataGoKrRequestFailed, httpx.HTTPError, ValueError, KeyError) as e:
|
||||
return None, time.perf_counter() - start, type(e).__name__
|
||||
|
||||
|
||||
async def _om(client: httpx.AsyncClient, lat: float, lon: float, model: str) -> dict:
|
||||
res = await client.get(OM_URL, params={
|
||||
"latitude": lat, "longitude": lon, "models": model, "timezone": "Asia/Seoul", "forecast_days": 3, "wind_speed_unit": "ms",
|
||||
"hourly": "temperature_2m,relative_humidity_2m,precipitation_probability,precipitation,wind_speed_10m",
|
||||
})
|
||||
res.raise_for_status()
|
||||
return res.json()["hourly"]
|
||||
|
||||
|
||||
async def _om_air(client: httpx.AsyncClient, lat: float, lon: float) -> dict:
|
||||
res = await client.get(OM_AIR_URL, params={"latitude": lat, "longitude": lon, "current": "pm2_5,pm10", "timezone": "Asia/Seoul"})
|
||||
res.raise_for_status()
|
||||
return res.json()["current"]
|
||||
|
||||
|
||||
def _diff(kma: dict, om: dict, until: datetime) -> dict:
|
||||
"""겹치는 시각의 차이. 비는 '기상청 비 형태 있음 또는 확률 60% 이상'과 'Open-Meteo 강수 0.1mm 이상 또는 확률 60% 이상'이 같은지."""
|
||||
idx = {datetime.fromisoformat(t).replace(tzinfo=KST): i for i, t in enumerate(om["time"])}
|
||||
temp, hum, wind, pop, rain_same, n = [], [], [], [], 0, 0
|
||||
for at, k in kma.items():
|
||||
i = idx.get(at)
|
||||
if i is None or at > until or om["temperature_2m"][i] is None:
|
||||
continue
|
||||
n += 1
|
||||
temp.append(abs(k["temp_c"] - om["temperature_2m"][i]))
|
||||
if om["relative_humidity_2m"][i] is not None:
|
||||
hum.append(abs(k["humidity"] - om["relative_humidity_2m"][i]))
|
||||
if k["wind_ms"] is not None and om["wind_speed_10m"][i] is not None:
|
||||
wind.append(abs(k["wind_ms"] - om["wind_speed_10m"][i]))
|
||||
om_pop = om["precipitation_probability"][i]
|
||||
if om_pop is not None:
|
||||
pop.append(abs(k["rain_prob"] - om_pop))
|
||||
k_rain = k["rain_type"] is not RainType.NONE or k["rain_prob"] >= 60
|
||||
o_rain = (om["precipitation"][i] or 0) >= 0.1 or (om_pop or 0) >= 60
|
||||
rain_same += k_rain == o_rain
|
||||
mean = lambda xs: round(statistics.mean(xs), 2) if xs else None # noqa: E731
|
||||
return {"hours": n, "temp": mean(temp), "humidity": mean(hum), "wind": mean(wind), "pop": mean(pop), "rain_agree": round(rain_same / n, 3) if n else None}
|
||||
|
||||
|
||||
async def main(n: int) -> dict:
|
||||
now = now_kst()
|
||||
until = now + timedelta(hours=48)
|
||||
base = latest_vilage_base(now)
|
||||
regions = _regions(n)
|
||||
out = {"at": now.isoformat(), "base": base.isoformat(), "regions": []}
|
||||
async with httpx.AsyncClient(timeout=30) as client:
|
||||
(stations_raw, t_st, e_st), (air_raw, t_air, e_air) = await asyncio.gather(_timed(fetch_stations(client)), _timed(fetch_realtime(client)))
|
||||
out["airkorea"] = {"stations_sec": round(t_st, 2), "realtime_sec": round(t_air, 2), "error": e_st or e_air}
|
||||
stations = parse_stations(stations_raw or [])
|
||||
air = {a["station_name"]: a for a in parse_realtime(air_raw or [])}
|
||||
for r in regions:
|
||||
lat, lon = float(r["lat"]), float(r["lon"])
|
||||
(kma_raw, t_k, e_k), *oms, (om_air, t_oa, e_oa) = await asyncio.gather(
|
||||
_timed(fetch_vilage(client, int(r["nx"]), int(r["ny"]), base)),
|
||||
*[_timed(_om(client, lat, lon, m)) for m in OM_MODELS],
|
||||
_timed(_om_air(client, lat, lon)),
|
||||
)
|
||||
row = {"code": r["code"], "name": r["name"], "kma_sec": round(t_k, 2), "kma_error": e_k}
|
||||
hourly = parse_vilage(kma_raw)[0] if kma_raw else {}
|
||||
for m, (om, t_o, e_o) in zip(OM_MODELS, oms):
|
||||
row[m] = {"sec": round(t_o, 2), "error": e_o, **(_diff(hourly, om, until) if om and hourly else {})}
|
||||
near = min(stations, key=lambda s: math.hypot(s["lat"] - lat, (s["lon"] - lon) * math.cos(math.radians(lat))), default=None)
|
||||
obs = air.get(near["station_name"]) if near else None
|
||||
if obs and om_air and obs["pm25"] is not None and obs["pm10"] is not None:
|
||||
row["air"] = {
|
||||
"station": near["station_name"], "sec": round(t_oa, 2), "kr_pm25": obs["pm25"], "om_pm25": om_air["pm2_5"],
|
||||
"kr_pm10": obs["pm10"], "om_pm10": om_air["pm10"],
|
||||
"grade_pm25_same": _grade_pm25(obs["pm25"]) == _grade_pm25(om_air["pm2_5"]),
|
||||
"grade_pm10_same": _grade_pm10(obs["pm10"]) == _grade_pm10(om_air["pm10"]),
|
||||
}
|
||||
else:
|
||||
row["air"] = {"sec": round(t_oa, 2), "error": e_oa or "no observation"}
|
||||
out["regions"].append(row)
|
||||
return out
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--regions", type=int, default=20)
|
||||
print(json.dumps(asyncio.run(main(ap.parse_args().regions)), ensure_ascii=False, default=str))
|
||||
@@ -0,0 +1,106 @@
|
||||
"""TourAPI 키워드 검색으로 노을 명소 후보를 모아 seed/sunset_spot_tourapi.csv 로 쓴다 (일회성).
|
||||
|
||||
사람이 이 파일을 훑어 노을과 무관한 곳·중복을 걸러 seed/sunset_spot.csv 로 옮긴다.
|
||||
실행: docker exec o2o-weather-backend-1 python scripts/fetch_sunset_spots.py
|
||||
"""
|
||||
import asyncio
|
||||
import csv
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
|
||||
import httpx # noqa: E402
|
||||
|
||||
from common.utils.geo import haversine_km # noqa: E402
|
||||
from scripts.load_seed import read_regions # noqa: E402
|
||||
from services.external.data_go_kr import DataGoKrRequestFailed, get_all_items, get_body # noqa: E402
|
||||
|
||||
SEARCH_URL = "https://apis.data.go.kr/B551011/KorService2/searchKeyword2"
|
||||
DETAIL_URL = "https://apis.data.go.kr/B551011/KorService2/detailCommon2"
|
||||
KEYWORDS = ("노을", "일몰", "낙조", "석양", "해넘이")
|
||||
# 이름엔 노을 낱말이 없어도 개요에 일몰 명소라고 나오는 곳을 찾으려고 지형 낱말로 더 뒤진다. 수도권은 촘촘히, 그다음 광역시·서남해안.
|
||||
_SEA = ("해수욕장", "해변", "포구", "갯벌", "방조제", "해안")
|
||||
AREA_KEYWORDS = {
|
||||
"11": ("한강공원", "전망대", "공원", "호수공원", "섬"),
|
||||
"28": ("전망대", "공원", "호수공원", "섬", "항", "등대") + _SEA,
|
||||
"41": ("한강공원", "전망대", "호수공원", "섬", "항", "등대") + _SEA,
|
||||
"26": ("전망대", "공원", "등대") + _SEA,
|
||||
"27": ("전망대",),
|
||||
"30": ("전망대",),
|
||||
"31": ("전망대", "해수욕장", "해안"),
|
||||
"12": ("전망대",) + _SEA,
|
||||
"44": _SEA,
|
||||
"52": _SEA,
|
||||
"50": _SEA + ("오름",),
|
||||
}
|
||||
SUNSET_WORDS = re.compile("노을|일몰|낙조|석양|해넘이|해질녘|해 질")
|
||||
TOURIST_SPOT = "12"
|
||||
OUT = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "seed", "sunset_spot_tourapi.csv")
|
||||
_BASE = {"_type": "json", "MobileOS": "ETC", "MobileApp": "nalssigak"}
|
||||
|
||||
|
||||
def _clean(text: str) -> str:
|
||||
return re.sub(r"\s+", " ", re.sub(r"<[^>]+>", " ", text or "")).strip()
|
||||
|
||||
|
||||
def _snippet(overview: str) -> str:
|
||||
"""개요에서 노을 낱말이 든 문장 하나."""
|
||||
for sentence in re.split(r"(?<=[.!?다])\s+", overview):
|
||||
if SUNSET_WORDS.search(sentence):
|
||||
return sentence[:200]
|
||||
return ""
|
||||
|
||||
|
||||
async def main() -> int:
|
||||
regions = read_regions()
|
||||
found: dict[str, dict] = {}
|
||||
async with httpx.AsyncClient(timeout=30) as client:
|
||||
for kw in KEYWORDS:
|
||||
items = await get_all_items(client, SEARCH_URL, {**_BASE, "keyword": kw, "contentTypeId": TOURIST_SPOT}, page_size=100)
|
||||
print(f"{kw}: {len(items)}")
|
||||
for it in items:
|
||||
if it.get("mapx") and it.get("mapy"):
|
||||
found.setdefault(str(it["contentid"]), it)
|
||||
for sido, kws in AREA_KEYWORDS.items():
|
||||
for kw in kws:
|
||||
items = await get_all_items(client, SEARCH_URL, {**_BASE, "keyword": kw, "contentTypeId": TOURIST_SPOT, "lDongRegnCd": sido}, page_size=100)
|
||||
for it in items:
|
||||
if it.get("mapx") and it.get("mapy"):
|
||||
found.setdefault(str(it["contentid"]), it)
|
||||
print(f"{sido}: total {len(found)}")
|
||||
rows = []
|
||||
for cid, it in found.items():
|
||||
try:
|
||||
body = await get_body(client, DETAIL_URL, {**_BASE, "contentId": cid})
|
||||
except DataGoKrRequestFailed as e:
|
||||
print(f"detail {cid}: {e}")
|
||||
continue
|
||||
raw = (body.get("items") or {}).get("item") or [{}]
|
||||
overview = _clean((raw[0] if isinstance(raw, list) else raw).get("overview", ""))
|
||||
title = _clean(it.get("title", ""))
|
||||
in_title = bool(SUNSET_WORDS.search(title))
|
||||
snippet = _snippet(overview)
|
||||
if not in_title and not snippet:
|
||||
continue
|
||||
lat, lon = round(float(it["mapy"]), 5), round(float(it["mapx"]), 5)
|
||||
if not (33 <= lat <= 39 and 124 <= lon <= 132):
|
||||
print(f"skip {cid} {title}: 좌표가 국내 밖 ({lat}, {lon})")
|
||||
continue
|
||||
near = min(regions, key=lambda r: haversine_km(lat, lon, r["lat"], r["lon"]))
|
||||
rows.append({
|
||||
"source": f"tourapi:{cid}", "region_name": near["name"], "name": title, "addr": _clean(it.get("addr1", "")),
|
||||
"lat": lat, "lon": lon, "in_title": int(in_title), "snippet": snippet,
|
||||
})
|
||||
rows.sort(key=lambda r: (r["region_name"], r["name"]))
|
||||
with open(OUT, "w", encoding="utf-8", newline="") as f:
|
||||
w = csv.DictWriter(f, fieldnames=list(rows[0]) if rows else ["source"])
|
||||
w.writeheader()
|
||||
w.writerows(rows)
|
||||
print(f"candidates {len(found)}, kept {len(rows)} -> {OUT}")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(asyncio.run(main()))
|
||||
@@ -0,0 +1,121 @@
|
||||
import json
|
||||
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")
|
||||
|
||||
CAT = {1: "밖에서 놀기", 2: "먹고 마시기", 3: "집안일", 4: "생활 고민"}
|
||||
WD = {"mon": "월", "tue": "화", "wed": "수", "thu": "목", "fri": "금", "sat": "토", "sun": "일", "holiday": "공휴일", "default": "그 외"}
|
||||
FIELD = {"rain_prob": ("비 확률", "%"), "wind_ms": ("바람", "m/s"), "feels_c": ("체감", "°"), "pm25": ("초미세먼지", "㎍/㎥"), "cloudy_ratio": ("흐린 시간 비율", "%")}
|
||||
|
||||
|
||||
def win(w):
|
||||
if "around" in w:
|
||||
return f"일몰 앞뒤 {w['hours']}시간"
|
||||
h = lambda v: f"다음 날 {v - 24}시" if v >= 24 else f"{v}시"
|
||||
s = f"{w['from']}~" + ("24시" if w['to'] == 24 else h(w['to']))
|
||||
if w.get("lookahead_days"):
|
||||
s += f" (비는 {w['lookahead_days']}일 뒤까지 봄)"
|
||||
return s
|
||||
|
||||
|
||||
def temp(r):
|
||||
off = f", 산 정상 보정 {r['offset']:+}°" if r.get("offset") else ""
|
||||
t = r["type"]
|
||||
if t == "range":
|
||||
return f"체감 {r['lo']}~{r['hi']}°가 좋음{off}"
|
||||
if t == "away":
|
||||
return f"체감이 {r['lo']}~{r['hi']}°에서 멀수록(덥거나 추울수록) 좋음"
|
||||
if t == "higher":
|
||||
return f"더울수록 좋음 ({r['zero']}°=0점 → {r['full']}°=100점)"
|
||||
return f"추울수록 좋음 ({r['zero']}°=0점 → {r['full']}°=100점)"
|
||||
|
||||
|
||||
def rain(r):
|
||||
return "비 올수록 좋음" if r["dir"] == "wet" else "비 안 올수록 좋음"
|
||||
|
||||
|
||||
def wind(r):
|
||||
t = r["type"]
|
||||
if t == "calm":
|
||||
return f"잔잔할수록 좋음 (초속 {r['ok']}m까지 괜찮음, {r['limit']}m면 0점)"
|
||||
return {"moderate": "적당한 바람(초속 2~5m)이 좋음", "strong": "셀수록 좋음 (초속 8m=100점)", "ignore": "상관없음 (50점 고정)"}[t]
|
||||
|
||||
|
||||
def hum(r):
|
||||
t = r["type"]
|
||||
if t == "range":
|
||||
return f"{r['lo']}~{r['hi']}%가 좋음 (최적 {r['best']}%)"
|
||||
return {"higher": "높을수록 좋음 (40%=0점 → 90%=100점)", "lower": "낮을수록 좋음 (90%=0점 → 40%=100점)", "ignore": "상관없음 (50점 고정)"}[t]
|
||||
|
||||
|
||||
def tim(r):
|
||||
t = r["type"]
|
||||
if t == "weekday":
|
||||
return "요일별 점수: " + ", ".join(f"{WD[k]} {v}" for k, v in r.items() if k != "type")
|
||||
if t == "moon":
|
||||
return "달이 어두울수록 좋음 (보름 20점 → 그믐 100점)"
|
||||
if t == "sunset_score":
|
||||
return "그날 노을 점수를 그대로 씀"
|
||||
return f"고정 {r['value']}점"
|
||||
|
||||
|
||||
def zero(z):
|
||||
if z["field"] == "warning":
|
||||
return f"{z['value']} 특보가 있으면"
|
||||
name, unit = FIELD[z["field"]]
|
||||
op = "이상" if z["op"] == ">=" else "미만"
|
||||
s = f"{name} {z['value']}{unit} {op}이면"
|
||||
return s + (f" 최대 {z['cap']}점" if "cap" in z else " 0점")
|
||||
|
||||
|
||||
AX = [("temp", "기온", temp), ("rain", "비", rain), ("wind", "바람", wind), ("humidity", "습도", hum), ("air", "미세먼지", None), ("time", "시간·요일", tim)]
|
||||
|
||||
|
||||
def main() -> None:
|
||||
"""각 설정(seed)을 사람이 읽는 문서로 뽑는다. 어드민이 생기기 전까지 쓴다."""
|
||||
with open(SEED, encoding="utf-8") as f:
|
||||
d = json.load(f)
|
||||
out = []
|
||||
P = out.append
|
||||
P("# 각 데이터 정리\n")
|
||||
P("어드민이 생기기 전까지 각 설정을 확인하는 문서입니다. 원본은 `backend/seed/index_definition.json`이고, 이 파일을 고친 뒤 시드를 다시 넣으면 DB(`index_definition`)에 반영됩니다. 점수 계산은 `backend/services/calc/index_calc.py`에 있습니다.\n")
|
||||
P("## 점수 계산 방식\n")
|
||||
P("- 각마다 6가지 요소(기온·비·바람·습도·미세먼지·시간)를 0~100점으로 매기고, 아래 비중(%)으로 섞습니다.")
|
||||
P("- 최종 점수 = 비중대로 섞은 점수 × (0.75 + 0.25 × 가장 낮은 요소 점수 ÷ 100). 비중 0%인 요소는 '가장 낮은 요소'에서 뺍니다. 가장 낮은 요소가 0점이면 25%가 깎입니다.")
|
||||
P("- '0점 조건'에 걸리면 0점, '최대 N점' 조건에 걸리면 N점을 넘지 못합니다.")
|
||||
P("- 시간대가 여러 개면 그중 가장 좋은 시간대 점수를 씁니다.")
|
||||
P("- 미세먼지는 모든 각이 같은 규칙입니다: 초미세먼지 15㎍/㎥ 이하 100점 → 75㎍/㎥ 이상 0점.")
|
||||
P("- 바람·미세먼지·노을 정보가 없으면 70점으로 둡니다.\n")
|
||||
P("## 한눈에 보기\n")
|
||||
P("| 순서 | 각 | 코드 | 분류 | 시간대 | 기온 | 비 | 바람 | 습도 | 미세먼지 | 시간 | 재미 각 | 계절 핵심 |")
|
||||
P("|---:|---|---|---|---|---:|---:|---:|---:|---:|---:|:---:|:---:|")
|
||||
for x in sorted(d, key=lambda x: x["sort_order"]):
|
||||
P(f"| {x['sort_order']} | {x['name']} | `{x['code']}` | {CAT[x['category']]} | {' / '.join(win(w) for w in x['windows'])} | "
|
||||
+ " | ".join(f"{x['weight_' + a]}%" for a in ("temp", "rain", "wind", "humidity", "air", "time"))
|
||||
+ f" | {'○' if x['is_fun'] else ''} | {'○' if x['is_core'] else ''} |")
|
||||
P("\n## 각별 자세히\n")
|
||||
for x in sorted(d, key=lambda x: x["sort_order"]):
|
||||
P(f"### {x['name']} (`{x['code']}`)\n")
|
||||
P(f"- 설명: {x['description']}")
|
||||
P(f"- 분류: {CAT[x['category']]} · 아이콘 `{x['icon']}` · 재미 각 {'예' if x['is_fun'] else '아니오'} · 계절 핵심 {'예' if x['is_core'] else '아니오'} · 계산 근거 화면 {'있음' if x['has_detail'] else '없음'}")
|
||||
P(f"- 시간대: {' / '.join(win(w) for w in x['windows'])}")
|
||||
P("- 요소별 규칙 (비중):")
|
||||
for key, label, fn in AX:
|
||||
w = x["weight_" + key]
|
||||
rule = "초미세먼지 낮을수록 좋음" if fn is None else fn(x["factor_rules"][key])
|
||||
P(f" - {label} {w}%: {rule}")
|
||||
zs = [zero(z) for z in x["zero_rules"]]
|
||||
P(f"- 점수 깎이는 조건: {', '.join(zs) if zs else '없음'}")
|
||||
if x.get("limit_description"):
|
||||
P(f"- 반영 못 하는 것: {x['limit_description']}")
|
||||
if x.get("sentences"):
|
||||
P(f"- 문장: {json.dumps(x['sentences'], ensure_ascii=False)}")
|
||||
P("")
|
||||
with open(OUT, "w", encoding="utf-8") as f:
|
||||
f.write("\n".join(out) + "\n")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -50,9 +50,10 @@ async def _set_ranking_spots(s, spots: list[dict]) -> None:
|
||||
async def main() -> int:
|
||||
rows = read_regions()
|
||||
code_by_name = {r["name"]: r["code"] for r in rows}
|
||||
# source(tourapi contentid·manual)는 출처 기록용이라 DB엔 넣지 않는다. 서쪽이 트인 곳을 sort_order 0 으로 앞세운다.
|
||||
spots = [
|
||||
{"region_code": code_by_name[r["region_name"]], "name": r["name"], "description": r["description"],
|
||||
"lat": float(r["lat"]), "lon": float(r["lon"]), "sort_order": int(r["sort_order"])}
|
||||
"lat": float(r["lat"]), "lon": float(r["lon"]), "sort_order": 0 if r["west_open"] == "1" else 1}
|
||||
for r in _read("sunset_spot.csv")
|
||||
]
|
||||
places = [
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
"""피드·날씨 API 동시 접속 부하 측정. 예: python scripts/load_test.py --base http://localhost:9810 --regions 1114000000,4113500000 --users 10,50,100"""
|
||||
import argparse
|
||||
import asyncio
|
||||
import statistics
|
||||
import time
|
||||
|
||||
import httpx
|
||||
|
||||
PATHS = ["/v1/feed", "/v1/weather/now", "/v1/weather/today", "/v1/index/list", "/v1/sky", "/v1/week"]
|
||||
|
||||
|
||||
async def _user(client: httpx.AsyncClient, regions: list[str], deadline: float, out: list[tuple[str, float, int]]) -> None:
|
||||
i = 0
|
||||
while time.perf_counter() < deadline:
|
||||
path, region = PATHS[i % len(PATHS)], regions[i % len(regions)]
|
||||
i += 1
|
||||
start = time.perf_counter()
|
||||
try:
|
||||
res = await client.get(path, params={"region": region})
|
||||
code = res.status_code if res.status_code != 200 or res.json()["result"]["success"] else 299
|
||||
except (httpx.HTTPError, ValueError):
|
||||
code = 0
|
||||
out.append((path, time.perf_counter() - start, code))
|
||||
|
||||
|
||||
def _pct(xs: list[float], p: float) -> float:
|
||||
return sorted(xs)[min(len(xs) - 1, int(len(xs) * p))] * 1000
|
||||
|
||||
|
||||
async def run(base: str, regions: list[str], users: int, seconds: float) -> None:
|
||||
out: list[tuple[str, float, int]] = []
|
||||
limits = httpx.Limits(max_connections=users, max_keepalive_connections=users)
|
||||
async with httpx.AsyncClient(base_url=base, timeout=120, limits=limits) as client:
|
||||
deadline = time.perf_counter() + seconds
|
||||
await asyncio.gather(*[_user(client, regions[u % len(regions):] + regions[:u % len(regions)], deadline, out) for u in range(users)])
|
||||
lat = [d for _, d, _ in out]
|
||||
bad = sum(1 for *_, c in out if c != 200)
|
||||
print(f"users {users:>3} req {len(out):>5} rps {len(out) / seconds:6.1f} p50 {_pct(lat, .5):6.0f}ms p95 {_pct(lat, .95):6.0f}ms "
|
||||
f"p99 {_pct(lat, .99):6.0f}ms max {max(lat) * 1000:6.0f}ms 실패 {bad} ({bad / len(out):.1%})")
|
||||
for path in PATHS:
|
||||
xs = [d for p, d, _ in out if p == path]
|
||||
if xs:
|
||||
print(f" {path:<20} p50 {statistics.median(xs) * 1000:6.0f}ms p95 {_pct(xs, .95):6.0f}ms")
|
||||
|
||||
|
||||
def main() -> None:
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--base", default="http://localhost:9810")
|
||||
ap.add_argument("--regions", required=True)
|
||||
ap.add_argument("--users", default="10,50,100")
|
||||
ap.add_argument("--seconds", type=float, default=20)
|
||||
a = ap.parse_args()
|
||||
for n in (int(x) for x in a.users.split(",")):
|
||||
asyncio.run(run(a.base, a.regions.split(","), n, a.seconds))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -104,7 +104,7 @@
|
||||
"category": 4,
|
||||
"title": "시 한 구절",
|
||||
"read_minutes": 1,
|
||||
"icon": "stars",
|
||||
"icon": "moon",
|
||||
"show_from": null,
|
||||
"show_until": null,
|
||||
"body": [
|
||||
@@ -118,7 +118,7 @@
|
||||
"category": 4,
|
||||
"title": "시 한 구절",
|
||||
"read_minutes": 1,
|
||||
"icon": "stars",
|
||||
"icon": "moon",
|
||||
"show_from": null,
|
||||
"show_until": null,
|
||||
"body": [
|
||||
@@ -150,8 +150,7 @@
|
||||
"show_from": null,
|
||||
"show_until": null,
|
||||
"body": [
|
||||
"햇볕 좋은 날은 조금 먼 길로 돌아가도 괜찮아요.",
|
||||
"날씨각 (검수 전 예시)"
|
||||
"햇볕 좋은 날은 조금 먼 길로 돌아가도 괜찮아요."
|
||||
],
|
||||
"sort_order": 104
|
||||
},
|
||||
@@ -164,8 +163,7 @@
|
||||
"show_from": null,
|
||||
"show_until": null,
|
||||
"body": [
|
||||
"하늘이 맑은 날엔 창문부터 활짝 열어 두세요.",
|
||||
"날씨각 (검수 전 예시)"
|
||||
"하늘이 맑은 날엔 창문부터 활짝 열어 두세요."
|
||||
],
|
||||
"sort_order": 105
|
||||
},
|
||||
@@ -178,8 +176,7 @@
|
||||
"show_from": null,
|
||||
"show_until": null,
|
||||
"body": [
|
||||
"구름 낀 날은 빛이 부드러워서 사진이 더 예쁘게 나와요.",
|
||||
"날씨각 (검수 전 예시)"
|
||||
"구름 낀 날은 빛이 부드러워서 사진이 더 예쁘게 나와요."
|
||||
],
|
||||
"sort_order": 106
|
||||
},
|
||||
@@ -192,8 +189,7 @@
|
||||
"show_from": null,
|
||||
"show_until": null,
|
||||
"body": [
|
||||
"흐린 날엔 따뜻한 국물 한 그릇이 제일이에요.",
|
||||
"날씨각 (검수 전 예시)"
|
||||
"흐린 날엔 따뜻한 국물 한 그릇이 제일이에요."
|
||||
],
|
||||
"sort_order": 107
|
||||
},
|
||||
@@ -206,8 +202,7 @@
|
||||
"show_from": null,
|
||||
"show_until": null,
|
||||
"body": [
|
||||
"비 오는 날은 우산 속이 제일 가까운 거리예요.",
|
||||
"날씨각 (검수 전 예시)"
|
||||
"비 오는 날은 우산 속이 제일 가까운 거리예요."
|
||||
],
|
||||
"sort_order": 108
|
||||
},
|
||||
@@ -220,8 +215,7 @@
|
||||
"show_from": null,
|
||||
"show_until": null,
|
||||
"body": [
|
||||
"빗소리를 배경 삼아, 오늘은 조금 천천히 가요.",
|
||||
"날씨각 (검수 전 예시)"
|
||||
"빗소리를 배경 삼아, 오늘은 조금 천천히 가요."
|
||||
],
|
||||
"sort_order": 109
|
||||
},
|
||||
@@ -234,8 +228,7 @@
|
||||
"show_from": null,
|
||||
"show_until": null,
|
||||
"body": [
|
||||
"오늘 하루, 하늘 한 번 올려다보는 걸 잊지 마세요.",
|
||||
"날씨각 (검수 전 예시)"
|
||||
"오늘 하루, 하늘 한 번 올려다보는 걸 잊지 마세요."
|
||||
],
|
||||
"sort_order": 110
|
||||
},
|
||||
@@ -248,8 +241,7 @@
|
||||
"show_from": null,
|
||||
"show_until": null,
|
||||
"body": [
|
||||
"하루 끝, 내일 하늘은 오늘보다 조금 더 맑기를.",
|
||||
"날씨각 (검수 전 예시)"
|
||||
"하루 끝, 내일 하늘은 오늘보다 조금 더 맑기를."
|
||||
],
|
||||
"sort_order": 111
|
||||
},
|
||||
|
||||
@@ -1,4 +1,156 @@
|
||||
region_name,name,description,lat,lon,sort_order
|
||||
서울 마포구,망원한강공원,강 건너 서쪽이 넓게 트임 · 자전거 7분,37.55550,126.89500,1
|
||||
서울 마포구,하늘공원,억새 사이로 보는 노을 · 계단 있음,37.56830,126.88540,2
|
||||
서울 마포구,선유도공원,다리 위에서 강물까지 붉어요,37.54340,126.89960,3
|
||||
region_name,name,description,lat,lon,west_open,source
|
||||
서울 마포구,망원한강공원,강 건너 서쪽이 넓게 트임 · 자전거 7분,37.55550,126.89500,1,manual
|
||||
서울 마포구,하늘공원,억새 사이로 보는 노을 · 계단 있음,37.56830,126.88540,1,tourapi:2654607
|
||||
서울 마포구,선유도공원,다리 위에서 강물까지 붉어요,37.54340,126.89960,1,manual
|
||||
경기 수원시 권선구,일월호수공원,물가 노을 · 경기 수원시,37.2858,126.97456,0,tourapi:3081125
|
||||
경기 안산시 단원구,누에섬 등대전망대,바다 너머 서쪽이 트임 · 경기 안산시,37.18728,126.63227,1,tourapi:128346
|
||||
경기 안산시 단원구,송산그린시티전망대,바다 너머 서쪽이 트임 · 경기 화성시,37.28746,126.73997,1,tourapi:2757448
|
||||
경기 양평군,이포보전망대,물가 노을 · 경기 여주시,37.40538,127.54374,0,tourapi:3018228
|
||||
경기 파주시,헤이리무장애노을숲길,노을 산책길 · 경기 파주시,37.7902,126.7024,0,tourapi:3032506
|
||||
경기 평택시,칠곡호수공원,물가 노을 · 경기 안성시,37.04814,127.15714,0,tourapi:2772184
|
||||
경기 화성시 만세구,궁평항,바다 너머 서쪽이 트임 · 경기 화성시,37.11535,126.68134,1,tourapi:2514454
|
||||
경기 화성시 만세구,매향항선착장,바다 너머 서쪽이 트임 · 경기 화성시,37.07364,126.73301,1,tourapi:2737278
|
||||
경기 화성시 만세구,석천항,바다 너머 서쪽이 트임 · 경기 화성시,37.02975,126.76401,1,tourapi:2747282
|
||||
경남 거제시,노을이 물드는 언덕,바다 너머 서쪽이 트임 · 경남 거제시,34.95452,128.51947,1,tourapi:2414735
|
||||
경남 사천시,실안낙조,바다 너머 서쪽이 트임 · 경남 사천시,34.9395,128.0421,1,tourapi:2782734
|
||||
경남 진주시,남강댐 노을공원,물가 노을 · 경남 진주시,35.16124,128.03041,0,tourapi:2788143
|
||||
경남 창원시 진해구,불모산 노을 전망대,높은 곳에서 서쪽이 트임 · 경남 창원시,35.14642,128.75429,1,tourapi:2784039
|
||||
경남 통영시,평인 노을길,바다 너머 서쪽이 트임 · 경남 통영시,34.84404,128.39187,1,tourapi:2652408
|
||||
경북 울릉군,남서일몰전망대,바다 너머 서쪽이 트임 · 경북 울릉군,37.46815,130.83224,1,tourapi:2616157
|
||||
경북 울릉군,석포일출일몰전망대,높은 곳에서 서쪽이 트임 · 경북 울릉군,37.54725,130.90914,1,tourapi:1136251
|
||||
대구 달서구,앞산 해넘이전망대,높은 곳에서 서쪽이 트임 · 대구 남구,35.83216,128.5655,1,tourapi:2703807
|
||||
대구 달성군,달성노을공원,강 너머 서쪽이 트임 · 대구 달성군,35.73726,128.41572,1,tourapi:2742203
|
||||
대구 달성군,달성보전망대,물가 노을 · 대구 달성군,35.7365,128.42022,0,tourapi:2742212
|
||||
부산 강서구,금빛노을브릿지,강 너머 서쪽이 트임 · 부산 북구,35.20978,129.00287,1,tourapi:3545436
|
||||
부산 기장군,나사해변(나사리해수욕장),바닷가 노을 · 울산 울주군,35.35634,129.34163,0,tourapi:2777937
|
||||
부산 사하구,낙조정,강 너머 서쪽이 트임 · 부산 사하구,35.10963,128.93946,1,tourapi:3027444
|
||||
부산 사하구,다대포해수욕장,바다 너머 서쪽이 트임 · 부산 사하구,35.04625,128.96315,1,tourapi:126079
|
||||
부산 사하구,부네치아 선셋 전망대,바다 너머 서쪽이 트임 · 부산 사하구,35.07927,128.95186,1,tourapi:3544138
|
||||
부산 사하구,아미산 전망대,높은 곳에서 서쪽이 트임 · 부산 사하구,35.05275,128.96078,1,tourapi:2733473
|
||||
부산 수영구,삼익비치수변공원,바닷가 노을 · 부산 수영구,35.14624,129.11693,0,tourapi:2782626
|
||||
부산 영도구,감지해변,바닷가 노을 · 부산 영도구,35.06,129.0775,0,tourapi:2785289
|
||||
부산 영도구,영도 하늘전망대,높은 곳에서 서쪽이 트임 · 부산 영도구,35.0719,129.0547,1,tourapi:2740063
|
||||
부산 영도구,중리노을전망대,바다 너머 서쪽이 트임 · 부산 영도구,35.0692,129.0643,1,tourapi:3017435
|
||||
부산 해운대구,청사포 다릿돌전망대,바닷가 노을 · 부산 해운대구,35.16331,129.19538,0,tourapi:2607943
|
||||
부산 해운대구,해월전망대,바닷가 노을 · 부산 해운대구,35.15588,129.18264,0,tourapi:3353856
|
||||
서울 강동구,광나루자전거공원,강 너머 서쪽이 트임 · 서울 강동구,37.5453,127.118,1,tourapi:3065938
|
||||
서울 강동구,일자산 허브천문공원,높은 곳에서 서쪽이 트임 · 서울 강동구,37.5373,127.15421,1,tourapi:2773317
|
||||
서울 마포구,노을공원,높은 곳에서 서쪽이 트임 · 서울 마포구,37.57405,126.87551,1,tourapi:2733971
|
||||
서울 성북구,채석장 전망대,높은 곳에서 보는 도심 노을 · 서울 종로구,37.57831,127.01161,0,tourapi:2657713
|
||||
서울 용산구,반포한강공원,강 너머 서쪽이 트임 · 서울 서초구,37.50769,126.99275,1,tourapi:970138
|
||||
서울 종로구,인왕산 무무대 전망대,높은 곳에서 보는 도심 노을 · 서울 종로구,37.58401,126.96397,0,tourapi:4061713
|
||||
서울 종로구,정동전망대,높은 곳에서 보는 도심 노을 · 서울 중구,37.56481,126.97585,0,tourapi:2015800
|
||||
인천 강화군,민머루해변,바다 너머 서쪽이 트임 · 인천 강화군,37.6516,126.33281,1,tourapi:128818
|
||||
인천 강화군,장화리일몰조망지,바다 너머 서쪽이 트임 · 인천 강화군,37.61798,126.37838,1,tourapi:2768079
|
||||
인천 강화군,적석사 낙조대,높은 곳에서 서쪽이 트임 · 인천 강화군,37.73745,126.41096,1,tourapi:2765235
|
||||
인천 강화군,황청포구,바다 너머 서쪽이 트임 · 인천 강화군,37.71222,126.35366,1,tourapi:2768108
|
||||
인천 강화군,후포항 선수포구,바다 너머 서쪽이 트임 · 인천 강화군,37.64051,126.39204,1,tourapi:129612
|
||||
인천 검단구,아라빛섬,바다 너머 서쪽이 트임 · 인천 검단구,37.59275,126.61411,1,tourapi:2781446
|
||||
인천 서해구,경인아라뱃길 아라타워 전망대,높은 곳에서 서쪽이 트임 · 인천 검단구,37.55838,126.60738,1,tourapi:2767585
|
||||
인천 서해구,노을공원(인천),바다 너머 서쪽이 트임 · 인천 서해구,37.5298,126.61377,1,tourapi:2767605
|
||||
인천 연수구,구봉도 낙조전망대,바다 너머 서쪽이 트임 · 경기 안산시,37.28826,126.53452,1,tourapi:2615560
|
||||
인천 연수구,구봉솔숲해수욕장,바다 너머 서쪽이 트임 · 경기 안산시,37.28205,126.55311,1,tourapi:2761552
|
||||
인천 연수구,메추리섬,바다 너머 서쪽이 트임 · 경기 안산시,37.2034,126.5386,1,tourapi:3035853
|
||||
인천 연수구,미추홀공원,바다 너머 서쪽이 트임 · 인천 연수구,37.38236,126.6495,1,tourapi:2765400
|
||||
인천 연수구,소래해넘이전망대,바다 너머 서쪽이 트임 · 인천 남동구,37.38725,126.72698,1,tourapi:3393766
|
||||
인천 연수구,영흥도 하늘고래전망대,바다 너머 서쪽이 트임 · 인천 옹진군,37.25918,126.50107,1,tourapi:3078307
|
||||
인천 연수구,오이도포구해양관광단지,바다 너머 서쪽이 트임 · 경기 시흥시,37.34214,126.68898,1,tourapi:3035637
|
||||
인천 연수구,인천 오션스코프(인천대교 전망대),바다 너머 서쪽이 트임 · 인천 연수구,37.39586,126.62809,1,tourapi:2768138
|
||||
인천 연수구,장경리해수욕장,바다 너머 서쪽이 트임 · 인천 옹진군,37.2722,126.4483,1,tourapi:128997
|
||||
인천 연수구,쪽박섬,바다 너머 서쪽이 트임 · 경기 안산시,37.2143,126.5422,1,tourapi:2764322
|
||||
인천 영종구,거잠포해변,바다 너머 서쪽이 트임 · 인천 영종구,37.42213,126.42545,1,tourapi:1619630
|
||||
인천 영종구,백운산전망대,높은 곳에서 서쪽이 트임 · 인천 영종구,37.49249,126.51658,1,tourapi:2767621
|
||||
인천 영종구,선녀바위해변,바다 너머 서쪽이 트임 · 인천 영종구,37.4396,126.3779,1,tourapi:129255
|
||||
인천 영종구,영종도 마시안해변,바다 너머 서쪽이 트임 · 인천 영종구,37.4317,126.4163,1,tourapi:264517
|
||||
인천 영종구,왕산해수욕장,바다 너머 서쪽이 트임 · 인천 영종구,37.45648,126.36931,1,tourapi:129256
|
||||
인천 영종구,을왕리해수욕장,바다 너머 서쪽이 트임 · 인천 영종구,37.44595,126.37272,1,tourapi:128767
|
||||
인천 영종구,진촌해변,바다 너머 서쪽이 트임 · 인천 옹진군,37.55034,126.33407,1,tourapi:129252
|
||||
인천 영종구,하나개해수욕장,바다 너머 서쪽이 트임 · 인천 영종구,37.38464,126.40927,1,tourapi:129254
|
||||
인천 옹진군,송도랜드마크시티1호수변공원,바다 너머 서쪽이 트임 · 인천 연수구,37.40728,126.61014,1,tourapi:3061256
|
||||
인천 옹진군,아암도해안공원,바다 너머 서쪽이 트임 · 인천 연수구,37.41396,126.63939,1,tourapi:1619731
|
||||
인천 제물포구,북성포구,바다 너머 서쪽이 트임 · 인천 제물포구,37.48314,126.61548,1,tourapi:2765523
|
||||
인천 제물포구,월미공원 월미전망대,높은 곳에서 서쪽이 트임 · 인천 제물포구,37.47019,126.59598,1,tourapi:3003184
|
||||
인천 제물포구,월미도등대길,바다 너머 서쪽이 트임 · 인천 제물포구,37.46931,126.59512,1,tourapi:2753119
|
||||
전남 고흥군,염포해수욕장,바닷가 노을 · 전남 고흥군,34.43182,127.49304,0,tourapi:1623658
|
||||
전남 고흥군,중산 일몰전망대,바다 너머 서쪽이 트임 · 전남 고흥군,34.73851,127.3317,1,tourapi:2674019
|
||||
전남 목포시,설레미해수욕장,바다 너머 서쪽이 트임 · 전남 신안군,34.96142,126.13444,1,tourapi:2723780
|
||||
전남 순천시,와온해변,바다 너머 서쪽이 트임 · 전남 순천시,34.84934,127.5237,1,tourapi:2707924
|
||||
전남 순천시,용산전망대,높은 곳에서 서쪽이 트임 · 전남 순천시,34.87305,127.51932,1,tourapi:228886
|
||||
전남 신안군,고하도 전망대,높은 곳에서 서쪽이 트임 · 전남 목포시,34.77794,126.35921,1,tourapi:2706019
|
||||
전남 신안군,노을공원,바다 너머 서쪽이 트임 · 전남 목포시,34.80896,126.36576,1,tourapi:2784217
|
||||
전남 신안군,영암금호방조제,바다 너머 서쪽이 트임 · 전남 해남군,34.72628,126.38815,1,tourapi:3014405
|
||||
전남 신안군,원평해수욕장,바다 너머 서쪽이 트임 · 전남 신안군,34.77545,125.91336,1,tourapi:2723745
|
||||
전남 신안군,채일봉 전망대,높은 곳에서 서쪽이 트임 · 전남 신안군,34.78304,126.10841,1,tourapi:2742145
|
||||
전남 여수시,끝등전망대,높은 곳에서 서쪽이 트임 · 전남 여수시,34.58812,127.77496,1,tourapi:3008466
|
||||
전남 여수시,낭도해변,바다 너머 서쪽이 트임 · 전남 여수시,34.59953,127.5407,1,tourapi:2931111
|
||||
전남 여수시,여수 갯벌 노을마을,바다 너머 서쪽이 트임 · 전남 여수시,34.79025,127.56798,1,tourapi:3008356
|
||||
전남 여수시,여자만 해넘이 전망대,바다 너머 서쪽이 트임 · 전남 여수시,34.637,127.57594,1,tourapi:3009077
|
||||
전남 영광군,가마미해수욕장,바다 너머 서쪽이 트임 · 전남 영광군,35.39973,126.40908,1,tourapi:126289
|
||||
전남 영광군,구시포해수욕장,바다 너머 서쪽이 트임 · 전북 고창군,35.44572,126.43532,1,tourapi:126290
|
||||
전남 영광군,백수해안도로 노을전망대,바다 너머 서쪽이 트임 · 전남 영광군,35.3486,126.3875,1,tourapi:2715691
|
||||
전남 영광군,백암해안전망대,바다 너머 서쪽이 트임 · 전남 영광군,35.32387,126.3788,1,tourapi:2751332
|
||||
전남 완도군,망끝전망대,바다 너머 서쪽이 트임 · 전남 완도군,34.13901,126.50529,1,tourapi:129540
|
||||
전남 완도군,사구미해수욕장,바다 너머 서쪽이 트임 · 전남 해남군,34.32088,126.57916,1,tourapi:126272
|
||||
전남 완도군,일몰공원,바다 너머 서쪽이 트임 · 전남 완도군,34.36203,126.64194,1,tourapi:3035715
|
||||
전남 진도군,세방낙조 전망대,바다 너머 서쪽이 트임 · 전남 진도군,34.44042,126.10222,1,tourapi:128224
|
||||
전남 함평군,안악해변,바다 너머 서쪽이 트임 · 전남 함평군,35.1398,126.3906,1,tourapi:129232
|
||||
전북 고창군,동호해수욕장,바다 너머 서쪽이 트임 · 전북 고창군,35.51435,126.48165,1,tourapi:126286
|
||||
전북 고창군,모항해수욕장,바다 너머 서쪽이 트임 · 전북 부안군,35.58286,126.50774,1,tourapi:127689
|
||||
전북 고창군,부안 줄포만 노을빛 정원,바다 너머 서쪽이 트임 · 전북 부안군,35.5809,126.6683,1,tourapi:252578
|
||||
전북 고창군,서해안 바람공원,바다 너머 서쪽이 트임 · 전북 고창군,35.531,126.51476,1,tourapi:2662512
|
||||
전북 고창군,선운산 낙조대,높은 곳에서 서쪽이 트임 · 전북 고창군,35.50262,126.58656,1,tourapi:1596119
|
||||
전북 군산시,만경낙조전망대,바다 너머 서쪽이 트임 · 전북 김제시,35.89392,126.8049,1,tourapi:3079580
|
||||
전북 부안군,격포해수욕장,바다 너머 서쪽이 트임 · 전북 부안군,35.62924,126.4698,1,tourapi:126288
|
||||
전북 부안군,고사포해수욕장,바다 너머 서쪽이 트임 · 전북 부안군,35.66187,126.50824,1,tourapi:127865
|
||||
전북 부안군,선유도해수욕장,바다 너머 서쪽이 트임 · 전북 군산시,35.81613,126.41105,1,tourapi:2022531
|
||||
전북 부안군,적벽강,바다 너머 서쪽이 트임 · 전북 부안군,35.63596,126.46289,1,tourapi:129690
|
||||
제주 서귀포시,강정포구,바닷가 노을 · 제주 서귀포시,33.22716,126.47502,0,tourapi:2779517
|
||||
제주 서귀포시,구두미포구,바닷가 노을 · 제주 서귀포시,33.23683,126.59651,0,tourapi:2781394
|
||||
제주 서귀포시,노을해안로,바다 너머 서쪽이 트임 · 제주 서귀포시,33.24251,126.2244,1,tourapi:2778890
|
||||
제주 서귀포시,보목포구,바닷가 노을 · 제주 서귀포시,33.23925,126.60677,0,tourapi:2738742
|
||||
제주 서귀포시,수월봉과 차귀해안,바다 너머 서쪽이 트임 · 제주 제주시,33.29412,126.16301,1,tourapi:228859
|
||||
제주 서귀포시,신창풍차해안도로,바다 너머 서쪽이 트임 · 제주 제주시,33.3431,126.17213,1,tourapi:2663250
|
||||
제주 서귀포시,월평포구,바다 너머 서쪽이 트임 · 제주 서귀포시,33.23445,126.46346,1,tourapi:2742257
|
||||
제주 서귀포시,자구내포구,바다 너머 서쪽이 트임 · 제주 제주시,33.30936,126.16514,1,tourapi:2792595
|
||||
제주 서귀포시,정물오름,높은 곳에서 서쪽이 트임 · 제주 제주시,33.33803,126.33022,1,tourapi:1926379
|
||||
제주 서귀포시,중문색달해수욕장,바닷가 노을 · 제주 서귀포시,33.24543,126.41121,0,tourapi:126449
|
||||
제주 제주시,구엄포구,바다 너머 서쪽이 트임 · 제주 제주시,33.4843,126.3764,1,tourapi:2738659
|
||||
제주 제주시,금능돌담해변길,바다 너머 서쪽이 트임 · 제주 제주시,33.39031,126.22906,1,tourapi:3037793
|
||||
제주 제주시,느지리오름,높은 곳에서 서쪽이 트임 · 제주 제주시,33.36291,126.2608,1,tourapi:2740127
|
||||
제주 제주시,닭머르해안길,바다 너머 서쪽이 트임 · 제주 제주시,33.5378,126.61325,1,tourapi:2652545
|
||||
제주 제주시,삼양해안도로,바닷가 노을 · 제주 제주시,33.52534,126.57882,0,tourapi:2765248
|
||||
제주 제주시,연대포구,바다 너머 서쪽이 트임 · 제주 제주시,33.49503,126.42671,1,tourapi:2738683
|
||||
제주 제주시,용담해안도로,바다 너머 서쪽이 트임 · 제주 제주시,33.51558,126.5121,1,tourapi:2738705
|
||||
제주 제주시,코난해변,바다 너머 서쪽이 트임 · 제주 제주시,33.55757,126.81119,1,tourapi:2837222
|
||||
제주 제주시,큰노꼬메오름,높은 곳에서 서쪽이 트임 · 제주 제주시,33.38944,126.4104,1,tourapi:2738712
|
||||
제주 제주시,한담해안산책로,바다 너머 서쪽이 트임 · 제주 제주시,33.4592,126.3106,1,tourapi:2930935
|
||||
제주 제주시,협재해수욕장,바다 너머 서쪽이 트임 · 제주 제주시,33.39375,126.23943,1,tourapi:127490
|
||||
충남 당진시,마섬포구,바다 너머 서쪽이 트임 · 충남 당진시,37.0235,126.57958,1,tourapi:2732176
|
||||
충남 당진시,왜목마을 해수욕장,바닷가 노을 · 충남 당진시,37.04448,126.52614,0,tourapi:2022541
|
||||
충남 보령시,독산해수욕장,바다 너머 서쪽이 트임 · 충남 보령시,36.2225,126.5309,1,tourapi:129583
|
||||
충남 보령시,보령 노을광장,바다 너머 서쪽이 트임 · 충남 보령시,36.30547,126.51631,1,tourapi:915245
|
||||
충남 보령시,보령방조제,바다 너머 서쪽이 트임 · 충남 보령시,36.44258,126.53035,1,tourapi:1938116
|
||||
충남 보령시,성주산 낙조전망대,높은 곳에서 서쪽이 트임 · 충남 보령시,36.33871,126.63592,1,tourapi:4115119
|
||||
충남 보령시,운여해변,바다 너머 서쪽이 트임 · 충남 태안군,36.43358,126.35595,1,tourapi:2664196
|
||||
충남 보령시,은포리해안도로,바다 너머 서쪽이 트임 · 충남 보령시,36.37198,126.52272,1,tourapi:2616051
|
||||
충남 보령시,충청수영해안경관전망대,높은 곳에서 서쪽이 트임 · 충남 보령시,36.44012,126.53471,1,tourapi:3080119
|
||||
충남 부여군,성당포구마을,물가 노을 · 전북 익산시,36.13129,126.92076,0,tourapi:803243
|
||||
충남 서산시,황금산몽돌해변,바다 너머 서쪽이 트임 · 충남 서산시,36.99154,126.32975,1,tourapi:2736722
|
||||
충남 서천군,갈목해변,바다 너머 서쪽이 트임 · 충남 서천군,36.0763,126.6312,1,tourapi:2750364
|
||||
충남 서천군,마량포구,바다 너머 서쪽이 트임 · 충남 서천군,36.12915,126.50501,1,tourapi:2782229
|
||||
충남 서천군,비인 선도리 쌍도해안,바다 너머 서쪽이 트임 · 충남 서천군,36.13287,126.58277,1,tourapi:1041580
|
||||
충남 아산시,아산만방조제,바다 너머 서쪽이 트임 · 충남 아산시,36.89544,126.91134,1,tourapi:2606913
|
||||
충남 예산군,선장포노을공원,강 너머 서쪽이 트임 · 충남 아산시,36.7904,126.85961,1,tourapi:2753921
|
||||
충남 태안군,기지포해수욕장,바다 너머 서쪽이 트임 · 충남 태안군,36.56278,126.32236,1,tourapi:128903
|
||||
충남 태안군,꽃지해수욕장,바다 너머 서쪽이 트임 · 충남 태안군,36.50132,126.33465,1,tourapi:126695
|
||||
충남 태안군,두에기해변,바다 너머 서쪽이 트임 · 충남 태안군,36.51911,126.32866,1,tourapi:2715693
|
||||
충남 태안군,마검포해수욕장,바다 너머 서쪽이 트임 · 충남 태안군,36.60765,126.28931,1,tourapi:128904
|
||||
충남 태안군,먼동해수욕장,바다 너머 서쪽이 트임 · 충남 태안군,36.88361,126.18748,1,tourapi:2758238
|
||||
충남 태안군,몽대포구,바다 너머 서쪽이 트임 · 충남 태안군,36.67284,126.27376,1,tourapi:129621
|
||||
충남 태안군,안면해수욕장,바다 너머 서쪽이 트임 · 충남 태안군,36.54951,126.3287,1,tourapi:128905
|
||||
충남 태안군,어은돌해수욕장,바다 너머 서쪽이 트임 · 충남 태안군,36.75285,126.12941,1,tourapi:128894
|
||||
충남 태안군,태안 노을지는갯마을,바다 너머 서쪽이 트임 · 충남 태안군,36.74156,126.19561,1,tourapi:129352
|
||||
충남 태안군,파도리해수욕장,바다 너머 서쪽이 트임 · 충남 태안군,36.74104,126.13515,1,tourapi:127864
|
||||
충남 홍성군,궁리포구,바다 너머 서쪽이 트임 · 충남 홍성군,36.58845,126.45721,1,tourapi:1937784
|
||||
충남 홍성군,남당노을전망대,바다 너머 서쪽이 트임 · 충남 홍성군,36.54428,126.4656,1,tourapi:3065226
|
||||
충남 홍성군,어사리 노을공원,바다 너머 서쪽이 트임 · 충남 홍성군,36.55615,126.46837,1,tourapi:2678991
|
||||
|
@@ -0,0 +1,199 @@
|
||||
source,region_name,name,addr,lat,lon,in_title,snippet
|
||||
tourapi:3061205,경기 김포시,갈현체육공원,인천광역시 계양구 황어로 66 (갈현동),37.57767,126.72856,0,"보면 공원에서 가장 높은 지대에 전망을 볼 수 있는 정자가 있어 계양산과 그 아래 하부도로까지 한눈에 볼 수 있으며, 계양산 해넘이와 경인아라뱃길의 경관까지 볼 수 있다."
|
||||
tourapi:3081125,경기 수원시 권선구,일월호수공원,경기도 수원시 장안구 일월천로 77 (천천동),37.2858,126.97456,0,현재는 농업용수 공급이 아닌 시민들의 건강 증진과 함께 산책을 겸한 나들이 장소이자 일몰 감상지 이기도 하고 철새들의 낙원이자 외래어종 제어를 위한 토종 어종 가물치가 서식하는 등 다양한 기능을 하는 곳이다.
|
||||
tourapi:128346,경기 안산시 단원구,누에섬 등대전망대,경기도 안산시 단원구 선감동,37.18728,126.63227,0,"누에섬 등대전망대는 대부도와 탄도항 전곡항 선감도 등 주변의 멋진 섬들을 감상할 수 있고, 탄도항의 풍력발전소와 일몰이 어우러진 풍경을 찍기 위해 많은 사람이 찾는 곳이다."
|
||||
tourapi:4059557,경기 안산시 단원구,서해안 황금해안길,경기도 화성시 만세구 서신면 해안길 477,37.17609,126.62551,0,"특히 백 년 넘은 해송 천여 그루가 장관을 이루는 궁평송림은 상쾌한 솔향과 함께 걷는 즐거움을 선사하며, 해 질 녘 소나무 사이로 붉게 타오르는 낙조는 화성 8경 중 하나인 궁평낙조로 불릴 만큼 수려한 경관을 자랑한다."
|
||||
tourapi:2757448,경기 안산시 단원구,송산그린시티전망대,경기도 화성시 만세구 송산면 고정리 산1-38,37.28746,126.73997,0,간척지 너머 서해바다에 펼쳐지는 낙조는 장관이다.
|
||||
tourapi:3018228,경기 양평군,이포보전망대,경기도 여주시 대신면 여양로 2001,37.40538,127.54374,0,"수려한 경관까지 자랑해 자전거 라이더들이 거쳐가는 남한강 성지 중 하나이자 차박, 차크닉을 즐길 수 있는 곳이고, 일몰과 야경 명소로도 유명하다."
|
||||
tourapi:3032506,경기 파주시,헤이리무장애노을숲길,경기도 파주시 탄현면 법흥리,37.7902,126.7024,1,헤이리 무장애 노을숲길은 파주시에서 2019년 완공한 길로 헤이리 예술마을 7번 게이트 옆에 위치하고 있다.
|
||||
tourapi:2772184,경기 평택시,칠곡호수공원,경기도 안성시 원곡면 만세로 1100,37.04814,127.15714,0,경기도 안성에 위치한 노을과 음악이 만나는 ‘칠곡호수공원’은 2026년 3월 27일 개장한 곳이다.
|
||||
tourapi:2514454,경기 화성시 만세구,궁평항,경기도 화성시 서신면 궁평항로 1049-24,37.11535,126.68134,0,낙조가 아름다운 곳으로 유명한 궁평항은 2008년 국가 어항으로 지정되었다.
|
||||
tourapi:2863634,경기 화성시 만세구,궁평항광장,경기도 화성시 만세구 서신면 궁평항로 1069-11,37.11616,126.68337,0,광장에서 연결된 방파제 끝으로 나 있는 해상 전망 데크와 바닷가에 있는 궁평낙조길을 따라 바닷길 산책이 가능하다.
|
||||
tourapi:2737278,경기 화성시 만세구,매향항선착장,경기도 화성시 우정읍 매향리,37.07364,126.73301,0,서해안의 아름다운 일몰을 감상할 수 있는 매향리 작은 포구이다.
|
||||
tourapi:2747282,경기 화성시 만세구,석천항,경기도 화성시 우정읍 매향리,37.02975,126.76401,0,석천항은 일몰이 아름다운 장소로 유명하여 많은 사람들이 석양을 감상하기 위해 방문한다.
|
||||
tourapi:2414735,경남 거제시,노을이 물드는 언덕,경상남도 거제시 사등면 가조로 565,34.95452,128.51947,1,가조도에 위치한 노을이 물드는 언덕은 일몰이 아름답기로 유명한 관광지이며 노을이 물드는 언덕은 2009년 7월 가조도 연륙교 개통 이후 늘어나는 관광객을 위해 더욱더 풍성한 볼거리를 제공하고자 조성된 공간이다.
|
||||
tourapi:2782734,경남 사천시,실안낙조,경상남도 사천시 실안동,34.9395,128.0421,1,"사천팔경 중 제2경인 실안낙조는 전국 9대 일몰지의 하나로, 해 질 녘 부채꼴 모양의 참나무 말뚝으로 만든 죽방렴과 섬, 바다, 그리고 일몰이 환상적인 조화를 이룬다."
|
||||
tourapi:2788143,경남 진주시,남강댐 노을공원,경상남도 진주시 내동면 삼계로 453,35.16124,128.03041,1,진주 남강과 진양호 인근에 자리한 남강댐 노을공원은 남강댐과 진양호의 풍경을 함께 감상할 수 있는 공원이다.
|
||||
tourapi:2784039,경남 창원시 진해구,불모산 노을 전망대,경상남도 창원시 진해구 소사동 산 24,35.14642,128.75429,1,"볼모산 노을 전망대는 창원 불모산 정상에 있는 전망대로, 노을이 아름다운 해넘이 해돋이 명소이다."
|
||||
tourapi:2652408,경남 통영시,평인 노을길,경상남도 통영시 평인일주로 132,34.84404,128.39187,1,평인노을길은 통영의 언택트 힐링관광지에 속한 해안 도로이다.
|
||||
tourapi:2616157,경북 울릉군,남서일몰전망대,경상북도 울릉군 서면 남서리,37.46815,130.83224,1,"남서 일몰 전망대는 울릉군 서면 남서리 사태구미 해안변에 펼쳐진 절벽 위에 있는 전망대로, 가슴이 저리도록 아름다운 일몰을 볼 수 있는 곳이다."
|
||||
tourapi:1136251,경북 울릉군,석포일출일몰전망대,경상북도 울릉군 북면 천부리,37.54725,130.90914,1,"석포일출일몰전망대는 1905년 러일전쟁을 위해 일본군이 망루를 설치하면서 막사 1동과 무선전신소, 등대, 우물터, 지하대피소(토굴)를 설치하였고, 러일전쟁 이후에도 러시아의 보복이 두려워 일본 육군 대대병력을 석포마을에 주둔시키는 등 1945년까지 망루를 운영했던 곳이다."
|
||||
tourapi:2703807,대구 달서구,앞산 해넘이전망대,대구광역시 남구 대명동,35.83216,128.5655,1,
|
||||
tourapi:2742203,대구 달성군,달성노을공원,대구광역시 달성군 논공읍 하리 899,35.73726,128.41572,1,달성노을공원은 낙동강 자전거길 코스 중간에 있다.
|
||||
tourapi:2742212,대구 달성군,달성보전망대,대구광역시 달성군 논공읍 비슬로 1193,35.7365,128.42022,0,"특히, 일출과 일몰 시간이 아름다워 많은 사람들이 사진 촬영을 즐기기에 좋은 장소이다."
|
||||
tourapi:3545436,부산 강서구,금빛노을브릿지,부산광역시 북구 낙동대로 1769 (구포동),35.20978,129.00287,1,"부산 북구의 금빛노을브릿지는 낙동강 위를 가로지르는 아름다운 보행교로, 자연과 도시가 조화를 이루는 특별한 공간이다."
|
||||
tourapi:2777937,부산 기장군,나사해변(나사리해수욕장),울산광역시 울주군 서생면 나사리,35.35634,129.34163,0,나사해변은 숨은 일몰 명소로도 유명하다.
|
||||
tourapi:2614714,부산 사하구,낙동강하구 (부산 국가지질공원),부산광역시 사하구 낙동남로 1240,35.10455,128.94601,0,"아미산 전망대에도 연안사주, 낙조 등 천혜의 절경을 조망할 수 있으며 낙동강하구 삼각주의 형성 과정 등 지질유산에 대한 다양한 자료를 전시하고 있다."
|
||||
tourapi:3027444,부산 사하구,낙조정,부산광역시 사하구 낙동남로 1169 (하단동),35.10963,128.93946,1,낙조정은 부산광역시 사하구 을숙도에 있는 철새 관찰 전망대이다.
|
||||
tourapi:769761,부산 사하구,다대포 꿈의 낙조분수,부산광역시 사하구 몰운대1길 14 (다대동),35.04639,128.96805,1,다대포 꿈의 낙조분수는 다대포해수욕장 입구 광장에 설치된 분수로 세계 최대 규모를 갖추고 있는 음악분수이다.
|
||||
tourapi:126079,부산 사하구,다대포해수욕장,부산광역시 사하구 몰운대1길 14,35.04625,128.96315,0,"낙동강과 남해안이 만나 양질의 모래밭을 만든 곳, 일출과 일몰 조망지이다."
|
||||
tourapi:2744553,부산 사하구,대항전망대,부산광역시 강서구 대항동 산1-4,35.0165,128.8259,0,남기남 작곡가의 '내 고향은 가덕도' 노래비와 함께 박상호의 '대항전망대에서 바라본 낙조'라는 시비가 서있다.
|
||||
tourapi:3544138,부산 사하구,부네치아 선셋 전망대,부산광역시 사하구 장림로93번길 72 (장림동),35.07927,128.95186,0,"부네치아 선셋 전망대는 부산의 일몰 명소로 알려져 있는데, 2층의 장림항 홍보관, 카페를 즐기며 장림포구의 전체적인 모습을 느낄 수 있다."
|
||||
tourapi:2733473,부산 사하구,아미산 전망대,부산광역시 사하구 다대낙조2길 77,35.05275,128.96078,0,"낙동강 하구만이 가진 특색 있는 모래섬들을 한눈에 조망할 수 있으며, 황금빛 낙조와 솔개의 아름다운 조합을 볼 수 있다."
|
||||
tourapi:2606204,부산 사하구,장림포구,부산광역시 사하구 장림로93번길 72 (장림동),35.08093,128.95746,0,"노을이 아름답고 다대포해수욕장으로 가는 길목에 있어 아미산전망대, 다대포 꿈의 낙조분수 등과 연계한 관광이 가능해 부산의 새로운 피서지로 떠오르고 있다."
|
||||
tourapi:2782626,부산 수영구,삼익비치수변공원,부산광역시 수영구 남천동,35.14624,129.11693,0,해 질 무렵의 노을도 더 가까이에서 감상할 수 있다.
|
||||
tourapi:2785289,부산 영도구,감지해변,부산광역시 영도구 감지길 110,35.06,129.0775,0,위로 드리운 일몰이 아름다워 뷰 포인트로 각광받고 있는 곳이다.
|
||||
tourapi:2740063,부산 영도구,영도 하늘전망대,부산광역시 영도구 동삼동,35.0719,129.0547,0,"특히 이곳은 부산의 대표적인 노을 명소로 손꼽히며, 주차장과 화장실 등 편의시설도 잘 갖춰져 있다."
|
||||
tourapi:3017435,부산 영도구,중리노을전망대,부산광역시 영도구 동삼동,35.0692,129.0643,1,천혜의 아름다운 낙조지역으로 알려진 중리바닷가에서 보다
|
||||
tourapi:3017467,부산 영도구,중리항 방파제 등대,부산광역시 영도구 중리남로 2-15 (동삼동),35.06799,129.06418,0,천혜의 아름다운 낙조 지역으로 알려진 중리 바닷가 방파제 끝단에 설치되어 있으며 황금빛 노을을 만끽할 수 있는 명소로 알려져 있다.
|
||||
tourapi:2607943,부산 해운대구,청사포 다릿돌전망대,부산광역시 해운대구 청사포로 167,35.16331,129.19538,0,"도심 속 어촌인 청사포, 수려한 해안경관, 일출, 낙조 등을 감상할 수 있어 부산의 대표적인 관광명소로 꼽힌다."
|
||||
tourapi:3353856,부산 해운대구,해월전망대,부산광역시 해운대구 중동,35.15588,129.18264,0,"이곳은 해운대와 동해를 한눈에 내려다볼 수 있는 명소로, 특히 일출과 일몰이 장관을 이루어 많은 관광객들이 찾는다."
|
||||
tourapi:3065938,서울 강동구,광나루자전거공원,서울특별시 강동구 선사로 83-19 (천호동),37.5453,127.118,0,한강 야경과 노을을 보면서 달릴 수 있다는 것이 가장 큰 장점이다.
|
||||
tourapi:2773317,서울 강동구,일자산 허브천문공원,서울특별시 강동구 둔촌동 산86,37.5373,127.15421,0,"공원 동쪽엔 새벽 일출을 감상할 수 있는 전망대, 서쪽으로는 일몰을 감상할 수 있는 관찰대가 있다."
|
||||
tourapi:3526353,서울 강서구,[서울둘레길 15코스] 노을·하늘공원코스,서울특별시 강서구 가양동,37.5637,126.8565,1,15코스인 노을·하늘공원코스는 복원된 자연길이라는 테마를 가지고 있으며 가양대교를 지나 한강과 강남을 바라볼 수 있다.
|
||||
tourapi:3043794,서울 광진구,자라나는 숲(광진숲 나루 전망대),서울특별시 광진구 천호대로 760 (광장동),37.54756,127.09777,0,일몰 후부터 오후 10시까지는 기둥 끝과 하단에 조명이 점등되어 전망대 전체가 신비로운 야경 공간으로 탈바꿈한다.
|
||||
tourapi:127859,서울 마포구,난지한강공원,서울특별시 마포구 한강난지로 162 (상암동),37.56303,126.88515,0,"한강르네상스 사업으로 새롭게 조성된 난지한강공원은 노을공원, 하늘공원과 연결되는 중앙연결브릿지, 평화의 공원 연결브릿지, 복합연결통로 완공으로 공원을 이용하는 시민들의 접근성을 개선시켰다."
|
||||
tourapi:2733971,서울 마포구,노을공원(서울),서울특별시 마포구 상암동,37.57405,126.87551,1,월드컵공원은 난지도 쓰레기매립지를 공원화하여 다섯 개의 테마공원으로 조성된 서울의 환경·생태공원이다.다섯 개의 테마공원 중 하나인 노을공원은 드넓은 잔디밭에 조각예술품과 전망데크 등이 있어 여유를 느낄 수 있는 곳이다.
|
||||
tourapi:2661506,서울 마포구,서울함공원,서울특별시 마포구 마포나루길 407,37.55585,126.89398,0,저녁에는 함수와 함미 갑판 위에서 버스킹 공연도 진행되어 한강의 아름다운 석양과 공연을 동시에 감상할 수 있다.
|
||||
tourapi:128021,서울 마포구,월드컵공원,서울특별시 마포구 월드컵로 243-60 (성산동),37.56353,126.89844,0,"대표 공원인 평화의 공원을 비롯하여, 하늘공원, 노을공원, 난지천공원, 난지한강공원의 5개 테마공원으로 조성되었다."
|
||||
tourapi:3058015,서울 마포구,월드컵공원 유아숲체험원,서울특별시 마포구 월드컵로 365 (상암동),37.56745,126.89112,0,"체험장 주위에는 하늘공원, 월드컵공원, 난지천공원, 노을캠핑장 등이 있어 많은 볼거리를 제공한다."
|
||||
tourapi:2654607,서울 마포구,하늘공원,서울특별시 마포구 하늘공원로 95,37.5691,126.88634,0,또한 노을과 야경이 아름답기로 알려진 명소이기도 하다.
|
||||
tourapi:2657713,서울 성북구,채석장 전망대,서울특별시 종로구 낙산5길 51 (창신동),37.57831,127.01161,0,해가 질 무렵이면 노을과 함께 펼쳐지는 멋진 야경이 한참을 이곳에 머무르게 한다.
|
||||
tourapi:970138,서울 용산구,반포한강공원,서울특별시 서초구 신반포로11길 40 (반포동),37.50769,126.99275,0,"또한 물방울놀이터, 인라인 전용트랙, 축구장, 농구장 등의 체육시설과 더불어 동작대교 남단에 설치된 전망대인 노을카페와 구름카페에서 탁 트인 한강수면과 그 위로 펼쳐진 넓은 하늘과 강변 빌딩숲을 감상할 수 있다."
|
||||
tourapi:970052,서울 용산구,세빛섬,서울특별시 서초구 올림픽대로 2085-14 (반포동),37.5125,126.996,0,가빛은 해 질 녘 노을빛처럼 하루의 끝을 갈무리하며 아름답고 우아하게 빛나고 있다.
|
||||
tourapi:4061713,서울 종로구,인왕산 무무대 전망대,서울 종로구 옥인동 산3-1,37.58401,126.96397,0,"낮에는 서촌의 고즈넉한 지붕 너머로 펼쳐지는 도심 파노라마를, 해 질 무렵 매직아워에는 붉게 물드는 하늘과 도심이 어우러지는 풍경을, 밤에는 반짝이는 서울 야경을 서로 다른 세 가지 표정으로 즐길 수 있다."
|
||||
tourapi:2015800,서울 종로구,정동전망대,서울특별시 중구 덕수궁길 15 (서소문동),37.56481,126.97585,0,일몰 시간대에는 황홀한 노을을 감상할 수 있어 많은 관광객과 사진작가들이 찾는 장소이다.
|
||||
tourapi:128818,인천 강화군,민머루해변,인천광역시 강화군 삼산면 어류정길212번길,37.6516,126.33281,0,백사장의 길이가 약 1㎞ 정도 펼쳐진 곳으로 해수욕과 서해 바다의 아름다운 석양을 조망할 수 있으며 갯벌체험도 가능하다.
|
||||
tourapi:827203,인천 강화군,소청도 등대,인천광역시 옹진군 대청면 소청서로 279 (소청도등대),37.7604,124.72828,0,"소청도 등대는 탁 트인 바다를 배경으로 아름다운 풍경을 자랑하며, 특히 일출과 일몰이 아름답기로 유명하다."
|
||||
tourapi:2768079,인천 강화군,장화리일몰조망지,인천광역시 강화군 화도면 장화리 1408,37.61798,126.37838,1,강화섬 서남단 장화리 해변에는 서해안의 일몰을 조망할 수 있는 장화리 일몰조망지가 조성되어 있다.
|
||||
tourapi:2765235,인천 강화군,적석사 낙조대,인천광역시 강화군 내가면 연촌길 181,37.73745,126.41096,1,인천시 강화군 중심부에 있는 고려산(436.3m)의 형제 봉우리 낙조봉(340m)에 있는 사찰 적석사에서 만들어 놓은 낙조대이다.
|
||||
tourapi:2768108,인천 강화군,황청포구,인천광역시 강화군 내가면 황청포구로 492,37.71222,126.35366,0,노을을 보며 낚시하기에도 낭만 있는 분위기를 연출할 수 있어 가족과 함께 오면 추억을 쌓을 수 있다.
|
||||
tourapi:129612,인천 강화군,후포항 선수포구,인천광역시 강화군 화도면 해안남로2903번길,37.64051,126.39204,0,보면 멋진 일몰 풍경도 감상할 수 있다.
|
||||
tourapi:2781446,인천 검단구,아라빛섬,인천광역시 검단구 오류동,37.59275,126.61411,0,"아라빛섬에는 노을 명소인 정서진 광장부터 홍보관, 인천광역시의 전경을 파노라마처럼 볼 수 있는 전망대가 위치한 경인항 통합운영센터등이 있다."
|
||||
tourapi:2767585,인천 서해구,경인아라뱃길 아라타워 전망대,인천광역시 검단구 정서진1로 41,37.55838,126.60738,0,"전망대는 23층으로 서해의 일몰을 감상할 수 있는 명소로 유명하며, 전망대에서 정서진 공원과 함께 서해바다와 인천대교까지 조망할 수 있다."
|
||||
tourapi:2767605,인천 서해구,노을공원(인천),인천광역시 서해구 로봇랜드로 291 (청라동),37.5298,126.61377,1,"쪽으로는 영종도도 볼 수 있고, 해 질 녘이면 멋진 노을을 감상할 수 있다."
|
||||
tourapi:2615560,인천 연수구,구봉도 낙조전망대,경기도 안산시 단원구 구봉타운길 43,37.28826,126.53452,1,이 중 할배 바위와 할미 바위 사이로 보이는 석양은 서해안 최고의 절경으로 유명하다.
|
||||
tourapi:2761552,인천 연수구,구봉솔숲해수욕장,경기도 안산시 단원구 대부북동,37.28205,126.55311,0,"해수욕과 갯벌 체험을 할 수 있고, 아름다운 낙조를 감상할 수 있어 대부도의 낙조 명소로 유명하다."
|
||||
tourapi:3035853,인천 연수구,메추리섬,경기도 안산시 단원구 대부남동,37.2034,126.5386,0,쪽으로 함께 보이는 다른 바위섬들을 바라보며 조용한 걷기 여행을 즐기고 시간이 되면 멋진 일몰도 함께 감상할 수 있다.
|
||||
tourapi:2765400,인천 연수구,미추홀공원,인천광역시 연수구 해송로 59,37.38236,126.6495,0,"또한, 미추홀공원은 인천의 아름다운 자연경관을 감상할 수 있는 최적의 장소로, 특히 일몰 시간에 찾으면 더욱 아름다운 풍경을 즐길 수 있다."
|
||||
tourapi:2722883,인천 연수구,생명의나무 전망대,경기도 시흥시 오이도로 170 (정왕동),37.34559,126.68751,0,생명의 나무는 오이도 황새바위길에 있는 일몰·야간 명소이다.
|
||||
tourapi:3393766,인천 연수구,소래해넘이전망대,인천광역시 남동구 아암대로 1454 (논현동),37.38725,126.72698,1,소래해넘이전망대는 인천광역시의 아름다운 일몰을 감상할 수 있는 최적의 장소이다.
|
||||
tourapi:3078307,인천 연수구,영흥도 하늘고래전망대,인천광역시 옹진군 영흥면 영흥북로 74,37.25918,126.50107,0,일몰이 되어 낙조와 함께 하늘고래전망대에도 하나둘씩 조명이 켜지고 점등된 하늘고래전망대와 주변의 영흥대교의 조명이 어우러져 섬마을의 명소가 된다.
|
||||
tourapi:3035637,인천 연수구,오이도포구해양관광단지,경기도 시흥시 오이도중앙로 67 (정왕동),37.34214,126.68898,0,이뿐만 아이라 퇴역 경비함을 활용하여 만든 복합문화공간 오아시스 함상전망대와 노을의 노래 전망대 등 해변을 걸으며 서해안의 일몰을 관람할 수 있는 다양한 시설이 마련되어 있다.
|
||||
tourapi:2768138,인천 연수구,인천 오션스코프(인천대교 전망대),인천광역시 연수구 인천타워대로 385-1 (송도동),37.39586,126.62809,0,"인천대교전망대는 서해와 일몰, 인천대교를 조망하는 전망대이자 전시공간을 제공할 목적으로 기획되었다."
|
||||
tourapi:128997,인천 연수구,장경리해수욕장,인천광역시 옹진군 영흥면 영흥로 723,37.2722,126.4483,0,해수욕장 주변에는 100년이 넘는 소나무 숲이 우거져 있어 노송지대에서 보는 낙조는 아름답기로 소문이 나 있는 곳이다.
|
||||
tourapi:2764322,인천 연수구,쪽박섬,경기도 안산시 단원구 대부남동,37.2143,126.5422,0,이곳에서 바라보는 낙조는 매우 아름답기로 유명하다.
|
||||
tourapi:1619630,인천 영종구,거잠포해변,인천광역시 영종구 잠진도길 11,37.42213,126.42545,0,"매도랑 너머로 떠오르는 붉은 해는 장관을 이루며, 이곳에서는 일출과 일몰을 모두 감상할 수 있다."
|
||||
tourapi:2767621,인천 영종구,백운산전망대,인천광역시 영종구 운서동 산1-1,37.49249,126.51658,0,"인천 영종도 공항신도시에 있는 255m 높이의 백운산에 있는 전망대로, 인천 해넘이 명소로 서해 낙조와 인천 국제도시의 야경을 볼 수 있는 장소로 유명한 곳이다."
|
||||
tourapi:129255,인천 영종구,선녀바위해변,인천광역시 영종구 을왕동,37.4396,126.3779,0,용유 3경 선녀바위를 보고 일몰 시각을 맞추어 아름다운 낙조도 함께 감상하기에 좋은 해변이다.
|
||||
tourapi:264517,인천 영종구,영종도 마시안해변,인천광역시 영종구 마시란로 118 (덕교동),37.4317,126.4163,0,해 질 무렵 전망 좋은 카페에서 커피와 함께 아름다운 노을을 감상하기 좋다.
|
||||
tourapi:129256,인천 영종구,왕산해수욕장,인천광역시 영종구 을왕동,37.45648,126.36931,0,왕산해수욕장은 용유팔경 중 제1경으로 낙조를 자랑하는 해수욕장이다.
|
||||
tourapi:128767,인천 영종구,을왕리해수욕장,인천광역시 영종구 용유서로302번길 16-15 (을왕동),37.44595,126.37272,0,"울창한 송림과 해수욕장 양쪽 옆으로 기암괴석이 늘어서 있어 경관이 매우 아름다우며, 특히 낙조가 아름답기로 서해안에서 손꼽힌다."
|
||||
tourapi:129252,인천 영종구,진촌해변,인천 옹진군 북도면 장봉리,37.55034,126.33407,0,낙조 때 황금빛으로 물들어 가는 하늘은 탄성을 자아내게 한다.
|
||||
tourapi:799958,인천 영종구,큰풀안해수욕장,인천광역시 옹진군 자월면 대이작로160번길,37.17032,126.26301,0,이곳에서 바라보는 일몰은 매우 아름다워 사진 촬영 명소로도 잘 알려져 있다.
|
||||
tourapi:129254,인천 영종구,하나개해수욕장,인천광역시 영종구 하나개로 150 (무의동),37.38464,126.40927,0,해가 질 때의 붉은빛 노을은 해수욕장의 또 다른 장관이다.
|
||||
tourapi:3061256,인천 옹진군,송도랜드마크시티1호수변공원,인천광역시 연수구 송도동 308-2,37.40728,126.61014,0,시원한 서해바다를 가로지르는 인천대교를 볼 수 있고 일몰시간에 만나는 아름다운 노을은 많은 사람들에게 명소로 유명하다.
|
||||
tourapi:1619731,인천 옹진군,아암도해안공원,인천광역시 연수구 아암대로 612,37.41396,126.63939,0,고층 빌딩들이 즐비한 도시의 스카이라인 너머로 지는 일몰이 볼 만하다.
|
||||
tourapi:2765523,인천 제물포구,북성포구,인천광역시 제물포구 북성포길 49,37.48314,126.61548,0,일몰과 야경이 아름다운 곳으로 유명한 북성포구는 인천항의 항만 풍광으로 색다른 일몰을 조망할 수 있는 곳이다.
|
||||
tourapi:3003184,인천 제물포구,월미공원 월미전망대,인천 제물포구 북성동1가 125,37.47019,126.59598,0,"특히 일몰 시간에는 서해의 낙조를 감상할 수 있으며, 야간에는 조명이 더해진 유리전망대에서 색다른 경관을 만날 수 있다."
|
||||
tourapi:2753119,인천 제물포구,월미도등대길,인천광역시 제물포구 북성동1가 120,37.46931,126.59512,0,"월미도 등대길을 따라 걸으면 탁 트인 서해의 풍경과 낙조를 감상할 수 있으며, 등대길 난간에 설치되어 있는 인천과 월미도의 역사를 담은 사진 자료를 볼 수 있다."
|
||||
tourapi:2754729,인천 제물포구,월미산유리전망대,인천광역시 제물포구 북성동1가 125,37.47128,126.60265,0,"3층 높이(23m)의 유리전망대는 서해의 낙조, 야경과 함께 인천항 주변의 섬, 인천대교 연안 여객선터미널 등을 조망할 수 있다."
|
||||
tourapi:1623658,전남 고흥군,염포해수욕장,전남광주통합특별시 고흥군 봉래면 외초리,34.43182,127.49304,0,몽돌에 앉아 해넘이를 보면서 마음속 짐을 털어 낼 수 있는 아늑한 해수욕장이다.
|
||||
tourapi:2674019,전남 고흥군,중산 일몰전망대,전남광주통합특별시 고흥군 남양면 고흥로 3777,34.73851,127.3317,1,고흥 팔경 중 8경인 중산 일몰은 일상에 지친 사람들에게 최고의 힐링 포인트이다.
|
||||
tourapi:2723780,전남 목포시,설레미해수욕장,전남광주통합특별시 신안군 증도면 우전리 산37-6,34.96142,126.13444,0,"가볍게 해변을 따라 산책을 하기에도 좋고, 일몰을 감상하기에도 좋다."
|
||||
tourapi:127327,전남 순천시,순천만 화포포구,전남광주통합특별시 순천시 별량면 학산리,34.85082,127.49195,0,화포마을 뒤편의 봉화산(235.9m)은 일출과 일몰을 동시에 감상할 수 있으며 순천만의 경관이 한눈에 보이는 정상에는 고흥 마복산에서 타오른 봉화를 순천에 전하던 봉화터가 아직 그대로 남아있다.
|
||||
tourapi:2707924,전남 순천시,와온해변,전남광주통합특별시 순천시 해룡면 상내리,34.84934,127.5237,0,낙조풍경이 아름다운 곳으로 와온해변 앞에 있는 솔섬 너머로 해가 넘어가는 모습은 장관을 연출 시킨다.
|
||||
tourapi:228886,전남 순천시,용산전망대,전남광주통합특별시 순천시 해룡면 순천만길 513-51,34.87305,127.51932,0,"순천만의 가장 아름다운 모습을 찾으라고 한다면, 순천만 S자 곡선의 낙조를 꼽을 수 있는데 해 질 무렵 수로가 S자로 흐르는 풍경이 아름다워 많은 사진작가들이 순천만을 찾고 있다."
|
||||
tourapi:2706019,전남 신안군,고하도 전망대,전남광주통합특별시 목포시 고하도안길 234 (달동),34.77794,126.35921,0,"정상에 오르면 다도해의 크고 작은 섬들과 목포대교, 유달산 일대가 한눈에 들어오며 해 질 무렵에는 붉게 물드는 노을을 감상할 수 있다."
|
||||
tourapi:2784217,전남 신안군,노을공원,전남광주통합특별시 목포시 청호로219번길 34-22,34.80896,126.36576,1,노을공원은 2012년 목포지방해양수산청에서 시민들에게 휴식공간을 제공하기 위해서 조성한 해양문화 쉼터이다.
|
||||
tourapi:2742112,전남 신안군,둔장해변,전남광주통합특별시 신안군 자은면 한운리,34.91859,126.06036,0,"국내에서 열두 번째로 큰 섬인 자은도에는 해수욕장만 무려 9개가 있는데, 그중에서도 바람이 세기로 유명해 윈드 비치(Wind Beach)라고도 불리는 둔장해변은 국토해양부가 선정한 ‘해안누리길 5선’에 들어갈 만큼 아름다운 해변과 멋진 일몰이 유명한 곳이다."
|
||||
tourapi:126696,전남 신안군,백길해변,전남광주통합특별시 신안군 자은면 유각리,34.85003,126.0396,0,"예전에는 뱃길이 멀어 사람들의 발길이 뜸했는데 암태도와 자은도 사이에 은암대교가 개통되고 압해대교 개통 후 압해 송공선착장에서 여객선이 운항하면서 많은 피서객들의 발길이 끊이지 않고 있으며, 이 연도교 위에서 바라보는 낙조가 또한 일품이다."
|
||||
tourapi:3014405,전남 신안군,영암금호방조제,전남광주통합특별시 해남군 산이면 구성리,34.72628,126.38815,0,"또한 이곳은 방조제의 일출과 일몰, 야경의 관람 포인트로 선박 제조회사인 현대삼호중공업의 야경 등을 넓은 공간에서 호젓하게 조망할 수 있는 숨겨진 명소이다."
|
||||
tourapi:2388283,전남 신안군,외달도 해수욕장,전남광주통합특별시 목포시 외달도길 47-17,34.7806,126.29417,0,"외달도는 청정해역의 자연 그대로 간직하고, 주변의 크고 작은 섬들의 다도해의 아름다운 풍광과 아늑함이 느껴지며, 낙조가 아름다워 특히 연인들에게 인기가 있는 섬으로 ‘사랑의 섬’이라는 별명을 가지고 있다."
|
||||
tourapi:2723745,전남 신안군,원평해수욕장,전남광주통합특별시 신안군 비금면 원평해수욕장길 64,34.77545,125.91336,0,물고기가 많이 나며 석양이 아름다운 곳이다.
|
||||
tourapi:2742145,전남 신안군,채일봉 전망대,전남광주통합특별시 신안군 팔금면 원산리,34.78304,126.10841,0,채일봉 전망대에 오르면 아름다운 다도해와 함께 일출과 일몰을 모두 감상할 수 있어 감탄이 절로 나온다.
|
||||
tourapi:3008466,전남 여수시,끝등전망대,전남광주통합특별시 여수시 돌산읍 금성리,34.58812,127.77496,0,끝등전망대는 이러한 천혜의 여수 절경과 어우러지는 장소로 장엄한 해돋이와 황홀한 해넘이의 장관을 감상할 수 있다.
|
||||
tourapi:2931111,전남 여수시,낭도해변,전남광주통합특별시 여수시 화정면 낭도리,34.59953,127.5407,0,"맞은편에는 고흥의 팔영산이 보여 경치가 좋으며, 저녁에는 일몰이 아름다워 조용하게 휴식하고 싶은 사람들에게 추천하는 숨은 명소다."
|
||||
tourapi:3008356,전남 여수시,여수 갯벌 노을마을,전남광주통합특별시 여수시 서부로 785-24 장척마을회관,34.79025,127.56798,1,"여수 갯벌 노을마을(장척마을) 뒤로 호암산을 등지고 가치산을 안고 있으며 마을 앞으로 펼쳐져 있는 여자만에는 복개도, 장구도 그리고 모개도의 세 무인도가 놓여 있다."
|
||||
tourapi:3009077,전남 여수시,여자만 해넘이 전망대,전남광주통합특별시 여수시 화양면 화서로 7-30,34.637,127.57594,1,여자만은 여수반도의 서쪽에 위치해 있기 때문에 바다가 보이는 곳이면 어디나 해넘이 명소이고 전망 명소가 된다.
|
||||
tourapi:126289,전남 영광군,가마미해수욕장,전남광주통합특별시 영광군 홍농읍 가마미로 355,35.39973,126.40908,0,또한 칠산바다를 붉게 물들이는 이 곳의 서해낙조는 동해일출과는 사뭇 다른 운치를 안겨준다.
|
||||
tourapi:126290,전남 영광군,구시포해수욕장,전북특별자치도 고창군 상하면 진암구시포로 545,35.44572,126.43532,0,앞바다에는 가막도를 비롯한 섬들이 아름답게 떠 있고 해 질 무렵 서해 칠산바다를 붉게 물들이는 낙조를 볼 수 있다.
|
||||
tourapi:2715639,전남 영광군,백수해안공원,전남광주통합특별시 영광군 백수읍 백암리 223-2,35.32562,126.37903,0,"해안 따라 조성된 둘레길이 있으며, 노을 전망대가 언덕 위에 자리하고 있다."
|
||||
tourapi:1874060,전남 영광군,백수해안도로,전남광주통합특별시 영광군 백수읍 해안로 957,35.36446,126.39603,0,"영광군 백수읍 길용리에서 백암리 석구미 마을까지 16.8㎞에 달하는 해안도로로, 기암괴석·광활한 갯벌·불타는 석양이 만나 황홀한 풍경을 연출하는 서해안의 대표적인 드라이브 코스이다."
|
||||
tourapi:2715691,전남 영광군,백수해안도로 노을전망대,전남광주통합특별시 영광군 백수읍 대신리,35.3486,126.3875,1,황홀한 낙조로 유명한 백수해안도로에는 노을전망대가 있다.
|
||||
tourapi:2751332,전남 영광군,백암해안전망대,전남광주통합특별시 영광군 백수읍 해안로 565-17,35.32387,126.3788,0,백암해안전망대는 영광에서 노을을 감상하기 가장 좋은 곳 중 하나이다.
|
||||
tourapi:264528,전남 영광군,위도해수욕장,전북특별자치도 부안군 위도면 진리,35.60423,126.28359,0,"특히 이곳에서 바라보는 일몰은 무척 아름다운데, 먼바다의 왕등도 원경이 붉은 태양과 더불어 펼쳐지는 곳이다."
|
||||
tourapi:2615324,전남 완도군,가사동백숲해변,전남광주통합특별시 완도군 약산면 해동리,34.36984,126.9278,0,"조약도 중앙에는 삼문산이 있으며 삼문산에 조성된 둘레길을 걸으며 산책하기 좋으며, 산 정상에 오르면 다도해해상국립공원과 일출과 일몰을 감상할 수 있다."
|
||||
tourapi:2723663,전남 완도군,거문도해수욕장,전남광주통합특별시 여수시 삼산면 덕촌리,34.01997,127.30431,0,"인근 거문도 등대 절벽 위에서 보는 망망대해 쪽빛바다와 해돋이, 해넘이는 장엄하기까지 하다."
|
||||
tourapi:129540,전남 완도군,망끝전망대,전남광주통합특별시 완도군 보길면 정자리 산 148-6,34.13901,126.50529,0,끝없이 탁 트인 시원한 바다와 함께 서해바다로 붉은 몸을 감추는 우리나라에서 가장 아름다운 일몰을 볼 수 있는 곳이 망끝이다.
|
||||
tourapi:228865,전남 완도군,보옥리 공룡알해변,전남광주통합특별시 완도군 보길면 보옥리,34.12505,126.51359,0,외진 지역이라 전기나 편의시설이 없으므로 일몰 이후는 이곳에서 이동하는 것이 좋다.
|
||||
tourapi:126272,전남 완도군,사구미해수욕장,전남광주통합특별시 해남군 송지면 사구미길 20,34.32088,126.57916,0,또한 사구미에서 보는 일몰의 장관도 일품이다.
|
||||
tourapi:3035715,전남 완도군,일몰공원,전남광주통합특별시 완도군 군외면 대문리,34.36203,126.64194,1,일몰공원은 해남군과 마주 보고 있는 서쪽 해안에 위치해 있으며 완도의 서쪽 해안 드라이브길을 이용해서 방문할 수 있다.
|
||||
tourapi:129544,전남 완도군,지리해수욕장,전남광주통합특별시 완도군 청산면 청산로 1462-58,34.19481,126.8621,0,지리해수욕장은 청산도의 대표적인 해수욕장으로 일몰이 아름다운 해수욕장 가운데 하나이다.
|
||||
tourapi:128224,전남 진도군,세방낙조 전망대,전남광주통합특별시 진도군 지산면 가학리 산27-3,34.44042,126.10222,1,진도 해안도로 중에서 가장 아름답다는『세방낙조 전망대』에서 내려다보는 다도해의 경관은 압권이다.
|
||||
tourapi:129232,전남 함평군,안악해변,전남광주통합특별시 함평군 손불면 안악길 132,35.1398,126.3906,0,그리고 함평만이 바라보이는 해수욕장 주변의 해변도로는 석양을 감상하기에 좋아 드라이브 코스로 알려졌으며 안악해변은 특히 일몰 풍경이 일품이다.
|
||||
tourapi:126286,전북 고창군,동호해수욕장,전북특별자치도 고창군 해리면 명사십리로 887,35.51435,126.48165,0,이곳에서 바라보는 서해의 낙조가 특히 아름다움을 자아낸다.
|
||||
tourapi:2588908,전북 고창군,모항갯벌체험장,전북특별자치도 부안군 변산면 모항길 107,35.58723,126.51387,0,"이곳에서는 숙박도 가능하여, 갯벌 체험을 하고 1박을 하며 서해의 일몰을 감상할 수 있다."
|
||||
tourapi:127689,전북 고창군,모항해수욕장,전북특별자치도 부안군 변산면 모항길 22,35.58286,126.50774,0,모항해수욕장은 마실길 코스로 산책로가 발달해 있어 노을 지는 서해안을 즐기며 산책하기 좋고 주변에 갯벌 체험장이 있어 해수욕을 즐기고 갯벌 체험을 즐기고자 하는 가족 단위 여행객에게 인기가 많다.
|
||||
tourapi:252578,전북 고창군,부안 줄포만 노을빛 정원,전북특별자치도 부안군 줄포면 생태공원로 38,35.5809,126.6683,1,줄포리 일대에 위치한 부안 줄포만 노을빛 정원은 저지대 침수에 대비하기 위해 제방을 쌓은 것이 시민의 쉼터로 자리 잡은 경우다.
|
||||
tourapi:2662512,전북 고창군,서해안 바람공원,전북특별자치도 고창군 심원면 애향갯벌로 311,35.531,126.51476,0,또한 서해안의 아름다운 일몰을 감상할 수 있기도 하다.
|
||||
tourapi:126236,전북 고창군,선운산 (전북 서해안 국가지질공원),전북특별자치도 고창군 아산면 선운사로 158-6,35.50268,126.58656,0,일몰이 아름다운 것으로 알려진 선운산의 낙조대와 천마봉 일대는 화산암 중 하나인 유문암으로 구성되어 있다.
|
||||
tourapi:1596119,전북 고창군,선운산 낙조대,전북특별자치도 고창군 아산면 선운사로 158-6,35.50262,126.58656,1,낙조대는 선운산도립공원 내에 위치한 곳이다.
|
||||
tourapi:3079580,전북 군산시,만경낙조전망대,전북특별자치도 김제시 만경읍 토정길 216,35.89392,126.8049,1,"만경낙조전망대는 전북 김제에 위치한 새만금 광역 탐방로의 작은 언덕 위에 자리한 전망 명소로, 아름다운 낙조를 감상하기 좋은 곳으로 잘 알려져 있다."
|
||||
tourapi:126288,전북 부안군,격포해수욕장,전북특별자치도 부안군 변산면 변산해변로 29-14,35.62924,126.4698,0,이곳의 낙조는 변산팔경 중 으뜸으로 서해에 떠 있는 섬들 너머로 온 바다를 붉게 물들이는 석양은 절경 중의 절경이다.
|
||||
tourapi:127865,전북 부안군,고사포해수욕장,전북특별자치도 부안군 변산면 노루목길 8-8,35.66187,126.50824,0,또 서해의 해수욕장답게 일몰이 아름답기로 유명하다.
|
||||
tourapi:2743326,전북 부안군,변산해안도로 (부안변산해안도로),전북특별자치도 부안군 변산면 변산해변로 765,35.66276,126.51093,0,일몰 때는 여기저기 노을로 더욱 진하게 물드는 변산의 절경을 감상해 보자.
|
||||
tourapi:2022531,전북 부안군,선유도해수욕장,전북특별자치도 군산시 옥도면,35.81613,126.41105,0,못해 차라리 코발트빛인 앞바다를 붉은 낙조가 물들이며 떨어지는 저녁하늘은 명사십리가 주는 또 하나의 선물이다.
|
||||
tourapi:129690,전북 부안군,적벽강 (전북 서해안 국가지질공원),전북특별자치도 부안군 변산면 죽막길 20-4,35.63596,126.46289,0,"변산해변의 절경을 만들어 내는 적벽강은 붉은색을 띤 바위와 절벽으로 해안이 이루어져 있어 맑은 물에 붉은색이 신비롭게 조화를 이루며, 특히 석양 무렵 햇빛을 받아 바위가 진홍색으로 물들 때 장관을 이룬다."
|
||||
tourapi:2779517,제주 서귀포시,강정포구,제주특별자치도 서귀포시 말질로 291,33.22716,126.47502,0,해군 기지가 있는 이곳은 제주 민군 복합형 관광미항이 개장되면서 일반인들도 환상적인 일출과 일몰을 감상할 수 있게 됐다.
|
||||
tourapi:2779522,제주 서귀포시,고산일과해안도로,제주특별자치도 서귀포시 대정읍 영락하동로 9-6,33.25642,126.20994,0,"고산일과해안도로는 차귀도항에서 신도리를 거쳐 일과 사거리에 이르는 약 12㎞의 해안도로이며, 해가 지는 방향에 있어 노을이 가장 아름다운 구간 중에 하나이며 '노을해안로'라고도 불린다."
|
||||
tourapi:2781394,제주 서귀포시,구두미포구,제주특별자치도 서귀포시 보목동,33.23683,126.59651,0,구두미포구는 섶섬과 가장 가까운 곳이자 아름다운 제주의 석양을 오롯이 담을 수 있는 사진 명소로 더욱 유명하다.
|
||||
tourapi:2778890,제주 서귀포시,노을해안로,제주특별자치도 서귀포시 대정읍 노을해안로 24,33.24251,126.2244,1,노을해안로는 대정읍 일과리에서 신도1리로 향하는 약 12㎞의 코스이다.
|
||||
tourapi:2738742,제주 서귀포시,보목포구,제주특별자치도 서귀포시 보목포로 46 (보목동),33.23925,126.60677,0,위로 떨어지는 아름다운 일몰을 볼 수 있기도 하다.
|
||||
tourapi:228859,제주 서귀포시,수월봉과 차귀해안,제주특별자치도 제주시 한경면 노을해안로 1013-70,33.29412,126.16301,0,수월정에 앉아서 차귀도로 떨어지는 낙조의 모습은 제주도에서 아름답기로 손꼽히는 일몰 중 하나이다.
|
||||
tourapi:2663250,제주 서귀포시,신창풍차해안도로,제주특별자치도 제주시 한경면 한경해안로 485,33.3431,126.17213,0,특히 신창 해안도로는 아름다운 일몰로도 손꼽히는 장소이기에 사진을 찍고 일몰을 감상하는 것도 좋다.
|
||||
tourapi:1898906,제주 서귀포시,엉알해안,제주특별자치도 제주시 한경면 고산리,33.29942,126.16762,0,"해안절벽이 퇴적층으로 이루어져 있으며, 낙조가 아름다운 곳이다."
|
||||
tourapi:3056663,제주 서귀포시,엉알해안산책로,제주특별자치도 제주시 한경면 노을해안로 1143,33.30805,126.16412,0,엉알해안산책로를 걷는 동안 해안 절벽 곳곳에 있는 다양한 화산암괴와 지층이 휘어진 탄낭구조를 볼 수 있으며 엉알해안과 고산리 선사유적을 지나면 자구내 포구에 도착하는데 자구내 포구는 낙조가 아름답기로 유명하다.
|
||||
tourapi:2742257,제주 서귀포시,월평포구,제주특별자치도 서귀포시 말질로 462,33.23445,126.46346,0,특히 석양을 받아 붉게 물드는 포구의 따스하고 아늑한 풍경은 올레길의 마지막을 향해 걷는 이들의 마음마저 보듬어 준다.
|
||||
tourapi:2792595,제주 서귀포시,자구내포구,제주특별자치도 제주시 한경면 노을해안로 1161,33.30936,126.16514,0,"자구내포구는 작은 포구라 관광 명소는 아니지만, 노을이 아름다운 곳으로 유명하다."
|
||||
tourapi:1926379,제주 서귀포시,정물오름,제주특별자치도 제주시 한림읍 금악리,33.33803,126.33022,0,마셨다고 한다.정물오름은 억새뿐 아니라 노을 명소로도 손색이 없는 곳이다.
|
||||
tourapi:126449,제주 서귀포시,중문색달해수욕장,제주특별자치도 서귀포시 색달동,33.24543,126.41121,0,색달해변이 한눈에 보이는 쉬리의 언덕은 이곳의 또 다른 명소로 영화 쉬리의 마지막 장면의 촬영지이기도 하며 제주에서 가장 아름다운 일출과 일몰을 볼 수 있는 장소이다.
|
||||
tourapi:3026734,제주 서귀포시,표선소금막해변,제주특별자치도 서귀포시 표선면 표선동서로 378-18,33.33398,126.84152,0,"또한, 일몰이 장관인데 가을부터 겨울철에는 한라산 뒤쪽으로 넘어가는 일몰을 볼 수가 있고, 봄부터 여름에는 바다로 넘어가는 일몰을 볼 수 있다."
|
||||
tourapi:2738659,제주 제주시,구엄포구,제주특별자치도 제주시 애월읍 구엄리,33.4843,126.3764,0,노을이 아름다운 애월 해안도로를 따라가다
|
||||
tourapi:3037793,제주 제주시,금능돌담해변길,제주특별자치도 제주시 한림읍 금능9길 24,33.39031,126.22906,0,풍경을 조망할 수 있으며 비양도와 어우러지는 제주 일몰 명소이기도 하다.
|
||||
tourapi:2740127,제주 제주시,느지리오름,제주특별자치도 제주시 한림읍 봉수대길 5,33.36291,126.2608,0,특히 정상에서 바라보는 해안과 석양의 모습은 장관으로 널리 알려져 있다.
|
||||
tourapi:2652545,제주 제주시,닭머르해안길,제주특별자치도 제주시 조천읍 신촌북3길 62-1,33.5378,126.61325,0,특히 이곳은 일몰 장소로도 손꼽히는 곳이기에 해가 지기 바로 직전에 사진을 담는 것을 추천한다.
|
||||
tourapi:2765248,제주 제주시,삼양해안도로,제주특별자치도 제주시 삼양삼동 2582-1,33.52534,126.57882,0,"검은 모래 해변을 따라 연결된 이곳은 양쪽의 도로변을 따라 가로등이 이어지며, 일몰과 야경이 아름다워 관광객들이 많이 찾는다."
|
||||
tourapi:2738683,제주 제주시,연대포구,제주특별자치도 제주시 외도이동,33.49503,126.42671,0,제주에는 해안 산책로가 예쁜 곳이 많지만 그중에서도 연대 포구 해안 산책로는 동네 주민들이 적극 추천할 정도로 일몰이 예쁘고 산책로에서 보는 포구의 모습이 평화롭다.
|
||||
tourapi:2738705,제주 제주시,용담해안도로,제주특별자치도 제주시 서해안로 687-8 (용담이동),33.51558,126.5121,0,"특히, 도두봉은 노을 명소로도 유명한 오름이고 공항과 가깝기 때문에 제주도에 도착하거나 출발하기 전에 들르기 좋다."
|
||||
tourapi:3061701,제주 제주시,용두암해안도로,제주특별자치도 제주시 서해안로 687-8 (용담이동),33.51555,126.51209,0,"해안도로 곳곳에는 차를 대어 놓고 바다를 조망할 수 있는 공원이 조성되어 있고, 노을 명소로 유명한 도두봉 오름도 있다."
|
||||
tourapi:2837222,제주 제주시,코난해변,제주특별자치도 제주시 구좌읍 행원리,33.55757,126.81119,0,또한 일몰 맛집이기 때문에 시간 맞춰 방문하는 것도 추천한다.
|
||||
tourapi:2738712,제주 제주시,큰노꼬메오름,제주특별자치도 제주시 애월읍 유수암리,33.38944,126.4104,0,데크로 잘 정돈된 정상 전망대에는 오랜 시간 머물며 노을을 관람하는 탐방객이 많다.
|
||||
tourapi:2930935,제주 제주시,한담해안산책로,제주특별자치도 제주시 애월읍 곽지리,33.4592,126.3106,0,제주도의 서쪽에 있어 아름다운 일몰을 잘 감상할 수 있다는 점도 이곳의 매력 포인트다.
|
||||
tourapi:127490,제주 제주시,협재해수욕장,제주특별자치도 제주시 한림읍 한림로 329-10,33.39375,126.23943,0,"멀지 않은 곳에는 한림공원과 협재굴, 명월대, 황룡사, 영각사 등이 있어 해수욕과 함께 주변을 둘러볼 수 있으며 특히 해수욕장 정면에 보이는 비양도의 모습은 맑고 깨끗한 해수와 어울려 아름다운 풍광을 연출하며 이곳에서 바라보는 낙조 또한 아름답다."
|
||||
tourapi:2732176,충남 당진시,마섬포구,충청남도 당진시 석문면 석문방조제로 1755,37.0235,126.57958,0,해 질 녘 풍경도 좋아 관광객은 물론 사진가들도 많이 찾는다.
|
||||
tourapi:2022541,충남 당진시,왜목마을 해수욕장,충청남도 당진시 석문면 왜목길 26,37.04448,126.52614,0,뻗어나간 부분의 해안이 동쪽을 향하고 있어 우리나라에서 유일하게 일출과 일몰 그리고 월출까지 볼 수 있는 곳이다.
|
||||
tourapi:127866,충남 보령시,대천해수욕장,충청남도 보령시 머드로 123,36.3103,126.5136,0,특히 보도와 어우러지는 노을이 아름답다.
|
||||
tourapi:129583,충남 보령시,독산해수욕장,충청남도 보령시 웅천읍 소황리,36.2225,126.5309,0,"물이 빠져나간 갯벌에는 조개, 맛살, 골뱅이 등이 많아 갯벌 체험의 장으로도 손색이 없으며, 잔잔한 바다를 붉게 물들이며 사라지는 낙조는 장관을 연출한다."
|
||||
tourapi:2783140,충남 보령시,명장섬해수욕장(장고도),충청남도 보령시 오천면 삽시도리,36.40118,126.34511,0,퇴적 단층들이 선명하게 드러나 있는 장고도 해안은 지질학적으로도 연구 대상이 될 만하고 명장섬 너머로 떨어지는 일몰은 서해안의 어느 곳에서도 볼 수 없는 장관을 연출한다.
|
||||
tourapi:915245,충남 보령시,보령 노을광장,충청남도 보령시 해수욕장4길 7,36.30547,126.51631,1,보령 노을광장은 보령 대천해수욕장 남부에 위치한 광장이다.
|
||||
tourapi:1957654,충남 보령시,보령 해수욕장 관광특구,충청남도 보령시,36.31382,126.50978,0,무창포는 서해의 아름다운 낙조 장소로도 손꼽힌다.
|
||||
tourapi:1938116,충남 보령시,보령방조제,충청남도 보령시 오천면,36.44258,126.53035,0,"방조제 위에 건설된 도로는 갓길이 없어 방조제에 주차할 수는 없지만 인근 주차장에 차를 세우고 방파제 인도를 따라 한적하게 산책해도 좋고, 오천항 주변을 산책하고 시간이 맞는다면 보령방조제에서 일몰을 감상하며 하루를 마무리하는 것도 좋겠다."
|
||||
tourapi:4115119,충남 보령시,성주산 낙조전망대,충남 보령시 성주면 개화리 114-22,36.33871,126.63592,1,
|
||||
tourapi:2664196,충남 보령시,운여해변,충청남도 태안군 고남면 장삼포로 535-57,36.43358,126.35595,0,운여해변은 아름다운 낙조풍경을 볼 수 있는 곳으로 유명하다.
|
||||
tourapi:2616051,충남 보령시,은포리해안도로,충청남도 보령시 주교면 송학리,36.37198,126.52272,0,위로 떨어지는 노을이 특히 아름다워 해넘이 명소로도 유명하다.
|
||||
tourapi:3080119,충남 보령시,충청수영해안경관전망대,충청남도 보령시 오천면 충청수영로 623-25,36.44012,126.53471,0,해발 약 170m 높이에 2층 구조로 구성되어 있으며 서해안 전망대인 만큼 낙조가 특히 아름답다.
|
||||
tourapi:803243,충남 부여군,성당포구마을,전북특별자치도 익산시 성당면 성당로 762,36.13129,126.92076,0,"시원한 강바람이 가슴까지 불어오는 금강낙조, 세곡을 운반하기 위한 장소였던 성당창, 생태계의 아름다움이 남아 있는 생태공원 마음의 평온을 지키는 보호수 성당포구 은행나무, 싸늘해진 날씨에도 바위틈에서 언제나 의연한 고란초, 금강의 아름다운 풍경과 고란초를 배경으로 걷는 둘레길 이 모든 생태체험 코스를 단 한 번에 즐길 수 있다."
|
||||
tourapi:2736722,충남 서산시,황금산몽돌해변,충청남도 서산시 대산읍 독곶리 산 230-2,36.99154,126.32975,0,"해안절벽에 부딪히는 파도소리는 막혀있던 마을을 풀어주며, 몽돌해변의 아름다운 일몰은 전문 사진작가들도 즐겨 찾는 서산의 랜드마크로 자리매김하였다."
|
||||
tourapi:2750364,충남 서천군,갈목해변,충청남도 서천군 마서면 송석리,36.0763,126.6312,0,일몰 무렵에는 서해를 물들이는 노을이 장관을 연출하기도 한다.
|
||||
tourapi:2782229,충남 서천군,마량포구,충청남도 서천군 서면 마량리,36.12915,126.50501,0,쪽으로 툭 튀어나온 끄트머리에 있어 지형적 위치상 일몰과 일출을 함께 볼 수 있다.
|
||||
tourapi:1041580,충남 서천군,비인 선도리 쌍도해안,충청남도 서천군 비인면 선도리,36.13287,126.58277,0,비인해수욕장 일대의 조개구이 및 칼국수와 서해의 아름다운 일몰도 빼놓을 수 없다.
|
||||
tourapi:2746185,충남 서천군,비인해변,충청남도 서천군 비인면 선도리,36.1286,126.5914,0,"부근에 동백꽃으로 유명한 마량리 동백숲, 일출과 일몰을 동시에 볼 수 있는 마량포구, 서천의 관광지 중 하나인 춘장대 해수욕장이 있어 함께 둘러보기 좋다."
|
||||
tourapi:2606913,충남 아산시,아산만방조제,충청남도 아산시 인주면 공세리,36.89544,126.91134,0,1980~90년대에는 수학여행 단골 코스로 각광받기도 했으며 일몰 시 노을이 특히 아름답고 바다낚시와 민물낚시가 모두 가능하여 많은 관광객이 찾아오고 있다.
|
||||
tourapi:2753921,충남 예산군,선장포노을공원,충청남도 아산시 선장면 선장로 121-10,36.7904,126.85961,1,아산시 선장포노을공원은 아름다운 자연경관과 다양한 편의시설을 갖춘 휴식 공간이다.
|
||||
tourapi:2783143,충남 태안군,[태안 해변길 5코스] 노을길,충청남도 태안군 안면읍 해안관광로 409,36.586,126.3169,1,태안해변길 중 가장 인기가 좋은 태안 노을길은 백사장항을 출발하여 꽃지해수욕장까지 이어지는 해변 길로 안면도 북쪽에서 섬의 남쪽으로 내려가는 코스다.
|
||||
tourapi:128903,충남 태안군,기지포해수욕장,충청남도 태안군 안면읍 해안관광로 745-19,36.56278,126.32236,0,"해질 무렵에 바라보는 풍경은 망망대해 위에 내파수도, 나치도, 토끼섬 등 알알이 박힌 수많은 섬들과 낙조가 어우러져 한 폭의 그림을 연상케 한다."
|
||||
tourapi:126695,충남 태안군,꽃지해수욕장,충청남도 태안군 안면읍 승언리,36.50132,126.33465,0,2개의 바위 너머로 붉게 물드는 낙조는 태안을 상징하는 아름다운 풍광 중 으뜸으로 꼽힌다.
|
||||
tourapi:129600,충남 태안군,꽃지해안공원,충청남도 태안군 안면읍 꽃지해안로 310,36.49533,126.33659,0,"꽃지해안공원은 낙조가 아름답기로 유명한 할미, 할아비바위가 있는 안면도 최대의 해변인 꽃지해수욕장에 조성된 테마공원이다."
|
||||
tourapi:2715693,충남 태안군,두에기해변,충청남도 태안군 안면읍 승언리 2004-8,36.51911,126.32866,0,특히 일몰 때에는 붉은 해와 갈매기가 어우러진 멋진 풍경도 감상할 수 있다.
|
||||
tourapi:128904,충남 태안군,마검포해수욕장,충청남도 태안군 남면 신온리,36.60765,126.28931,0,"이곳은 이른 봄 실치회로 더 잘 알려진 곳으로 그 외 멸치, 까나리, 주꾸미 등이 생산되며 저녁때 바라보는 낙조가 장관이다."
|
||||
tourapi:2758238,충남 태안군,먼동해수욕장,충청남도 태안군 원북면 구례포길 47-508,36.88361,126.18748,0,먼동해수욕장은 아름다운 해안선과 갯바위가 어우러진 낙조가 유명한 곳이다.
|
||||
tourapi:129621,충남 태안군,몽대포구,충청남도 태안군 남면 몽대로 495-43,36.67284,126.27376,0,"너머로 조용하고 화려하게 떨어지는 해넘이가 일품이며, 낙조를 구경하며 붉게 물든 방파제 위를 산책하기 제격인 곳이다."
|
||||
tourapi:128905,충남 태안군,안면해수욕장,충청남도 태안군 안면읍 해안관광로 554-4,36.54951,126.3287,0,"조용하고 한적한 분위기 속에서 일출과 낙조를 감상할 수 있으며, 산림욕을 하며 바다를 볼 수 있는 곳으로 유명하다."
|
||||
tourapi:128894,충남 태안군,어은돌해수욕장,충청남도 태안군 소원면 모항리,36.75285,126.12941,0,해안의 끝으로 보이는 석양이 그야말로 장관이다.
|
||||
tourapi:129352,충남 태안군,태안 노을지는갯마을,충청남도 태안군 소원면 법산길 274-7,36.74156,126.19561,1,노을지는갯마을은 충남 태안군 소원면의 중부지역에 위치한 법산2리 마을로 옛 이름은 고좌 마을이다.
|
||||
tourapi:127864,충남 태안군,파도리해수욕장,충청남도 태안군 소원면 모항파도로 490-85,36.74104,126.13515,0,사진 명소로 소문난 자연 동굴로 깊지 않고 2개의 굴로 이루어져 노을이 질 무렵 붉은 하늘을 배경으로 환상적인 사진을 찍기 좋다.
|
||||
tourapi:1937784,충남 홍성군,궁리포구,충청남도 홍성군 서부면 궁리,36.58845,126.45721,0,만나는 일몰은 수평선이 아니라 바다
|
||||
tourapi:3065226,충남 홍성군,남당노을전망대,충청남도 홍성군 서부면 남당리,36.54428,126.4656,1,남당항 바로 옆에 있는 남당노을전망대는 이름 그대로 아름다운 석양을 볼 수 있는 전망대이다.
|
||||
tourapi:2678991,충남 홍성군,어사리 노을공원,충청남도 홍성군 서부면 남당항자전거길 53,36.55615,126.46837,1,"어사리 노을공원은 산책로와 전망대, 광장, 휴게시설 및 운동시설이 갖춰져 있어 천혜의 자원인 천수만 노을을 감상할 수 있다."
|
||||
tourapi:128255,충남 홍성군,홍성 속동갯벌마을,충청남도 홍성군 서부면 남당항로 689,36.57699,126.46459,0,"2005년도 서해안 임해관광도로의 개설로 그동안 오지였던 마을이 관광객, 체험객이 찾아오는 마을이 되었으며, 마을관광객의 증대를 위하여 봄에는 유채꽃단지 조성, 가을에는 코스모스 단지를 조성하였으며 홍성 8경 중에 하나인 마을의 갯벌과 속동 전망대에서 바라보는 낙조는 많은 관광객들의 발길을 머물게 한다."
|
||||
|
@@ -0,0 +1,11 @@
|
||||
name,label,note
|
||||
강원 강릉시,강릉,바다·커피거리
|
||||
강원 속초시,속초,바다·설악산
|
||||
강원 춘천시,춘천,호수·닭갈비
|
||||
경기 가평군,가평,계곡·자라섬
|
||||
경기 양평군,양평,두물머리
|
||||
인천 제물포구,인천,월미도·차이나타운
|
||||
대전 중구,대전,성심당·대청호
|
||||
전북 전주시 완산구,전주,한옥마을
|
||||
충남 태안군,태안,해변·꽃지
|
||||
충북 단양군,단양,도담삼봉·패러글라이딩
|
||||
|
@@ -20,9 +20,26 @@ _AIR_DELAY = timedelta(minutes=20)
|
||||
_RETRY_SEC = 600
|
||||
_NEAREST = 5
|
||||
GRADE_LABEL = {AirGrade.GOOD: "좋음", AirGrade.NORMAL: "보통", AirGrade.BAD: "나쁨", AirGrade.VERY_BAD: "매우나쁨"}
|
||||
# 환경부 예보 등급 상한(㎍/㎥): 좋음·보통·나쁨, 넘으면 매우나쁨
|
||||
_PM25_LIMITS = (15, 35, 75)
|
||||
_PM10_LIMITS = (30, 80, 150)
|
||||
_background: set[asyncio.Task] = set()
|
||||
|
||||
|
||||
def _grade(value: Optional[int], limits: tuple[int, int, int]) -> Optional[AirGrade]:
|
||||
if value is None:
|
||||
return None
|
||||
return AirGrade(next((n for n, hi in enumerate(limits, start=1) if value <= hi), len(limits) + 1))
|
||||
|
||||
|
||||
def pm25_grade(value: Optional[int]) -> Optional[AirGrade]:
|
||||
return _grade(value, _PM25_LIMITS)
|
||||
|
||||
|
||||
def pm10_grade(value: Optional[int]) -> Optional[AirGrade]:
|
||||
return _grade(value, _PM10_LIMITS)
|
||||
|
||||
|
||||
class AirService:
|
||||
def __init__(self, crud: AirCRUD = Depends(AirCRUD)) -> None:
|
||||
self.crud = crud
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
from collections import Counter
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import date
|
||||
from math import cos, pi
|
||||
from statistics import mean
|
||||
from typing import Optional
|
||||
|
||||
@@ -7,8 +9,6 @@ from common.enums import RainType, Sky
|
||||
from common.utils.text import hour_label
|
||||
|
||||
AXES = ("temp", "rain", "wind", "humidity", "air", "uv", "sun", "view", "time")
|
||||
# 모든 지수의 상세에 늘 나오는 축. 나머지(자외선·햇빛·가시거리)는 비중이 있는 지수에만 나온다.
|
||||
BASE_AXES = ("temp", "rain", "wind", "humidity", "air", "time")
|
||||
_WEEKDAY = ("mon", "tue", "wed", "thu", "fri", "sat", "sun")
|
||||
_WEEKDAY_KO = ("월", "화", "수", "목", "금", "토", "일")
|
||||
_UNKNOWN = 70
|
||||
@@ -45,6 +45,16 @@ class Context:
|
||||
lookahead_rain_prob: int
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class DayForecast:
|
||||
"""중기예보(일 단위) 하루치. 시간별 예보가 닿지 않는 날의 예상 점수 재료."""
|
||||
temp_min_c: Optional[float]
|
||||
temp_max_c: Optional[float]
|
||||
rain_prob_am: int
|
||||
rain_prob_pm: int
|
||||
sky: Sky
|
||||
|
||||
|
||||
@dataclass
|
||||
class Result:
|
||||
score: int
|
||||
@@ -53,6 +63,7 @@ class Result:
|
||||
zero_reason: Optional[str]
|
||||
summary: str
|
||||
window: tuple[int, int] = field(default=(0, 0))
|
||||
estimated: bool = False
|
||||
|
||||
|
||||
def _clamp(v: float) -> int:
|
||||
@@ -74,7 +85,7 @@ def _peak(v: float, lo: float, hi: float, best: Optional[float], per_out: float)
|
||||
|
||||
def temp_score(rule: dict, feels: float) -> tuple[int, str]:
|
||||
t = feels + rule.get("offset", 0)
|
||||
shown = f"정상 {round(t)}°" if rule.get("offset") else f"체감 {round(t)}°"
|
||||
shown = f"산 정상 기준 {round(t)}°" if rule.get("offset") else f"체감 {round(t)}°"
|
||||
if rule["type"] == "range":
|
||||
lo, hi = rule["lo"], rule["hi"]
|
||||
return _peak(t, lo, hi, rule.get("best"), 8), f"{shown}, 편한 범위 {lo}~{hi}° {'안' if lo <= t <= hi else '밖'}"
|
||||
@@ -85,15 +96,18 @@ def temp_score(rule: dict, feels: float) -> tuple[int, str]:
|
||||
return _linear(t, rule["zero"], rule["full"]), shown
|
||||
|
||||
|
||||
def rain_score(rule: dict, max_prob: int, raining: bool) -> tuple[int, str]:
|
||||
def rain_score(rule: dict, max_prob: int, raining: bool, until: str = "") -> tuple[int, str]:
|
||||
prob = f"{until} 비 확률 {max_prob}%" if until else f"비 확률 {max_prob}%"
|
||||
if rule["dir"] == "wet":
|
||||
return (100 if raining else _clamp(max_prob)), (f"비 소식, 확률 {max_prob}%" if raining else f"비 확률 {max_prob}%, 비 오면 올라가요")
|
||||
return (0 if raining else _clamp(100 - max_prob)), (f"비 소식, 확률 {max_prob}%" if raining else f"비 확률 {max_prob}%")
|
||||
return (100 if raining else _clamp(max_prob)), (f"비 소식, {prob}" if raining else f"{prob}, 비 오면 올라가요")
|
||||
return (0 if raining else _clamp(100 - max_prob)), (f"비 소식, {prob}" if raining else prob)
|
||||
|
||||
|
||||
def wind_score(rule: dict, wind: Optional[float]) -> tuple[int, str]:
|
||||
if wind is None or rule["type"] == "ignore":
|
||||
return (_UNKNOWN if wind is None else 50), ("바람 정보 없음" if wind is None else f"바람 초속 {wind:g}m")
|
||||
if wind is None:
|
||||
return _UNKNOWN, f"바람 정보가 없어 {_UNKNOWN}점으로 둬요"
|
||||
if rule["type"] == "ignore":
|
||||
return 50, f"바람 초속 {wind:g}m, 이 각엔 상관없어 50점으로 둬요"
|
||||
note = f"바람 초속 {wind:g}m"
|
||||
if rule["type"] == "calm":
|
||||
ok = rule["ok"]
|
||||
@@ -117,13 +131,13 @@ def humidity_score(rule: dict, humidity: float) -> tuple[int, str]:
|
||||
return _linear(humidity, 40, 90), note
|
||||
if rule["type"] == "lower":
|
||||
return _linear(humidity, 90, 40), note
|
||||
return 50, note
|
||||
return 50, f"{note}, 이 각엔 상관없어 50점으로 둬요"
|
||||
|
||||
|
||||
def air_score(pm25: Optional[int], label: Optional[str]) -> tuple[int, str]:
|
||||
if pm25 is None:
|
||||
return _UNKNOWN, "미세먼지 정보 없음"
|
||||
return _linear(pm25, 75, 15), f"초미세먼지 {pm25}{', ' + label if label else ''}"
|
||||
return _UNKNOWN, f"미세먼지 정보가 없어 {_UNKNOWN}점으로 둬요"
|
||||
return _linear(pm25, 75, 15), f"초미세먼지 {pm25}㎍/㎥{', ' + label if label else ''}"
|
||||
|
||||
|
||||
def uv_score(rule: dict, uv: Optional[float]) -> tuple[int, str]:
|
||||
@@ -154,9 +168,29 @@ def time_score(rule: dict, ctx: Context) -> tuple[int, str]:
|
||||
return _clamp(20 + 80 * (1 - ctx.moon)), f"달 밝기 {round(ctx.moon * 100)}%"
|
||||
if kind == "sunset_score":
|
||||
return (ctx.sunset_score if ctx.sunset_score is not None else _UNKNOWN), (
|
||||
f"노을 점수 {ctx.sunset_score}" if ctx.sunset_score is not None else "노을 점수 계산 전"
|
||||
f"노을 점수 {ctx.sunset_score}" if ctx.sunset_score is not None else f"노을 점수 계산 전이라 {_UNKNOWN}점으로 둬요"
|
||||
)
|
||||
return _clamp(rule["value"]), "시간대 그대로"
|
||||
return _clamp(rule["value"]), f"날짜와 상관없이 이 시간대 기본 점수 {_clamp(rule['value'])}점"
|
||||
|
||||
|
||||
_TEMP_LABEL = {"range": "기온 알맞음", "away": "덥거나 추움", "lower": "추움", "higher": "더움"}
|
||||
_WIND_LABEL = {"calm": "바람 잔잔", "moderate": "바람 적당", "strong": "바람 셈", "ignore": "바람 무관"}
|
||||
_HUMIDITY_LABEL = {"range": "습도 알맞음", "higher": "습도 높음", "lower": "습도 낮음", "ignore": "습도 무관"}
|
||||
_TIME_LABEL = {"weekday": "요일 알맞음", "moon": "달 어두움", "sunset_score": "노을 예쁨", "fixed": "시간대 알맞음"}
|
||||
# Open-Meteo 보조 축. 비중이 있는 지수에만 나온다.
|
||||
_OM_LABEL = {"uv": "자외선", "sun": "햇빛", "view": "가시거리"}
|
||||
|
||||
|
||||
def axis_label(axis: str, rules: dict) -> str:
|
||||
"""축 값은 '이 각에 좋은 정도'라서, 라벨도 바깥으로 갈수록 좋아지는 쪽으로 읽히게 쓴다."""
|
||||
if axis in _OM_LABEL:
|
||||
return _OM_LABEL[axis]
|
||||
if axis == "rain":
|
||||
return "비 옴" if rules["rain"]["dir"] == "wet" else "비 안 옴"
|
||||
if axis == "air":
|
||||
return "공기 맑음"
|
||||
table = {"temp": _TEMP_LABEL, "wind": _WIND_LABEL, "humidity": _HUMIDITY_LABEL, "time": _TIME_LABEL}[axis]
|
||||
return table[rules[axis]["type"]]
|
||||
|
||||
|
||||
def _zero(rules: list[dict], agg: dict) -> tuple[Optional[str], Optional[int]]:
|
||||
@@ -169,7 +203,8 @@ def _zero(rules: list[dict], agg: dict) -> tuple[Optional[str], Optional[int]]:
|
||||
continue
|
||||
hit = (v >= r["value"]) if r["op"] == ">=" else (v < r["value"]) if r["op"] == "<" else (v == r["value"])
|
||||
if hit:
|
||||
return zero_text(r), r.get("cap", 0)
|
||||
cap = r.get("cap", 0)
|
||||
return f"{_cond(r)[0]} {_tail(cap)}", cap
|
||||
return None, None
|
||||
|
||||
|
||||
@@ -177,43 +212,65 @@ _FIELD_TEXT = {
|
||||
"rain_prob": "비 확률", "wind_ms": "바람", "feels_c": "체감", "pm25": "초미세먼지", "cloudy_ratio": "흐린 하늘",
|
||||
"gust_ms": "돌풍", "ground_c": "지표면 온도",
|
||||
}
|
||||
_UNIT = {"rain_prob": "%", "wind_ms": "m/s", "feels_c": "°", "pm25": "", "cloudy_ratio": "%", "gust_ms": "m/s", "ground_c": "°"}
|
||||
_UNIT = {"rain_prob": "%", "wind_ms": "m/s", "feels_c": "°", "pm25": "㎍/㎥", "cloudy_ratio": "%", "gust_ms": "m/s", "ground_c": "°"}
|
||||
|
||||
|
||||
def zero_text(r: dict) -> str:
|
||||
def _cond(r: dict) -> tuple[str, str, str]:
|
||||
"""조건 하나를 (이유, '…이거나', '…이면') 꼴로."""
|
||||
if r["field"] == "warning":
|
||||
return "강풍 특보가 있으면"
|
||||
op = "이상" if r["op"] == ">=" else "미만"
|
||||
return f"{_FIELD_TEXT[r['field']]} {r['value']}{_UNIT[r['field']]} {op}이면"
|
||||
return "강풍 특보가 있어", "강풍 특보가 있거나", "강풍 특보가 있으면"
|
||||
base = f"{_FIELD_TEXT[r['field']]} {r['value']}{_UNIT[r['field']]} {'이상' if r['op'] == '>=' else '미만'}"
|
||||
return f"{base}이라", f"{base}이거나", f"{base}이면"
|
||||
|
||||
|
||||
def _tail(cap: int) -> str:
|
||||
return f"최대 {cap}점" if cap else "0점"
|
||||
|
||||
|
||||
def zero_rules_text(rules: list[dict]) -> str:
|
||||
if not rules:
|
||||
return "없음 (재미로 보는 지수)"
|
||||
parts = [zero_text(r) for r in rules]
|
||||
caps = {r.get("cap") for r in rules}
|
||||
tail = f"{caps.pop()}점 아래로" if caps != {None} and len(caps) == 1 else "바로 0점"
|
||||
return " 또는 ".join(p.removesuffix("이면") for p in parts) + f"이면 {tail}"
|
||||
groups: dict[int, list[dict]] = {}
|
||||
for r in rules:
|
||||
groups.setdefault(r.get("cap", 0), []).append(r)
|
||||
return ", ".join(
|
||||
" ".join([_cond(r)[1] for r in rs[:-1]] + [_cond(rs[-1])[2]]) + f" {_tail(cap)}" for cap, rs in groups.items()
|
||||
)
|
||||
|
||||
|
||||
_SKY_WORD = {Sky.CLEAR: "맑음", Sky.PARTLY: "구름 많음", Sky.CLOUDY: "흐림"}
|
||||
|
||||
|
||||
def _summary(hours: list[Hour]) -> str:
|
||||
mid = hours[len(hours) // 2]
|
||||
wind = mid.wind_ms
|
||||
tag = f"비 {mid.rain_prob}%" if mid.rain_prob >= 50 else (
|
||||
"바람 살랑" if wind is not None and wind <= 2 else "바람 조금" if wind is not None and wind <= 5 else "바람 강함" if wind is not None else "맑음"
|
||||
"바람 살랑" if wind is not None and wind <= 2 else "바람 조금" if wind is not None and wind <= 5 else "바람 강함" if wind is not None else _SKY_WORD[mid.sky]
|
||||
)
|
||||
return f"{hour_label(mid.hour % 24)} {round(mid.feels_c)}°, {tag}"
|
||||
|
||||
|
||||
def _weighted(factors: dict[str, int], weights: dict[str, int]) -> int:
|
||||
worst = min((factors[a] for a in AXES if weights[a]), default=100)
|
||||
return round(sum(factors[a] * weights[a] for a in AXES) / 100 * (1 - _WORST_PULL + _WORST_PULL * worst / 100))
|
||||
|
||||
|
||||
def _until(definition) -> str:
|
||||
ahead = max((w.get("lookahead_days", 0) for w in getattr(definition, "windows", None) or []), default=0)
|
||||
return {1: "내일까지", 2: "모레까지"}.get(ahead, f"{ahead}일 뒤까지") if ahead else ""
|
||||
|
||||
|
||||
def evaluate(definition, windows: list[list[Hour]], ctx: Context) -> Optional[Result]:
|
||||
"""지수 하나를 하루치로 계산한다. 시간대가 여러 개면 가장 좋은 쪽."""
|
||||
best: Optional[Result] = None
|
||||
weights = {a: getattr(definition, f"weight_{a}", 0) for a in AXES}
|
||||
rules = definition.factor_rules
|
||||
until = _until(definition)
|
||||
for hours in windows:
|
||||
if not hours:
|
||||
continue
|
||||
max_prob = max(max(h.rain_prob for h in hours), ctx.lookahead_rain_prob)
|
||||
own_prob = max(h.rain_prob for h in hours)
|
||||
max_prob = max(own_prob, ctx.lookahead_rain_prob)
|
||||
raining = any(h.rain_type is not RainType.NONE for h in hours)
|
||||
winds = [h.wind_ms for h in hours if h.wind_ms is not None]
|
||||
feels = mean(h.feels_c for h in hours)
|
||||
@@ -224,7 +281,7 @@ def evaluate(definition, windows: list[list[Hour]], ctx: Context) -> Optional[Re
|
||||
grounds = [h.ground_c for h in hours if h.ground_c is not None]
|
||||
scored = {
|
||||
"temp": temp_score(rules["temp"], feels),
|
||||
"rain": rain_score(rules["rain"], max_prob, raining),
|
||||
"rain": rain_score(rules["rain"], max_prob, raining, until if max_prob > own_prob else ""),
|
||||
"wind": wind_score(rules["wind"], max(winds) if winds else None),
|
||||
"humidity": humidity_score(rules["humidity"], mean(h.humidity for h in hours)),
|
||||
"air": air_score(ctx.pm25, ctx.air_label),
|
||||
@@ -235,8 +292,7 @@ def evaluate(definition, windows: list[list[Hour]], ctx: Context) -> Optional[Re
|
||||
}
|
||||
factors = {a: v for a, (v, _) in scored.items()}
|
||||
notes = {a: n for a, (_, n) in scored.items()}
|
||||
worst = min((factors[a] for a in AXES if weights[a]), default=100)
|
||||
score = round(sum(factors[a] * weights[a] for a in AXES) / 100 * (1 - _WORST_PULL + _WORST_PULL * worst / 100))
|
||||
score = _weighted(factors, weights)
|
||||
agg = {
|
||||
"rain_prob": max_prob, "wind_ms": max(winds) if winds else None, "pm25": ctx.pm25,
|
||||
"feels_c": (min(h.feels_c for h in hours), max(h.feels_c for h in hours)),
|
||||
@@ -251,3 +307,118 @@ def evaluate(definition, windows: list[list[Hour]], ctx: Context) -> Optional[Re
|
||||
if best is None or result.score > best.score:
|
||||
best = result
|
||||
return best
|
||||
|
||||
|
||||
def hour_temp(lo: float, hi: float, hour: int) -> float:
|
||||
"""최저·최고 기온으로 그 시각 기온을 어림한다. 새벽 6시 최저, 오후 3시 최고. 24시 넘으면 다음 날 같은 시각."""
|
||||
h = hour % 24
|
||||
f = (1 - cos(pi * (h - 6) / 9)) / 2 if 6 <= h <= 15 else (1 + cos(pi * ((h - 15) % 24) / 15)) / 2
|
||||
return round(lo + (hi - lo) * f, 1)
|
||||
|
||||
|
||||
def estimate(definition, fc: DayForecast, windows: list[list[int]], ctx: Context, next_fc: Optional[DayForecast] = None) -> Optional[Result]:
|
||||
"""중기예보로 내는 예상 점수. 기온·비는 정의 규칙 그대로, 바람·습도·미세먼지·자외선·햇빛·가시거리는 정보 없음으로 둔다. 0점 조건은 비 확률만 본다."""
|
||||
if fc.temp_min_c is None or fc.temp_max_c is None:
|
||||
return None
|
||||
best: Optional[Result] = None
|
||||
weights = {a: getattr(definition, f"weight_{a}", 0) for a in AXES}
|
||||
rules = definition.factor_rules
|
||||
until = _until(definition)
|
||||
after = next_fc or fc
|
||||
for hours in windows:
|
||||
if not hours:
|
||||
continue
|
||||
temps = [hour_temp(fc.temp_min_c, fc.temp_max_c, h) for h in hours]
|
||||
own_prob = max(fc.rain_prob_am if h < 12 else fc.rain_prob_pm if h < 24 else after.rain_prob_am for h in hours)
|
||||
max_prob = max(own_prob, ctx.lookahead_rain_prob)
|
||||
humidity = (50, "습도 이 각엔 상관없어 50점으로 둬요") if rules["humidity"]["type"] == "ignore" else (
|
||||
_UNKNOWN, f"습도 정보가 없어 {_UNKNOWN}점으로 둬요"
|
||||
)
|
||||
temp, temp_note = temp_score(rules["temp"], mean(temps))
|
||||
scored = {
|
||||
"temp": (temp, f"{temp_note} (최저·최고 기온으로 어림)"),
|
||||
"rain": rain_score(rules["rain"], max_prob, False, until if max_prob > own_prob else ""),
|
||||
"wind": wind_score(rules["wind"], None),
|
||||
"humidity": humidity,
|
||||
"air": air_score(None, None),
|
||||
**{a: (_UNKNOWN, f"{_OM_LABEL[a]} 정보가 없어 {_UNKNOWN}점으로 둬요") if weights[a] else (0, "") for a in _OM_LABEL},
|
||||
"time": time_score(rules["time"], ctx),
|
||||
}
|
||||
factors = {a: v for a, (v, _) in scored.items()}
|
||||
notes = {a: n for a, (_, n) in scored.items()}
|
||||
score = _weighted(factors, weights)
|
||||
reason, cap = _zero([r for r in definition.zero_rules if r["field"] == "rain_prob"], {"rain_prob": max_prob})
|
||||
if reason is not None:
|
||||
score = min(score, cap)
|
||||
mid = hours[len(hours) // 2]
|
||||
summary = f"{hour_label(mid % 24)} {round(hour_temp(fc.temp_min_c, fc.temp_max_c, mid))}° 예상, 비 {max_prob}%"
|
||||
result = Result(score=score, factors=factors, notes=notes, zero_reason=reason, summary=summary, window=(hours[0], hours[-1]), estimated=True)
|
||||
if best is None or result.score > best.score:
|
||||
best = result
|
||||
return best
|
||||
|
||||
|
||||
# 나들이 날씨 점수: 낮 10~17시에 바깥에서 놀기 좋은 정도. 주말 전국 순위·당일치기 추천에 쓴다.
|
||||
OUTING_HOURS = (10, 18)
|
||||
_OUTING_WEIGHTS = {"temp": 35, "rain": 40, "sky": 15, "wind": 10}
|
||||
_OUTING_RULES = {"temp": {"type": "range", "lo": 17, "hi": 24, "best": 21}, "rain": {"dir": "dry"}, "wind": {"type": "calm", "ok": 4, "limit": 12}}
|
||||
_OUTING_SKY = {Sky.CLEAR: 100, Sky.PARTLY: 80, Sky.CLOUDY: 50}
|
||||
_OUTING_RAIN_PROB, _OUTING_RAIN_CAP = 60, 30
|
||||
|
||||
|
||||
@dataclass
|
||||
class Outing:
|
||||
score: int
|
||||
factors: dict[str, int]
|
||||
notes: dict[str, str]
|
||||
reason: str # 순위 옆 한 줄 근거 ("비 10% · 체감 21° · 맑음")
|
||||
capped: bool # 비 때문에 최대 30점으로 묶였는지
|
||||
estimated: bool = False
|
||||
|
||||
|
||||
def _outing(scored: dict[str, tuple[int, str]], prob: int, raining: bool, temp_word: str, sky: Sky, estimated: bool) -> Outing:
|
||||
factors = {a: v for a, (v, _) in scored.items()}
|
||||
notes = {a: n for a, (_, n) in scored.items()}
|
||||
worst = min(factors.values())
|
||||
score = round(sum(factors[a] * w for a, w in _OUTING_WEIGHTS.items()) / 100 * (1 - _WORST_PULL + _WORST_PULL * worst / 100))
|
||||
capped = raining or prob >= _OUTING_RAIN_PROB
|
||||
if capped:
|
||||
score = min(score, _OUTING_RAIN_CAP)
|
||||
notes["rain"] += f", 비 확률 {_OUTING_RAIN_PROB}% 이상이거나 비 소식이면 최대 {_OUTING_RAIN_CAP}점"
|
||||
reason = " · ".join(["비 소식" if raining else f"비 {prob}%", temp_word, _SKY_WORD[sky]])
|
||||
return Outing(score=score, factors=factors, notes=notes, reason=reason, capped=capped, estimated=estimated)
|
||||
|
||||
|
||||
def outing(hours: list[Hour]) -> Optional[Outing]:
|
||||
"""시간별 예보로 내는 나들이 점수. 10~17시가 다 있어야 한다."""
|
||||
if len(hours) < OUTING_HOURS[1] - OUTING_HOURS[0]:
|
||||
return None
|
||||
prob = max(h.rain_prob for h in hours)
|
||||
raining = any(h.rain_type is not RainType.NONE for h in hours)
|
||||
feels = mean(h.feels_c for h in hours)
|
||||
winds = [h.wind_ms for h in hours if h.wind_ms is not None]
|
||||
sky = Counter(h.sky for h in hours).most_common(1)[0][0]
|
||||
scored = {
|
||||
"temp": temp_score(_OUTING_RULES["temp"], feels),
|
||||
"rain": rain_score(_OUTING_RULES["rain"], prob, raining),
|
||||
"sky": (round(mean(_OUTING_SKY[h.sky] for h in hours)), f"하늘 {_SKY_WORD[sky]}"),
|
||||
"wind": wind_score(_OUTING_RULES["wind"], max(winds) if winds else None),
|
||||
}
|
||||
return _outing(scored, prob, raining, f"체감 {round(feels)}°", sky, False)
|
||||
|
||||
|
||||
def outing_estimate(fc: DayForecast) -> Optional[Outing]:
|
||||
"""중기예보(하루 단위)로 내는 예상 나들이 점수. 바람은 정보 없음으로 둔다."""
|
||||
if fc.temp_min_c is None or fc.temp_max_c is None:
|
||||
return None
|
||||
hours = range(*OUTING_HOURS)
|
||||
temp = mean(hour_temp(fc.temp_min_c, fc.temp_max_c, h) for h in hours)
|
||||
prob = max(fc.rain_prob_am, fc.rain_prob_pm)
|
||||
value, note = temp_score(_OUTING_RULES["temp"], temp)
|
||||
scored = {
|
||||
"temp": (value, f"{note} (최저·최고 기온으로 어림)"),
|
||||
"rain": rain_score(_OUTING_RULES["rain"], prob, False),
|
||||
"sky": (_OUTING_SKY[fc.sky], f"하늘 {_SKY_WORD[fc.sky]}"),
|
||||
"wind": wind_score(_OUTING_RULES["wind"], None),
|
||||
}
|
||||
return _outing(scored, prob, False, f"낮 {round(temp)}°", fc.sky, True)
|
||||
@@ -58,4 +58,38 @@ def best_times(kind: SkyType, sun_at: datetime, twilight_at: datetime, high_clou
|
||||
]
|
||||
|
||||
|
||||
GRADE_LABEL = {SkyGrade.RED: "붉음", SkyGrade.GLOW: "고움", SkyGrade.SOFT: "은은함", SkyGrade.GRAY: "흐림"}
|
||||
GRADE_LABEL = {SkyGrade.RED: "붉음", SkyGrade.GLOW: "고움", SkyGrade.SOFT: "은은함", SkyGrade.GRAY: "잿빛"}
|
||||
|
||||
GO_SCORE = 60
|
||||
MAYBE_SCORE = 40
|
||||
VERDICT_LINE = {"go": "나가 볼 만해요", "maybe": "애매해요", "rest": "쉬어요"}
|
||||
|
||||
|
||||
def verdict(value: int) -> str:
|
||||
return "go" if value >= GO_SCORE else "maybe" if value >= MAYBE_SCORE else "rest"
|
||||
|
||||
|
||||
def mean_layers(rows: list[Layers]) -> Layers:
|
||||
return Layers(*(statistics.mean(getattr(r, k) for r in rows) for k in ("low", "mid", "high")))
|
||||
|
||||
|
||||
def reason(near20: Layers, far100: Layers) -> str:
|
||||
"""score() 가 깎는 순서대로 본다: 먼 쪽 빛이 막혔나 → 머리 위 낮은 구름 → 물들 중·높은 구름의 양."""
|
||||
if far100.low + 0.5 * far100.mid >= 60:
|
||||
return "해 지는 쪽 먼 하늘이 구름에 막혀 빛이 못 들어와요"
|
||||
if near20.low >= 60:
|
||||
return "낮은 구름이 머리 위를 덮어 붉은빛을 가려요"
|
||||
canvas = round(max(near20.mid, near20.high))
|
||||
if canvas < 10:
|
||||
return "물들 구름이 거의 없어 하늘이 은은하게 끝나요"
|
||||
if canvas > 85:
|
||||
return f"중·높은 구름이 {canvas}%로 두꺼워 빛이 덜 비쳐요"
|
||||
if 25 <= canvas <= 75:
|
||||
return f"중·높은 구름이 {canvas}% 알맞게 깔리고 해 지는 쪽이 트였어요"
|
||||
return f"물들 중·높은 구름이 {canvas}%로 {'적은' if canvas < 25 else '많은'} 편이에요"
|
||||
|
||||
|
||||
def sunset_timeline(golden_at: datetime, sun_at: datetime, peak_at: datetime | None, blue_at: datetime) -> list[dict]:
|
||||
"""일몰 전 골든아워 → 해 짐 → 가장 붉을 때 → 블루아워. 분 아래는 버린다."""
|
||||
rows = [("golden", "골든아워", golden_at), ("sun", "해 져요", sun_at), ("peak", "가장 붉을 때", peak_at), ("blue", "블루아워", blue_at)]
|
||||
return [{"at": at.replace(second=0, microsecond=0).isoformat(), "kind": kind, "label": label} for kind, label, at in rows if at is not None]
|
||||
@@ -4,6 +4,7 @@ from datetime import date, datetime, timedelta, timezone
|
||||
|
||||
_SUN_ALTITUDE = -0.833
|
||||
_CIVIL_ALTITUDE = -6.0
|
||||
_GOLDEN_ALTITUDE = 6.0
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -14,6 +15,7 @@ class SunTimes:
|
||||
sunset_azimuth: int
|
||||
dawn_start_at: datetime
|
||||
sunrise_azimuth: int
|
||||
golden_start_at: datetime
|
||||
|
||||
|
||||
def _solar(d: date, lon: float) -> tuple[float, float]:
|
||||
@@ -41,6 +43,7 @@ def sun_times(d: date, lat: float, lon: float) -> SunTimes:
|
||||
at = lambda minutes: base + timedelta(minutes=minutes) # noqa: E731
|
||||
h_sun = _hour_angle(lat, decl, _SUN_ALTITUDE) * 4
|
||||
h_civil = _hour_angle(lat, decl, _CIVIL_ALTITUDE) * 4
|
||||
h_golden = _hour_angle(lat, decl, _GOLDEN_ALTITUDE) * 4
|
||||
phi, dl = math.radians(lat), math.radians(decl)
|
||||
azimuth = math.degrees(math.acos(max(-1.0, min(1.0, math.sin(dl) / math.cos(phi)))))
|
||||
return SunTimes(
|
||||
@@ -50,4 +53,5 @@ def sun_times(d: date, lat: float, lon: float) -> SunTimes:
|
||||
sunset_azimuth=round(360 - azimuth),
|
||||
dawn_start_at=at(noon_min - h_civil),
|
||||
sunrise_azimuth=round(azimuth),
|
||||
golden_start_at=at(noon_min + h_golden),
|
||||
)
|
||||
@@ -0,0 +1,101 @@
|
||||
import asyncio
|
||||
import xml.etree.ElementTree as ET
|
||||
from datetime import date, datetime, timedelta
|
||||
from typing import Optional
|
||||
|
||||
import httpx
|
||||
|
||||
from config.settings import settings
|
||||
from services.external.data_go_kr import DataGoKrNotConfigured, DataGoKrRequestFailed
|
||||
|
||||
# 한국문화정보원 한눈에보는문화정보조회서비스 (분야별 목록). 응답은 XML.
|
||||
REALM_URL = "https://apis.data.go.kr/B553457/cultureinfo/realm2"
|
||||
EXHIBITION = "D000"
|
||||
# event.source_id 접두어. TourAPI contentid(숫자)와 겹치지 않게 한다.
|
||||
SOURCE_PREFIX = "kcis:"
|
||||
IMAGE_CREDIT = "ⓒ한국문화정보원"
|
||||
_PAGE_SIZE = 100
|
||||
_ATTEMPTS = 3
|
||||
_BACKOFF_SEC = 1.5
|
||||
|
||||
# 법정동 시도 코드 앞 두 자리 → 문화정보 API 의 sido 값
|
||||
SIDO_NAME = {
|
||||
"11": "서울", "26": "부산", "27": "대구", "28": "인천", "29": "광주", "30": "대전", "31": "울산", "36": "세종", "41": "경기",
|
||||
"43": "충북", "44": "충남", "46": "전남", "47": "경북", "48": "경남", "50": "제주", "51": "강원", "52": "전북",
|
||||
}
|
||||
|
||||
|
||||
async def _get_page(client: httpx.AsyncClient, params: dict) -> tuple[list[dict], int]:
|
||||
"""한 쪽을 받아 (item 목록, totalCount). 로그·예외에 키를 남기지 않는다."""
|
||||
if not settings.data_go_kr_service_key:
|
||||
raise DataGoKrNotConfigured("DATA_GO_KR_SERVICE_KEY is empty")
|
||||
last = ""
|
||||
for attempt in range(_ATTEMPTS):
|
||||
try:
|
||||
res = await client.get(REALM_URL, params={"serviceKey": settings.data_go_kr_service_key, **params})
|
||||
root = ET.fromstring(res.content)
|
||||
except (httpx.HTTPError, ET.ParseError) as e:
|
||||
last = type(e).__name__
|
||||
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}")
|
||||
|
||||
|
||||
async def fetch_exhibitions(client: httpx.AsyncClient, sido_code: str, since: date, days: int) -> list[dict]:
|
||||
"""시도의 전시(미술관·박물관 등) 중 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")}
|
||||
items: list[dict] = []
|
||||
page = 1
|
||||
while True:
|
||||
chunk, total = await _get_page(client, {**params, "PageNo": page, "numOfrows": _PAGE_SIZE})
|
||||
items.extend(chunk)
|
||||
if not chunk or len(items) >= total:
|
||||
return items
|
||||
page += 1
|
||||
|
||||
|
||||
def _date(v: Optional[str]) -> Optional[date]:
|
||||
digits = "".join(ch for ch in (v or "") if ch.isdigit())
|
||||
try:
|
||||
return datetime.strptime(digits[:8], "%Y%m%d").date()
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
|
||||
def _coord(v: Optional[str]) -> Optional[float]:
|
||||
try:
|
||||
return round(float(v), 5) if v else None
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
|
||||
def parse_exhibitions(items: list[dict], sido_code: str, since: date) -> list[dict]:
|
||||
rows: dict[str, dict] = {}
|
||||
for it in items:
|
||||
start, end = _date(it.get("startDate")), _date(it.get("endDate"))
|
||||
if not it.get("seq") or start is None or end is None or end < since:
|
||||
continue
|
||||
x, y = _coord(it.get("gpsX")), _coord(it.get("gpsY"))
|
||||
# 경도는 120 이상이라 값으로 가린다 (gpsX/gpsY 가 뒤바뀌어 오는 경우 대비).
|
||||
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],
|
||||
"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,
|
||||
})
|
||||
return list(rows.values())
|
||||
@@ -146,6 +146,8 @@ def parse_mid(land: dict, ta: dict, base: datetime) -> dict[date, dict]:
|
||||
"temp_min_c": float(ta[f"taMin{n}"]), "temp_max_c": float(ta[f"taMax{n}"]),
|
||||
"sky": max((s for s, _ in parsed), key=lambda s: s.value), "rain_type": rains[0] if rains else RainType.NONE,
|
||||
"rain_prob": max(probs) if probs else 0,
|
||||
"rain_prob_am": land.get(f"rnSt{n}Am", land.get(f"rnSt{n}", 0)),
|
||||
"rain_prob_pm": land.get(f"rnSt{n}Pm", land.get(f"rnSt{n}", 0)),
|
||||
}
|
||||
return days
|
||||
|
||||
|
||||
@@ -1,10 +1,13 @@
|
||||
from datetime import date, datetime
|
||||
from typing import Optional
|
||||
|
||||
import httpx
|
||||
|
||||
from services.external.data_go_kr import get_all_items
|
||||
|
||||
FESTIVAL_URL = "https://apis.data.go.kr/B551011/KorService2/searchFestival2"
|
||||
# 공공누리 3유형: 출처 표시
|
||||
IMAGE_CREDIT = "ⓒ한국관광공사"
|
||||
|
||||
|
||||
async def fetch_festivals(client: httpx.AsyncClient, sido_code: str, since: date) -> list[dict]:
|
||||
@@ -14,6 +17,13 @@ async def fetch_festivals(client: httpx.AsyncClient, sido_code: str, since: date
|
||||
return [it for it in items if it.get("eventenddate", "") >= since.strftime("%Y%m%d")]
|
||||
|
||||
|
||||
def _coord(v) -> Optional[float]:
|
||||
try:
|
||||
return round(float(v), 5) if v not in (None, "") else None
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
|
||||
def parse_festivals(items: list[dict], sido_code: str) -> list[dict]:
|
||||
rows = []
|
||||
for it in items:
|
||||
@@ -25,6 +35,7 @@ def parse_festivals(items: list[dict], sido_code: str) -> list[dict]:
|
||||
rows.append({
|
||||
"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,
|
||||
"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")),
|
||||
})
|
||||
return rows
|
||||
@@ -11,18 +11,20 @@ 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 ArticleCategory, ErrorType, PostType, RefType, SkyGrade
|
||||
from common.enums import AirGrade, ArticleCategory, ErrorType, PostType, RefType, SkyGrade, 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 hour_label, ieyo, month_day
|
||||
from common.utils.text import compass, day_range, hour_label, short_day
|
||||
from crud.feed_crud import FeedCRUD
|
||||
from crud.region_crud import RegionCRUD
|
||||
from crud.season_crud import SeasonCRUD
|
||||
from crud.weather_crud import WeatherCRUD
|
||||
from router.v1.feed.protocol import (
|
||||
BandArticle, BandEvent, Bands, Cut, GakSlide, Hero, HourCell, HoursSlide, PostData, Res_Feed, Row, RowsSlide, SunsetSlide,
|
||||
TopIndex, WeekDay, WeekSlide,
|
||||
PlanSlide, PlanStep, TopIndex, WeekDay, WeekSlide,
|
||||
)
|
||||
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.sun import sun_times
|
||||
from services.index_service import IndexBoard, IndexItem, IndexService
|
||||
@@ -30,7 +32,9 @@ from services.now_service import NowService, NowWeather
|
||||
from services.season_service import SeasonService
|
||||
from services.sky_service import SkyService, SkyView
|
||||
from services.weather_service import TodayWeather, WeatherService
|
||||
from services.week_service import DayPlan, EventItem, WeekService
|
||||
from services.week_service import DayPlan, EventItem, WeekService, image_credit
|
||||
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).
|
||||
LINEUP = [
|
||||
@@ -48,13 +52,17 @@ LINEUP = [
|
||||
(12, PostType.QUOTE, RefType.NONE, None),
|
||||
(13, PostType.EVENT, RefType.NONE, 2),
|
||||
(14, PostType.EVENT, RefType.NONE, 3),
|
||||
(15, PostType.WEEKEND_PLAN, RefType.NONE, 1), # 이번 주말 첫째 날 (보통 토요일)
|
||||
(16, PostType.WEEKEND_PLAN, RefType.NONE, 2),
|
||||
(17, PostType.AIR, RefType.NONE, None),
|
||||
(18, PostType.DAY_TRIP, RefType.NONE, None),
|
||||
]
|
||||
# 시간대별 순서. 목록에 없는 종류는 그 시간대에 꺼진다. '오늘 하루 날씨'는 히어로 바로 아래 고정이라 따로 둔다. 행사는 사이사이 무작위.
|
||||
ORDER = {
|
||||
"morning": [PostType.ALERT, PostType.GAK, PostType.GAK, PostType.GAK, PostType.SEASON, PostType.SUNSET, PostType.TIP, PostType.WEEK, PostType.QUOTE],
|
||||
"day": [PostType.GAK, PostType.ALERT, PostType.GAK, PostType.GAK, PostType.SUNSET, PostType.WEEK, PostType.SEASON, PostType.TIP, PostType.QUOTE],
|
||||
"evening": [PostType.SUNSET, PostType.GAK, PostType.ALERT, PostType.GAK, PostType.GAK, PostType.TOMORROW, PostType.WEEK, PostType.SEASON, PostType.TIP, PostType.QUOTE],
|
||||
"night": [PostType.TOMORROW, PostType.ALERT, PostType.SUNSET, PostType.WEEK, PostType.GAK, PostType.GAK, PostType.GAK, 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.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],
|
||||
}
|
||||
_SKY_MODE = {"morning": "morning", "day": "day", "evening": "sunset", "night": "night"}
|
||||
_CATEGORY_META = {ArticleCategory.SEASON.value: "계절 소식", ArticleCategory.TIP.value: "날씨 상식", ArticleCategory.GAK.value: "각 원리", ArticleCategory.QUOTE.value: "한 문장"}
|
||||
@@ -65,6 +73,35 @@ _RAIN_PROB = 40
|
||||
_SUNSET_FULL = 60
|
||||
_FEED_DAY_START = 3 # 03:00 에 그날 카드가 바뀐다
|
||||
_COMMUTE_HOURS = (("내일 출근 8시", 8), ("내일 퇴근 7시", 19))
|
||||
_RAIN_LOOK = ("umbrella", "☔ 우산 챙겨!")
|
||||
# 특보 종류 → (아이콘, 공유 문구 끝, 본문 한 줄)
|
||||
_WARNING_LOOK = {
|
||||
WarningType.RAIN: (*_RAIN_LOOK, "하천·저지대 근처는 피해 다녀요."),
|
||||
WarningType.TYPHOON: ("rain", "🌀 오늘은 집콕!", "창문 단단히 닫고 외출은 줄여요."),
|
||||
WarningType.SNOW: ("snow", "❄️ 눈길 조심!", "길이 미끄러우니 대중교통이 좋아요."),
|
||||
WarningType.HEAT: ("thermo", "🥵 물 자주 마시고 그늘로!", "낮 12시~5시엔 그늘에서 쉬어 가요."),
|
||||
WarningType.TROPICAL_NIGHT: ("muggy", "🥵 오늘 밤 시원하게 자!", "자기 전 미지근한 물로 씻으면 잠이 잘 와요."),
|
||||
WarningType.COLD: ("coldwind", "🥶 따뜻하게 껴입어!", "장갑·목도리 챙기고 수도관 얼지 않게 해요."),
|
||||
WarningType.WIND: ("coldwind", "🌬️ 바람 조심!", "간판·화분처럼 날아갈 물건을 조심해요."),
|
||||
WarningType.STORM_SURGE: ("coldwind", "🌊 바닷가 조심!", "바닷가·방파제엔 가지 마세요."),
|
||||
WarningType.HIGH_SEAS: ("coldwind", "🌊 바닷가 조심!", "바닷가·방파제엔 가지 마세요."),
|
||||
WarningType.DRY: ("fallen_leaf", "🔥 불조심!", "산·들에서 불 피우지 마세요."),
|
||||
WarningType.YELLOW_DUST: ("cloud", "😷 마스크 챙겨!", "마스크 쓰고 창문은 닫아 둬요."),
|
||||
}
|
||||
_AIR_STALE = timedelta(hours=3)
|
||||
# 등급 → (큰 줄, 공유 문구 끝)
|
||||
_AIR_LINE = {
|
||||
AirGrade.GOOD: ("공기 맑아요,\n창문 활짝 열어도 돼요", "🍃 환기하자!"),
|
||||
AirGrade.NORMAL: ("공기 무난해요,\n평소대로 다녀도 돼요", "🙂 괜찮대"),
|
||||
AirGrade.BAD: ("공기가 탁해요,\n마스크 챙겨요", "😷 마스크 챙겨!"),
|
||||
AirGrade.VERY_BAD: ("공기가 많이 탁해요,\n바깥은 짧게", "😷 오늘은 실내로!"),
|
||||
}
|
||||
_AIR_ADVICE = {
|
||||
AirGrade.BAD: "KF80 마스크 쓰고, 오래 뛰는 바깥 운동은 줄여요",
|
||||
AirGrade.VERY_BAD: "외출은 줄이고 창문은 닫아 둬요. 나가면 KF94 마스크",
|
||||
}
|
||||
_QUOTE_MOOD = {"rain": "비 오는 오늘", "cloud": "흐린 오늘", "clear": "맑은 오늘"}
|
||||
_WEEKDAY_KO = ("월", "화", "수", "목", "금", "토", "일")
|
||||
|
||||
|
||||
def _pick(articles: list[Article], day: date) -> Optional[Article]:
|
||||
@@ -169,9 +206,12 @@ def _top(i: IndexItem) -> TopIndex:
|
||||
|
||||
|
||||
async def build_feed_day(day: date, crud: FeedCRUD, season_crud: SeasonCRUD) -> ErrorType:
|
||||
"""그날 피드 카드를 넣는다. 이미 있으면 그대로 둔다. 모든 카드는 03:00 부터 다음 날 03:00 까지 유효하다."""
|
||||
err, exists = await DB_SESSION_MNG.execute_lambda(lambda s: crud.has_day(s, day))
|
||||
if err is not ErrorType.SUCCESS or exists:
|
||||
"""그날 피드 카드를 넣는다. 이미 있는 번호는 그대로 두고, 새로 생긴 종류만 더한다. 모든 카드는 03:00 부터 다음 날 03:00 까지 유효하다."""
|
||||
err, made = await DB_SESSION_MNG.execute_lambda(lambda s: crud.positions(s, day))
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return err
|
||||
lineup = [x for x in LINEUP if x[0] not in made]
|
||||
if not lineup:
|
||||
return err
|
||||
_, season = await DB_SESSION_MNG.execute_lambda(lambda s: season_crud.articles(s, day, ArticleCategory.SEASON.value))
|
||||
_, tips = await DB_SESSION_MNG.execute_lambda(lambda s: season_crud.articles(s, day, ArticleCategory.TIP.value))
|
||||
@@ -179,7 +219,7 @@ async def build_feed_day(day: date, crud: FeedCRUD, season_crud: SeasonCRUD) ->
|
||||
start = kst_midnight(day) + timedelta(hours=_FEED_DAY_START)
|
||||
end = start + timedelta(days=1)
|
||||
rows = []
|
||||
for position, post_type, ref_type, rank in LINEUP:
|
||||
for position, post_type, ref_type, rank in lineup:
|
||||
ref = refs.get(post_type)
|
||||
if ref_type is RefType.ARTICLE and ref is None:
|
||||
continue
|
||||
@@ -248,17 +288,23 @@ class FeedService:
|
||||
|
||||
async def _assemble(self, region: Region, now: datetime, day: date, slot: str, sunset_at: datetime) -> tuple[Res_Feed, bool]:
|
||||
"""피드와 '일부 재료를 못 가져왔는지'. 빠진 피드는 짧게만 캐시해 다음 요청이 다시 채우게 한다."""
|
||||
(err_t, today), (err_n, now_w), (err_s, sky), (err_i, board), (err_w, days), (err_e, events) = await asyncio.gather(
|
||||
self.weather.today(region.code), self.now_service.now(region.code), self.sky.view(region.code),
|
||||
self.index.board(region.code), self.week.week(region.code), self.week.events(region.code, None),
|
||||
(err_t, today), (err_tm, tomorrow), (err_n, now_w), (err_s, sky), (err_i, board), (err_w, days), (err_e, events) = await asyncio.gather(
|
||||
self.weather.today(region.code), self.weather.today(region.code, now.date() + timedelta(days=1)), self.now_service.now(region.code),
|
||||
self.sky.view(region.code), self.index.board(region.code), self.week.week(region.code), self.week.events(region.code, None),
|
||||
)
|
||||
partial = any(e is not ErrorType.SUCCESS for e in (err_t, err_n, err_s, err_i, err_w, err_e))
|
||||
partial = any(e is not ErrorType.SUCCESS for e in (err_t, err_tm, err_n, err_s, err_i, err_w, err_e))
|
||||
today = today if err_t is ErrorType.SUCCESS else None
|
||||
tomorrow = tomorrow if err_tm is ErrorType.SUCCESS else None
|
||||
now_w = now_w if err_n is ErrorType.SUCCESS else None
|
||||
sky = sky if err_s is ErrorType.SUCCESS else None
|
||||
board = board if err_i is ErrorType.SUCCESS else None
|
||||
days = days if err_w is ErrorType.SUCCESS else []
|
||||
events = events if err_e is ErrorType.SUCCESS else []
|
||||
trip, trip_partial = await self._trip(region, now)
|
||||
partial = partial or trip_partial
|
||||
weekend = _weekends(days)[:1]
|
||||
suns = await asyncio.gather(*(self.weather.sun(region, d.day) for d in (weekend[0] if weekend else [])))
|
||||
sunsets = {x.sun_date: x.sunset_at for x in suns if x is not None}
|
||||
hour = now.replace(minute=0, second=0, microsecond=0)
|
||||
_, hourly = await DB_SESSION_MNG.execute_lambda(
|
||||
lambda s: self.weather_crud.hourly_between(s, region.code, hour, kst_midnight(now.date() + timedelta(days=2)))
|
||||
@@ -267,8 +313,8 @@ class FeedService:
|
||||
_, articles = await DB_SESSION_MNG.execute_lambda(lambda s: self.season_crud.articles(s, now.date(), None))
|
||||
by_article = {a.article_id: a for a in articles or []}
|
||||
quotes = [a for a in articles or [] if a.category == ArticleCategory.QUOTE.value]
|
||||
ctx = _Ctx(region=region, now=now, slot=slot, sunset_at=sunset_at, today=today, now_w=now_w, sky=sky, board=board,
|
||||
days=days, events=events, hourly=hourly or [], articles=by_article, quotes=quotes)
|
||||
ctx = _Ctx(region=region, now=now, slot=slot, sunset_at=sunset_at, today=today, tomorrow=tomorrow, now_w=now_w, sky=sky, board=board,
|
||||
days=days, events=events, sunsets=sunsets, hourly=hourly or [], articles=by_article, quotes=quotes, trip=trip)
|
||||
|
||||
gak = sorted(board.items[:3], key=lambda i: _gak_key(i, now.hour)) if board else []
|
||||
cards = []
|
||||
@@ -288,7 +334,8 @@ class FeedService:
|
||||
hero=self._hero(now, slot, hourly[0] if hourly else None, now_w, board),
|
||||
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) for e in events[:4]],
|
||||
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]],
|
||||
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)
|
||||
@@ -298,6 +345,23 @@ class FeedService:
|
||||
)
|
||||
return feed, partial
|
||||
|
||||
async def _trip(self, region: Region, now: datetime) -> tuple[Optional[tuple[TripPick, list[EventItem]]], bool]:
|
||||
"""당일치기 도시와 그날 그 도시 근처 행사, 그리고 재료를 못 가져왔는지. 주말 점수는 워커가 미리 계산해 둔 것만 쓴다."""
|
||||
rank = WeekendRank()
|
||||
err, scores = await rank.scores(now, compute=False)
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return None, True
|
||||
err, _, cities = await rank.targets()
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return None, True
|
||||
pick = pick_trip(region, scores, cities, weekend_days(now.date()))
|
||||
if pick is None:
|
||||
return None, False
|
||||
err, items = await self.week.events(pick.city.code, None)
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return (pick, []), True
|
||||
return (pick, pick_events(pick.best.day, items)), False
|
||||
|
||||
def _hero(self, now: datetime, slot: str, cur: Optional[WeatherHourly], now_w: Optional[NowWeather], board: Optional[IndexBoard]) -> Hero:
|
||||
top = board.items[0] if board and board.items else None
|
||||
bubble = None
|
||||
@@ -318,28 +382,26 @@ class FeedService:
|
||||
|
||||
def _gak(self, p: Post, i: IndexItem) -> PostData:
|
||||
d = i.definition
|
||||
return PostData(**self._base(p), title=f"{d.name} {i.score.score}", icon=d.icon, caption=f"{i.score.summary}. 오늘의 각 {i.rank}위는 {ieyo(d.name)}.",
|
||||
return PostData(**self._base(p), title=f"{d.name} {i.score.score}점", icon=d.icon, caption=_gak_caption(i),
|
||||
slides=[GakSlide(kind="gak", index_id=d.index_id, code=d.code, name=d.name, rank=i.rank, score=i.score.score, line=d.description, summary=i.score.summary)],
|
||||
share_messages=[f"오늘 {d.name} 어때? {d.name} {i.score.score}이래"])
|
||||
share_messages=[f"오늘 {d.name} 어때? {d.name} {i.score.score}점이래"])
|
||||
|
||||
def _render(self, p: Post, c: "_Ctx") -> Optional[PostData]:
|
||||
"""카드 하나를 그 구 데이터로 채운다. 켜질 조건이 안 맞거나 채울 데이터가 없으면 None."""
|
||||
base = self._base(p)
|
||||
t = PostType(p.post_type)
|
||||
if t is PostType.WEATHER and c.today is not None:
|
||||
slides = [HoursSlide(kind="hours", eyebrow="오늘 하루 · 3시간마다", line=c.today.headline, hours=[
|
||||
HourCell(label=f"{x.at.astimezone(KST).hour}시", icon=x.icon, temp_c=float(x.row.temp_c) if x.row else None, tone=x.tone) for x in c.today.slots
|
||||
])]
|
||||
if c.now_w is not None and c.now_w.air is not None and c.now_w.air_text:
|
||||
slides.append(RowsSlide(kind="rows", eyebrow="미세먼지", line=c.now_w.air_text, icon="vent", rows=[
|
||||
Row(label="초미세먼지", value=str(c.now_w.air.pm25) if c.now_w.air.pm25 is not None else "-"),
|
||||
Row(label="미세먼지", value=str(c.now_w.air.pm10) if c.now_w.air.pm10 is not None else "-"),
|
||||
Row(label="측정소", value=c.now_w.air.station_name),
|
||||
]))
|
||||
return PostData(**base, title="오늘 하루의 날씨", icon=c.today.slots[4].icon, caption=c.today.headline, slides=slides,
|
||||
days = [("오늘 하루", c.today)] + ([("내일", c.tomorrow)] if c.tomorrow is not None else [])
|
||||
slides = [HoursSlide(kind="hours", eyebrow=f"{label} · 3시간마다", line=w.headline, hours=[
|
||||
HourCell(label=f"{x.at.astimezone(KST).hour}시", icon=x.icon, temp_c=float(x.row.temp_c) if x.row else None, tone=x.tone) for x in w.slots
|
||||
]) for label, w in days]
|
||||
caption = (c.now_w.rain_2h_text if c.now_w else None) or "3시간마다 바뀌는 하늘을 넘겨 보세요"
|
||||
return PostData(**base, title="오늘·내일 날씨", icon=c.today.slots[4].icon, caption=caption, slides=slides,
|
||||
share_messages=[f"{c.region.short_name} 오늘 날씨: {c.today.headline}"])
|
||||
if t is PostType.ALERT:
|
||||
return self._alert(base, c)
|
||||
if t is PostType.AIR:
|
||||
return self._air(base, c)
|
||||
if t is PostType.SUNSET and c.sky is not None:
|
||||
return self._sunset(base, c)
|
||||
if t is PostType.TOMORROW and c.now_w is not None:
|
||||
@@ -354,26 +416,70 @@ class FeedService:
|
||||
if len(soon) < rank:
|
||||
return None
|
||||
e = soon[rank - 1]
|
||||
rows = [Row(label="장소", value=e.event.place_name), Row(label="기간", value=f"{e.event.start_date:%m.%d}~{e.event.end_date:%m.%d}")]
|
||||
if e.fit:
|
||||
rows.append(Row(label="그날 날씨", value=e.fit))
|
||||
caption = f"{month_day(e.event.start_date)}부터 {month_day(e.event.end_date)}까지예요." if e.event.is_confirmed else "올해 정확한 일정은 공식 안내로 확인해 주세요."
|
||||
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))]
|
||||
caption = _event_caption(e)
|
||||
return PostData(**base, title=e.event.name, icon=e.event.icon, caption=caption,
|
||||
slides=[RowsSlide(kind="rows", eyebrow=f"{c.region.name.split()[0]} 행사 · {e.status_label}", line=e.event.name, icon=e.event.icon, rows=rows)],
|
||||
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))],
|
||||
share_messages=[f"{e.event.name} 같이 갈래?"])
|
||||
if t is PostType.WEEK and c.days:
|
||||
weekends = _weekends(c.days)
|
||||
if not weekends:
|
||||
return None
|
||||
first = weekends[0]
|
||||
return PostData(**base, title="이번 주말 추천", icon="calendar", caption=" ".join(f"{d.weekday}요일은 {d.pick}." for d in first),
|
||||
slides=[WeekSlide(kind="week", eyebrow=f"{label} · {c.region.short_name}", line=w[0].pick, days=[
|
||||
WeekDay(day=d.day, weekday=d.weekday, icon=d.icon, text=d.headline) for d in w
|
||||
]) for label, w in zip(("이번 주말", "다음 주말"), weekends)], share_messages=["이번 주말 같이 놀자 🙌"])
|
||||
slides = []
|
||||
for label, w in zip(("이번 주말", "다음 주말"), weekends):
|
||||
f = forecast(w)
|
||||
slides.append(WeekSlide(kind="week", eyebrow=f"{label} · {day_range(w[0].day, w[-1].day)}", line=f.line, tip=f.tip, days=[
|
||||
WeekDay(day=d.day, weekday=d.weekday, icon=d.icon, text=d.headline, temp_min_c=d.temp_min_c, temp_max_c=d.temp_max_c, rain_prob=d.rain_prob)
|
||||
for d in w
|
||||
]))
|
||||
first = forecast(weekends[0])
|
||||
return PostData(**base, title="이번 주말 예보", icon="calendar", caption=first.caption, slides=slides, share_messages=["이번 주말 같이 놀자 🙌"])
|
||||
if t is PostType.WEEKEND_PLAN and c.days:
|
||||
return self._weekend_plan(base, c, p.index_rank or 1)
|
||||
if t is PostType.QUOTE:
|
||||
return self._quote(base, c)
|
||||
if t is PostType.DAY_TRIP and c.trip is not None:
|
||||
return self._day_trip(base, *c.trip)
|
||||
return None
|
||||
|
||||
def _day_trip(self, base: dict, pick: TripPick, events: list[EventItem]) -> PostData:
|
||||
"""1~2시간 거리 후보 도시 중 이번 주말 나들이 점수 1위. 첫 장은 도시·날씨, 뒤로 그날 그곳 행사 최대 2장."""
|
||||
b = pick.best
|
||||
when = f"{_WEEKDAY_KO[b.day.weekday()]}요일"
|
||||
rows = [Row(label="거리", value=f"여기서 약 {pick.distance_km}km"), Row(label="예상 날씨" if b.estimated else "날씨", value=b.reason)]
|
||||
if b.temp_min_c is not None and b.temp_max_c is not None:
|
||||
rows.append(Row(label="기온", value=f"{round(b.temp_min_c)}~{round(b.temp_max_c)}°"))
|
||||
if pick.note:
|
||||
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))]
|
||||
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:
|
||||
label, x = pick.runner_up
|
||||
caption = f"다음은 {label}, {_WEEKDAY_KO[x.day.weekday()]}요일 {x.score}점이에요."
|
||||
else:
|
||||
caption = "아침 일찍 출발하면 하루가 넉넉해요."
|
||||
return PostData(**base, title=f"{pick.label} 당일치기", icon=b.icon, caption=caption, slides=slides,
|
||||
share_messages=[f"{when} {pick.label} 당일치기 어때? 나들이 {b.score}점이래 🚗"])
|
||||
|
||||
def _weekend_plan(self, base: dict, c: "_Ctx", nth: int) -> Optional[PostData]:
|
||||
"""이번 주말 nth 번째 날의 시간대별 동선."""
|
||||
weekends = _weekends(c.days)
|
||||
if not weekends or len(weekends[0]) < nth:
|
||||
return None
|
||||
used: frozenset[int] = frozenset()
|
||||
for prev in weekends[0][:nth - 1]:
|
||||
used |= {e.event.event_id for e in pick_events(prev.day, c.events, used)}
|
||||
d = weekends[0][nth - 1]
|
||||
nxt = next((x for x in c.days if x.day == d.day + timedelta(days=1)), None)
|
||||
card = day_plan(d, c.sunsets.get(d.day), pick_events(d.day, c.events, used), nxt.temp_min_c if nxt else None)
|
||||
return PostData(**base, title=f"{d.weekday}요일 플랜", icon="calendar", caption=card.caption,
|
||||
slides=[PlanSlide(kind="plan", eyebrow=card.eyebrow, line=card.line, steps=[
|
||||
PlanStep(time=x.time, icon=x.icon, title=x.title, sub=x.sub, image=x.image, image_credit=x.image_credit) for x in card.steps
|
||||
])], share_messages=[f"{d.weekday}요일 이렇게 놀자! {card.line.splitlines()[0].rstrip(',')}"])
|
||||
|
||||
def _alert(self, base: dict, c: "_Ctx") -> Optional[PostData]:
|
||||
"""오늘 남은 시간·내일 출퇴근에 비 확률 40% 이상이거나 특보가 있을 때만 켠다."""
|
||||
tomorrow = c.now.date() + timedelta(days=1)
|
||||
@@ -387,15 +493,37 @@ class FeedService:
|
||||
if later:
|
||||
rows.append(Row(label="오늘", value=f"{hour_label(later[0].forecast_at.astimezone(KST).hour)}부터 비 {later[0].rain_prob}%"))
|
||||
rows += [Row(label=label, value=f"비 {r.rain_prob}%") for label, r in commute]
|
||||
probs = [r.rain_prob for r in later] + [r.rain_prob for _, r in commute]
|
||||
rain_tip = "큰 우산이 든든해요." if probs and max(probs) >= 60 else "접는 우산이면 충분해요."
|
||||
icon, tail, caption = _WARNING_LOOK[warnings[0].warning_type] if warnings else (*_RAIN_LOOK, rain_tip)
|
||||
if warnings:
|
||||
title, line = warnings[0].text, "바깥 활동 전에 꼭 확인하세요"
|
||||
elif later:
|
||||
title, line = "우산 챙겨요", f"{hour_label(later[0].forecast_at.astimezone(KST).hour)}쯤 비 소식이 있어요"
|
||||
else:
|
||||
title, line = "내일 우산 챙겨요", f"{commute[0][0]}에 비 소식이 있어요"
|
||||
return PostData(**base, title=title, icon="umbrella", caption=line,
|
||||
slides=[RowsSlide(kind="rows", eyebrow=f"생활 알림 · {c.region.short_name}", line=line, icon="umbrella", rows=rows)],
|
||||
share_messages=[f"{line} ☔ 우산 챙겨!"])
|
||||
return PostData(**base, title=title, icon=icon, caption=caption,
|
||||
slides=[RowsSlide(kind="rows", eyebrow=f"생활 알림 · {c.region.short_name}", line=line, icon=icon, rows=rows)],
|
||||
share_messages=[f"{line} {tail}"])
|
||||
|
||||
def _air(self, base: dict, c: "_Ctx") -> Optional[PostData]:
|
||||
"""가까운 측정소의 지금 초미세먼지·미세먼지. 측정값이 없거나 3시간 넘게 지났으면 끈다."""
|
||||
air = c.now_w.air if c.now_w else None
|
||||
if air is None or c.now - air.measured_at > _AIR_STALE:
|
||||
return None
|
||||
values = [(name, v, g) for name, v, g in (("초미세먼지", air.pm25, pm25_grade(air.pm25)), ("미세먼지", air.pm10, pm10_grade(air.pm10))) if g]
|
||||
if not values:
|
||||
return None
|
||||
worst = max(g for _, _, g in values)
|
||||
label = AIR_GRADE_LABEL[worst]
|
||||
rows = [Row(label=name, value=f"{v}㎍/㎥ · {AIR_GRADE_LABEL[g]}") for name, v, g in values]
|
||||
if worst in _AIR_ADVICE:
|
||||
rows.append(Row(label="이렇게 해요", value=_AIR_ADVICE[worst]))
|
||||
line, tail = _AIR_LINE[worst]
|
||||
icon = "vent" if worst <= AirGrade.NORMAL else "cloud"
|
||||
return PostData(**base, title=f"미세먼지 {label}", icon=icon, caption=f"{air.station_name} 측정소 · {air.measured_at.astimezone(KST).hour}시 기준",
|
||||
slides=[RowsSlide(kind="rows", eyebrow=f"지금 공기 · {c.region.short_name}", line=line, icon=icon, rows=rows)],
|
||||
share_messages=[f"{c.region.short_name} 지금 미세먼지 {label} {tail}"])
|
||||
|
||||
def _sunset(self, base: dict, c: "_Ctx") -> Optional[PostData]:
|
||||
"""해 지기 전엔 오늘, 진 뒤엔 내일 노을. 60점 미만이면 한 줄 카드."""
|
||||
@@ -412,12 +540,15 @@ class FeedService:
|
||||
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)
|
||||
slides = [SunsetSlide(kind="sunset", eyebrow=f"{when} 노을 · {c.region.name}", line=f"{peak_at:%H:%M}, 서쪽이 가장 붉어요", score=target.score,
|
||||
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])]
|
||||
if c.sky.spots:
|
||||
slides.append(RowsSlide(kind="rows", eyebrow="가까운 노을 명소", line=f"해 지는 쪽 {c.sky.sunset_azimuth}°, 서쪽이 트인 곳", icon="sunset",
|
||||
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)]))
|
||||
return PostData(**base, title=f"{when} 노을 {target.score}", icon="sunset", caption=f"{grade}. {peak_at:%H:%M}쯤이 가장 예뻐요.",
|
||||
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}에 같이 볼래?"])
|
||||
|
||||
def _tomorrow(self, base: dict, c: "_Ctx") -> PostData:
|
||||
@@ -428,10 +559,9 @@ class FeedService:
|
||||
s = next((x for x in i.trend if x.score_date == tomorrow), None)
|
||||
if s is not None and (best is None or s.score > best[1].score):
|
||||
best = (i, s)
|
||||
caption = c.now_w.tomorrow_text + "."
|
||||
if best is not None:
|
||||
rows.append(Row(label="내일 1위 각", value=f"{best[0].definition.name} {best[1].score}"))
|
||||
caption += f" 내일 1위는 {ieyo(best[0].definition.name)}."
|
||||
rows.append(Row(label="내일 1위 각", value=f"{best[0].definition.name} {best[1].score}점"))
|
||||
caption = _temp_change(c.today, c.tomorrow) or "출근 전에 한 번 더 확인해 주세요."
|
||||
icon = c.now_w.commute[0].icon if c.now_w.commute else "sun"
|
||||
return PostData(**base, title="내일 미리보기", icon=icon, caption=caption,
|
||||
slides=[RowsSlide(kind="rows", eyebrow=f"내일 · {c.region.short_name}", line=c.now_w.tomorrow_text, icon=icon, rows=rows)],
|
||||
@@ -447,10 +577,45 @@ class FeedService:
|
||||
if a is None:
|
||||
return None
|
||||
rows = [Row(label="출처", value=a.body[1])] if len(a.body) > 1 else []
|
||||
return PostData(**base, title=a.title, icon=a.icon, caption=a.body[0],
|
||||
mood = "잠들기 전" if a.code.startswith("quote-night-") else _QUOTE_MOOD[weather]
|
||||
return PostData(**base, title=a.title, icon=a.icon, caption=f"{mood}에 어울리는 한 문장이에요.",
|
||||
slides=[RowsSlide(kind="rows", eyebrow="오늘의 한 문장", line=a.body[0], icon=a.icon, rows=rows)], share_messages=[a.body[0]])
|
||||
|
||||
|
||||
def _gak_caption(i: IndexItem) -> str:
|
||||
"""슬라이드에 없는 내일 점수, 없으면 하기 좋은 시간."""
|
||||
nxt = next((x for x in i.trend if x.score_date > i.score.score_date), None)
|
||||
if nxt is not None:
|
||||
diff = nxt.score - i.score.score
|
||||
how = "비슷해요" if abs(diff) < 5 else f"오늘보다 {abs(diff)}점 {'높아요' if diff > 0 else '낮아요'}"
|
||||
return f"내일은 {nxt.score}점, {how}."
|
||||
spans = [_span(w) for w in i.definition.windows or []]
|
||||
return f"하기 좋은 때는 {spans[0][0]}~{spans[0][1]}시예요." if spans else f"오늘의 각 {i.rank}위예요."
|
||||
|
||||
|
||||
def _temp_change(today: Optional[TodayWeather], tomorrow: Optional[TodayWeather]) -> Optional[str]:
|
||||
"""내일 낮 최고기온을 오늘과 견준 한 줄."""
|
||||
highs = [max((float(x.row.temp_c) for x in w.slots if x.row), default=None) if w else None for w in (today, tomorrow)]
|
||||
if None in highs:
|
||||
return None
|
||||
diff = round(highs[1] - highs[0])
|
||||
if abs(diff) < 2:
|
||||
return f"내일 낮 최고 {round(highs[1])}°, 오늘이랑 비슷해요."
|
||||
return f"내일 낮 최고 {round(highs[1])}°, 오늘보다 {abs(diff)}° {'더워요' if diff > 0 else '쌀쌀해요'}."
|
||||
|
||||
|
||||
def _event_caption(e: EventItem) -> str:
|
||||
"""진행 상태·거리·그날 날씨 중 있는 것. 다 없으면 일정 확정 여부."""
|
||||
parts = ["지금 진행 중" if e.status == "live" else e.status_label]
|
||||
if e.distance_km is not None:
|
||||
parts.append(f"여기서 {round(e.distance_km)}km")
|
||||
if e.fit:
|
||||
parts.append(e.fit)
|
||||
if len(parts) > 1 or e.status == "live":
|
||||
return " · ".join(parts)
|
||||
return "일정이 확정됐어요." if e.event.is_confirmed else "올해 정확한 일정은 공식 안내로 확인해 주세요."
|
||||
|
||||
|
||||
@dataclass
|
||||
class _Ctx:
|
||||
region: Region
|
||||
@@ -458,11 +623,14 @@ class _Ctx:
|
||||
slot: str
|
||||
sunset_at: datetime
|
||||
today: Optional[TodayWeather]
|
||||
tomorrow: Optional[TodayWeather]
|
||||
now_w: Optional[NowWeather]
|
||||
sky: Optional[SkyView]
|
||||
board: Optional[IndexBoard]
|
||||
days: list[DayPlan]
|
||||
events: list[EventItem]
|
||||
sunsets: dict[date, datetime]
|
||||
hourly: list[WeatherHourly]
|
||||
articles: dict[int, Article]
|
||||
quotes: list[Article]
|
||||
trip: Optional[tuple[TripPick, list[EventItem]]] = None
|
||||
@@ -7,22 +7,25 @@ from typing import Optional
|
||||
from fastapi import Depends
|
||||
|
||||
from common.database.db_session_manager import DB_SESSION_MNG
|
||||
from common.database.model.models import IndexDefinition, IndexScore, OpenMeteoHourly, Region, WeatherHourly
|
||||
from common.database.model.models import IndexDefinition, IndexScore, OpenMeteoHourly, Region, WeatherDaily, WeatherHourly
|
||||
from common.enums import AirGrade, ErrorType, RainType, Sky, SkyType, WarningType
|
||||
from common.utils.kma_time import KST, kst_midnight, now_kst
|
||||
from crud.index_crud import IndexCRUD
|
||||
from crud.region_crud import RegionCRUD
|
||||
from crud.sky_crud import SkyCRUD
|
||||
from crud.weather_crud import WeatherCRUD
|
||||
from crud.week_crud import WeekCRUD
|
||||
from services.air_service import GRADE_LABEL, AirService
|
||||
from services.calc.index_calc import AXES, Context, Hour, evaluate
|
||||
from services.calc.index_calc import AXES, Context, DayForecast, Hour, Result, estimate, evaluate
|
||||
from services.calc.moon import illumination
|
||||
from services.calc.sun import sun_times
|
||||
from services.warning_service import WarningService
|
||||
from services.weather_service import WeatherService
|
||||
|
||||
# 시간별 예보로 늘 계산하는 날 수 (오늘~모레). 이번 주말은 시간별 예보가 없으면 중기예보로 예상 점수를 낸다.
|
||||
DAYS = 3
|
||||
_LOOKAHEAD_HOURS = (9, 18)
|
||||
_WEEKDAY_KO = ("월", "화", "수", "목", "금", "토", "일")
|
||||
|
||||
# 메인 하늘 영역의 '오늘 날씨 점수': 낮 9~21시 밖에 나가기 좋은 정도.
|
||||
WEATHER_SCORE_DEF = SimpleNamespace(
|
||||
@@ -58,6 +61,34 @@ def _hour(r: WeatherHourly) -> Hour:
|
||||
)
|
||||
|
||||
|
||||
def slot_days(today: date) -> list[date]:
|
||||
"""각 상세 창 점수 칸 4개: 오늘, 내일, 그다음 아직 안 나온 주말 날을 가까운 순으로."""
|
||||
days = [today, today + timedelta(days=1)]
|
||||
d = today + timedelta(days=2)
|
||||
while len(days) < 4:
|
||||
if d.weekday() >= 5:
|
||||
days.append(d)
|
||||
d += timedelta(days=1)
|
||||
return days
|
||||
|
||||
|
||||
def slot_label(day: date, today: date) -> str:
|
||||
n = (day - today).days
|
||||
return "오늘" if n == 0 else "내일" if n == 1 else f"{_WEEKDAY_KO[day.weekday()]} {day.month}.{day.day}"
|
||||
|
||||
|
||||
def window_hours(defn, day: date, region: Region) -> list[list[int]]:
|
||||
"""시간대 정의를 그날 기준 시각 목록으로. 24 이상은 다음 날 시각."""
|
||||
out = []
|
||||
for w in defn.windows:
|
||||
if w.get("around") == "sunset":
|
||||
h = sun_times(day, float(region.lat), float(region.lon)).sunset_at.astimezone(KST).hour
|
||||
out.append(list(range(h - w.get("hours", 1), h + w.get("hours", 1) + 1)))
|
||||
else:
|
||||
out.append(list(range(w["from"], w["to"])))
|
||||
return out
|
||||
|
||||
|
||||
def _slot_end_hour(h: int) -> int:
|
||||
"""h시~h+1시를 덮는 3시간 구간의 끝 시각. 일조처럼 '직전 3시간 합'인 값에 쓴다 (7시→9시, 12시→15시)."""
|
||||
return (h + 3) // 3 * 3
|
||||
@@ -90,12 +121,7 @@ def windows_for(
|
||||
by_om = by_om or {}
|
||||
start = kst_midnight(day)
|
||||
out = []
|
||||
for w in defn.windows:
|
||||
if w.get("around") == "sunset":
|
||||
h = sun_times(day, float(region.lat), float(region.lon)).sunset_at.astimezone(KST).hour
|
||||
hours = range(h - w.get("hours", 1), h + w.get("hours", 1) + 1)
|
||||
else:
|
||||
hours = range(w["from"], w["to"])
|
||||
for hours in window_hours(defn, day, region):
|
||||
rows = [by_at.get(start + timedelta(hours=h)) for h in hours]
|
||||
out.append([
|
||||
replace(_hour(r), hour=h, **_om_fields(
|
||||
@@ -106,8 +132,38 @@ def windows_for(
|
||||
return out
|
||||
|
||||
|
||||
def day_forecast(d: WeatherDaily) -> DayForecast:
|
||||
return DayForecast(
|
||||
temp_min_c=float(d.temp_min_c) if d.temp_min_c is not None else None,
|
||||
temp_max_c=float(d.temp_max_c) if d.temp_max_c is not None else None,
|
||||
rain_prob_am=d.rain_prob if d.rain_prob_am is None else d.rain_prob_am,
|
||||
rain_prob_pm=d.rain_prob if d.rain_prob_pm is None else d.rain_prob_pm,
|
||||
sky=Sky(d.sky),
|
||||
)
|
||||
|
||||
|
||||
def _lookahead_days(defn) -> int:
|
||||
return max((w.get("lookahead_days", 0) for w in defn.windows), default=0)
|
||||
|
||||
|
||||
def day_result(
|
||||
defn, day: date, region: Region, by_at: dict[datetime, WeatherHourly], daily: dict[date, DayForecast], ctx: Context, short: bool,
|
||||
by_om: Optional[dict[datetime, OpenMeteoHourly]] = None,
|
||||
) -> Optional[Result]:
|
||||
"""short(오늘~모레)이거나 시간대가 시간별 예보로 다 채워지면 그대로 계산, 아니면 중기예보로 예상 점수."""
|
||||
windows = windows_for(defn, day, region, by_at, by_om)
|
||||
if short or all(len(w) == len(h) for w, h in zip(windows, window_hours(defn, day, region))):
|
||||
return evaluate(defn, windows, replace(ctx, lookahead_rain_prob=lookahead_rain(defn, day, by_at)))
|
||||
fc = daily.get(day)
|
||||
if fc is None:
|
||||
return None
|
||||
ahead = [daily[d] for i in range(1, _lookahead_days(defn) + 1) if (d := day + timedelta(days=i)) in daily]
|
||||
prob = max((max(f.rain_prob_am, f.rain_prob_pm) for f in ahead), default=0)
|
||||
return estimate(defn, fc, window_hours(defn, day, region), replace(ctx, lookahead_rain_prob=prob), daily.get(day + timedelta(days=1)))
|
||||
|
||||
|
||||
def lookahead_rain(defn, day: date, by_at: dict[datetime, WeatherHourly]) -> int:
|
||||
days = max((w.get("lookahead_days", 0) for w in defn.windows), default=0)
|
||||
days = _lookahead_days(defn)
|
||||
if not days:
|
||||
return 0
|
||||
probs = [
|
||||
@@ -125,12 +181,13 @@ class IndexService:
|
||||
regions: RegionCRUD = Depends(RegionCRUD),
|
||||
crud: IndexCRUD = Depends(IndexCRUD),
|
||||
weather: WeatherCRUD = Depends(WeatherCRUD),
|
||||
week: WeekCRUD = Depends(WeekCRUD),
|
||||
sky: SkyCRUD = Depends(SkyCRUD),
|
||||
weather_service: WeatherService = Depends(WeatherService),
|
||||
air_service: AirService = Depends(AirService),
|
||||
warning_service: WarningService = Depends(WarningService),
|
||||
) -> None:
|
||||
self.regions, self.crud, self.weather, self.sky = regions, crud, weather, sky
|
||||
self.regions, self.crud, self.weather, self.week, self.sky = regions, crud, weather, week, sky
|
||||
self.weather_service, self.air_service, self.warning_service = weather_service, air_service, warning_service
|
||||
|
||||
async def board(self, region_code: str) -> tuple[ErrorType, Optional[IndexBoard]]:
|
||||
@@ -144,8 +201,9 @@ class IndexService:
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return err, None
|
||||
today = now.date()
|
||||
slots = slot_days(today)
|
||||
err, defs = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.definitions(s))
|
||||
err2, scores = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.scores(s, region.code, today, today + timedelta(days=DAYS - 1)))
|
||||
err2, scores = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.scores(s, region.code, today, slots[-1]))
|
||||
if ErrorType.DB_ERROR in (err, err2):
|
||||
return ErrorType.DB_ERROR, None
|
||||
by_key = {(x.index_id, x.score_date): x for x in scores}
|
||||
@@ -153,26 +211,30 @@ class IndexService:
|
||||
items = [
|
||||
IndexItem(
|
||||
definition=d, score=by_key[(d.index_id, today)], rank=i + 1,
|
||||
trend=[by_key[k] for k in ((d.index_id, today + timedelta(days=n)) for n in range(DAYS)) if k in by_key],
|
||||
trend=[by_key[k] for k in ((d.index_id, day) for day in slots) if k in by_key],
|
||||
)
|
||||
for i, d in enumerate(ranked)
|
||||
]
|
||||
return ErrorType.SUCCESS, IndexBoard(region=region, day=today, weather_score=weather_score, items=items)
|
||||
|
||||
async def ensure(self, region: Region, now: datetime) -> tuple[ErrorType, Optional[int]]:
|
||||
"""재료(예보·미세먼지)가 지수 계산 뒤에 바뀌었으면 사흘치를 다시 계산한다. 오늘 날씨 점수도 같이 낸다."""
|
||||
_, _, warnings = await asyncio.gather(
|
||||
self.weather_service.ensure_vilage(region, now), self.air_service.ensure(now), self.warning_service.for_region(region, now)
|
||||
"""재료(예보·미세먼지)가 지수 계산 뒤에 바뀌었으면 오늘~모레와 이번 주말을 다시 계산한다. 오늘 날씨 점수도 같이 낸다."""
|
||||
_, _, _, warnings = await asyncio.gather(
|
||||
self.weather_service.ensure_vilage(region, now), self.weather_service.ensure_mid(region, now), self.air_service.ensure(now),
|
||||
self.warning_service.for_region(region, now),
|
||||
)
|
||||
today = now.date()
|
||||
start = kst_midnight(today)
|
||||
days = sorted({today + timedelta(days=i) for i in range(DAYS)} | set(slot_days(today)))
|
||||
err, rows = await DB_SESSION_MNG.execute_lambda(
|
||||
lambda s: self.weather.hourly_between(s, region.code, start, start + timedelta(days=DAYS + 2))
|
||||
lambda s: self.weather.hourly_between(s, region.code, start, kst_midnight(days[-1]) + timedelta(days=3))
|
||||
)
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return err, None
|
||||
if not rows:
|
||||
return ErrorType.EXTERNAL_API_ERROR, None
|
||||
_, daily_rows = await DB_SESSION_MNG.execute_lambda(lambda s: self.week.daily(s, region.code, today, days[-1] + timedelta(days=2)))
|
||||
daily = {d.forecast_date: day_forecast(d) for d in daily_rows or []}
|
||||
om_err, om_rows = await DB_SESSION_MNG.execute_lambda(
|
||||
lambda s: self.weather.openmeteo_between(s, region.code, start, start + timedelta(days=DAYS + 2))
|
||||
)
|
||||
@@ -187,35 +249,36 @@ class IndexService:
|
||||
today_ctx = Context(day=today, is_holiday=False, moon=0, sunset_score=None, lookahead_rain_prob=0, **base_ctx)
|
||||
weather_result = evaluate(WEATHER_SCORE_DEF, windows_for(WEATHER_SCORE_DEF, today, region, by_at, by_om), today_ctx)
|
||||
|
||||
issued = max(r.issued_at for r in rows)
|
||||
issued = max([r.issued_at for r in rows] + [d.issued_at for d in daily_rows or []])
|
||||
inputs_at = max(issued, air.measured_at) if air else issued
|
||||
if by_om:
|
||||
inputs_at = max(inputs_at, max(r.fetched_at for r in by_om.values()))
|
||||
err, computed = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.last_computed(s, region.code, today))
|
||||
if err is ErrorType.SUCCESS and computed is not None and computed >= inputs_at:
|
||||
_, scored = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.score_dates(s, region.code, today, days[-1]))
|
||||
wanted = {d for d in days if d >= today + timedelta(days=DAYS) and d in daily and None not in (daily[d].temp_min_c, daily[d].temp_max_c)}
|
||||
if err is ErrorType.SUCCESS and computed is not None and computed >= inputs_at and wanted <= (scored or set()):
|
||||
return ErrorType.SUCCESS, weather_result.score if weather_result else None
|
||||
|
||||
err, defs = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.definitions(s))
|
||||
_, holidays = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.holidays(s, today, today + timedelta(days=DAYS)))
|
||||
_, holidays = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.holidays(s, today, days[-1]))
|
||||
_, sky_scores = await DB_SESSION_MNG.execute_lambda(lambda s: self.sky.scores(s, [region.code], today))
|
||||
sunset = {x.score_date: x.score for x in sky_scores or [] if x.sky_type == SkyType.SUNSET.value}
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return err, None
|
||||
out = []
|
||||
for i in range(DAYS):
|
||||
day = today + timedelta(days=i)
|
||||
for day in days:
|
||||
ctx = Context(
|
||||
day=day, is_holiday=day in (holidays or set()), moon=illumination(datetime.combine(day, time(23), tzinfo=KST)),
|
||||
sunset_score=sunset.get(day), lookahead_rain_prob=0, **base_ctx,
|
||||
)
|
||||
for d in defs:
|
||||
day_ctx = replace(ctx, lookahead_rain_prob=lookahead_rain(d, day, by_at))
|
||||
result = evaluate(d, windows_for(d, day, region, by_at, by_om), day_ctx)
|
||||
result = day_result(d, day, region, by_at, daily, ctx, short=day < today + timedelta(days=DAYS), by_om=by_om)
|
||||
if result is None:
|
||||
continue
|
||||
out.append({
|
||||
"region_code": region.code, "score_date": day, "index_id": d.index_id, "score": result.score, "summary": result.summary,
|
||||
**{f"{a}_score": result.factors[a] for a in AXES}, "zero_reason": result.zero_reason, "notes": result.notes, "computed_at": now,
|
||||
**{f"{a}_score": result.factors[a] for a in AXES}, "zero_reason": result.zero_reason, "notes": result.notes,
|
||||
"estimated": result.estimated, "computed_at": now,
|
||||
})
|
||||
err = await DB_SESSION_MNG.execute_lambda_run([lambda s: self.crud.upsert_scores(s, out)])
|
||||
return err, weather_result.score if weather_result else None
|
||||
@@ -63,7 +63,7 @@ def _weather_word(rain: RainType, sky: Sky, rain_mm: float) -> tuple[str, str]:
|
||||
return "snow", "눈"
|
||||
if rain is not RainType.NONE:
|
||||
return "rain", "약한 비" if rain_mm < 1 else "비"
|
||||
return {Sky.CLEAR: ("sun", "맑음"), Sky.PARTLY: ("sun_cloud", "구름많음"), Sky.CLOUDY: ("cloud", "흐림")}[sky]
|
||||
return {Sky.CLEAR: ("sun", "맑음"), Sky.PARTLY: ("sun_cloud", "구름 많음"), Sky.CLOUDY: ("cloud", "흐림")}[sky]
|
||||
|
||||
|
||||
def _rain_2h_text(hours: list[RainHour]) -> tuple[bool, str]:
|
||||
|
||||
@@ -13,6 +13,7 @@ from common.database.model.models import Article, SeasonWeek, SolarTerm
|
||||
from common.enums import ArticleCategory, ErrorType
|
||||
from common.logger import LOG
|
||||
from common.utils.kma_time import now_kst
|
||||
from common.utils.text import day_range
|
||||
from crud.season_crud import SeasonCRUD
|
||||
from services.external.data_go_kr import DataGoKrNotConfigured, DataGoKrRequestFailed
|
||||
from services.external.kasi import fetch_solar_terms
|
||||
@@ -52,7 +53,12 @@ class SeasonService:
|
||||
progress = None
|
||||
if now_t and next_t:
|
||||
progress = round((today - now_t.term_date).days / (next_t.term_date - now_t.term_date).days, 2)
|
||||
since_term = f"{now_t.name} 지나 {(today - now_t.term_date).days}일째" if now_t else f"{week}번째 주"
|
||||
if now_t is None:
|
||||
since_term = day_range(start, start + timedelta(days=6))
|
||||
elif now_t.term_date == today:
|
||||
since_term = f"오늘은 {now_t.name}"
|
||||
else:
|
||||
since_term = f"{now_t.name} 지나 {(today - now_t.term_date).days}일째"
|
||||
headline = f"{since_term}, {poem.headline}" if poem is not None else since_term
|
||||
return ErrorType.SUCCESS, SeasonWeekView(
|
||||
year=year, week=week, start=start, end=start + timedelta(days=6), headline=headline, poem=poem,
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import asyncio
|
||||
import math
|
||||
import statistics
|
||||
from dataclasses import dataclass
|
||||
from datetime import date, datetime, timedelta, timezone
|
||||
@@ -12,17 +13,22 @@ 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, SkyType
|
||||
from common.enums import ErrorType, SkyGrade, SkyType
|
||||
from common.logger import LOG
|
||||
from common.utils.geo import 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, Layers, best_times, confidence, grade, score
|
||||
from services.calc.sky_score import (
|
||||
DISTANCES_KM, GRADE_LABEL, VERDICT_LINE, Layers, best_times, confidence, grade, mean_layers, reason, score, sunset_timeline, verdict,
|
||||
)
|
||||
from services.calc.sun import SunTimes, sun_times
|
||||
from services.external.open_meteo import OpenMeteoRequestFailed, fetch_clouds, parse_clouds
|
||||
from services.week_service import EVENT_RADIUS_KM
|
||||
|
||||
DAYS = 3
|
||||
SPOT_RADIUS_KM = EVENT_RADIUS_KM
|
||||
SPOT_LIMIT = 3
|
||||
_MARKER_TTL = 24 * 3600
|
||||
_background: set[asyncio.Task] = set()
|
||||
|
||||
@@ -33,6 +39,22 @@ class Spot:
|
||||
distance_km: float
|
||||
|
||||
|
||||
@dataclass
|
||||
class SkyPlan:
|
||||
"""노을 탭 맨 위 결론: 나가 볼 만한지, 왜, 몇 시에 어디로."""
|
||||
day: date
|
||||
when: str
|
||||
verdict: str
|
||||
headline: str
|
||||
reason: str
|
||||
score: int
|
||||
grade_label: str
|
||||
best_at: Optional[datetime]
|
||||
spot: Optional[Spot]
|
||||
timeline: list[dict]
|
||||
outlook: str
|
||||
|
||||
|
||||
@dataclass
|
||||
class SkyView:
|
||||
region: Region
|
||||
@@ -41,6 +63,7 @@ class SkyView:
|
||||
sunrise: Optional[SkyScore]
|
||||
days: list[SkyScore]
|
||||
spots: list[Spot]
|
||||
plan: Optional[SkyPlan] = None
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -50,6 +73,57 @@ class RankItem:
|
||||
score: SkyScore
|
||||
|
||||
|
||||
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 = [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]
|
||||
|
||||
|
||||
_DAY_WORD = ("오늘", "내일", "모레")
|
||||
_FALLBACK_REASON = {"go": "구름 조건이 좋아요", "maybe": "구름 조건이 반반이에요", "rest": "구름 조건이 나빠요"}
|
||||
_OUTLOOK_GAP = 10
|
||||
|
||||
|
||||
def _word(d: date, today: date) -> str:
|
||||
i = (d - today).days
|
||||
return _DAY_WORD[i] if 0 <= i < len(_DAY_WORD) else f"{d.month}.{d.day}"
|
||||
|
||||
|
||||
def _subject(word: str) -> str:
|
||||
"""받침 있으면 '이', 없으면 '가'. 오늘이 · 모레가"""
|
||||
last = ord(word[-1]) - 0xAC00
|
||||
return f"{word}{'이' if 0 <= last < 11172 and last % 28 else '가'}"
|
||||
|
||||
|
||||
def outlook(target: SkyScore, days: list[SkyScore], today: date) -> str:
|
||||
"""target 다음 날들 중 가장 나은 날과 비교한다. 10점 넘게 차이 나야 낫다고 말한다."""
|
||||
later = [x for x in days if x.score_date > target.score_date]
|
||||
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)}도 비슷해요"
|
||||
|
||||
|
||||
def build_plan(target: SkyScore, st: SunTimes, layers: Optional[list[Layers]], spots: list[Spot], days: list[SkyScore], today: date) -> SkyPlan:
|
||||
v = verdict(target.score)
|
||||
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
|
||||
return SkyPlan(
|
||||
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)],
|
||||
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)),
|
||||
outlook=outlook(target, days, today),
|
||||
)
|
||||
|
||||
|
||||
def _slot(now: datetime) -> str:
|
||||
"""노을은 13시, 일출은 21시 이후 예보로 다시 계산한다."""
|
||||
return "am" if now.hour < 13 else "pm" if now.hour < 21 else "night"
|
||||
@@ -115,17 +189,45 @@ class SkyService:
|
||||
]
|
||||
if not sunsets:
|
||||
return ErrorType.EXTERNAL_API_ERROR, None
|
||||
err, spots = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.spots(s, region.code))
|
||||
lat, lon = float(region.lat), float(region.lon)
|
||||
dlat, dlon = SPOT_RADIUS_KM / 111, SPOT_RADIUS_KM / (111 * math.cos(math.radians(lat)))
|
||||
err, spots = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.spots_in_box(s, lat, lon, dlat, dlon))
|
||||
if err is not ErrorType.SUCCESS:
|
||||
LOG.error(f"[sky] spots {region.code}: {err.name}")
|
||||
near = nearest_spots(lat, lon, spots or [])
|
||||
first = sun_times(now.date(), lat, lon)
|
||||
plan = await self._plan(region, sunsets, near, now)
|
||||
return ErrorType.SUCCESS, SkyView(
|
||||
region=region,
|
||||
sunset_azimuth=sun_times(now.date(), lat, lon).sunset_azimuth,
|
||||
sunset_azimuth=first.sunset_azimuth,
|
||||
sunset=next((x for x in sunsets if x.score_date == now.date()), None),
|
||||
sunrise=upcoming_sunrise[0] if upcoming_sunrise else None,
|
||||
days=sunsets,
|
||||
spots=[Spot(spot=p, distance_km=round(haversine_km(lat, lon, float(p.lat), float(p.lon)), 1)) for p in (spots or [])],
|
||||
spots=near,
|
||||
plan=plan,
|
||||
)
|
||||
|
||||
async def _plan(self, region: Region, sunsets: list[SkyScore], spots: list[Spot], now: datetime) -> Optional[SkyPlan]:
|
||||
"""블루아워가 끝나기 전엔 오늘, 지나면 내일 노을로 결론을 낸다. 구름 층은 점수 계산 때 받은 값을 다시 읽는다."""
|
||||
lat, lon = float(region.lat), float(region.lon)
|
||||
target, st = None, None
|
||||
for x in sunsets:
|
||||
st = sun_times(x.score_date, lat, lon)
|
||||
if st.dusk_end_at > now:
|
||||
target = x
|
||||
break
|
||||
if target is None or st is None:
|
||||
return None
|
||||
err, rows = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.clouds_at(s, region.code, _nearest_hour(st.sunset_at)))
|
||||
if err is not ErrorType.SUCCESS:
|
||||
LOG.error(f"[sky] plan clouds {region.code}: {err.name}")
|
||||
by_km: dict[int, list[Layers]] = {}
|
||||
for r in rows or []:
|
||||
if r.kind == SkyType.SUNSET.value:
|
||||
by_km.setdefault(r.distance_km, []).append(Layers(r.cloud_low, r.cloud_mid, r.cloud_high))
|
||||
layers = [mean_layers(by_km[km]) for km in DISTANCES_KM if km in by_km]
|
||||
return build_plan(target, st, layers if len(layers) == len(DISTANCES_KM) else None, spots, sunsets, now.date())
|
||||
|
||||
async def ranking(self) -> tuple[ErrorType, list[RankItem]]:
|
||||
err, regions = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.ranking_regions(s))
|
||||
if err is not ErrorType.SUCCESS:
|
||||
|
||||
@@ -6,8 +6,10 @@ from typing import Optional
|
||||
|
||||
import httpx
|
||||
from fastapi import Depends
|
||||
from redis.exceptions import RedisError
|
||||
|
||||
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, SunTime, WeatherHourly
|
||||
from common.enums import ErrorType, RainType, Sky, SkyType, SlotTone
|
||||
@@ -19,12 +21,13 @@ from crud.weather_crud import WeatherCRUD
|
||||
from services.calc.sun import sun_times
|
||||
from services.calc.weather_calc import discomfort_index, feels_like_c
|
||||
from services.external.data_go_kr import DataGoKrNotConfigured, DataGoKrRequestFailed
|
||||
from services.external.kma import day_start_base, fetch_vilage, parse_vilage
|
||||
from services.external.kma import day_start_base, fetch_mid, fetch_vilage, latest_mid_base, parse_mid, parse_vilage
|
||||
|
||||
SLOT_HOURS = range(0, 24, 3)
|
||||
_WAIT_STEPS, _WAIT_SEC = 15, 0.2
|
||||
# 단기예보 끝날 몇 시간만 있는 날은 하루 값을 만들지 않는다 (중기예보 값을 덮어쓰지 않게).
|
||||
_MIN_DAY_HOURS = 8
|
||||
MID_DAYS = 11 # 중기예보가 닿는 오늘+10일까지
|
||||
_background: set[asyncio.Task] = set()
|
||||
|
||||
|
||||
@@ -60,11 +63,12 @@ def _hourly_rows(region_code: str, hourly: dict[datetime, dict], issued: datetim
|
||||
|
||||
|
||||
def _daily_rows(region_code: str, hourly: dict[datetime, dict], daily: dict[date, dict], issued: datetime) -> list[dict]:
|
||||
by_day: dict[date, list[dict]] = {}
|
||||
by_day: dict[date, list[tuple[datetime, dict]]] = {}
|
||||
for at, v in hourly.items():
|
||||
by_day.setdefault(at.date(), []).append(v)
|
||||
by_day.setdefault(at.date(), []).append((at, v))
|
||||
rows = []
|
||||
for d, vs in by_day.items():
|
||||
for d, hours in by_day.items():
|
||||
vs = [v for _, v in hours]
|
||||
if len(vs) < _MIN_DAY_HOURS and d not in daily:
|
||||
continue
|
||||
temps = [v["temp_c"] for v in vs]
|
||||
@@ -75,7 +79,9 @@ def _daily_rows(region_code: str, hourly: dict[datetime, dict], daily: dict[date
|
||||
"temp_max_c": daily.get(d, {}).get("temp_max_c", max(temps)),
|
||||
"sky": Counter(v["sky"] for v in vs).most_common(1)[0][0].value,
|
||||
"rain_type": (rains[0] if rains else RainType.NONE).value,
|
||||
"rain_prob": max(v["rain_prob"] for v in vs), "issued_at": issued,
|
||||
"rain_prob": max(v["rain_prob"] for v in vs),
|
||||
"rain_prob_am": max((v["rain_prob"] for t, v in hours if t.hour < 12), default=None),
|
||||
"rain_prob_pm": max((v["rain_prob"] for t, v in hours if t.hour >= 12), default=None), "issued_at": issued,
|
||||
})
|
||||
return rows
|
||||
|
||||
@@ -91,17 +97,17 @@ def _slot_view(at: datetime, row: Optional[WeatherHourly], sun: SunTime) -> tupl
|
||||
icon = "snow" if rain is RainType.SNOW else "rain"
|
||||
note = {RainType.SNOW: "눈", RainType.SHOWER: "소나기", RainType.SLEET: "비·눈"}.get(rain, f"비 {row.rain_prob}%")
|
||||
return icon, tone, note
|
||||
if is_sunset:
|
||||
return "sunset", tone, "노을"
|
||||
if sky is Sky.CLOUDY:
|
||||
return "cloud", tone, "흐림"
|
||||
if sky is Sky.PARTLY:
|
||||
return ("cloud" if is_night else "sun_cloud"), tone, "구름 조금"
|
||||
return ("cloud" if is_night else "sun_cloud"), tone, "구름 많음"
|
||||
if is_sunset:
|
||||
return "sunset", tone, "노을"
|
||||
if temp <= 10:
|
||||
return ("stars" if is_night else "sun"), tone, "쌀쌀"
|
||||
return ("moon" if is_night else "sun"), tone, "쌀쌀"
|
||||
if temp >= 28:
|
||||
return ("stars" if is_night else "sun"), tone, "더워요"
|
||||
return ("stars", tone, "맑음") if is_night else ("sun", tone, "햇볕")
|
||||
return ("moon" if is_night else "sun"), tone, "더워요"
|
||||
return ("moon", tone, "맑음") if is_night else ("sun", tone, "햇볕")
|
||||
|
||||
|
||||
def _headline(slots: list[Slot]) -> str:
|
||||
@@ -123,7 +129,8 @@ class WeatherService:
|
||||
self.crud = crud
|
||||
self.sky = sky
|
||||
|
||||
async def today(self, region_code: str) -> tuple[ErrorType, Optional[TodayWeather]]:
|
||||
async def today(self, region_code: str, day: Optional[date] = None) -> tuple[ErrorType, Optional[TodayWeather]]:
|
||||
"""day 하루의 3시간 칸. 기본은 오늘."""
|
||||
err, region = await DB_SESSION_MNG.execute_lambda(lambda s: self.regions.get(s, region_code))
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return err, None
|
||||
@@ -132,8 +139,9 @@ class WeatherService:
|
||||
|
||||
now = now_kst()
|
||||
await self.ensure_vilage(region, now)
|
||||
sun = await self._ensure_sun(region, now.date())
|
||||
start = kst_midnight(now.date())
|
||||
day = day or now.date()
|
||||
sun = await self._ensure_sun(region, day)
|
||||
start = kst_midnight(day)
|
||||
err, rows = await DB_SESSION_MNG.execute_lambda(
|
||||
lambda s: self.crud.hourly_between(s, region.code, start, start + timedelta(days=1))
|
||||
)
|
||||
@@ -142,9 +150,9 @@ class WeatherService:
|
||||
if not rows:
|
||||
return ErrorType.EXTERNAL_API_ERROR, None
|
||||
|
||||
err, sky_scores = await DB_SESSION_MNG.execute_lambda(lambda s: self.sky.scores(s, [region.code], now.date()))
|
||||
err, sky_scores = await DB_SESSION_MNG.execute_lambda(lambda s: self.sky.scores(s, [region.code], day))
|
||||
sunset_score = next(
|
||||
(x.score for x in sky_scores or [] if x.sky_type == SkyType.SUNSET.value and x.score_date == now.date()), None
|
||||
(x.score for x in sky_scores or [] if x.sky_type == SkyType.SUNSET.value and x.score_date == day), None
|
||||
)
|
||||
by_at = {r.forecast_at: r for r in rows}
|
||||
slots = []
|
||||
@@ -156,15 +164,16 @@ class WeatherService:
|
||||
note = f"노을 {sunset_score}"
|
||||
slots.append(Slot(at=at, row=row, icon=icon, tone=tone, note=note))
|
||||
issued = max((r.issued_at for r in rows), default=None)
|
||||
return ErrorType.SUCCESS, TodayWeather(region=region, day=now.date(), issued_at=issued, headline=_headline(slots), slots=slots)
|
||||
return ErrorType.SUCCESS, TodayWeather(region=region, day=day, issued_at=issued, headline=_headline(slots), slots=slots)
|
||||
|
||||
async def ensure_vilage(self, region: Region, now: datetime) -> None:
|
||||
async def ensure_vilage(self, region: Region, now: datetime, background: bool = True) -> None:
|
||||
"""예보가 지났으면 새로 받는다. 이미 있으면 뒤에서 갱신하고, background=False 면 받을 때까지 기다린다."""
|
||||
latest = latest_vilage_base(now)
|
||||
err, issued = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.latest_issued(s, region.code))
|
||||
if err is not ErrorType.SUCCESS or (issued is not None and issued >= latest):
|
||||
return
|
||||
if issued is None:
|
||||
await self._refresh(region, now, latest, wait=True)
|
||||
if issued is None or not background:
|
||||
await self._refresh(region, now, latest, wait=issued is None)
|
||||
return
|
||||
task = asyncio.create_task(self._refresh(region, now, latest, wait=False))
|
||||
_background.add(task)
|
||||
@@ -200,6 +209,32 @@ class WeatherService:
|
||||
])
|
||||
LOG.info(f"[weather] {region.code} base {base:%m-%d %H}시 hourly {len(hourly_rows)} daily {len(daily_rows)}: {err.name}")
|
||||
|
||||
async def ensure_mid(self, region: Region, now: datetime) -> None:
|
||||
base = latest_mid_base(now)
|
||||
key = f"mid:{region.code}:{base:%Y%m%d%H}"
|
||||
try:
|
||||
if await REDIS.conn.exists(key):
|
||||
return
|
||||
async with redis_lock(f"lock:mid:{region.code}") as acquired:
|
||||
if not acquired:
|
||||
return
|
||||
async with httpx.AsyncClient(timeout=20) as client:
|
||||
land, ta = await fetch_mid(client, region.mid_land_code, region.mid_temp_code, base)
|
||||
days = parse_mid(land, ta, base)
|
||||
rows = [
|
||||
{"region_code": region.code, "forecast_date": d, **{**v, "sky": v["sky"].value, "rain_type": v["rain_type"].value}, "issued_at": base}
|
||||
for d, v in days.items()
|
||||
if d < now.date() + timedelta(days=MID_DAYS)
|
||||
]
|
||||
err = await DB_SESSION_MNG.execute_lambda_run([lambda s: self.crud.upsert_daily(s, rows)])
|
||||
if err is ErrorType.SUCCESS:
|
||||
await REDIS.conn.set(key, "1", ex=13 * 3600)
|
||||
except (DataGoKrNotConfigured, DataGoKrRequestFailed, RedisError) as e:
|
||||
LOG.error(f"[weather] mid {region.code}: {e}")
|
||||
|
||||
async def sun(self, region: Region, d: date) -> Optional[SunTime]:
|
||||
return await self._ensure_sun(region, d)
|
||||
|
||||
async def _ensure_sun(self, region: Region, d: date) -> Optional[SunTime]:
|
||||
err, sun = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.get_sun(s, region.code, d))
|
||||
if err is not ErrorType.SUCCESS:
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import asyncio
|
||||
from dataclasses import dataclass
|
||||
from datetime import date, datetime, timedelta
|
||||
from datetime import date, timedelta
|
||||
from typing import Optional
|
||||
|
||||
import httpx
|
||||
@@ -13,15 +13,19 @@ 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.logger import LOG
|
||||
from common.utils.geo import haversine_km
|
||||
from common.utils.kma_time import KST, kst_midnight, now_kst
|
||||
from common.utils.text import hour_label
|
||||
from crud.index_crud import IndexCRUD
|
||||
from crud.region_crud import RegionCRUD
|
||||
from crud.weather_crud import WeatherCRUD
|
||||
from crud.week_crud import WeekCRUD
|
||||
from services.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.data_go_kr import DataGoKrNotConfigured, DataGoKrRequestFailed
|
||||
from services.external.kasi import fetch_holidays
|
||||
from services.external.kma import fetch_mid, latest_mid_base, parse_mid
|
||||
from services.external.tour_api import IMAGE_CREDIT as TOUR_CREDIT
|
||||
from services.external.tour_api import fetch_festivals, parse_festivals
|
||||
from services.index_service import IndexService
|
||||
|
||||
@@ -29,9 +33,12 @@ DAYS = 11 # 중기예보가 닿는 오늘+10일까지
|
||||
EVENT_DAYS = 30
|
||||
# 몇 달씩 이어지는 상설 행사는 '이번 주 행사'로 보이지 않게 뺀다.
|
||||
MAX_EVENT_DAYS = 60
|
||||
EVENT_RADIUS_KM = 30
|
||||
# 행사는 시도 단위로 받는다. 구 중심이 이 거리 안에 있는 시도는 경계가 반경에 걸칠 수 있어 같이 받는다.
|
||||
_SIDO_REACH_KM = EVENT_RADIUS_KM + 20
|
||||
_ERRORS = (DataGoKrNotConfigured, DataGoKrRequestFailed, RedisError)
|
||||
_WEEKDAY_KO = ("월", "화", "수", "목", "금", "토", "일")
|
||||
_SKY_WORD = {Sky.CLEAR: "맑음", Sky.PARTLY: "구름많음", Sky.CLOUDY: "흐림"}
|
||||
_SKY_WORD = {Sky.CLEAR: "맑음", Sky.PARTLY: "구름 많음", Sky.CLOUDY: "흐림"}
|
||||
_RAIN_WORD = {RainType.RAIN: "비", RainType.SLEET: "비·눈", RainType.SNOW: "눈", RainType.SHOWER: "소나기"}
|
||||
|
||||
|
||||
@@ -48,6 +55,7 @@ class DayPlan:
|
||||
pick: str
|
||||
rain_hours: Optional[tuple[int, int]]
|
||||
is_rainy: bool
|
||||
rain_prob: int
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -62,6 +70,7 @@ class EventItem:
|
||||
status: str
|
||||
status_label: str
|
||||
fit: Optional[str]
|
||||
distance_km: Optional[float] = None
|
||||
|
||||
|
||||
def _icon(sky: Sky, rain: RainType) -> str:
|
||||
@@ -84,6 +93,35 @@ def _rain_hours(rows) -> Optional[tuple[int, int]]:
|
||||
return (rainy[0], rainy[-1] + 1) if rainy else None
|
||||
|
||||
|
||||
def image_credit(e: Event) -> Optional[str]:
|
||||
"""사진 출처 표기. 직접 넣은 행사(source_id 없음)는 출처를 모르니 None."""
|
||||
if not e.image_url or e.source_id is None:
|
||||
return None
|
||||
return CULTURE_CREDIT if e.source_id.startswith(CULTURE_PREFIX) else TOUR_CREDIT
|
||||
|
||||
|
||||
def nearby_sidos(region: Region, regions: list[Region]) -> list[str]:
|
||||
"""반경 안에 걸칠 수 있는 시도들. 자기 시도는 항상 앞에."""
|
||||
lat, lon = float(region.lat), float(region.lon)
|
||||
near = {r.code[:2] for r in regions if haversine_km(lat, lon, float(r.lat), float(r.lon)) <= _SIDO_REACH_KM}
|
||||
return [region.code[:2]] + sorted(near - {region.code[:2]})
|
||||
|
||||
|
||||
def event_distance(region: Region, e: Event) -> Optional[float]:
|
||||
if e.lat is None or e.lon is None:
|
||||
return None
|
||||
return round(haversine_km(float(region.lat), float(region.lon), float(e.lat), float(e.lon)), 1)
|
||||
|
||||
|
||||
def is_nearby(region: Region, e: Event, distance_km: Optional[float]) -> bool:
|
||||
"""좌표가 있으면 반경 안, 없으면 같은 구(구를 아는 행사) 또는 같은 시도."""
|
||||
if distance_km is not None:
|
||||
return distance_km <= EVENT_RADIUS_KM
|
||||
if e.region_code is not None:
|
||||
return e.region_code == region.code
|
||||
return e.sido_code == region.code[:2]
|
||||
|
||||
|
||||
def _status(e: Event, today: date) -> tuple[str, str]:
|
||||
if e.start_date <= today <= e.end_date:
|
||||
return "live", "진행 중"
|
||||
@@ -116,7 +154,7 @@ class WeekService:
|
||||
return err, []
|
||||
now = now_kst()
|
||||
today = now.date()
|
||||
await asyncio.gather(self.index_service.ensure(region, now), self._ensure_mid(region, now), self._ensure_holidays(today))
|
||||
await asyncio.gather(self.index_service.ensure(region, now), self._ensure_holidays(today))
|
||||
last = today + timedelta(days=DAYS - 1)
|
||||
start = kst_midnight(today)
|
||||
err, daily = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.daily(s, region.code, today, last))
|
||||
@@ -131,14 +169,14 @@ class WeekService:
|
||||
for d in daily:
|
||||
rows = [r for r in hourly or [] if r.forecast_at.astimezone(KST).date() == d.forecast_date]
|
||||
rain_hours = _rain_hours(rows)
|
||||
top = sorted((x for x in scores or [] if x.score_date == d.forecast_date), key=lambda x: x.score, reverse=True)[:2]
|
||||
top = sorted((x for x in scores or [] if x.score_date == d.forecast_date and not x.estimated), key=lambda x: x.score, reverse=True)[:2]
|
||||
holiday = (holidays or {}).get(d.forecast_date)
|
||||
weekday = _WEEKDAY_KO[d.forecast_date.weekday()]
|
||||
word = _weather_word(d, rain_hours)
|
||||
temps = f" {round(float(d.temp_min_c))}~{round(float(d.temp_max_c))}°" if d.temp_min_c is not None and d.temp_max_c is not None else ""
|
||||
is_rainy = d.rain_type != RainType.NONE.value
|
||||
if top:
|
||||
summary = ", ".join(f"{names.get(x.index_id, '')} {x.score}" for x in top)
|
||||
summary = ", ".join(f"{names.get(x.index_id, '')} {x.score}점" for x in top)
|
||||
pick = "비 오는 날, 실내 일정이 좋아요" if is_rainy else f"{names.get(top[0].index_id, '')} 추천"
|
||||
else:
|
||||
summary, pick = f"비 확률 {d.rain_prob}%", ("실내 일정이 좋아요" if is_rainy else "바깥 일정 잡기 좋아요")
|
||||
@@ -147,6 +185,7 @@ class WeekService:
|
||||
temp_min_c=float(d.temp_min_c) if d.temp_min_c is not None else None,
|
||||
temp_max_c=float(d.temp_max_c) if d.temp_max_c is not None else None,
|
||||
headline=f"{weekday}요일 · {word}{temps}", summary=summary, pick=pick, rain_hours=rain_hours, is_rainy=is_rainy,
|
||||
rain_prob=d.rain_prob,
|
||||
))
|
||||
return ErrorType.SUCCESS, plans
|
||||
|
||||
@@ -170,18 +209,23 @@ class WeekService:
|
||||
return err, []
|
||||
now = now_kst()
|
||||
today = now.date()
|
||||
sido = region.code[:2]
|
||||
err, regions = await DB_SESSION_MNG.execute_lambda(lambda s: self.regions.search(s))
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return err, []
|
||||
sidos = nearby_sidos(region, regions)
|
||||
await asyncio.gather(
|
||||
self._ensure_events(sido, today), self.index_service.weather_service.ensure_vilage(region, now), self._ensure_mid(region, now)
|
||||
*(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),
|
||||
)
|
||||
err, events = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.events(s, sido, today, today + timedelta(days=EVENT_DAYS)))
|
||||
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)))
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return err, []
|
||||
by_day = {d.forecast_date: d for d in daily or []}
|
||||
items = []
|
||||
events = sorted((e for e in events if (e.end_date - e.start_date).days <= MAX_EVENT_DAYS), key=lambda e: abs((e.start_date - today).days))
|
||||
for e in events:
|
||||
near = [(e, event_distance(region, e)) for e in events if (e.end_date - e.start_date).days <= MAX_EVENT_DAYS]
|
||||
near = sorted(((e, d) for e, d in near if is_nearby(region, e, d)), key=lambda x: (abs((x[0].start_date - today).days), x[1] if x[1] is not None else EVENT_RADIUS_KM))
|
||||
for e, dist in near:
|
||||
if area is not None and e.area not in (None, area):
|
||||
continue
|
||||
status, label = _status(e, today)
|
||||
@@ -191,32 +235,9 @@ class WeekService:
|
||||
if d is not None:
|
||||
temp = f" {round(float(d.temp_max_c))}°" if d.temp_max_c is not None else ""
|
||||
fit = f"{_WEEKDAY_KO[first.weekday()]}요일 {_weather_word(d, None)}{temp}"
|
||||
items.append(EventItem(event=e, status=status, status_label=label, fit=fit))
|
||||
items.append(EventItem(event=e, status=status, status_label=label, fit=fit, distance_km=dist))
|
||||
return ErrorType.SUCCESS, items
|
||||
|
||||
async def _ensure_mid(self, region: Region, now: datetime) -> None:
|
||||
base = latest_mid_base(now)
|
||||
key = f"mid:{region.code}:{base:%Y%m%d%H}"
|
||||
try:
|
||||
if await REDIS.conn.exists(key):
|
||||
return
|
||||
async with redis_lock(f"lock:mid:{region.code}") as acquired:
|
||||
if not acquired:
|
||||
return
|
||||
async with httpx.AsyncClient(timeout=20) as client:
|
||||
land, ta = await fetch_mid(client, region.mid_land_code, region.mid_temp_code, base)
|
||||
days = parse_mid(land, ta, base)
|
||||
rows = [
|
||||
{"region_code": region.code, "forecast_date": d, **{**v, "sky": v["sky"].value, "rain_type": v["rain_type"].value}, "issued_at": base}
|
||||
for d, v in days.items()
|
||||
if d < now.date() + timedelta(days=DAYS)
|
||||
]
|
||||
err = await DB_SESSION_MNG.execute_lambda_run([lambda s: self.weather.upsert_daily(s, rows)])
|
||||
if err is ErrorType.SUCCESS:
|
||||
await REDIS.conn.set(key, "1", ex=13 * 3600)
|
||||
except _ERRORS as e:
|
||||
LOG.error(f"[week] mid {region.code}: {e}")
|
||||
|
||||
async def _ensure_holidays(self, today: date) -> None:
|
||||
for year in sorted({today.year, (today + timedelta(days=DAYS)).year}):
|
||||
key = f"holiday:{year}"
|
||||
@@ -238,6 +259,14 @@ class WeekService:
|
||||
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:
|
||||
@@ -248,6 +277,7 @@ class WeekService:
|
||||
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)
|
||||
|
||||
@@ -0,0 +1,158 @@
|
||||
from dataclasses import dataclass
|
||||
from datetime import date, datetime
|
||||
from typing import Optional
|
||||
|
||||
from common.utils.kma_time import KST
|
||||
from common.utils.text import day_range, short_day
|
||||
from services.week_service import DayPlan, EventItem, image_credit
|
||||
|
||||
_HOT = 28
|
||||
_COLD = 10
|
||||
_BIG_GAP = 10
|
||||
_MAX_EVENTS = 2
|
||||
|
||||
|
||||
@dataclass
|
||||
class Step:
|
||||
time: str
|
||||
icon: str
|
||||
title: str
|
||||
sub: str
|
||||
image: Optional[str] = None
|
||||
image_credit: Optional[str] = None
|
||||
|
||||
|
||||
@dataclass
|
||||
class WeekendForecast:
|
||||
line: str
|
||||
tip: Optional[str]
|
||||
caption: str
|
||||
|
||||
|
||||
@dataclass
|
||||
class DayPlanCard:
|
||||
eyebrow: str
|
||||
line: str
|
||||
steps: list[Step]
|
||||
caption: str
|
||||
|
||||
|
||||
def _gap(d: DayPlan) -> Optional[float]:
|
||||
return d.temp_max_c - d.temp_min_c if d.temp_max_c is not None and d.temp_min_c is not None else None
|
||||
|
||||
|
||||
def _deg(v: Optional[float]) -> str:
|
||||
return f"{round(v)}°" if v is not None else "-"
|
||||
|
||||
|
||||
def forecast(days: list[DayPlan]) -> WeekendForecast:
|
||||
"""주말 예보 카드의 큰 줄·팁·캡션. 비 > 더위 > 추위 > 일교차 순으로 하나만 짚는다."""
|
||||
rainy = [d for d in days if d.is_rainy]
|
||||
clear = [d for d in days if not d.is_rainy]
|
||||
names = "·".join(d.weekday for d in days)
|
||||
if not rainy and all(d.icon == "sun" for d in days):
|
||||
line = f"{names} {'둘 다 ' if len(days) > 1 else ''}맑음!\n나들이 확정각"
|
||||
elif not rainy:
|
||||
line = f"{names} 비 소식 없음!\n{'흐려도' if any(d.icon == 'cloud' for d in days) else '구름 좀 껴도'} 나들이각"
|
||||
elif not clear:
|
||||
line = f"{names} {'내내 ' if len(days) > 1 else ''}비 소식\n실내 일정 각"
|
||||
else:
|
||||
line = f"{clear[0].weekday}요일이 정답!\n{rainy[0].weekday}요일은 비 와요"
|
||||
lows = [d.temp_min_c for d in days if d.temp_min_c is not None]
|
||||
highs = [d.temp_max_c for d in days if d.temp_max_c is not None]
|
||||
gaps = [g for g in (_gap(d) for d in days) if g is not None]
|
||||
if rainy:
|
||||
tip = f"{rainy[0].weekday}요일은 비 {rainy[0].rain_prob}%, 우산 꼭 챙겨요!"
|
||||
elif highs and max(highs) >= _HOT:
|
||||
tip = f"낮 최고 {_deg(max(highs))}, 물이랑 모자 챙기기!"
|
||||
elif lows and min(lows) <= _COLD:
|
||||
tip = f"아침 {_deg(min(lows))}까지 떨어져요. 두꺼운 겉옷 필수!"
|
||||
elif gaps and max(gaps) >= _BIG_GAP:
|
||||
tip = f"아침저녁 {_deg(min(lows))}라 반팔만 입으면 큰일 나요. 겉옷 하나 꼭!"
|
||||
else:
|
||||
tip = None
|
||||
carry = "우산" if rainy else "겉옷" if tip else "가벼운 옷"
|
||||
caption = f"이번 주말은 {carry}만 챙기면 돼요. 토·일 플랜은 피드에 따로 올려둘게요."
|
||||
return WeekendForecast(line=line, tip=tip, caption=caption)
|
||||
|
||||
|
||||
def pick_events(d: date, events: list[EventItem], exclude: frozenset[int] = frozenset()) -> list[EventItem]:
|
||||
"""그날 열리는 행사 중 가까운 순. 일요일은 그날 끝나는 것을 먼저 (마지막 날 찬스)."""
|
||||
sunday = d.weekday() == 6
|
||||
open_ = [e for e in events if e.event.start_date <= d <= e.event.end_date and e.event.event_id not in exclude]
|
||||
open_.sort(key=lambda e: (sunday and e.event.end_date != d, e.distance_km if e.distance_km is not None else 9999))
|
||||
return open_[:_MAX_EVENTS]
|
||||
|
||||
|
||||
def _place(e: EventItem) -> str:
|
||||
parts = e.event.place_name.split()
|
||||
return " ".join(parts[1:3]) if len(parts) >= 3 else e.event.place_name
|
||||
|
||||
|
||||
def _event_step(time: str, e: EventItem, d: date) -> Step:
|
||||
if e.event.end_date == d:
|
||||
parts = ["오늘이 마지막 날", _place(e)]
|
||||
elif e.event.start_date == d:
|
||||
parts = ["오늘 시작", _place(e)]
|
||||
else:
|
||||
parts = [_place(e), day_range(e.event.start_date, e.event.end_date)]
|
||||
sub = " · ".join(x for x in parts if x)
|
||||
return Step(time=time, icon=e.event.icon, title=e.event.name, sub=sub, image=e.event.image_url, image_credit=image_credit(e.event))
|
||||
|
||||
|
||||
def day_plan(d: DayPlan, sunset_at: Optional[datetime], picks: list[EventItem], next_min: Optional[float]) -> DayPlanCard:
|
||||
"""그날 시간대별 동선. picks 는 pick_events 로 고른 행사. 일요일은 내일 출근을 생각해 일찍 들어오는 걸로 끝낸다."""
|
||||
ending = [e for e in picks if e.event.end_date == d.day] if d.day.weekday() == 6 else []
|
||||
gap = _gap(d)
|
||||
steps: list[Step] = []
|
||||
if d.rain_hours is not None:
|
||||
start, end = d.rain_hours
|
||||
steps.append(Step(time=f"{start}~{end}시", icon="umbrella", title="이 시간엔 실내로", sub=f"비 {d.rain_prob}% · 전시·카페 추천"))
|
||||
if start >= 13:
|
||||
steps.insert(0, Step(time=f"~{start}시", icon="sun", title="비 오기 전에 바깥", sub=f"최고 {_deg(d.temp_max_c)}"))
|
||||
elif end <= 16:
|
||||
steps.append(Step(time=f"{end}시~", icon="sun", title="비 그치면 바깥", sub=f"최고 {_deg(d.temp_max_c)}"))
|
||||
elif d.is_rainy:
|
||||
steps.append(Step(time="종일", icon="umbrella", title="실내로 알차게", sub=f"비 {d.rain_prob}% · 전시·카페·영화"))
|
||||
else:
|
||||
if gap is not None and gap >= _BIG_GAP:
|
||||
steps.append(Step(time="오전", icon="coldwind", title="겉옷 입고 출발", sub=f"아침 {_deg(d.temp_min_c)}, 쌀쌀해요"))
|
||||
hot = d.temp_max_c is not None and d.temp_max_c >= _HOT
|
||||
steps.append(Step(time="12~16시", icon=d.icon, title="그늘 찾아 바깥" if hot else "바깥 골든타임", sub=f"최고 {_deg(d.temp_max_c)}" + (", 물 챙기기" if hot else ", 걷기 딱 좋아요")))
|
||||
for t, e in zip(["오전", "오후"] if len(picks) > 1 else ["오후"], picks):
|
||||
steps.append(_event_step(t, e, d.day))
|
||||
if d.day.weekday() == 6:
|
||||
steps.append(Step(time="저녁", icon="moon", title="일찍 귀가 추천", sub=f"월요일 아침 {_deg(next_min)}" if next_min is not None else "내일은 월요일"))
|
||||
elif sunset_at is not None:
|
||||
steps.append(Step(time=f"{sunset_at.astimezone(KST):%H:%M}", icon="sunset", title="노을 보고 저녁", sub="해 지면 금방 쌀쌀해져요" if gap is not None and gap >= _BIG_GAP else "바깥 자리에서 저녁"))
|
||||
steps = _sort(steps)
|
||||
if ending:
|
||||
line = f"오늘 끝나는 축제\n{len(ending)}개나 있어요!" if len(ending) > 1 else f"{ending[0].event.name}\n오늘이 마지막 날!"
|
||||
caption = f"{d.weekday}요일엔 끝나는 축제부터 챙기기. 놓치면 내년이에요 🥲"
|
||||
elif d.is_rainy:
|
||||
line = f"비 오는 {d.weekday}요일,\n실내로 알차게"
|
||||
caption = f"{d.weekday}요일은 우산 필수. 비 피해서 알차게 놀아요!"
|
||||
elif d.icon == "sun":
|
||||
line = "해 좋은 낮 4시간,\n밖에서 꽉 채우기"
|
||||
caption = f"{d.weekday}요일은 낮이 제일 예뻐요. 12시부터 16시까지는 무조건 밖으로!"
|
||||
else:
|
||||
line = f"{'흐려도' if d.icon == 'cloud' else '구름 좀 껴도'} 비는 없어요,\n낮엔 밖으로"
|
||||
caption = f"{d.weekday}요일은 비 소식 없어요. 12시부터 16시까지 바깥 일정 잡기 좋아요!"
|
||||
eyebrow = f"{d.weekday}요일 {short_day(d.day)} · " + ("마지막 날 찬스" if ending else "이렇게 놀아요")
|
||||
return DayPlanCard(eyebrow=eyebrow, line=line, steps=steps, caption=caption)
|
||||
|
||||
|
||||
_ORDER = {"오전": 1, "종일": 2, "오후": 4, "저녁": 6}
|
||||
|
||||
|
||||
def _sort(steps: list[Step]) -> list[Step]:
|
||||
"""시간 라벨 순서대로. 숫자 시각은 오전·한낮·노을(17시 이후, 저녁 칸 앞) 자리로."""
|
||||
def key(s: Step) -> float:
|
||||
t = s.time
|
||||
if t[0].isdigit():
|
||||
h = int(t.split("~")[0].split(":")[0])
|
||||
return 5.5 if h >= 17 else 1.5 if h < 12 else 3
|
||||
if t.startswith("~"):
|
||||
return 0
|
||||
return _ORDER.get(t, 4)
|
||||
return sorted(steps, key=key)
|
||||
@@ -0,0 +1,217 @@
|
||||
import asyncio
|
||||
import csv
|
||||
import json
|
||||
import os
|
||||
from dataclasses import asdict, dataclass
|
||||
from datetime import date, datetime, timedelta
|
||||
from functools import lru_cache
|
||||
from types import SimpleNamespace
|
||||
from typing import Optional
|
||||
|
||||
from redis.exceptions import RedisError
|
||||
|
||||
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
|
||||
from common.enums import ErrorType, RainType, Sky
|
||||
from common.logger import LOG
|
||||
from common.utils.geo import haversine_km
|
||||
from common.utils.kma_time import kst_midnight, now_kst
|
||||
from crud.region_crud import RegionCRUD
|
||||
from crud.sky_crud import SkyCRUD
|
||||
from crud.weather_crud import WeatherCRUD
|
||||
from crud.week_crud import WeekCRUD
|
||||
from services.calc.index_calc import OUTING_HOURS, outing, outing_estimate
|
||||
from services.index_service import day_forecast, windows_for
|
||||
from services.weather_service import WeatherService
|
||||
from services.week_service import _icon
|
||||
|
||||
# 주말 전국 날씨 순위·당일치기 추천. 대표 지역(노을 순위 30곳)과 당일치기 후보 도시의 토·일 나들이 점수를
|
||||
# 워커가 하루 두 번(06:40·18:40) 미리 계산해 Redis 에 둔다. 없으면 순위 API 가 그 자리에서 계산한다.
|
||||
_SEED = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "seed", "trip_city.csv")
|
||||
_KEY = "weekend_rank:{:%Y%m%d}"
|
||||
_TTL = 13 * 3600
|
||||
_PARALLEL = 4 # 기상청 동시 호출 수
|
||||
_WAIT_STEPS, _WAIT_SEC = 60, 0.5
|
||||
_WINDOW = SimpleNamespace(windows=[{"from": OUTING_HOURS[0], "to": OUTING_HOURS[1]}])
|
||||
# 당일치기: 내 지역에서 직선 이 거리 안의 후보 도시만 (1~2시간 거리), 너무 가까운 곳(같은 동네)은 뺀다.
|
||||
TRIP_MIN_KM, TRIP_MAX_KM = 20, 200
|
||||
TRIP_MIN_SCORE = 50
|
||||
|
||||
|
||||
@dataclass
|
||||
class DayScore:
|
||||
region_code: str
|
||||
day: date
|
||||
score: int
|
||||
reason: str
|
||||
icon: str
|
||||
temp_min_c: Optional[float]
|
||||
temp_max_c: Optional[float]
|
||||
rain_prob: int
|
||||
estimated: bool
|
||||
|
||||
|
||||
@dataclass
|
||||
class TripCity:
|
||||
name: str
|
||||
label: str
|
||||
note: str
|
||||
|
||||
|
||||
@dataclass
|
||||
class TripPick:
|
||||
city: Region
|
||||
label: str
|
||||
note: str
|
||||
distance_km: int
|
||||
best: DayScore
|
||||
runner_up: Optional[tuple[str, DayScore]]
|
||||
|
||||
|
||||
@lru_cache(maxsize=1)
|
||||
def trip_cities() -> tuple[TripCity, ...]:
|
||||
"""당일치기 후보 도시 (seed/trip_city.csv). 늘리려면 이 파일에 줄만 더한다."""
|
||||
with open(_SEED, encoding="utf-8") as f:
|
||||
return tuple(TripCity(**row) for row in csv.DictReader(f))
|
||||
|
||||
|
||||
def weekend_days(today: date) -> list[date]:
|
||||
"""이번 주 토·일 중 오늘 이후."""
|
||||
sat = today + timedelta(days=5 - today.weekday())
|
||||
return [d for d in (sat, sat + timedelta(days=1)) if d >= today]
|
||||
|
||||
|
||||
def _sat(today: date) -> date:
|
||||
return today + timedelta(days=5 - today.weekday())
|
||||
|
||||
|
||||
def rank_days(scores: list[DayScore], codes: set[str], days: list[date]) -> list[tuple[date, list[DayScore]]]:
|
||||
"""날마다 점수 높은 순. 같으면 비 확률 낮은 순."""
|
||||
return [(d, sorted((x for x in scores if x.day == d and x.region_code in codes), key=lambda x: (-x.score, x.rain_prob, x.region_code))) for d in days]
|
||||
|
||||
|
||||
def pick_trip(region: Region, scores: list[DayScore], cities: dict[str, tuple[Region, TripCity]], days: list[date]) -> Optional[TripPick]:
|
||||
"""내 지역에서 1~2시간 거리 후보 도시 중 이번 주말 하루라도 나들이 점수가 가장 높은 곳. 다른 도시 1위를 함께 돌려준다."""
|
||||
near = {}
|
||||
for code, (city, meta) in cities.items():
|
||||
km = haversine_km(float(region.lat), float(region.lon), float(city.lat), float(city.lon))
|
||||
if TRIP_MIN_KM <= km <= TRIP_MAX_KM:
|
||||
near[code] = (city, meta, round(km))
|
||||
best_by_city = {}
|
||||
for x in scores:
|
||||
if x.region_code in near and x.day in days:
|
||||
cur = best_by_city.get(x.region_code)
|
||||
if cur is None or (x.score, -x.rain_prob, -x.day.toordinal()) > (cur.score, -cur.rain_prob, -cur.day.toordinal()):
|
||||
best_by_city[x.region_code] = x
|
||||
ranked = sorted(best_by_city.values(), key=lambda x: (-x.score, x.rain_prob, x.day, near[x.region_code][2]))
|
||||
if not ranked or ranked[0].score < TRIP_MIN_SCORE:
|
||||
return None
|
||||
top = ranked[0]
|
||||
city, meta, km = near[top.region_code]
|
||||
second = (near[ranked[1].region_code][1].label, ranked[1]) if len(ranked) > 1 else None
|
||||
return TripPick(city=city, label=meta.label, note=meta.note, distance_km=km, best=top, runner_up=second)
|
||||
|
||||
|
||||
class WeekendRank:
|
||||
def __init__(self) -> None:
|
||||
self.regions, self.sky, self.weather, self.week = RegionCRUD(), SkyCRUD(), WeatherCRUD(), WeekCRUD()
|
||||
self.weather_service = WeatherService(self.regions, self.weather, self.sky)
|
||||
|
||||
async def targets(self) -> tuple[ErrorType, list[Region], dict[str, tuple[Region, TripCity]]]:
|
||||
"""순위 대표 지역과 당일치기 후보 도시."""
|
||||
err, ranking = await DB_SESSION_MNG.execute_lambda(lambda s: self.sky.ranking_regions(s))
|
||||
err2, regions = await DB_SESSION_MNG.execute_lambda(lambda s: self.regions.search(s))
|
||||
if ErrorType.DB_ERROR in (err, err2):
|
||||
return ErrorType.DB_ERROR, [], {}
|
||||
by_name = {r.name: r for r in regions}
|
||||
cities = {}
|
||||
for c in trip_cities():
|
||||
if c.name not in by_name:
|
||||
LOG.error(f"[weekend] trip_city.csv: region not found {c.name}")
|
||||
continue
|
||||
cities[by_name[c.name].code] = (by_name[c.name], c)
|
||||
return ErrorType.SUCCESS, ranking, cities
|
||||
|
||||
async def scores(self, now: Optional[datetime] = None, compute: bool = True) -> tuple[ErrorType, list[DayScore]]:
|
||||
"""이번 주말 점수. 캐시에 없고 compute 면 계산해 넣는다."""
|
||||
now = now or now_kst()
|
||||
days = weekend_days(now.date())
|
||||
key = _KEY.format(_sat(now.date()))
|
||||
try:
|
||||
cached = await REDIS.conn.get(key)
|
||||
except RedisError as e:
|
||||
LOG.error(f"[weekend] cache get: {e}")
|
||||
cached = None
|
||||
if cached:
|
||||
return ErrorType.SUCCESS, [x for x in _load(cached) if x.day in days]
|
||||
if not compute:
|
||||
return ErrorType.NOT_FOUND, []
|
||||
return await self.refresh(now)
|
||||
|
||||
async def refresh(self, now: Optional[datetime] = None) -> tuple[ErrorType, list[DayScore]]:
|
||||
now = now or now_kst()
|
||||
days = weekend_days(now.date())
|
||||
key = _KEY.format(_sat(now.date()))
|
||||
err, ranking, cities = await self.targets()
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return err, []
|
||||
targets = list({r.code: r for r in ranking + [c for c, _ in cities.values()]}.values())
|
||||
async with redis_lock(f"lock:{key}", ttl_sec=120) as acquired:
|
||||
if not acquired:
|
||||
return await self._wait(key, days)
|
||||
gate = asyncio.Semaphore(_PARALLEL)
|
||||
out = await asyncio.gather(*(self._region(r, now, days, gate) for r in targets))
|
||||
scores = [x for xs in out for x in xs]
|
||||
if not scores:
|
||||
return ErrorType.EXTERNAL_API_ERROR, []
|
||||
try:
|
||||
await REDIS.conn.set(key, json.dumps([{**asdict(x), "day": x.day.isoformat()} for x in scores], ensure_ascii=False), ex=_TTL)
|
||||
except RedisError as e:
|
||||
LOG.error(f"[weekend] cache set: {e}")
|
||||
LOG.info(f"[weekend] {len(targets)} regions {len(scores)} scores")
|
||||
return ErrorType.SUCCESS, scores
|
||||
|
||||
async def _wait(self, key: str, days: list[date]) -> tuple[ErrorType, list[DayScore]]:
|
||||
"""다른 요청·워커가 계산 중이면 끝날 때까지 캐시를 본다."""
|
||||
for _ in range(_WAIT_STEPS):
|
||||
await asyncio.sleep(_WAIT_SEC)
|
||||
try:
|
||||
cached = await REDIS.conn.get(key)
|
||||
except RedisError as e:
|
||||
LOG.error(f"[weekend] cache wait: {e}")
|
||||
return ErrorType.CACHE_ERROR, []
|
||||
if cached:
|
||||
return ErrorType.SUCCESS, [x for x in _load(cached) if x.day in days]
|
||||
return ErrorType.EXTERNAL_API_ERROR, []
|
||||
|
||||
async def _region(self, region: Region, now: datetime, days: list[date], gate: asyncio.Semaphore) -> list[DayScore]:
|
||||
"""주말이 단기예보 안이면 10~17시 시간별로, 아니면 중기예보로 예상 점수."""
|
||||
async with gate:
|
||||
await asyncio.gather(self.weather_service.ensure_vilage(region, now, background=False), self.weather_service.ensure_mid(region, now))
|
||||
start = kst_midnight(days[0])
|
||||
err, hourly = await DB_SESSION_MNG.execute_lambda(lambda s: self.weather.hourly_between(s, region.code, start, start + timedelta(days=len(days))))
|
||||
err2, daily = await DB_SESSION_MNG.execute_lambda(lambda s: self.week.daily(s, region.code, days[0], days[-1]))
|
||||
if ErrorType.DB_ERROR in (err, err2):
|
||||
LOG.error(f"[weekend] {region.code}: DB_ERROR")
|
||||
return []
|
||||
by_at = {r.forecast_at: r for r in hourly}
|
||||
by_day = {d.forecast_date: d for d in daily}
|
||||
out = []
|
||||
for d in days:
|
||||
row = by_day.get(d)
|
||||
result = outing(windows_for(_WINDOW, d, region, by_at)[0]) or (outing_estimate(day_forecast(row)) if row else None)
|
||||
if result is None or row is None:
|
||||
continue
|
||||
out.append(DayScore(
|
||||
region_code=region.code, day=d, score=result.score, reason=result.reason, icon=_icon(Sky(row.sky), RainType(row.rain_type)),
|
||||
temp_min_c=float(row.temp_min_c) if row.temp_min_c is not None else None,
|
||||
temp_max_c=float(row.temp_max_c) if row.temp_max_c is not None else None,
|
||||
rain_prob=row.rain_prob, estimated=result.estimated,
|
||||
))
|
||||
return out
|
||||
|
||||
|
||||
def _load(raw: str) -> list[DayScore]:
|
||||
return [DayScore(**{**x, "day": date.fromisoformat(x["day"])}) for x in json.loads(raw)]
|
||||
@@ -118,10 +118,11 @@ def offline(monkeypatch):
|
||||
monkeypatch.setattr(warning_service, "fetch_warning_events", lambda *a: _async([]))
|
||||
monkeypatch.setattr(sky_service, "fetch_clouds", clouds)
|
||||
monkeypatch.setattr(jobs, "fetch_weather", openmeteo_weather)
|
||||
monkeypatch.setattr(week_service, "fetch_mid", lambda *a: _async(({}, {})))
|
||||
monkeypatch.setattr(weather_service, "fetch_mid", lambda *a: _async(({}, {})))
|
||||
monkeypatch.setattr(week_service, "fetch_holidays", lambda *a: _async([]))
|
||||
monkeypatch.setattr(week_service, "fetch_festivals", lambda *a: _async([{
|
||||
monkeypatch.setattr(week_service, "fetch_festivals", lambda c, sido, since: _async([{
|
||||
"contentid": "77", "title": "테스트 축제", "addr1": "서울", "eventstartdate": now.strftime("%Y%m%d"),
|
||||
"eventenddate": (now + timedelta(days=2)).strftime("%Y%m%d"),
|
||||
}]))
|
||||
"eventenddate": (now + timedelta(days=2)).strftime("%Y%m%d"), "firstimage": "http://tong.visitkorea.or.kr/test.jpg",
|
||||
}] if sido == "11" else []))
|
||||
monkeypatch.setattr(week_service, "fetch_exhibitions", lambda *a: _async([]))
|
||||
monkeypatch.setattr(season_service, "fetch_solar_terms", lambda *a: _async([]))
|
||||
@@ -0,0 +1,79 @@
|
||||
from datetime import date
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
|
||||
from config.settings import settings
|
||||
from services.external import culture_api
|
||||
from services.external.culture_api import fetch_exhibitions, parse_exhibitions
|
||||
from services.external.data_go_kr import DataGoKrRequestFailed
|
||||
|
||||
_ITEM = """<item><serviceName>공연/전시</serviceName><seq>{seq}</seq><title>{title}</title><startDate>{start}</startDate><endDate>{end}</endDate>
|
||||
<place>테스트 미술관</place><realmName>전시</realmName><area>서울</area><sigungu>종로구</sigungu><thumbnail>{thumb}</thumbnail>
|
||||
<gpsX>126.97689</gpsX><gpsY>37.57592</gpsY></item>"""
|
||||
|
||||
|
||||
def _page(items: list[str], total: int) -> str:
|
||||
return (f"<?xml version='1.0' encoding='UTF-8'?><response><header><resultCode>00</resultCode><resultMsg>NORMAL SERVICE.</resultMsg></header>"
|
||||
f"<body><items>{''.join(items)}</items><numOfrows>2</numOfrows><PageNo>1</PageNo><totalCount>{total}</totalCount></body></response>")
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
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)
|
||||
|
||||
|
||||
def _client(handler) -> httpx.AsyncClient:
|
||||
return httpx.AsyncClient(transport=httpx.MockTransport(handler))
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_fetch_exhibitions_pages_through_xml(key):
|
||||
seen = []
|
||||
|
||||
def handler(req: httpx.Request) -> httpx.Response:
|
||||
seen.append(dict(req.url.params))
|
||||
page = int(req.url.params["PageNo"])
|
||||
items = [_ITEM.format(seq=page * 10 + i, title=f"전시{page}-{i}", start="20261001", end="20261130", thumb="") for i in range(2 if page == 1 else 1)]
|
||||
return httpx.Response(200, text=_page(items, 3), headers={"content-type": "application/xml"})
|
||||
|
||||
async with _client(handler) as client:
|
||||
items = await fetch_exhibitions(client, "11", date(2026, 10, 6), 30)
|
||||
assert [it["title"] for it in items] == ["전시1-0", "전시1-1", "전시2-0"]
|
||||
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_reports_unregistered_key(key):
|
||||
body = ("<OpenAPI_ServiceResponse><cmmMsgHeader><errMsg>SERVICE_KEY_IS_NOT_REGISTERED_ERROR</errMsg>"
|
||||
"<returnAuthMsg>등록되지 않은 서비스키</returnAuthMsg><returnReasonCode>30</returnReasonCode></cmmMsgHeader></OpenAPI_ServiceResponse>")
|
||||
async with _client(lambda req: httpx.Response(403, text=body)) as client:
|
||||
with pytest.raises(DataGoKrRequestFailed, match="30 SERVICE_KEY_IS_NOT_REGISTERED_ERROR"):
|
||||
await fetch_exhibitions(client, "11", date(2026, 10, 6), 30)
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_fetch_exhibitions_skips_unknown_sido(key):
|
||||
async with _client(lambda req: pytest.fail("호출하면 안 된다")) as client:
|
||||
assert await fetch_exhibitions(client, "99", date(2026, 10, 6), 30) == []
|
||||
|
||||
|
||||
def test_parse_exhibitions_maps_fields_and_drops_ended_or_duplicate():
|
||||
items = [
|
||||
{"seq": "501", "title": "가을 특별전", "place": "테스트 미술관", "startDate": "20261001", "endDate": "2026-11-30",
|
||||
"thumbnail": "http://www.culture.go.kr/upload/a.jpg", "gpsX": "126.97689", "gpsY": "37.57592"},
|
||||
{"seq": "501", "title": "가을 특별전", "place": "테스트 미술관", "startDate": "20261001", "endDate": "20261130", "thumbnail": "", "gpsX": "", "gpsY": ""},
|
||||
{"seq": "502", "title": "끝난 전시", "place": "테스트 박물관", "startDate": "20260101", "endDate": "20261005"},
|
||||
{"seq": "503", "title": "날짜 없음", "place": "테스트 박물관", "startDate": "", "endDate": ""},
|
||||
{"seq": "504", "title": "좌표 뒤바뀜", "place": "테스트 박물관", "startDate": "20261001", "endDate": "20261010", "gpsX": "37.5", "gpsY": "127.0"},
|
||||
]
|
||||
rows = parse_exhibitions(items, "11", date(2026, 10, 6))
|
||||
assert [r["source_id"] for r in rows] == ["kcis:501", "kcis:504"]
|
||||
assert rows[0]["end_date"] == date(2026, 11, 30)
|
||||
assert rows[1]["lat"] == 37.5 and rows[1]["lon"] == 127.0
|
||||
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 all(len(r["source_id"]) <= 20 for r in rows)
|
||||
@@ -30,6 +30,18 @@ async def test_build_day_adds_weekend_post_every_day():
|
||||
assert (await _posts(thursday))[0] == PostType.WEATHER.value
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_build_day_adds_new_card_types_to_existing_day():
|
||||
"""이미 만든 날에 새 종류(미세먼지)가 생기면 빠진 카드만 더한다."""
|
||||
thursday = date(2026, 10, 15)
|
||||
await build_feed_day(thursday, FeedCRUD(), SeasonCRUD())
|
||||
await DB_SESSION_MNG.execute_lambda_run([lambda s: s.execute(text(f"DELETE FROM post WHERE feed_date='{thursday}' AND post_type={PostType.AIR.value}"))])
|
||||
before = len(await _posts(thursday))
|
||||
await build_feed_day(thursday, FeedCRUD(), SeasonCRUD())
|
||||
after = await _posts(thursday)
|
||||
assert len(after) == before + 1 and after.count(PostType.AIR.value) == 1
|
||||
|
||||
|
||||
def test_weekends_groups_this_and_next_weekend():
|
||||
from types import SimpleNamespace
|
||||
from services.feed_service import _weekends
|
||||
@@ -45,9 +57,16 @@ async def test_feed_assembles_hero_stories_posts_and_bands(offline):
|
||||
assert body["hero"]["temp_c"] == 20 and body["hero"]["top1"]["rank"] == 1 and "top3" not in body["hero"]
|
||||
assert len(body["stories"]) == 27
|
||||
weather = next(p for p in body["posts"] if p["post_type"] == PostType.WEATHER.value)
|
||||
assert [s["kind"] for s in weather["slides"]] == ["hours", "rows"]
|
||||
assert [s["kind"] for s in weather["slides"]] == ["hours", "hours"]
|
||||
assert len(weather["slides"][0]["hours"]) == 8
|
||||
assert body["bands"]["events"][0]["name"] == "테스트 축제"
|
||||
assert body["bands"]["events"][0]["image"] == "https://tong.visitkorea.or.kr/test.jpg"
|
||||
assert body["bands"]["events"][0]["image_credit"] == "ⓒ한국관광공사"
|
||||
assert "미세먼지" not in weather["caption"]
|
||||
air = next(p for p in body["posts"] if p["post_type"] == PostType.AIR.value)
|
||||
assert [(r["label"], r["value"]) for r in air["slides"][0]["rows"]] == [("초미세먼지", "10㎍/㎥ · 좋음"), ("미세먼지", "20㎍/㎥ · 좋음")]
|
||||
event = next(p for p in body["posts"] if p["post_type"] == PostType.EVENT.value)
|
||||
assert event["slides"][0]["eyebrow"].startswith("가까운 행사 · ")
|
||||
|
||||
|
||||
def test_feed_cache_expires_when_time_slot_changes():
|
||||
@@ -175,3 +194,142 @@ async def test_feed_missing_gak_is_cached_only_briefly(offline, monkeypatch):
|
||||
assert PostType.GAK.value not in [p["post_type"] for p in body["posts"]]
|
||||
keys = [k async for k in REDIS.conn.scan_iter(f"feed:{REGION}:*")]
|
||||
assert keys and 0 < await REDIS.conn.ttl(keys[0]) <= 60
|
||||
|
||||
|
||||
def _alert_ctx(warnings=(), rain_prob=0):
|
||||
from datetime import datetime
|
||||
from types import SimpleNamespace
|
||||
|
||||
from common.utils.kma_time import KST
|
||||
|
||||
now = datetime(2026, 10, 2, 9, tzinfo=KST)
|
||||
hourly = [SimpleNamespace(forecast_at=datetime(2026, 10, 2, 15, tzinfo=KST), rain_prob=rain_prob)]
|
||||
return SimpleNamespace(now=now, hourly=hourly, region=SimpleNamespace(short_name="종로구"), now_w=SimpleNamespace(warnings=list(warnings)))
|
||||
|
||||
|
||||
def _base():
|
||||
from datetime import datetime
|
||||
|
||||
return dict(post_id=1, post_type=PostType.ALERT, like_count=0, comment_count=0, published_at=datetime(2026, 10, 2))
|
||||
|
||||
|
||||
def _alert(ctx):
|
||||
from services.feed_service import FeedService
|
||||
|
||||
return FeedService._alert(None, _base(), ctx)
|
||||
|
||||
|
||||
def test_alert_uses_umbrella_only_for_rain():
|
||||
from common.enums import WarningLevel, WarningType
|
||||
from services.warning_service import WarningItem
|
||||
|
||||
heat = _alert(_alert_ctx([WarningItem(WarningType.HEAT, WarningLevel.ADVISORY, "폭염주의보")]))
|
||||
cold = _alert(_alert_ctx([WarningItem(WarningType.COLD, WarningLevel.WARNING, "한파경보")]))
|
||||
rain = _alert(_alert_ctx(rain_prob=60))
|
||||
assert heat.icon != "umbrella" and "우산" not in heat.share_messages[0]
|
||||
assert cold.icon == "coldwind" and "우산" not in cold.share_messages[0]
|
||||
assert rain.icon == "umbrella" and rain.share_messages[0].endswith("☔ 우산 챙겨!")
|
||||
|
||||
|
||||
def test_event_caption_adds_what_slide_lacks():
|
||||
from types import SimpleNamespace
|
||||
|
||||
from services.feed_service import _event_caption
|
||||
from services.week_service import EventItem
|
||||
|
||||
ev = lambda confirmed=True: SimpleNamespace(is_confirmed=confirmed) # noqa: E731
|
||||
full = EventItem(event=ev(), status="live", status_label="진행 중", fit="토요일 맑음 22°", distance_km=12.3)
|
||||
assert _event_caption(full) == "지금 진행 중 · 여기서 12km · 토요일 맑음 22°"
|
||||
bare = EventItem(event=ev(False), status="soon", status_label="D-12", fit=None)
|
||||
assert _event_caption(bare) == "올해 정확한 일정은 공식 안내로 확인해 주세요."
|
||||
|
||||
|
||||
def test_text_helpers_short_day_and_compass():
|
||||
from common.utils.text import compass, day_range
|
||||
|
||||
assert day_range(date(2026, 10, 4), date(2026, 10, 11)) == "10.4~10.11"
|
||||
assert compass(263) == "서" and compass(247) == "서남서"
|
||||
|
||||
|
||||
def _air(pm25, pm10, measured_hours_ago=0):
|
||||
from datetime import datetime
|
||||
from types import SimpleNamespace
|
||||
|
||||
from common.utils.kma_time import KST
|
||||
from services.feed_service import FeedService
|
||||
|
||||
now = datetime(2026, 10, 2, 9, 30, tzinfo=KST)
|
||||
air = None if pm25 is None and pm10 is None else SimpleNamespace(
|
||||
station_name="테스트", pm25=pm25, pm10=pm10, measured_at=now.replace(minute=0) - timedelta(hours=measured_hours_ago))
|
||||
ctx = SimpleNamespace(now=now, region=SimpleNamespace(short_name="종로구"), now_w=SimpleNamespace(air=air))
|
||||
return FeedService._air(None, _base() | {"post_type": PostType.AIR}, ctx)
|
||||
|
||||
|
||||
def test_air_post_shows_both_values_and_advice_only_when_bad():
|
||||
good = _air(10, 20)
|
||||
assert [r.label for r in good.slides[0].rows] == ["초미세먼지", "미세먼지"] and good.title == "미세먼지 좋음"
|
||||
bad = _air(40, 60)
|
||||
assert bad.title == "미세먼지 나쁨" and bad.slides[0].rows[-1].label == "이렇게 해요"
|
||||
very = _air(20, 160)
|
||||
assert very.title == "미세먼지 매우나쁨" and "측정소" in very.caption and very.slides[0].rows[1].value == "160㎍/㎥ · 매우나쁨"
|
||||
|
||||
|
||||
def test_air_post_off_without_fresh_data():
|
||||
assert _air(None, None) is None
|
||||
assert _air(10, 20, measured_hours_ago=4) is None
|
||||
|
||||
|
||||
def _score(code, day, score, prob=10):
|
||||
from services.weekend_rank import DayScore
|
||||
|
||||
return DayScore(region_code=code, day=day, score=score, reason=f"비 {prob}% · 체감 21° · 맑음", icon="sun", temp_min_c=12.0, temp_max_c=22.0,
|
||||
rain_prob=prob, estimated=False)
|
||||
|
||||
|
||||
def test_pick_trip_takes_best_city_within_reach():
|
||||
from types import SimpleNamespace
|
||||
|
||||
from services.weekend_rank import TripCity, pick_trip
|
||||
|
||||
sat, sun = date(2026, 10, 10), date(2026, 10, 11)
|
||||
bundang = SimpleNamespace(lat=37.38, lon=127.12)
|
||||
city = lambda code, lat, lon, label: (code, (SimpleNamespace(code=code, lat=lat, lon=lon), TripCity(name=label, label=label, note=""))) # noqa: E731
|
||||
cities = dict([city("gn", 37.75, 128.88, "강릉"), city("cc", 37.88, 127.73, "춘천"), city("bs", 35.16, 129.16, "부산")])
|
||||
scores = [_score("gn", sat, 70), _score("gn", sun, 88), _score("cc", sat, 80), _score("bs", sat, 99)]
|
||||
pick = pick_trip(bundang, scores, cities, [sat, sun])
|
||||
assert pick.label == "강릉" and pick.best.day == sun and 150 < pick.distance_km < 170
|
||||
assert pick.runner_up[0] == "춘천" and pick.runner_up[1].score == 80
|
||||
assert pick_trip(bundang, [_score("gn", sat, 40)], cities, [sat, sun]) is None
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_feed_has_day_trip_card_with_city_event(offline, monkeypatch):
|
||||
"""분당 사용자: 캐시된 주말 점수에서 강릉이 1위면 강릉 당일치기 카드 + 강릉 근처 행사 사진."""
|
||||
import json
|
||||
from dataclasses import asdict
|
||||
|
||||
import services.week_service as week_service
|
||||
from common.cache.redis_client import REDIS
|
||||
from common.utils.kma_time import now_kst
|
||||
from services.weekend_rank import _KEY, _sat, weekend_days
|
||||
|
||||
today = now_kst().date()
|
||||
day = weekend_days(today)[-1]
|
||||
scores = [_score("5115000000", day, 90), _score("5111000000", day, 75), _score("2611000000", day, 99)]
|
||||
await REDIS.conn.set(_KEY.format(_sat(today)), json.dumps([{**asdict(x), "day": x.day.isoformat()} for x in scores]))
|
||||
|
||||
async def festivals(client, sido, since):
|
||||
return [{"contentid": "51", "title": "강릉 커피축제", "addr1": "강원 강릉시", "mapy": "37.77", "mapx": "128.90",
|
||||
"eventstartdate": today.strftime("%Y%m%d"), "eventenddate": (today + timedelta(days=7)).strftime("%Y%m%d"),
|
||||
"firstimage": "http://tong.visitkorea.or.kr/c.jpg"}] if sido == "51" else []
|
||||
|
||||
monkeypatch.setattr(week_service, "fetch_festivals", festivals)
|
||||
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)
|
||||
first, event = trip["slides"]
|
||||
assert "강릉" in first["line"] and "90점" in first["line"]
|
||||
rows = dict((r["label"], r["value"]) for r in first["rows"])
|
||||
assert rows["거리"].startswith("여기서 약 ") and rows["날씨"] == "비 10% · 체감 21° · 맑음"
|
||||
assert "춘천" in trip["caption"]
|
||||
assert event["line"] == "강릉 커피축제" and event["image"] == "https://tong.visitkorea.or.kr/c.jpg"
|
||||
@@ -12,7 +12,7 @@ from common.database.model.models import OpenMeteoHourly, WeatherHourly
|
||||
from common.utils.kma_time import kst_midnight, now_kst
|
||||
from crud.weather_crud import WeatherCRUD
|
||||
from router.router import app
|
||||
from services.index_service import _nearest_slot_end_hour, _slot_end_hour, windows_for
|
||||
from services.index_service import _nearest_slot_end_hour, _slot_end_hour, slot_days, slot_label, windows_for
|
||||
|
||||
REGION = "1141000000"
|
||||
|
||||
@@ -31,6 +31,12 @@ def _vilage(*_):
|
||||
return items
|
||||
|
||||
|
||||
def _mid(*_):
|
||||
land = {f"wf{n}{p}": "맑음" for n in range(4, 11) for p in ("Am", "Pm")} | {f"rnSt{n}{p}": 10 for n in range(4, 11) for p in ("Am", "Pm")}
|
||||
ta = {f"taMin{n}": 12 for n in range(4, 11)} | {f"taMax{n}": 22 for n in range(4, 11)}
|
||||
return land, ta
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def fakes(monkeypatch):
|
||||
now = now_kst()
|
||||
@@ -41,17 +47,22 @@ def fakes(monkeypatch):
|
||||
"dataTime": now.replace(minute=0).strftime("%Y-%m-%d %H:%M"),
|
||||
}]))
|
||||
monkeypatch.setattr(warning_service, "fetch_warning_events", lambda *a: _async([]))
|
||||
monkeypatch.setattr(weather_service, "fetch_mid", lambda *a: _async(_mid()))
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_index_list_ranks_all_27_with_3_day_trend(fakes):
|
||||
async def test_index_list_ranks_all_27_with_today_tomorrow_weekend_trend(fakes):
|
||||
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
|
||||
body = (await client.get("/v1/index/list", params={"region": REGION})).json()
|
||||
assert body["result"]["success"] is True
|
||||
assert len(body["items"]) == 27 and len(body["top3"]) == 3
|
||||
scores = [i["score"] for i in body["items"]]
|
||||
assert scores == sorted(scores, reverse=True)
|
||||
assert all(len(i["trend"]) == 3 for i in body["items"])
|
||||
today = now_kst().date()
|
||||
for i in body["items"]:
|
||||
assert [t["label"] for t in i["trend"]] == [slot_label(d, today) for d in slot_days(today)]
|
||||
assert not any(t["estimated"] for t in i["trend"][:2])
|
||||
assert all(t["estimated"] for t in i["trend"][2:] if date.fromisoformat(t["day"]) > today + timedelta(days=3))
|
||||
assert 0 <= body["weather_score"] <= 100
|
||||
|
||||
|
||||
@@ -67,9 +78,9 @@ async def test_index_detail_has_six_factors_and_rules(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()
|
||||
assert body["index"]["code"] == "yajang"
|
||||
assert [f["label"] for f in body["factors"]] == ["기온", "비", "바람", "습도", "공기", "시간대"]
|
||||
assert [f["label"] for f in body["factors"]] == ["기온 알맞음", "비 안 옴", "바람 잔잔", "습도 알맞음", "공기 맑음", "요일 알맞음"]
|
||||
assert sum(f["weight"] for f in body["factors"]) == 100
|
||||
assert body["zero_rules"] == "비 확률 80% 이상 또는 바람 14m/s 이상이면 바로 0점"
|
||||
assert body["zero_rules"] == "비 확률 80% 이상이거나 바람 14m/s 이상이면 0점"
|
||||
assert body["limit"].startswith("모기")
|
||||
|
||||
|
||||
|
||||
@@ -1,8 +1,12 @@
|
||||
from dataclasses import replace
|
||||
from datetime import date, datetime, timezone
|
||||
from types import SimpleNamespace
|
||||
|
||||
from common.enums import RainType, Sky
|
||||
from services.calc.index_calc import Context, Hour, evaluate, rain_score, sun_score, temp_score, uv_score, view_score, zero_rules_text
|
||||
from services.calc.index_calc import (
|
||||
OUTING_HOURS, Context, DayForecast, Hour, axis_label, estimate, evaluate, hour_temp, outing, outing_estimate, rain_score, sun_score, temp_score,
|
||||
uv_score, view_score, zero_rules_text,
|
||||
)
|
||||
from services.calc.moon import illumination
|
||||
|
||||
CTX = Context(day=date(2026, 10, 2), is_holiday=False, pm25=10, air_label="좋음", moon=0.5, sunset_score=80, wind_warning=False, lookahead_rain_prob=0)
|
||||
@@ -44,7 +48,7 @@ def test_temp_peaks_at_best_and_loses_8_per_degree_outside():
|
||||
assert temp_score({"type": "range", "lo": 18, "hi": 24, "best": 22}, 22)[0] == 100
|
||||
assert temp_score({"type": "range", "lo": 18, "hi": 24}, 15)[0] == 61
|
||||
assert temp_score({"type": "lower", "zero": 25, "full": 5}, 15)[0] == 50
|
||||
assert temp_score({"type": "range", "lo": 10, "hi": 20, "offset": -6}, 21)[1].startswith("정상 15°")
|
||||
assert temp_score({"type": "range", "lo": 10, "hi": 20, "offset": -6}, 21)[1].startswith("산 정상 기준 15°")
|
||||
|
||||
|
||||
def test_temp_away_rises_outside_comfort():
|
||||
@@ -63,7 +67,28 @@ def test_rain_dry_and_wet():
|
||||
def test_zero_rule_forces_zero_and_cap_limits():
|
||||
assert evaluate(_defn(), [[_h(19, prob=80)]], CTX).score == 0
|
||||
capped = _defn(zero_rules=[{"field": "rain_prob", "op": ">=", "value": 70, "cap": 20}])
|
||||
assert evaluate(capped, [[_h(19, prob=70)]], CTX).score <= 20
|
||||
r = evaluate(capped, [[_h(19, prob=70)]], CTX)
|
||||
assert r.score <= 20 and r.zero_reason == "비 확률 70% 이상이라 최대 20점"
|
||||
assert evaluate(_defn(), [[_h(19, prob=80)]], CTX).zero_reason == "비 확률 80% 이상이라 0점"
|
||||
|
||||
|
||||
def test_lookahead_rain_is_named_in_note():
|
||||
defn = _defn(windows=[{"from": 9, "to": 18, "lookahead_days": 2}])
|
||||
r = evaluate(defn, [[_h(10, prob=0)]], replace(CTX, lookahead_rain_prob=60))
|
||||
assert r.notes["rain"] == "모레까지 비 확률 60%"
|
||||
assert evaluate(defn, [[_h(10, prob=0)]], CTX).notes["rain"] == "비 확률 0%"
|
||||
|
||||
|
||||
def test_air_note_has_unit():
|
||||
assert evaluate(_defn(), [[_h(19)]], CTX).notes["air"] == "초미세먼지 10㎍/㎥, 좋음"
|
||||
|
||||
|
||||
def test_axis_label_reads_outward_as_good():
|
||||
rules = _defn().factor_rules
|
||||
assert [axis_label(a, rules) for a in ("temp", "rain", "wind", "humidity", "air", "time")] == \
|
||||
["기온 알맞음", "비 안 옴", "바람 잔잔", "습도 알맞음", "공기 맑음", "요일 알맞음"]
|
||||
wet = {"temp": {"type": "lower"}, "rain": {"dir": "wet"}, "wind": {"type": "strong"}, "humidity": {"type": "higher"}, "time": {"type": "moon"}}
|
||||
assert [axis_label(a, wet) for a in ("temp", "rain", "wind", "humidity", "time")] == ["추움", "비 옴", "바람 셈", "습도 높음", "달 어두움"]
|
||||
|
||||
|
||||
def test_best_window_is_chosen():
|
||||
@@ -73,7 +98,11 @@ def test_best_window_is_chosen():
|
||||
|
||||
def test_zero_rules_text():
|
||||
assert zero_rules_text([{"field": "rain_prob", "op": ">=", "value": 80}, {"field": "wind_ms", "op": ">=", "value": 14}]) == \
|
||||
"비 확률 80% 이상 또는 바람 14m/s 이상이면 바로 0점"
|
||||
"비 확률 80% 이상이거나 바람 14m/s 이상이면 0점"
|
||||
assert zero_rules_text([{"field": "rain_prob", "op": ">=", "value": 70}, {"field": "warning", "op": "==", "value": "wind"}]) == \
|
||||
"비 확률 70% 이상이거나 강풍 특보가 있으면 0점"
|
||||
assert zero_rules_text([{"field": "rain_prob", "op": ">=", "value": 70, "cap": 20}]) == "비 확률 70% 이상이면 최대 20점"
|
||||
assert zero_rules_text([{"field": "pm25", "op": ">=", "value": 75}]) == "초미세먼지 75㎍/㎥ 이상이면 0점"
|
||||
assert zero_rules_text([]) == "없음 (재미로 보는 지수)"
|
||||
|
||||
|
||||
@@ -118,5 +147,75 @@ def test_gust_and_ground_temperature_zero_rules():
|
||||
assert evaluate(gust, [[_h(19, wind=1.0, gust_ms=10.0)]], CTX).score == 100
|
||||
assert evaluate(gust, [[_h(19, wind=1.0)]], CTX).score == 100 # 값이 없으면 걸리지 않는다
|
||||
ground = [{"field": "ground_c", "op": ">=", "value": 45}]
|
||||
assert zero_rules_text(ground) == "지표면 온도 45° 이상이면 바로 0점"
|
||||
assert evaluate(_defn(zero_rules=ground), [[_h(19, wind=1.0, ground_c=47.0)]], CTX).zero_reason == "지표면 온도 45° 이상이면"
|
||||
assert zero_rules_text(ground) == "지표면 온도 45° 이상이면 0점"
|
||||
assert evaluate(_defn(zero_rules=ground), [[_h(19, wind=1.0, ground_c=47.0)]], CTX).zero_reason == "지표면 온도 45° 이상이라 0점"
|
||||
|
||||
|
||||
def test_estimate_and_labels_cover_openmeteo_axes():
|
||||
r = estimate(_uv_defn(), _fc(), [[19, 20]], CTX)
|
||||
assert r.factors["uv"] == 70 and r.factors["sun"] == 0 and r.factors["view"] == 0
|
||||
assert [axis_label(a, {}) for a in ("uv", "sun", "view")] == ["자외선", "햇빛", "가시거리"]
|
||||
|
||||
|
||||
def _fc(lo=15.0, hi=23.0, am=0, pm=0, sky=Sky.CLEAR):
|
||||
return DayForecast(temp_min_c=lo, temp_max_c=hi, rain_prob_am=am, rain_prob_pm=pm, sky=sky)
|
||||
|
||||
|
||||
def test_hour_temp_follows_min_at_dawn_and_max_mid_afternoon():
|
||||
assert hour_temp(10, 20, 6) == 10 and hour_temp(10, 20, 15) == 20
|
||||
assert 10 < hour_temp(10, 20, 21) < 20 and hour_temp(10, 20, 30) == 10
|
||||
|
||||
|
||||
def test_estimate_is_flagged_and_unknown_factors_are_70():
|
||||
r = estimate(_defn(), _fc(), [[19, 20]], CTX)
|
||||
assert r.estimated is True
|
||||
assert r.factors["wind"] == 70 and r.factors["humidity"] == 70 and r.factors["air"] == 70
|
||||
assert "예상" in r.summary
|
||||
|
||||
|
||||
def test_estimate_uses_rain_prob_of_the_window_half_day():
|
||||
morning, evening = estimate(_defn(), _fc(am=60, pm=0), [[9, 10]], CTX), estimate(_defn(), _fc(am=60, pm=0), [[19, 20]], CTX)
|
||||
assert morning.factors["rain"] == 40 and evening.factors["rain"] == 100
|
||||
|
||||
|
||||
def test_estimate_applies_rain_zero_rule_only():
|
||||
r = estimate(_defn(zero_rules=[{"field": "rain_prob", "op": ">=", "value": 80}, {"field": "wind_ms", "op": ">=", "value": 1}]), _fc(pm=80), [[19]], CTX)
|
||||
assert r.score == 0 and r.zero_reason.startswith("비 확률 80% 이상")
|
||||
|
||||
|
||||
def test_estimate_without_temps_gives_none():
|
||||
assert estimate(_defn(), _fc(lo=None, hi=None), [[19]], CTX) is None
|
||||
|
||||
|
||||
def _day(**kw):
|
||||
return [_h(h, **kw) for h in range(*OUTING_HOURS)]
|
||||
|
||||
|
||||
def test_outing_perfect_day_is_100_and_reason_names_rain_temp_sky():
|
||||
r = outing(_day(wind=1.0))
|
||||
assert r.score == 100 and r.estimated is False
|
||||
assert r.reason == "비 0% · 체감 21° · 맑음"
|
||||
|
||||
|
||||
def test_outing_cloudy_and_hot_days_lose_points():
|
||||
clear, cloudy, hot = outing(_day()), outing(_day(sky=Sky.CLOUDY)), outing(_day(feels=30.0))
|
||||
assert cloudy.score < clear.score and hot.score < clear.score
|
||||
assert "흐림" in cloudy.reason
|
||||
|
||||
|
||||
def test_outing_rain_caps_score():
|
||||
r = outing(_day(prob=70))
|
||||
assert r.score <= 30 and r.capped
|
||||
assert outing([_h(10, prob=30, rain=RainType.RAIN)] + _day()[1:]).score <= 30
|
||||
|
||||
|
||||
def test_outing_needs_all_hours():
|
||||
assert outing(_day()[:3]) is None
|
||||
|
||||
|
||||
def test_outing_estimate_from_mid_forecast():
|
||||
r = outing_estimate(_fc(lo=12, hi=22, am=10, pm=20))
|
||||
assert r.estimated is True and r.factors["wind"] == 70
|
||||
assert r.reason.startswith("비 20% · 낮 ")
|
||||
assert outing_estimate(_fc(pm=60)).score <= 30
|
||||
assert outing_estimate(_fc(lo=None, hi=None)) is None
|
||||
@@ -0,0 +1,73 @@
|
||||
from datetime import date, timedelta
|
||||
from types import SimpleNamespace
|
||||
|
||||
from common.enums import RainType, Sky
|
||||
from common.utils.kma_time import kst_midnight
|
||||
from services.calc.index_calc import Context, DayForecast
|
||||
from services.index_service import day_result, slot_days, slot_label
|
||||
|
||||
REGION = SimpleNamespace(lat=37.56, lon=126.97)
|
||||
SAT = date(2026, 10, 10)
|
||||
CTX = Context(day=SAT, is_holiday=False, pm25=10, air_label="좋음", moon=0.5, sunset_score=None, wind_warning=False, lookahead_rain_prob=0)
|
||||
DEFN = SimpleNamespace(
|
||||
weight_temp=40, weight_rain=40, weight_wind=20, weight_humidity=0, weight_air=0, weight_time=0,
|
||||
factor_rules={
|
||||
"temp": {"type": "range", "lo": 18, "hi": 24}, "rain": {"dir": "dry"}, "wind": {"type": "calm", "ok": 4, "limit": 12},
|
||||
"humidity": {"type": "ignore"}, "time": {"type": "fixed", "value": 100},
|
||||
},
|
||||
zero_rules=[], windows=[{"from": 11, "to": 16}],
|
||||
)
|
||||
FC = {SAT: DayForecast(temp_min_c=12, temp_max_c=22, rain_prob_am=10, rain_prob_pm=20, sky=Sky.CLEAR)}
|
||||
|
||||
|
||||
def _hourly(day: date) -> dict:
|
||||
start = kst_midnight(day)
|
||||
return {
|
||||
start + timedelta(hours=h): SimpleNamespace(
|
||||
forecast_at=start + timedelta(hours=h), feels_c=21, rain_type=RainType.NONE.value, rain_prob=0, wind_ms=1.0, humidity=50, sky=Sky.CLEAR.value,
|
||||
)
|
||||
for h in range(24)
|
||||
}
|
||||
|
||||
|
||||
def _d(day: int) -> date:
|
||||
return date(2026, 10, day)
|
||||
|
||||
|
||||
def test_slots_on_weekdays_are_today_tomorrow_sat_sun():
|
||||
for today in (5, 6, 7, 8):
|
||||
assert slot_days(_d(today)) == [_d(today), _d(today + 1), _d(10), _d(11)]
|
||||
|
||||
|
||||
def test_slots_on_friday_keep_this_sunday_then_next_saturday():
|
||||
assert slot_days(_d(9)) == [_d(9), _d(10), _d(11), _d(17)]
|
||||
|
||||
|
||||
def test_slots_on_saturday_and_sunday_move_to_next_weekend():
|
||||
assert slot_days(_d(10)) == [_d(10), _d(11), _d(17), _d(18)]
|
||||
assert slot_days(_d(11)) == [_d(11), _d(12), _d(17), _d(18)]
|
||||
|
||||
|
||||
def test_slot_labels():
|
||||
today = date(2026, 10, 6)
|
||||
assert [slot_label(d, today) for d in slot_days(today)] == ["오늘", "내일", "토 10.10", "일 10.11"]
|
||||
assert [slot_label(d, _d(9)) for d in slot_days(_d(9))] == ["오늘", "내일", "일 10.11", "토 10.17"]
|
||||
|
||||
|
||||
def test_weekend_in_short_range_uses_hourly_score():
|
||||
r = day_result(DEFN, SAT, REGION, _hourly(SAT), FC, CTX, short=False)
|
||||
assert r.estimated is False and r.factors["wind"] == 100
|
||||
|
||||
|
||||
def test_weekend_beyond_short_range_uses_mid_forecast_estimate():
|
||||
r = day_result(DEFN, SAT, REGION, {}, FC, CTX, short=False)
|
||||
assert r.estimated is True and r.factors["wind"] == 70 and r.factors["rain"] == 80
|
||||
|
||||
|
||||
def test_partial_hourly_falls_back_to_estimate():
|
||||
partial = {k: v for k, v in _hourly(SAT).items() if k.hour < 13}
|
||||
assert day_result(DEFN, SAT, REGION, partial, FC, CTX, short=False).estimated is True
|
||||
|
||||
|
||||
def test_no_mid_forecast_gives_no_score():
|
||||
assert day_result(DEFN, SAT, REGION, {}, {}, CTX, short=False) is None
|
||||
@@ -0,0 +1,49 @@
|
||||
import pytest
|
||||
from httpx import ASGITransport, AsyncClient
|
||||
|
||||
import services.air_service as air_service
|
||||
import services.now_service as now_service
|
||||
import services.season_service as season_service
|
||||
import services.sky_service as sky_service
|
||||
import services.warning_service as warning_service
|
||||
import services.weather_service as weather_service
|
||||
import services.week_service as week_service
|
||||
from router.router import app
|
||||
from services.external.data_go_kr import DataGoKrRequestFailed
|
||||
from services.external.open_meteo import OpenMeteoRequestFailed
|
||||
|
||||
REGION = "1114000000"
|
||||
ENDPOINTS = ["/v1/feed", "/v1/weather/today", "/v1/weather/now", "/v1/sky", "/v1/week", "/v1/index/list", "/v1/season/week"]
|
||||
SOURCES = {
|
||||
"vilage": (weather_service, "fetch_vilage", DataGoKrRequestFailed),
|
||||
"ultra": (now_service, "fetch_ultra", DataGoKrRequestFailed),
|
||||
"air": (air_service, "fetch_realtime", DataGoKrRequestFailed),
|
||||
"warning": (warning_service, "fetch_warning_events", DataGoKrRequestFailed),
|
||||
"clouds": (sky_service, "fetch_clouds", OpenMeteoRequestFailed),
|
||||
"mid": (weather_service, "fetch_mid", DataGoKrRequestFailed),
|
||||
"holiday": (week_service, "fetch_holidays", DataGoKrRequestFailed),
|
||||
"festival": (week_service, "fetch_festivals", DataGoKrRequestFailed),
|
||||
"solar_term": (season_service, "fetch_solar_terms", DataGoKrRequestFailed),
|
||||
}
|
||||
|
||||
|
||||
def _break(monkeypatch, source: str, mode: str) -> None:
|
||||
module, name, exc = SOURCES[source]
|
||||
|
||||
async def fail(*_a, **_k):
|
||||
raise exc(f"{source} down")
|
||||
|
||||
async def empty(*_a, **_k):
|
||||
return ({}, {}) if source == "mid" else []
|
||||
|
||||
monkeypatch.setattr(module, name, {"fail": fail, "empty": empty}[mode])
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
@pytest.mark.parametrize("mode", ["fail", "empty"])
|
||||
@pytest.mark.parametrize("source", list(SOURCES))
|
||||
async def test_every_screen_survives_one_broken_source(offline, monkeypatch, source, mode):
|
||||
_break(monkeypatch, source, mode)
|
||||
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
|
||||
codes = {path: (await client.get(path, params={"region": REGION})).status_code for path in ENDPOINTS}
|
||||
assert all(c == 200 for c in codes.values()), codes
|
||||
@@ -48,8 +48,14 @@ async def test_sky_view_scores_three_days_with_spots(monkeypatch, clean):
|
||||
assert body["sunset"]["grade"] == 4 and body["sunset"]["grade_label"] == "붉음"
|
||||
assert body["sunset"]["confidence"] == 1
|
||||
assert len(body["days"]) == 3
|
||||
assert [s["name"] for s in body["spots"]] == ["망원한강공원", "하늘공원", "선유도공원"]
|
||||
assert [s["name"] for s in body["spots"]] == ["망원한강공원", "선유도공원", "하늘공원"]
|
||||
assert 255 <= body["sunset_azimuth"] <= 280
|
||||
plan = body["plan"]
|
||||
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("비슷해요")
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
@@ -65,6 +71,52 @@ async def test_sky_ranking_has_30_spots_sorted(monkeypatch, clean):
|
||||
assert body["items"][0]["rank"] == 1 and body["items"][0]["note"]
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
@pytest.mark.parametrize("region, expected", [
|
||||
("4113500000", "일자산 허브천문공원"), # 분당구: 자기 구엔 명소가 없어도 30km 안 서울 명소
|
||||
("2812500000", "북성포구"), # 인천 제물포구(옛 중구)
|
||||
("2635000000", "중리노을전망대"), # 해운대구: 동쪽 바다보다 서쪽이 트인 영도가 먼저
|
||||
])
|
||||
async def test_sky_spots_by_distance(monkeypatch, clean, region, expected):
|
||||
async def fake_fetch(client, points, days=3):
|
||||
return _fake_response(points, days)
|
||||
|
||||
monkeypatch.setattr(sky_service, "fetch_clouds", fake_fetch)
|
||||
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
|
||||
body = (await client.get("/v1/sky", params={"region": region})).json()
|
||||
|
||||
spots = body["spots"]
|
||||
assert len(spots) == 3 and spots[0]["name"] == expected
|
||||
assert all(s["distance_km"] <= sky_service.SPOT_RADIUS_KM for s in spots)
|
||||
assert [s["distance_km"] for s in spots] == sorted(s["distance_km"] for s in spots)
|
||||
|
||||
|
||||
def test_nearest_spots_west_first_and_empty_outside_radius():
|
||||
from decimal import Decimal
|
||||
|
||||
from common.database.model.models import SunsetSpot
|
||||
|
||||
def spot(name, lat, west):
|
||||
return SunsetSpot(name=name, description="", lat=Decimal(str(lat)), lon=Decimal("127.0"), sort_order=0 if west else 1)
|
||||
|
||||
spots = [spot("가까운 동쪽", 37.01, False), spot("먼 서쪽", 37.1, True), spot("반경 밖", 37.5, True)]
|
||||
assert [x.spot.name for x in sky_service.nearest_spots(37.0, 127.0, spots)] == ["먼 서쪽", "가까운 동쪽"]
|
||||
assert sky_service.nearest_spots(33.0, 127.0, spots) == []
|
||||
|
||||
|
||||
def test_outlook_points_to_a_better_day_only_when_clearly_better():
|
||||
from datetime import date, timedelta
|
||||
|
||||
from common.database.model.models import SkyScore
|
||||
|
||||
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) == "내일·모레도 비슷해요"
|
||||
assert sky_service.outlook(day(2, 50), [day(2, 50)], today) == ""
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_clouds_are_stored_by_region_with_only_needed_hours(monkeypatch, clean):
|
||||
async def fake_fetch(client, points, days=3):
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
from datetime import datetime, timezone
|
||||
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 Layers, best_times, confidence, grade, score
|
||||
from services.calc.sky_score import GRADE_LABEL, Layers, best_times, confidence, grade, reason, score, sunset_timeline, verdict
|
||||
from services.calc.sun import sun_times
|
||||
|
||||
CLEAR = Layers(0, 0, 0)
|
||||
|
||||
@@ -43,3 +44,24 @@ def test_sunset_best_times_order():
|
||||
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 == ["해 져요", "가장 붉을 때", "보랏빛 하늘"]
|
||||
|
||||
|
||||
def test_reason_names_what_decided_the_score():
|
||||
canvas = Layers(low=0, mid=20, high=50)
|
||||
assert "알맞게" in reason(canvas, CLEAR)
|
||||
assert "먼 하늘" in reason(canvas, Layers(low=90, mid=50, high=0))
|
||||
assert "낮은 구름" in reason(Layers(100, 0, 0), CLEAR)
|
||||
assert "거의 없어" in reason(CLEAR, CLEAR)
|
||||
|
||||
|
||||
def test_verdict_bands_and_gray_label_is_not_weather_word():
|
||||
assert [verdict(v) for v in (60, 59, 40, 39)] == ["go", "maybe", "maybe", "rest"]
|
||||
assert GRADE_LABEL[SkyGrade.GRAY] != "흐림"
|
||||
|
||||
|
||||
def test_sunset_timeline_runs_golden_to_blue():
|
||||
sun = sun_times(date(2026, 10, 6), 37.56, 126.91)
|
||||
rows = sunset_timeline(sun.golden_start_at, sun.sunset_at, sun.sunset_at + timedelta(minutes=15), sun.dusk_end_at)
|
||||
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
|
||||
@@ -52,7 +52,7 @@ async def test_today_fetches_stores_and_returns_8_slots(monkeypatch, clean_regio
|
||||
assert body["result"]["success"] is True
|
||||
assert [s["label"] for s in body["slots"]] == ["0시", "3시", "6시", "9시", "12시", "15시", "18시", "21시"]
|
||||
assert all(s["temp_c"] == 18 for s in body["slots"])
|
||||
assert body["slots"][0]["icon"] == "stars"
|
||||
assert body["slots"][0]["icon"] == "moon"
|
||||
assert body["slots"][6]["icon"] == "sunset" and body["slots"][6]["note"] == "노을"
|
||||
assert len(calls) == 2
|
||||
|
||||
@@ -90,3 +90,19 @@ async def test_today_fetch_failure_without_data_is_external_error(monkeypatch, c
|
||||
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
|
||||
body = (await client.get("/v1/weather/today", params={"region": REGION})).json()
|
||||
assert body["result"]["desc"] == "EXTERNAL_API_ERROR"
|
||||
|
||||
|
||||
def test_slot_view_shows_sunset_only_when_clear():
|
||||
from datetime import datetime
|
||||
from types import SimpleNamespace
|
||||
|
||||
from common.enums import RainType, Sky
|
||||
from common.utils.kma_time import KST
|
||||
from services.weather_service import _slot_view
|
||||
|
||||
at = datetime(2026, 10, 2, 18, tzinfo=KST)
|
||||
sun = SimpleNamespace(sunrise_at=at.replace(hour=6), sunset_at=at.replace(minute=10), dusk_end_at=at.replace(minute=40))
|
||||
row = lambda sky: SimpleNamespace(rain_type=RainType.NONE.value, sky=sky.value, temp_c=18, rain_prob=0) # noqa: E731
|
||||
assert _slot_view(at, row(Sky.CLEAR), sun)[0::2] == ("sunset", "노을")
|
||||
assert _slot_view(at, row(Sky.CLOUDY), sun)[0::2] == ("cloud", "흐림")
|
||||
assert _slot_view(at, row(Sky.PARTLY), sun)[0::2] == ("cloud", "구름 많음")
|
||||
@@ -12,6 +12,7 @@ from common.enums import 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
|
||||
|
||||
REGION = "1144000000"
|
||||
@@ -28,7 +29,7 @@ def test_parse_mid_days_from_base():
|
||||
land = {"wf4Am": "맑음", "wf4Pm": "흐리고 비", "rnSt4Am": 10, "rnSt4Pm": 60}
|
||||
ta = {"taMin4": 10, "taMax4": 22}
|
||||
day = parse_mid(land, ta, base)[date(2026, 10, 6)]
|
||||
assert day == {"temp_min_c": 10.0, "temp_max_c": 22.0, "sky": Sky.CLOUDY, "rain_type": RainType.RAIN, "rain_prob": 60}
|
||||
assert day == {"temp_min_c": 10.0, "temp_max_c": 22.0, "sky": Sky.CLOUDY, "rain_type": RainType.RAIN, "rain_prob": 60, "rain_prob_am": 10, "rain_prob_pm": 60}
|
||||
|
||||
|
||||
def test_latest_mid_base():
|
||||
@@ -70,15 +71,16 @@ def _mid(*_):
|
||||
def fakes(monkeypatch):
|
||||
today = now_kst().date()
|
||||
monkeypatch.setattr(weather_service, "fetch_vilage", lambda *a: _async(_vilage()))
|
||||
monkeypatch.setattr(week_service, "fetch_mid", lambda *a: _async(_mid()))
|
||||
monkeypatch.setattr(weather_service, "fetch_mid", lambda *a: _async(_mid()))
|
||||
monkeypatch.setattr(week_service, "fetch_holidays", lambda c, y, m: _async(
|
||||
[{"holiday_date": today + timedelta(days=1), "name": "테스트공휴일"}] if m == (today + timedelta(days=1)).month and y == today.year else []
|
||||
))
|
||||
monkeypatch.setattr(week_service, "fetch_festivals", lambda *a: _async([
|
||||
monkeypatch.setattr(week_service, "fetch_festivals", lambda c, sido, since: _async([
|
||||
{"contentid": "1", "title": "가을 축제", "addr1": "서울 마포구", "eventstartdate": (today + timedelta(days=3)).strftime("%Y%m%d"),
|
||||
"eventenddate": (today + timedelta(days=4)).strftime("%Y%m%d")},
|
||||
"eventenddate": (today + timedelta(days=4)).strftime("%Y%m%d"), "firstimage": "http://tong.visitkorea.or.kr/a.jpg"},
|
||||
{"contentid": "2", "title": "상설 전시", "addr1": "서울", "eventstartdate": "20250101", "eventenddate": "20261231"},
|
||||
]))
|
||||
] if sido == "11" else []))
|
||||
monkeypatch.setattr(week_service, "fetch_exhibitions", lambda *a: _async([]))
|
||||
monkeypatch.setattr(air_service, "fetch_stations", lambda *a: _async([]))
|
||||
monkeypatch.setattr(air_service, "fetch_realtime", lambda *a: _async([]))
|
||||
monkeypatch.setattr(warning_service, "fetch_warning_events", lambda *a: _async([]))
|
||||
@@ -101,6 +103,59 @@ async def test_events_exclude_long_running_and_add_weather_fit(fakes):
|
||||
body = (await client.get("/v1/week/event/list", params={"region": REGION})).json()
|
||||
assert [e["name"] for e in body["events"]] == ["가을 축제"]
|
||||
assert body["events"][0]["fit"]
|
||||
assert body["events"][0]["image"] == "https://tong.visitkorea.or.kr/a.jpg"
|
||||
assert body["events"][0]["image_credit"] == "ⓒ한국관광공사"
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_events_include_culture_exhibitions_with_their_credit(fakes, monkeypatch):
|
||||
today = now_kst().date()
|
||||
monkeypatch.setattr(week_service, "fetch_exhibitions", lambda *a: _async([{
|
||||
"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",
|
||||
}]))
|
||||
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"]}
|
||||
assert set(by_name) == {"가을 축제", "가을 특별전"}
|
||||
assert by_name["가을 특별전"]["image"] == "https://www.culture.go.kr/x.jpg"
|
||||
assert by_name["가을 특별전"]["image_credit"] == "ⓒ한국문화정보원"
|
||||
assert by_name["가을 축제"]["image_credit"] == "ⓒ한국관광공사"
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_events_keep_tour_festivals_when_culture_api_fails(fakes, monkeypatch):
|
||||
async def fail(*_):
|
||||
raise DataGoKrRequestFailed("realm2 30 SERVICE_KEY_IS_NOT_REGISTERED_ERROR")
|
||||
|
||||
monkeypatch.setattr(week_service, "fetch_exhibitions", fail)
|
||||
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"]] == ["가을 축제"]
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_events_pick_within_30km_across_sido(fakes, monkeypatch):
|
||||
"""분당 사용자: 서울 잠실(약 15km)은 들어오고 같은 경기도 연천(약 80km)은 빠진다. 좌표 없는 행사는 같은 시도만."""
|
||||
today = now_kst().date()
|
||||
span = {"eventstartdate": (today + timedelta(days=1)).strftime("%Y%m%d"), "eventenddate": (today + timedelta(days=3)).strftime("%Y%m%d")}
|
||||
by_sido = {
|
||||
"11": [{"contentid": "11", "title": "잠실 축제", "addr1": "서울 송파구", "mapy": "37.5133", "mapx": "127.1001", **span},
|
||||
{"contentid": "12", "title": "좌표 없는 서울 축제", "addr1": "서울", **span}],
|
||||
"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)
|
||||
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"]} == {"잠실 축제", "좌표 없는 경기 축제"}
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
@@ -111,3 +166,26 @@ async def test_places_put_indoor_first_on_rainy_day(fakes):
|
||||
body = (await client.get("/v1/week/place/list", params={"region": REGION, "day": rainy_day})).json()
|
||||
assert body["rainy"] is True
|
||||
assert body["places"][0]["is_outdoor"] is False and body["places"][0]["is_good"] is True
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_weekend_ranking_scores_30_spots_and_caches(fakes, monkeypatch):
|
||||
from services.weekend_rank import weekend_days
|
||||
|
||||
calls = []
|
||||
|
||||
def vilage(*a):
|
||||
calls.append(a)
|
||||
return _async(_vilage())
|
||||
|
||||
monkeypatch.setattr(weather_service, "fetch_vilage", vilage)
|
||||
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
|
||||
body = (await client.get("/v1/week/ranking")).json()
|
||||
first = len(calls)
|
||||
again = (await client.get("/v1/week/ranking")).json()
|
||||
days = body["days"]
|
||||
assert [d["day"] for d in days] == [d.isoformat() for d in weekend_days(now_kst().date())]
|
||||
for d in days:
|
||||
assert len(d["items"]) == 30 and [x["rank"] for x in d["items"]] == list(range(1, 31))
|
||||
assert d["items"][0]["reason"].startswith("비 ") and 0 <= d["items"][0]["score"] <= 100
|
||||
assert first >= 34 and len(calls) == first and again == body
|
||||
@@ -0,0 +1,81 @@
|
||||
from datetime import date, datetime
|
||||
from types import SimpleNamespace
|
||||
|
||||
from common.utils.kma_time import KST
|
||||
from services.week_service import DayPlan, EventItem
|
||||
from services.weekend_plan import day_plan, forecast, pick_events
|
||||
|
||||
SAT, SUN = date(2026, 10, 10), date(2026, 10, 11)
|
||||
|
||||
|
||||
def _day(d: date, lo=12.0, hi=26.0, rainy=False, rain_hours=None, prob=10) -> DayPlan:
|
||||
weekday = "토" if d.weekday() == 5 else "일"
|
||||
return DayPlan(day=d, weekday=weekday, holiday=None, icon="rain" if rainy else "sun", temp_min_c=lo, temp_max_c=hi,
|
||||
headline="", summary="", pick="", rain_hours=rain_hours, is_rainy=rainy, rain_prob=prob)
|
||||
|
||||
|
||||
def _event(name, start, end, dist, image="https://img/x.jpg") -> EventItem:
|
||||
e = SimpleNamespace(event_id=hash(name), name=name, icon="fireworks", start_date=start, end_date=end, place_name="경기도 고양시 일산동구 호수로 595", image_url=image, source_id="1")
|
||||
return EventItem(event=e, status="live", status_label="진행 중", fit=None, distance_km=dist)
|
||||
|
||||
|
||||
def test_forecast_both_clear_with_big_gap_warns_about_jacket():
|
||||
f = forecast([_day(SAT), _day(SUN, lo=13)])
|
||||
assert f.line.startswith("토·일 둘 다 맑음!")
|
||||
assert "겉옷" in f.tip and "12°" in f.tip
|
||||
|
||||
|
||||
def test_forecast_one_rainy_day_picks_the_other():
|
||||
f = forecast([_day(SAT, rainy=True, prob=70), _day(SUN)])
|
||||
assert f.line.startswith("일요일이 정답!")
|
||||
assert f.tip == "토요일은 비 70%, 우산 꼭 챙겨요!"
|
||||
|
||||
|
||||
def test_saturday_plan_runs_morning_to_sunset_with_nearest_event():
|
||||
events = [_event("먼 축제", SAT, SUN, 40.0), _event("가까운 축제", SAT, SUN, 12.0)]
|
||||
card = day_plan(_day(SAT), datetime(2026, 10, 10, 18, 3, tzinfo=KST), pick_events(SAT, events), 13.0)
|
||||
assert [s.time for s in card.steps] == ["오전", "오전", "12~16시", "오후", "18:03"]
|
||||
assert card.steps[1].title == "가까운 축제"
|
||||
assert card.steps[-1].icon == "sunset"
|
||||
assert card.eyebrow == "토요일 10.10 · 이렇게 놀아요"
|
||||
|
||||
|
||||
def test_sunday_plan_leads_with_events_ending_today_and_ends_early():
|
||||
events = [_event("이어지는 축제", SAT, date(2026, 10, 20), 5.0), _event("끝나는 축제", date(2026, 10, 1), SUN, 30.0)]
|
||||
card = day_plan(_day(SUN), None, pick_events(SUN, events), 13.0)
|
||||
assert card.line == "끝나는 축제\n오늘이 마지막 날!"
|
||||
assert card.steps[-1].title == "일찍 귀가 추천" and "13°" in card.steps[-1].sub
|
||||
assert any(s.title == "끝나는 축제" and s.sub.startswith("오늘이 마지막 날") for s in card.steps)
|
||||
|
||||
|
||||
def test_afternoon_rain_moves_outdoor_time_before_it():
|
||||
card = day_plan(_day(SAT, rainy=True, rain_hours=(15, 19), prob=60), None, [], None)
|
||||
assert [s.time for s in card.steps[:2]] == ["~15시", "15~19시"]
|
||||
assert card.line.startswith("비 오는 토요일")
|
||||
|
||||
|
||||
def test_saturday_ignores_ending_hook_and_sunday_skips_saturday_events():
|
||||
near = _event("가까운 축제", SAT, SUN, 3.0)
|
||||
ends_sat = _event("토요일 끝", SAT, SAT, 50.0)
|
||||
far = _event("먼 축제", SAT, SUN, 40.0)
|
||||
sat = pick_events(SAT, [ends_sat, near, far])
|
||||
assert [e.event.name for e in sat] == ["가까운 축제", "먼 축제"]
|
||||
assert day_plan(_day(SAT), None, sat, None).line.startswith("해 좋은 낮")
|
||||
assert pick_events(SUN, [near, far], frozenset(e.event.event_id for e in sat)) == []
|
||||
|
||||
|
||||
def test_cloudy_weekend_is_not_called_clear():
|
||||
cloudy = [_day(SAT), _day(SUN)]
|
||||
for d in cloudy:
|
||||
d.icon = "cloud"
|
||||
f = forecast(cloudy)
|
||||
assert "맑음" not in f.line
|
||||
card = day_plan(cloudy[0], None, [], None)
|
||||
assert all(s.icon != "sun" for s in card.steps) and not card.line.startswith("해 좋은")
|
||||
|
||||
|
||||
def test_event_step_uses_event_icon():
|
||||
e = _event("가까운 축제", SAT, SUN, 3.0)
|
||||
e.event.icon = "photo"
|
||||
card = day_plan(_day(SAT), None, [e], None)
|
||||
assert next(s for s in card.steps if s.title == "가까운 축제").icon == "photo"
|
||||
@@ -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_openmeteo_weather
|
||||
from scheduler.jobs import build_today_feed, cleanup_old_rows, refresh_air_stations, refresh_weekend_rank, refresh_openmeteo_weather
|
||||
|
||||
|
||||
async def daily() -> None:
|
||||
@@ -17,9 +17,12 @@ async def daily() -> None:
|
||||
async def main() -> None:
|
||||
scheduler = AsyncIOScheduler(timezone="Asia/Seoul")
|
||||
scheduler.add_job(daily, "cron", hour=3, minute=0, max_instances=1, coalesce=True)
|
||||
# 주말 나들이 점수: 단기예보 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)
|
||||
scheduler.add_job(refresh_openmeteo_weather, "cron", hour="3,9,15,21", minute=10, max_instances=1, coalesce=True)
|
||||
scheduler.start()
|
||||
LOG.info("[worker] started, daily job at 03:00 KST, openmeteo job at 03·09·15·21:10 KST")
|
||||
LOG.info("[worker] started, daily job at 03:00 KST, weekend rank at 06:40·18:40 KST, openmeteo job at 03·09·15·21:10 KST")
|
||||
|
||||
stop = asyncio.Event()
|
||||
loop = asyncio.get_running_loop()
|
||||
|
||||
@@ -6,8 +6,11 @@ services:
|
||||
build:
|
||||
context: ./frontend
|
||||
target: prod
|
||||
args:
|
||||
# 비우면 같은 주소의 /v1 로 부르고 nginx 가 backend 로 넘긴다
|
||||
VITE_API_BASE_URL: ${VITE_API_BASE_URL:-}
|
||||
ports:
|
||||
- "8080:80"
|
||||
- "${FRONT_PORT:-8080}:80"
|
||||
restart: unless-stopped
|
||||
|
||||
# 개발형: docker compose --profile dev up --build frontend-dev → http://localhost:5173
|
||||
@@ -36,7 +39,7 @@ services:
|
||||
REDIS_HOST: redis
|
||||
REDIS_PORT: "6379"
|
||||
ports:
|
||||
- "9810:9800"
|
||||
- "${API_BIND:-9810}:9800"
|
||||
depends_on:
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
@@ -70,7 +73,7 @@ services:
|
||||
POSTGRES_PASSWORD: ${DB_PASSWORD}
|
||||
POSTGRES_DB: ${DB_NAME}
|
||||
ports:
|
||||
- "5440:5432"
|
||||
- "${PG_BIND:-5440}:5432"
|
||||
volumes:
|
||||
- pgdata:/var/lib/postgresql/data
|
||||
- ./backend/postgres-init:/docker-entrypoint-initdb.d:ro
|
||||
@@ -85,7 +88,7 @@ services:
|
||||
image: redis:7-alpine
|
||||
command: ["redis-server", "--appendonly", "yes"]
|
||||
ports:
|
||||
- "6390:6379"
|
||||
- "${REDIS_BIND:-6390}:6379"
|
||||
volumes:
|
||||
- redisdata:/data
|
||||
healthcheck:
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
#!/usr/bin/env bash
|
||||
# 킹서버 배포. 서버의 저장소 폴더에서 실행한다.
|
||||
# ./deploy.sh main 받아서 다시 빌드·재시작
|
||||
# ./deploy.sh --restore-db 덤프.dump 위 작업 후 DB 를 덤프로 덮어쓴다 (pg_dump -Fc 형식)
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")"
|
||||
|
||||
[ -f .env ] || { echo ".env 가 없습니다. .env.example 을 보고 만드세요." >&2; exit 1; }
|
||||
set -a; . ./.env; set +a
|
||||
|
||||
git pull --ff-only origin main
|
||||
docker compose up -d --build postgres redis backend worker frontend
|
||||
|
||||
if [ "${1:-}" = "--restore-db" ]; then
|
||||
dump="${2:?덤프 파일 경로가 필요합니다}"
|
||||
[ -f "$dump" ] || { echo "덤프 파일이 없습니다: $dump" >&2; exit 1; }
|
||||
docker compose stop backend worker
|
||||
docker compose exec -T postgres pg_restore -U "$DB_USER" -d "$DB_NAME" --clean --if-exists --no-owner < "$dump"
|
||||
docker compose exec -T redis redis-cli FLUSHDB
|
||||
docker compose start backend worker
|
||||
fi
|
||||
|
||||
docker compose ps
|
||||
@@ -1,4 +1,4 @@
|
||||
# 2026-10-06 회의 — 날씨각
|
||||
# 2026-10-02(금) 회의 — 날씨각
|
||||
|
||||
## 수정
|
||||
- 각 점수 하향. 100점은 "기온 22도·습도 30%·미풍" 같은 완벽한 조건에만 준다 (결정)
|
||||
@@ -0,0 +1,452 @@
|
||||
# 각 데이터 정리
|
||||
|
||||
어드민이 생기기 전까지 각 설정을 확인하는 문서입니다. 원본은 `backend/seed/index_definition.json`이고, 이 파일을 고친 뒤 시드를 다시 넣으면 DB(`index_definition`)에 반영됩니다. 점수 계산은 `backend/services/calc/index_calc.py`에 있습니다.
|
||||
|
||||
## 점수 계산 방식
|
||||
|
||||
- 각마다 6가지 요소(기온·비·바람·습도·미세먼지·시간)를 0~100점으로 매기고, 아래 비중(%)으로 섞습니다.
|
||||
- 최종 점수 = 비중대로 섞은 점수 × (0.75 + 0.25 × 가장 낮은 요소 점수 ÷ 100). 비중 0%인 요소는 '가장 낮은 요소'에서 뺍니다. 가장 낮은 요소가 0점이면 25%가 깎입니다.
|
||||
- '0점 조건'에 걸리면 0점, '최대 N점' 조건에 걸리면 N점을 넘지 못합니다.
|
||||
- 시간대가 여러 개면 그중 가장 좋은 시간대 점수를 씁니다.
|
||||
- 미세먼지는 모든 각이 같은 규칙입니다: 초미세먼지 15㎍/㎥ 이하 100점 → 75㎍/㎥ 이상 0점.
|
||||
- 바람·미세먼지·노을 정보가 없으면 70점으로 둡니다.
|
||||
|
||||
## 한눈에 보기
|
||||
|
||||
| 순서 | 각 | 코드 | 분류 | 시간대 | 기온 | 비 | 바람 | 습도 | 미세먼지 | 시간 | 재미 각 | 계절 핵심 |
|
||||
|---:|---|---|---|---|---:|---:|---:|---:|---:|---:|:---:|:---:|
|
||||
| 1 | 야장각 | `yajang` | 먹고 마시기 | 18~24시 | 30% | 25% | 15% | 10% | 10% | 10% | ○ | |
|
||||
| 2 | 피크닉각 | `picnic` | 밖에서 놀기 | 11~16시 | 30% | 25% | 15% | 10% | 10% | 10% | | ○ |
|
||||
| 3 | 치맥각 | `chimaek` | 먹고 마시기 | 18~23시 | 30% | 20% | 15% | 15% | 10% | 10% | ○ | |
|
||||
| 4 | 산책각 | `walk` | 밖에서 놀기 | 18~22시 | 30% | 25% | 15% | 10% | 15% | 5% | | |
|
||||
| 5 | 환기각 | `vent` | 집안일 | 10~12시 / 12~14시 / 14~16시 / 16~18시 | 10% | 15% | 15% | 10% | 45% | 5% | | |
|
||||
| 6 | 등산각 | `hiking` | 밖에서 놀기 | 7~12시 | 30% | 25% | 20% | 10% | 10% | 5% | | ○ |
|
||||
| 7 | 세차각 | `carwash` | 집안일 | 9~18시 (비는 2일 뒤까지 봄) | 5% | 60% | 10% | 10% | 10% | 5% | | |
|
||||
| 8 | 캠핑각 | `camping` | 밖에서 놀기 | 18~다음 날 8시 | 30% | 25% | 15% | 15% | 10% | 5% | | ○ |
|
||||
| 9 | 러닝각 | `running` | 밖에서 놀기 | 6~8시 / 19~22시 | 35% | 20% | 10% | 20% | 10% | 5% | | |
|
||||
| 10 | 별보기각 | `stars` | 밖에서 놀기 | 21~다음 날 2시 | 5% | 15% | 5% | 10% | 20% | 45% | | ○ |
|
||||
| 11 | 짬뽕각 | `jjamppong` | 먹고 마시기 | 11~14시 / 17~20시 | 40% | 25% | 15% | 10% | 5% | 5% | ○ | |
|
||||
| 12 | 막걸리각 | `makgeolli` | 먹고 마시기 | 17~22시 | 15% | 50% | 10% | 15% | 5% | 5% | ○ | |
|
||||
| 13 | 뜨아각 | `iced_hot` | 먹고 마시기 | 7~10시 | 50% | 10% | 15% | 10% | 5% | 10% | ○ | |
|
||||
| 14 | 빨래각 | `laundry` | 집안일 | 9~16시 | 20% | 35% | 20% | 20% | 0% | 5% | | |
|
||||
| 15 | 자전거각 | `bike` | 밖에서 놀기 | 9~19시 | 25% | 25% | 30% | 5% | 10% | 5% | | |
|
||||
| 16 | 멍뭉산책각 | `dog` | 밖에서 놀기 | 7~9시 / 17~20시 | 40% | 25% | 10% | 5% | 15% | 5% | | |
|
||||
| 17 | 김서림각 | `glasses` | 생활 고민 | 7~9시 | 50% | 10% | 5% | 30% | 0% | 5% | | |
|
||||
| 18 | 화장붕괴각 | `makeup` | 생활 고민 | 10~18시 | 40% | 10% | 10% | 35% | 0% | 5% | | |
|
||||
| 19 | 냉면각 | `naengmyeon` | 먹고 마시기 | 11~14시 | 55% | 15% | 5% | 15% | 5% | 5% | ○ | |
|
||||
| 20 | 택시대란각 | `taxi` | 생활 고민 | 22~다음 날 2시 | 15% | 55% | 10% | 5% | 0% | 15% | | |
|
||||
| 21 | 배달폭주각 | `delivery` | 생활 고민 | 17~21시 | 20% | 50% | 10% | 5% | 5% | 10% | | |
|
||||
| 22 | 가드닝각 | `garden` | 집안일 | 7~10시 | 30% | 30% | 10% | 15% | 10% | 5% | | |
|
||||
| 23 | 사진산책각 | `photo` | 밖에서 놀기 | 일몰 앞뒤 1시간 | 15% | 25% | 10% | 5% | 15% | 30% | | |
|
||||
| 24 | 야구각 | `baseball` | 밖에서 놀기 | 18~22시 | 25% | 40% | 10% | 5% | 10% | 10% | ○ | |
|
||||
| 25 | 공부각 | `study` | 집안일 | 13~18시 | 35% | 35% | 10% | 5% | 5% | 10% | ○ | |
|
||||
| 26 | 넷플릭스각 | `netflix` | 집안일 | 20~24시 | 30% | 35% | 15% | 5% | 0% | 15% | ○ | |
|
||||
| 27 | 군밤각 | `chestnut` | 먹고 마시기 | 17~21시 | 55% | 25% | 10% | 0% | 5% | 5% | ○ | |
|
||||
|
||||
## 각별 자세히
|
||||
|
||||
### 야장각 (`yajang`)
|
||||
|
||||
- 설명: 저녁 6시~자정, 바깥 자리에 앉기 좋은 정도
|
||||
- 분류: 먹고 마시기 · 아이콘 `yajang` · 재미 각 예 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
||||
- 시간대: 18~24시
|
||||
- 요소별 규칙 (비중):
|
||||
- 기온 30%: 체감 18~24°가 좋음
|
||||
- 비 25%: 비 안 올수록 좋음
|
||||
- 바람 15%: 잔잔할수록 좋음 (초속 2m까지 괜찮음, 10m면 0점)
|
||||
- 습도 10%: 30~60%가 좋음 (최적 35%)
|
||||
- 미세먼지 10%: 초미세먼지 낮을수록 좋음
|
||||
- 시간·요일 10%: 요일별 점수: 금 100, 토 100, 일 85, 그 외 78
|
||||
- 점수 깎이는 조건: 비 확률 80% 이상이면 0점, 바람 14m/s 이상이면 0점
|
||||
- 반영 못 하는 것: 모기, 가게 영업 여부, 자리 경쟁은 반영하지 못해요
|
||||
|
||||
### 피크닉각 (`picnic`)
|
||||
|
||||
- 설명: 낮 동안 돗자리 펴고 쉬기 좋은 정도
|
||||
- 분류: 밖에서 놀기 · 아이콘 `picnic` · 재미 각 아니오 · 계절 핵심 예 · 계산 근거 화면 있음
|
||||
- 시간대: 11~16시
|
||||
- 요소별 규칙 (비중):
|
||||
- 기온 30%: 체감 20~26°가 좋음
|
||||
- 비 25%: 비 안 올수록 좋음
|
||||
- 바람 15%: 잔잔할수록 좋음 (초속 3m까지 괜찮음, 9m면 0점)
|
||||
- 습도 10%: 30~60%가 좋음 (최적 35%)
|
||||
- 미세먼지 10%: 초미세먼지 낮을수록 좋음
|
||||
- 시간·요일 10%: 요일별 점수: 토 100, 일 100, 공휴일 100, 그 외 60
|
||||
- 점수 깎이는 조건: 비 확률 60% 이상이면 0점
|
||||
- 반영 못 하는 것: 잔디 상태, 공원 혼잡도는 반영하지 못해요
|
||||
|
||||
### 치맥각 (`chimaek`)
|
||||
|
||||
- 설명: 저녁에 바깥에서 치킨과 맥주가 당기는 정도
|
||||
- 분류: 먹고 마시기 · 아이콘 `chimaek` · 재미 각 예 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
||||
- 시간대: 18~23시
|
||||
- 요소별 규칙 (비중):
|
||||
- 기온 30%: 체감 20~27°가 좋음
|
||||
- 비 20%: 비 안 올수록 좋음
|
||||
- 바람 15%: 잔잔할수록 좋음 (초속 3m까지 괜찮음, 10m면 0점)
|
||||
- 습도 15%: 30~60%가 좋음 (최적 35%)
|
||||
- 미세먼지 10%: 초미세먼지 낮을수록 좋음
|
||||
- 시간·요일 10%: 요일별 점수: 금 100, 토 100, 그 외 74
|
||||
- 점수 깎이는 조건: 체감 10° 미만이면 0점, 비 확률 80% 이상이면 0점
|
||||
- 반영 못 하는 것: 야구 경기 같은 이벤트는 아직 반영하지 못해요
|
||||
|
||||
### 산책각 (`walk`)
|
||||
|
||||
- 설명: 걷기 좋은 정도 (해 진 뒤 기준)
|
||||
- 분류: 밖에서 놀기 · 아이콘 `walk` · 재미 각 아니오 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
||||
- 시간대: 18~22시
|
||||
- 요소별 규칙 (비중):
|
||||
- 기온 30%: 체감 15~23°가 좋음
|
||||
- 비 25%: 비 안 올수록 좋음
|
||||
- 바람 15%: 잔잔할수록 좋음 (초속 3m까지 괜찮음, 10m면 0점)
|
||||
- 습도 10%: 30~60%가 좋음 (최적 35%)
|
||||
- 미세먼지 15%: 초미세먼지 낮을수록 좋음
|
||||
- 시간·요일 5%: 고정 55점
|
||||
- 점수 깎이는 조건: 비 확률 90% 이상이면 0점, 초미세먼지 75㎍/㎥ 이상이면 0점
|
||||
- 반영 못 하는 것: 길 공사, 조명은 반영하지 못해요
|
||||
|
||||
### 환기각 (`vent`)
|
||||
|
||||
- 설명: 창문 열어 공기 바꾸기 좋은 정도
|
||||
- 분류: 집안일 · 아이콘 `vent` · 재미 각 아니오 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
||||
- 시간대: 10~12시 / 12~14시 / 14~16시 / 16~18시
|
||||
- 요소별 규칙 (비중):
|
||||
- 기온 10%: 체감 15~26°가 좋음
|
||||
- 비 15%: 비 안 올수록 좋음
|
||||
- 바람 15%: 적당한 바람(초속 2~5m)이 좋음
|
||||
- 습도 10%: 30~60%가 좋음 (최적 35%)
|
||||
- 미세먼지 45%: 초미세먼지 낮을수록 좋음
|
||||
- 시간·요일 5%: 고정 100점
|
||||
- 점수 깎이는 조건: 초미세먼지 75㎍/㎥ 이상이면 0점
|
||||
- 반영 못 하는 것: 집 방향과 주변 공사 먼지는 반영하지 못해요
|
||||
|
||||
### 등산각 (`hiking`)
|
||||
|
||||
- 설명: 산에 오르기 좋은 정도 (오전 기준)
|
||||
- 분류: 밖에서 놀기 · 아이콘 `hiking` · 재미 각 아니오 · 계절 핵심 예 · 계산 근거 화면 있음
|
||||
- 시간대: 7~12시
|
||||
- 요소별 규칙 (비중):
|
||||
- 기온 30%: 체감 10~20°가 좋음, 산 정상 보정 -6°
|
||||
- 비 25%: 비 안 올수록 좋음
|
||||
- 바람 20%: 잔잔할수록 좋음 (초속 4m까지 괜찮음, 12m면 0점)
|
||||
- 습도 10%: 30~60%가 좋음 (최적 35%)
|
||||
- 미세먼지 10%: 초미세먼지 낮을수록 좋음
|
||||
- 시간·요일 5%: 요일별 점수: 토 100, 일 100, 공휴일 100, 그 외 50
|
||||
- 점수 깎이는 조건: 비 확률 70% 이상이면 0점, wind 특보가 있으면
|
||||
- 반영 못 하는 것: 등산로 통제, 낙석 정보는 산림청 안내를 확인하세요
|
||||
|
||||
### 세차각 (`carwash`)
|
||||
|
||||
- 설명: 세차한 뒤 깨끗함이 오래가는 정도
|
||||
- 분류: 집안일 · 아이콘 `carwash` · 재미 각 아니오 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
||||
- 시간대: 9~18시 (비는 2일 뒤까지 봄)
|
||||
- 요소별 규칙 (비중):
|
||||
- 기온 5%: 체감 5~28°가 좋음
|
||||
- 비 60%: 비 안 올수록 좋음
|
||||
- 바람 10%: 잔잔할수록 좋음 (초속 4m까지 괜찮음, 10m면 0점)
|
||||
- 습도 10%: 낮을수록 좋음 (90%=0점 → 40%=100점)
|
||||
- 미세먼지 10%: 초미세먼지 낮을수록 좋음
|
||||
- 시간·요일 5%: 고정 100점
|
||||
- 점수 깎이는 조건: 비 확률 70% 이상이면 최대 20점
|
||||
- 반영 못 하는 것: 황사·꽃가루 같은 하늘 먼지는 일부만 반영해요
|
||||
|
||||
### 캠핑각 (`camping`)
|
||||
|
||||
- 설명: 하룻밤 캠핑하기 좋은 정도
|
||||
- 분류: 밖에서 놀기 · 아이콘 `camping` · 재미 각 아니오 · 계절 핵심 예 · 계산 근거 화면 있음
|
||||
- 시간대: 18~다음 날 8시
|
||||
- 요소별 규칙 (비중):
|
||||
- 기온 30%: 체감 12~22°가 좋음
|
||||
- 비 25%: 비 안 올수록 좋음
|
||||
- 바람 15%: 잔잔할수록 좋음 (초속 3m까지 괜찮음, 9m면 0점)
|
||||
- 습도 15%: 낮을수록 좋음 (90%=0점 → 40%=100점)
|
||||
- 미세먼지 10%: 초미세먼지 낮을수록 좋음
|
||||
- 시간·요일 5%: 요일별 점수: 금 100, 토 100, 그 외 60
|
||||
- 점수 깎이는 조건: 비 확률 60% 이상이면 0점, 바람 14m/s 이상이면 0점
|
||||
- 반영 못 하는 것: 캠핑장 예약 상황은 반영하지 못해요
|
||||
|
||||
### 러닝각 (`running`)
|
||||
|
||||
- 설명: 뛰기 좋은 정도 (아침·저녁 중 좋은 쪽)
|
||||
- 분류: 밖에서 놀기 · 아이콘 `running` · 재미 각 아니오 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
||||
- 시간대: 6~8시 / 19~22시
|
||||
- 요소별 규칙 (비중):
|
||||
- 기온 35%: 체감 8~18°가 좋음
|
||||
- 비 20%: 비 안 올수록 좋음
|
||||
- 바람 10%: 잔잔할수록 좋음 (초속 4m까지 괜찮음, 10m면 0점)
|
||||
- 습도 20%: 낮을수록 좋음 (90%=0점 → 40%=100점)
|
||||
- 미세먼지 10%: 초미세먼지 낮을수록 좋음
|
||||
- 시간·요일 5%: 고정 100점
|
||||
- 점수 깎이는 조건: 체감 35° 이상이면 0점, 비 확률 90% 이상이면 0점
|
||||
- 반영 못 하는 것: 노면 상태는 반영하지 못해요
|
||||
|
||||
### 별보기각 (`stars`)
|
||||
|
||||
- 설명: 밤하늘 별이 잘 보이는 정도
|
||||
- 분류: 밖에서 놀기 · 아이콘 `stars` · 재미 각 아니오 · 계절 핵심 예 · 계산 근거 화면 있음
|
||||
- 시간대: 21~다음 날 2시
|
||||
- 요소별 규칙 (비중):
|
||||
- 기온 5%: 체감 5~25°가 좋음
|
||||
- 비 15%: 비 안 올수록 좋음
|
||||
- 바람 5%: 잔잔할수록 좋음 (초속 5m까지 괜찮음, 12m면 0점)
|
||||
- 습도 10%: 낮을수록 좋음 (90%=0점 → 40%=100점)
|
||||
- 미세먼지 20%: 초미세먼지 낮을수록 좋음
|
||||
- 시간·요일 45%: 달이 어두울수록 좋음 (보름 20점 → 그믐 100점)
|
||||
- 점수 깎이는 조건: 흐린 시간 비율 80% 이상이면 0점
|
||||
- 반영 못 하는 것: 도시 불빛은 지역 평균으로만 반영해요
|
||||
|
||||
### 짬뽕각 (`jjamppong`)
|
||||
|
||||
- 설명: 뜨끈한 국물이 당기는 정도
|
||||
- 분류: 먹고 마시기 · 아이콘 `jjamppong` · 재미 각 예 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
||||
- 시간대: 11~14시 / 17~20시
|
||||
- 요소별 규칙 (비중):
|
||||
- 기온 40%: 추울수록 좋음 (25°=0점 → 5°=100점)
|
||||
- 비 25%: 비 올수록 좋음
|
||||
- 바람 15%: 셀수록 좋음 (초속 8m=100점)
|
||||
- 습도 10%: 높을수록 좋음 (40%=0점 → 90%=100점)
|
||||
- 미세먼지 5%: 초미세먼지 낮을수록 좋음
|
||||
- 시간·요일 5%: 고정 100점
|
||||
- 점수 깎이는 조건: 없음
|
||||
- 반영 못 하는 것: 실제 주문량으로 검증하기 전이에요
|
||||
|
||||
### 막걸리각 (`makgeolli`)
|
||||
|
||||
- 설명: 비 오는 날 파전에 막걸리가 당기는 정도
|
||||
- 분류: 먹고 마시기 · 아이콘 `makgeolli` · 재미 각 예 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
||||
- 시간대: 17~22시
|
||||
- 요소별 규칙 (비중):
|
||||
- 기온 15%: 추울수록 좋음 (28°=0점 → 10°=100점)
|
||||
- 비 50%: 비 올수록 좋음
|
||||
- 바람 10%: 셀수록 좋음 (초속 8m=100점)
|
||||
- 습도 15%: 높을수록 좋음 (40%=0점 → 90%=100점)
|
||||
- 미세먼지 5%: 초미세먼지 낮을수록 좋음
|
||||
- 시간·요일 5%: 요일별 점수: 금 100, 토 100, 그 외 50
|
||||
- 점수 깎이는 조건: 없음
|
||||
- 반영 못 하는 것: 실제 판매량으로 검증하기 전이에요
|
||||
|
||||
### 뜨아각 (`iced_hot`)
|
||||
|
||||
- 설명: 아이스 대신 따뜻한 커피로 바꿀 때가 된 정도
|
||||
- 분류: 먹고 마시기 · 아이콘 `iced_hot` · 재미 각 예 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
||||
- 시간대: 7~10시
|
||||
- 요소별 규칙 (비중):
|
||||
- 기온 50%: 추울수록 좋음 (22°=0점 → 8°=100점)
|
||||
- 비 10%: 비 올수록 좋음
|
||||
- 바람 15%: 셀수록 좋음 (초속 8m=100점)
|
||||
- 습도 10%: 높을수록 좋음 (40%=0점 → 90%=100점)
|
||||
- 미세먼지 5%: 초미세먼지 낮을수록 좋음
|
||||
- 시간·요일 10%: 고정 100점
|
||||
- 점수 깎이는 조건: 없음
|
||||
- 반영 못 하는 것: 사람마다 달라서 재미로 봐 주세요
|
||||
|
||||
### 빨래각 (`laundry`)
|
||||
|
||||
- 설명: 빨래가 잘 마르는 정도
|
||||
- 분류: 집안일 · 아이콘 `laundry` · 재미 각 아니오 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
||||
- 시간대: 9~16시
|
||||
- 요소별 규칙 (비중):
|
||||
- 기온 20%: 더울수록 좋음 (10°=0점 → 25°=100점)
|
||||
- 비 35%: 비 안 올수록 좋음
|
||||
- 바람 20%: 적당한 바람(초속 2~5m)이 좋음
|
||||
- 습도 20%: 낮을수록 좋음 (90%=0점 → 40%=100점)
|
||||
- 미세먼지 0%: 초미세먼지 낮을수록 좋음
|
||||
- 시간·요일 5%: 고정 100점
|
||||
- 점수 깎이는 조건: 비 확률 60% 이상이면 0점
|
||||
- 반영 못 하는 것: 집 일조량은 반영하지 못해요
|
||||
|
||||
### 자전거각 (`bike`)
|
||||
|
||||
- 설명: 자전거 타기 좋은 정도
|
||||
- 분류: 밖에서 놀기 · 아이콘 `bike` · 재미 각 아니오 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
||||
- 시간대: 9~19시
|
||||
- 요소별 규칙 (비중):
|
||||
- 기온 25%: 체감 15~24°가 좋음
|
||||
- 비 25%: 비 안 올수록 좋음
|
||||
- 바람 30%: 잔잔할수록 좋음 (초속 3m까지 괜찮음, 8m면 0점)
|
||||
- 습도 5%: 30~60%가 좋음 (최적 35%)
|
||||
- 미세먼지 10%: 초미세먼지 낮을수록 좋음
|
||||
- 시간·요일 5%: 요일별 점수: 토 100, 일 100, 공휴일 100, 그 외 70
|
||||
- 점수 깎이는 조건: 비 확률 70% 이상이면 0점, 바람 10m/s 이상이면 0점
|
||||
- 반영 못 하는 것: 자전거 도로 공사는 반영하지 못해요
|
||||
|
||||
### 멍뭉산책각 (`dog`)
|
||||
|
||||
- 설명: 반려견과 산책하기 좋은 정도
|
||||
- 분류: 밖에서 놀기 · 아이콘 `dog` · 재미 각 아니오 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
||||
- 시간대: 7~9시 / 17~20시
|
||||
- 요소별 규칙 (비중):
|
||||
- 기온 40%: 체감 5~22°가 좋음
|
||||
- 비 25%: 비 안 올수록 좋음
|
||||
- 바람 10%: 잔잔할수록 좋음 (초속 5m까지 괜찮음, 12m면 0점)
|
||||
- 습도 5%: 30~60%가 좋음 (최적 35%)
|
||||
- 미세먼지 15%: 초미세먼지 낮을수록 좋음
|
||||
- 시간·요일 5%: 고정 100점
|
||||
- 점수 깎이는 조건: 체감 33° 이상이면 0점, 초미세먼지 75㎍/㎥ 이상이면 0점
|
||||
- 반영 못 하는 것: 노면 온도는 실측하지 못해요
|
||||
|
||||
### 김서림각 (`glasses`)
|
||||
|
||||
- 설명: 안경에 김이 서리기 쉬운 정도
|
||||
- 분류: 생활 고민 · 아이콘 `glasses` · 재미 각 아니오 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
||||
- 시간대: 7~9시
|
||||
- 요소별 규칙 (비중):
|
||||
- 기온 50%: 추울수록 좋음 (15°=0점 → -5°=100점)
|
||||
- 비 10%: 비 올수록 좋음
|
||||
- 바람 5%: 상관없음 (50점 고정)
|
||||
- 습도 30%: 높을수록 좋음 (40%=0점 → 90%=100점)
|
||||
- 미세먼지 0%: 초미세먼지 낮을수록 좋음
|
||||
- 시간·요일 5%: 고정 100점
|
||||
- 점수 깎이는 조건: 없음
|
||||
- 반영 못 하는 것: 실내 온도는 반영하지 못해요
|
||||
|
||||
### 화장붕괴각 (`makeup`)
|
||||
|
||||
- 설명: 화장이 무너지기 쉬운 정도
|
||||
- 분류: 생활 고민 · 아이콘 `makeup` · 재미 각 아니오 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
||||
- 시간대: 10~18시
|
||||
- 요소별 규칙 (비중):
|
||||
- 기온 40%: 더울수록 좋음 (20°=0점 → 32°=100점)
|
||||
- 비 10%: 비 올수록 좋음
|
||||
- 바람 10%: 셀수록 좋음 (초속 8m=100점)
|
||||
- 습도 35%: 높을수록 좋음 (40%=0점 → 90%=100점)
|
||||
- 미세먼지 0%: 초미세먼지 낮을수록 좋음
|
||||
- 시간·요일 5%: 고정 100점
|
||||
- 점수 깎이는 조건: 없음
|
||||
- 반영 못 하는 것: 피부 타입은 반영하지 못해요
|
||||
|
||||
### 냉면각 (`naengmyeon`)
|
||||
|
||||
- 설명: 시원한 냉면이 당기는 정도
|
||||
- 분류: 먹고 마시기 · 아이콘 `naengmyeon` · 재미 각 예 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
||||
- 시간대: 11~14시
|
||||
- 요소별 규칙 (비중):
|
||||
- 기온 55%: 더울수록 좋음 (18°=0점 → 32°=100점)
|
||||
- 비 15%: 비 안 올수록 좋음
|
||||
- 바람 5%: 잔잔할수록 좋음 (초속 4m까지 괜찮음, 12m면 0점)
|
||||
- 습도 15%: 높을수록 좋음 (40%=0점 → 90%=100점)
|
||||
- 미세먼지 5%: 초미세먼지 낮을수록 좋음
|
||||
- 시간·요일 5%: 고정 100점
|
||||
- 점수 깎이는 조건: 없음
|
||||
- 반영 못 하는 것: 실제 주문량으로 검증하기 전이에요
|
||||
|
||||
### 택시대란각 (`taxi`)
|
||||
|
||||
- 설명: 밤늦게 택시 잡기 어려운 정도
|
||||
- 분류: 생활 고민 · 아이콘 `taxi` · 재미 각 아니오 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
||||
- 시간대: 22~다음 날 2시
|
||||
- 요소별 규칙 (비중):
|
||||
- 기온 15%: 추울수록 좋음 (15°=0점 → -5°=100점)
|
||||
- 비 55%: 비 올수록 좋음
|
||||
- 바람 10%: 셀수록 좋음 (초속 8m=100점)
|
||||
- 습도 5%: 상관없음 (50점 고정)
|
||||
- 미세먼지 0%: 초미세먼지 낮을수록 좋음
|
||||
- 시간·요일 15%: 요일별 점수: 금 100, 토 100, 그 외 40
|
||||
- 점수 깎이는 조건: 없음
|
||||
- 반영 못 하는 것: 행사·공연 종료 시간은 반영하지 못해요
|
||||
|
||||
### 배달폭주각 (`delivery`)
|
||||
|
||||
- 설명: 배달 주문이 몰리는 정도
|
||||
- 분류: 생활 고민 · 아이콘 `delivery` · 재미 각 아니오 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
||||
- 시간대: 17~21시
|
||||
- 요소별 규칙 (비중):
|
||||
- 기온 20%: 추울수록 좋음 (22°=0점 → 0°=100점)
|
||||
- 비 50%: 비 올수록 좋음
|
||||
- 바람 10%: 셀수록 좋음 (초속 8m=100점)
|
||||
- 습도 5%: 상관없음 (50점 고정)
|
||||
- 미세먼지 5%: 초미세먼지 낮을수록 좋음
|
||||
- 시간·요일 10%: 요일별 점수: 금 100, 토 100, 일 100, 그 외 60
|
||||
- 점수 깎이는 조건: 없음
|
||||
- 반영 못 하는 것: 실제 배달 앱 지표로 검증하기 전이에요
|
||||
|
||||
### 가드닝각 (`garden`)
|
||||
|
||||
- 설명: 화분 돌보고 물 주기 좋은 정도
|
||||
- 분류: 집안일 · 아이콘 `garden` · 재미 각 아니오 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
||||
- 시간대: 7~10시
|
||||
- 요소별 규칙 (비중):
|
||||
- 기온 30%: 체감 12~25°가 좋음
|
||||
- 비 30%: 비 안 올수록 좋음
|
||||
- 바람 10%: 잔잔할수록 좋음 (초속 4m까지 괜찮음, 10m면 0점)
|
||||
- 습도 15%: 30~60%가 좋음 (최적 35%)
|
||||
- 미세먼지 10%: 초미세먼지 낮을수록 좋음
|
||||
- 시간·요일 5%: 고정 100점
|
||||
- 점수 깎이는 조건: 비 확률 70% 이상이면 0점
|
||||
- 반영 못 하는 것: 식물 종류는 반영하지 못해요
|
||||
|
||||
### 사진산책각 (`photo`)
|
||||
|
||||
- 설명: 노을 무렵 사진 찍으며 걷기 좋은 정도
|
||||
- 분류: 밖에서 놀기 · 아이콘 `photo` · 재미 각 아니오 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
||||
- 시간대: 일몰 앞뒤 1시간
|
||||
- 요소별 규칙 (비중):
|
||||
- 기온 15%: 체감 10~26°가 좋음
|
||||
- 비 25%: 비 안 올수록 좋음
|
||||
- 바람 10%: 잔잔할수록 좋음 (초속 5m까지 괜찮음, 12m면 0점)
|
||||
- 습도 5%: 30~60%가 좋음 (최적 35%)
|
||||
- 미세먼지 15%: 초미세먼지 낮을수록 좋음
|
||||
- 시간·요일 30%: 그날 노을 점수를 그대로 씀
|
||||
- 점수 깎이는 조건: 비 확률 80% 이상이면 0점
|
||||
- 반영 못 하는 것: 장소 혼잡도는 반영하지 못해요
|
||||
|
||||
### 야구각 (`baseball`)
|
||||
|
||||
- 설명: 저녁 6~10시, 야구장 직관하기 좋은 정도
|
||||
- 분류: 밖에서 놀기 · 아이콘 `baseball` · 재미 각 예 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
||||
- 시간대: 18~22시
|
||||
- 요소별 규칙 (비중):
|
||||
- 기온 25%: 체감 15~25°가 좋음
|
||||
- 비 40%: 비 안 올수록 좋음
|
||||
- 바람 10%: 잔잔할수록 좋음 (초속 3m까지 괜찮음, 10m면 0점)
|
||||
- 습도 5%: 30~60%가 좋음 (최적 35%)
|
||||
- 미세먼지 10%: 초미세먼지 낮을수록 좋음
|
||||
- 시간·요일 10%: 요일별 점수: 월 10, 그 외 100
|
||||
- 점수 깎이는 조건: 비 확률 70% 이상이면 0점
|
||||
- 반영 못 하는 것: 경기 일정과 시즌(3~10월)은 반영하지 못해요
|
||||
|
||||
### 공부각 (`study`)
|
||||
|
||||
- 설명: 오후 1~6시, 밖에 나가기 싫어서 공부가 잘되는 정도
|
||||
- 분류: 집안일 · 아이콘 `study` · 재미 각 예 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
||||
- 시간대: 13~18시
|
||||
- 요소별 규칙 (비중):
|
||||
- 기온 35%: 체감이 15~24°에서 멀수록(덥거나 추울수록) 좋음
|
||||
- 비 35%: 비 올수록 좋음
|
||||
- 바람 10%: 셀수록 좋음 (초속 8m=100점)
|
||||
- 습도 5%: 높을수록 좋음 (40%=0점 → 90%=100점)
|
||||
- 미세먼지 5%: 초미세먼지 낮을수록 좋음
|
||||
- 시간·요일 10%: 요일별 점수: 토 50, 일 50, 공휴일 50, 그 외 100
|
||||
- 점수 깎이는 조건: 없음
|
||||
- 반영 못 하는 것: 사람마다 달라서 재미로 봐 주세요
|
||||
|
||||
### 넷플릭스각 (`netflix`)
|
||||
|
||||
- 설명: 밤 8시~자정, 집에서 영화 보기 좋은 정도
|
||||
- 분류: 집안일 · 아이콘 `netflix` · 재미 각 예 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
||||
- 시간대: 20~24시
|
||||
- 요소별 규칙 (비중):
|
||||
- 기온 30%: 추울수록 좋음 (22°=0점 → 0°=100점)
|
||||
- 비 35%: 비 올수록 좋음
|
||||
- 바람 15%: 셀수록 좋음 (초속 8m=100점)
|
||||
- 습도 5%: 상관없음 (50점 고정)
|
||||
- 미세먼지 0%: 초미세먼지 낮을수록 좋음
|
||||
- 시간·요일 15%: 요일별 점수: 금 100, 토 100, 그 외 60
|
||||
- 점수 깎이는 조건: 없음
|
||||
- 반영 못 하는 것: 재미로 보는 지수예요
|
||||
|
||||
### 군밤각 (`chestnut`)
|
||||
|
||||
- 설명: 저녁 5~9시, 길거리 군밤이 당기는 정도
|
||||
- 분류: 먹고 마시기 · 아이콘 `chestnut` · 재미 각 예 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
||||
- 시간대: 17~21시
|
||||
- 요소별 규칙 (비중):
|
||||
- 기온 55%: 추울수록 좋음 (18°=0점 → 0°=100점)
|
||||
- 비 25%: 비 안 올수록 좋음
|
||||
- 바람 10%: 셀수록 좋음 (초속 8m=100점)
|
||||
- 습도 0%: 상관없음 (50점 고정)
|
||||
- 미세먼지 5%: 초미세먼지 낮을수록 좋음
|
||||
- 시간·요일 5%: 고정 100점
|
||||
- 점수 깎이는 조건: 없음
|
||||
- 반영 못 하는 것: 군밤 노점이 있는지는 반영하지 못해요
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
<title>날씨각 데이터 지도</title>
|
||||
<title>날씨각 데이터 흐름</title>
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com">
|
||||
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=IBM+Plex+Sans+KR:wght@400;500;700&family=IBM+Plex+Mono:wght@400;500&display=swap">
|
||||
<style>
|
||||
@@ -104,7 +104,7 @@ code{font-family:var(--mono);font-size:12.5px;background:var(--soft-db);padding:
|
||||
<div class="wrap">
|
||||
|
||||
<header>
|
||||
<h1>날씨각 데이터 지도</h1>
|
||||
<h1>날씨각 데이터 흐름</h1>
|
||||
<p class="lead">날씨각 서버는 정해진 시각에 데이터를 긁어 오지 않습니다. <b>누군가 그 구를 열었을 때</b> 갖고 있는 값이 오래됐으면 그때 받아서 저장·계산하고, 다음 사람부터는 저장된 값을 같이 씁니다. 정해진 시각에 도는 작업은 새벽 3시 하나뿐입니다.</p>
|
||||
<div class="rules">
|
||||
<div class="rule"><b>볼 때 받는다</b><span>외부 API는 사용자가 화면을 열 때, 값이 오래됐을 때만 부릅니다.</span></div>
|
||||
@@ -141,7 +141,7 @@ code{font-family:var(--mono);font-size:12.5px;background:var(--soft-db);padding:
|
||||
<span style="--c:var(--job)"><i></i>스케줄러 (정해진 시각에 실제로 돎)</span>
|
||||
</div>
|
||||
<dl class="what">
|
||||
<div style="--c:var(--kma)"><dt>단기예보</dt><dd>오늘~모레 시간별 기온·하늘 상태·비/눈 종류·강수확률·강수량·습도·풍속, 하루 최저·최고기온</dd></div>
|
||||
<div style="--c:var(--kma)"><dt>단기예보</dt><dd>오늘~글피(4일) 시간별 기온·하늘 상태·비/눈 종류·강수확률·강수량·습도·풍속, 하루 최저·최고기온</dd></div>
|
||||
<div style="--c:var(--kma)"><dt>초단기예보</dt><dd>앞으로 6시간 시간별 비/눈 종류·강수량·기온</dd></div>
|
||||
<div style="--c:var(--kma)"><dt>중기예보</dt><dd>4~10일 뒤 오전·오후 날씨(맑음·구름·흐림·비)와 최저·최고기온</dd></div>
|
||||
<div style="--c:var(--kma)"><dt>기상특보</dt><dd>최근 7일 구역별 특보 종류(강풍·호우 등)와 단계</dd></div>
|
||||
@@ -184,6 +184,40 @@ code{font-family:var(--mono);font-size:12.5px;background:var(--soft-db);padding:
|
||||
</table></div>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<h2>왜 이 출처를 쓰나</h2>
|
||||
<p class="sub">결론: 기온·비 같은 예보는 기상청에서 받고, 기상청에 없는 높이별 구름만 Open-Meteo에서 받습니다. 예보는 Open-Meteo 한 번 호출로도 받을 수 있지만, 아래 세 가지 이유로 기상청을 씁니다.</p>
|
||||
<div class="rules">
|
||||
<div class="rule"><b>1. 앱 안에서 숫자가 엇갈리지 않는다</b><span>폭염·한파·호우 특보는 Open-Meteo가 주지 않습니다. 그래서 특보는 기상청에서 받을 수밖에 없습니다. 그런데 기상청은 자기 예보를 보고 특보를 내립니다. 기온·비를 Open-Meteo에서 받으면, 같은 피드에 "폭염주의보"와 그보다 낮은 최고기온이 함께 나오는 식으로 서로 엇갈릴 수 있습니다. 그래서 예보도 특보와 같은 기상청에서 받습니다.</span></div>
|
||||
<div class="rule"><b>2. 비용과 약관</b><span>기상청 데이터는 공공데이터라 회사 서비스에 써도 무료입니다. Open-Meteo 무료판은 비상업용이고 하루 1만·월 30만 번까지만 부를 수 있어, 회사 서비스면 유료 플랜이 필요합니다.</span></div>
|
||||
<div class="rule"><b>3. 어차피 국내 API가 필요</b><span>특보, 측정소 실측 미세먼지, 공휴일·절기, 축제는 Open-Meteo에 없어서 어느 쪽을 골라도 공공데이터포털을 써야 합니다. 예보까지 같은 곳에서 받으면 키 하나로 관리됩니다.</span></div>
|
||||
</div>
|
||||
<p class="hit"><b>두 예보를 비교해 보니 (10/6, 전국 20개 구, 앞으로 48시간)</b>: 기온이 평균 1.3°, 많게는 3.6°(속초) 달랐고 습도는 9%p 달랐습니다. 우리 앱은 기온 기준으로 각 점수와 문구를 정합니다. 예를 들어 주말 예보는 아침 10° 이하면 "두꺼운 겉옷 필수", 낮 28° 이상이면 "물이랑 모자"라고 씁니다. 그래서 1~3° 차이면 사용자에게 보이는 내용이 바뀝니다. 즉 출처를 바꾸는 것은 가볍게 정할 일이 아닙니다.<br>
|
||||
다만 이 비교로는 두 예보가 다르다는 것만 알 수 있고, 어느 쪽이 실제 날씨에 더 맞는지는 알 수 없습니다. 그래서 기온 차이 자체는 기상청을 고른 이유가 아닙니다. 정확도는 비 오는 날을 포함해 3일간 두 예보를 모아 실측과 비교할 예정입니다(TODO).</p>
|
||||
|
||||
<h2 style="margin-top:22px">기상청 예보를 왜 API 3개로 받나</h2>
|
||||
<p class="sub">기상청에는 기간 전체를 한 번에 주는 API가 없고, 기간마다 따로 줍니다. 그래서 화면에 필요한 기간에 맞춰 나눠 부릅니다.</p>
|
||||
<div class="scroll"><table>
|
||||
<thead><tr><th>기상청 API</th><th>기간</th><th>단위</th><th>쓰는 곳</th></tr></thead>
|
||||
<tbody>
|
||||
<tr><td>초단기예보</td><td>앞으로 6시간</td><td>1시간 · 구</td><td>"2시간 안에 비", 지금 날씨</td></tr>
|
||||
<tr><td>단기예보</td><td>오늘~글피 (4일)</td><td>1시간 · 구</td><td>오늘·내일 날씨, 각 점수, 출퇴근, 4일 안의 주말 플랜</td></tr>
|
||||
<tr><td>중기예보</td><td>4~10일 뒤</td><td>오전·오후 · 도</td><td>주간 날씨, 4일 넘게 남은 주말 예보·플랜</td></tr>
|
||||
</tbody>
|
||||
</table></div>
|
||||
|
||||
<h2 style="margin-top:22px">구름만 Open-Meteo인 이유</h2>
|
||||
<p class="sub">기상청 하늘 상태는 맑음·구름많음·흐림 3단계뿐입니다. 노을이 예쁜지는 구름 높이가 정합니다. 높은 구름은 노을빛을 받아 물들고, 낮은 구름은 해를 가립니다. 높이별 구름 양과 여러 나라 예보 모델의 비교를 무료로 받을 수 있는 곳이 Open-Meteo여서 이 부분만 씁니다. 회사 서비스면 이 부분도 유료 플랜이 필요합니다.</p>
|
||||
|
||||
<h2 style="margin-top:22px">이렇게 나눠서 감수하는 것</h2>
|
||||
<div class="warns">
|
||||
<div class="warn"><div class="tag doc">장애</div><p>외부 기관 5곳(기상청·에어코리아·Open-Meteo·TourAPI·천문연)에 기대므로 어느 한 곳이 멈추면 그 칸이 빠집니다. 별개로, 지금은 응답 없는 API를 너무 오래 기다려서 기상청이 멈추면 피드를 연 사람 일부가 100초 가까이 기다립니다. 이건 출처 수가 아니라 기다리는 방식의 문제라, Open-Meteo 하나로 바꿔도 똑같이 생깁니다. 출시 전에 "빨리 포기하고 저장된 값 보여주기"로 고칠 예정입니다(운영 점검 보고서 참고).</p></div>
|
||||
<div class="warn"><div class="tag doc">먼 날짜</div><p>4~10일 뒤는 중기예보라 도 단위·오전/오후로만 나옵니다. 그래서 주말까지 4일 넘게 남은 월·화요일에는 주말 플랜에 "15~19시 비" 같은 시간대를 넣을 수 없습니다. Open-Meteo는 이 기간도 1시간 단위로 주는데, 그걸 포기한 셈입니다.</p></div>
|
||||
<div class="warn"><div class="tag doc">유료 결정</div><p>노을 구름 때문에 출시 전에 Open-Meteo 유료 여부를 정해야 합니다.</p></div>
|
||||
</div>
|
||||
<p class="hit"><b>다시 볼 때</b>: 정확도 비교(TODO)에서 Open-Meteo가 뚜렷하게 더 맞는다고 나오면 다시 검토합니다. 그래도 1번 이유(특보와 엇갈림)는 남기 때문에 통일보다는 4~10일 뒤만 Open-Meteo로 받는 방식이 먼저 후보입니다.</p>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<h2>확인이 필요한 것</h2>
|
||||
<p class="sub">코드를 읽다가 발견한 점입니다. 고치지는 않았습니다.</p>
|
||||
@@ -103,12 +103,13 @@
|
||||
- 각마다 **하기 좋은 시간대**가 있음 (확정). 예: 야장각 18~24시, 피크닉각 12~15시, 러닝각 20시 이후, 환기각 14~16시, 등산각 오전
|
||||
- 6요소(기온·비·바람·습도·공기·시간대)를 0~100점으로 바꾸고 **각별 비중**으로 합산 (확정)
|
||||
- **바로 0점 조건**이 있음 (확정). 예: 야장각은 비 확률 80% 이상이거나 돌풍 14m/s 초과면 0점
|
||||
- 추이는 **오늘·내일·모레** (단기예보 범위), 칸 이름은 요일 (확정)
|
||||
- 추이는 4칸: **오늘·내일, 그다음 아직 안 나온 주말 날을 가까운 순으로** (확정). 월~목 = 오늘/내일/토/일, 금 = 금/토/일/다음 토, 토 = 토/일/다음 토/다음 일, 일 = 일/월/다음 토/다음 일. 칸 이름은 "오늘", "내일", "토 10.10"
|
||||
- 주말 날이 단기예보(시간별) 범위 밖이면 중기예보(최저·최고 기온, 오전·오후 비 확률)로 **예상 점수**를 내고 "예상"으로 표시. 기온·비 규칙은 그대로, 바람·습도·미세먼지는 정보 없음(70점), 0점 조건은 비 확률만 본다
|
||||
|
||||
### 4-2. 계산 순서
|
||||
|
||||
```
|
||||
각 하나에 대해, 하루(오늘·내일·모레) 각각:
|
||||
각 하나에 대해, 하루(오늘·내일·모레와 추이 칸의 주말 날) 각각:
|
||||
1. 그 각의 시간대에 들어가는 1시간 예보를 모은다 (단기예보 TMP·POP·PCP·REH·WSD, 미세먼지 등급, 일몰·달)
|
||||
2. 시간마다 6요소 점수를 0~100으로 바꾼다 (4-3의 곡선)
|
||||
3. 시간마다 바로 0점 조건을 본다 → 걸리면 그 시간은 0점
|
||||
@@ -196,7 +197,7 @@
|
||||
|
||||
| 요소 | 데이터 | 로직 |
|
||||
|---|---|---|
|
||||
| 이번 주 7일 띠 | 오늘~모레는 단기예보, 그 뒤는 **기상청 중기예보**(오전·오후 날씨, 최저·최고, 강수확률) | 3일 이후는 각 점수 없이 날씨만 보여 줘요 (중기예보에는 바람·습도·시간별 값이 없어서) |
|
||||
| 이번 주 7일 띠 | 오늘~모레는 단기예보, 그 뒤는 **기상청 중기예보**(오전·오후 날씨, 최저·최고, 강수확률) | 3일 이후는 각 점수 없이 날씨만 보여 줘요 (중기예보에는 바람·습도·시간별 값이 없어서). 각 상세 창의 주말 예상 점수는 이 띠에 쓰지 않아요 |
|
||||
| 날짜별 추천 한 줄 | 그날 각 순위 + 템플릿/AI 문구 | 예: 그날 1위 각 + 그 각에 맞는 지역 → "낮엔 여의도 피크닉, 밤엔 불꽃축제" |
|
||||
| 날씨 맞춤 데이트 명소 | DB 명소 표(지역, 실내·야외, 추천 시간) | 고른 날이 비 오면 실내 먼저, 맑으면 야외 먼저. 지역 드롭다운(성수, 연남·망원, 여의도, 잠실, 북촌·익선) (확정: 서울·데이트 명소, 맛집 제외) |
|
||||
| 서울 축제·행사 | 아래 6-1 | 진행 중 / 이번 주 / 2주 뒤 상태 표시, 그날 날씨가 맞는지 한 줄 |
|
||||
|
||||
@@ -0,0 +1,210 @@
|
||||
<title>날씨각 포스트 타입별 내용</title>
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com">
|
||||
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=IBM+Plex+Sans+KR:wght@400;500;700&family=IBM+Plex+Mono:wght@400;500&display=swap">
|
||||
<style>
|
||||
/* 레이아웃: 요약 표 → 타입별 카드(켜지는 조건 · 본문 · 슬라이드 · 데이터 · 문제). 데이터흐름.html 과 같은 토큰. */
|
||||
:root{
|
||||
--bg:#f5f7f9; --panel:#ffffff; --fg:#17212b; --muted:#5d6b78; --line:#d9e0e6; --grid:#e9eef2;
|
||||
--accent:#2f6fd6; --warn:#a4400f; --soft-warn:#fdefe6; --soft:#eef3fb;
|
||||
--sans:"IBM Plex Sans KR",-apple-system,"Apple SD Gothic Neo","Malgun Gothic",sans-serif;
|
||||
--mono:"IBM Plex Mono",ui-monospace,Menlo,monospace;
|
||||
}
|
||||
@media (prefers-color-scheme:dark){:root:not([data-theme="light"]){
|
||||
--bg:#10161c; --panel:#18212a; --fg:#e4eaf0; --muted:#a3b0bc; --line:#2c3844; --grid:#212c36;
|
||||
--accent:#6fa0f0; --warn:#f0a070; --soft-warn:#3a261c; --soft:#1c2a40; color-scheme:dark}}
|
||||
:root[data-theme="dark"]{
|
||||
--bg:#10161c; --panel:#18212a; --fg:#e4eaf0; --muted:#a3b0bc; --line:#2c3844; --grid:#212c36;
|
||||
--accent:#6fa0f0; --warn:#f0a070; --soft-warn:#3a261c; --soft:#1c2a40; color-scheme:dark}
|
||||
*{box-sizing:border-box}
|
||||
body{background:var(--bg);color:var(--fg);font:15px/1.6 var(--sans);margin:0}
|
||||
.wrap{max-width:1000px;margin:0 auto;padding-inline:20px;padding-block:36px 64px;display:flex;flex-direction:column;gap:36px}
|
||||
h1{font-size:28px;margin:0 0 6px;text-wrap:balance}
|
||||
h2{font-size:19px;margin:0 0 10px;text-wrap:balance}
|
||||
h3{font-size:17px;margin:0;text-wrap:balance}
|
||||
p{margin:0}
|
||||
.lead{color:var(--muted);max-width:70ch}
|
||||
code,.mono{font-family:var(--mono);font-size:.88em}
|
||||
section{min-width:0}
|
||||
.scroll{overflow-x:auto;border:1px solid var(--line);border-radius:8px;background:var(--panel)}
|
||||
table{border-collapse:collapse;width:100%;min-width:720px;font-size:13.5px}
|
||||
th,td{text-align:left;padding:9px 12px;border-bottom:1px solid var(--grid);vertical-align:top}
|
||||
th{color:var(--muted);font-weight:500;font-size:12.5px;letter-spacing:.03em}
|
||||
tr:last-child td{border-bottom:0}
|
||||
td.bad{color:var(--warn);font-weight:500}
|
||||
.types{display:flex;flex-direction:column;gap:14px}
|
||||
.type{background:var(--panel);border:1px solid var(--line);border-radius:8px;padding:16px 18px;display:flex;flex-direction:column;gap:10px;min-width:0}
|
||||
.type header{display:flex;gap:10px;align-items:baseline;flex-wrap:wrap}
|
||||
.type header .no{font-family:var(--mono);font-size:12px;color:var(--muted)}
|
||||
dl{display:grid;grid-template-columns:110px minmax(0,1fr);gap:6px 14px;margin:0;font-size:14px}
|
||||
dt{color:var(--muted)}
|
||||
dd{margin:0;min-width:0}
|
||||
.issue{background:var(--soft-warn);border-radius:6px;padding:10px 12px;font-size:14px}
|
||||
.issue b{color:var(--warn)}
|
||||
.note{background:var(--soft);border-radius:6px;padding:10px 12px;font-size:14px}
|
||||
ul{margin:0;padding-left:18px}
|
||||
@media (max-width:560px){dl{grid-template-columns:1fr}dt{margin-top:6px}}
|
||||
</style>
|
||||
|
||||
<div class="wrap">
|
||||
<header>
|
||||
<h1>포스트 타입별 내용</h1>
|
||||
<p class="lead">피드 카드 13종이 각각 어떤 데이터로 무엇을 보여 주는지 정리했습니다. 기준 코드는 <code>backend/services/feed_service.py</code>입니다. 카드 한 장은 위에서부터 슬라이드(그림 영역), 제목, 본문(<code>caption</code>) 순으로 보입니다 (<code>frontend/src/b/Post.tsx:381</code>). 2026-10-06 기준.</p>
|
||||
</header>
|
||||
|
||||
<section>
|
||||
<h2>한눈에 보기</h2>
|
||||
<div class="scroll"><table>
|
||||
<thead><tr><th>타입</th><th>켜지는 조건</th><th>본문(caption)</th><th>슬라이드</th><th>본문 판단</th></tr></thead>
|
||||
<tbody>
|
||||
<tr><td>1 오늘·내일 날씨</td><td>오늘 예보가 있을 때</td><td>앞으로 2시간 비 소식</td><td>3시간 간격 8칸 × 오늘·내일</td><td>새 정보</td></tr>
|
||||
<tr><td>2 각</td><td>항상 3장 (1~3위)</td><td>내일 점수와 오늘 대비 (없으면 하기 좋은 시간)</td><td>각 그림·점수·설명</td><td>새 정보</td></tr>
|
||||
<tr><td>3 노을</td><td>노을 점수가 있을 때</td><td>다음 날 노을 점수</td><td>노을 점수·시각 + 가까운 명소</td><td>새 정보</td></tr>
|
||||
<tr><td>4 계절 소식</td><td>그날 고른 글이 있을 때</td><td>글 둘째 문단</td><td>글 첫 문단</td><td>괜찮음</td></tr>
|
||||
<tr><td>5 축제·행사</td><td>30km 안, 7일 안에 열리는 행사 1~3위</td><td>"지금 진행 중 · 여기서 12km · 토요일 맑음 22°"</td><td>사진 + 장소·기간</td><td>새 정보</td></tr>
|
||||
<tr><td>6 날씨 상식</td><td>그날 고른 글이 있을 때</td><td>글 둘째 문단</td><td>글 첫 문단</td><td>괜찮음</td></tr>
|
||||
<tr><td>7 주말 예보</td><td>주말 예보가 있을 때</td><td>"이번 주말은 ○○만 챙기면 돼요…"</td><td>토·일 비교 + 옷차림·우산 팁</td><td>괜찮음</td></tr>
|
||||
<tr><td>8 생활 알림</td><td>비 40% 이상 또는 특보</td><td>특보 종류별 할 일 / 비는 우산 크기</td><td>특보·비 시각 표</td><td>새 정보</td></tr>
|
||||
<tr><td>9 내일 미리보기</td><td>지금 날씨를 받았을 때</td><td>내일 낮 최고기온, 오늘과 비교</td><td>출퇴근 날씨 + 내일 1위 각</td><td>새 정보</td></tr>
|
||||
<tr><td>10 한 문장</td><td>날씨에 맞는 문장이 있을 때</td><td>"맑은 오늘에 어울리는 한 문장이에요."</td><td>문장 + 출처(있을 때)</td><td>새 정보</td></tr>
|
||||
<tr><td>11 주말 플랜</td><td>이번 주말 토·일 각각</td><td>그날 한 줄 조언</td><td>시간대별 동선(바깥·행사·노을)</td><td>괜찮음</td></tr>
|
||||
<tr><td>12 미세먼지</td><td>가까운 측정소 값이 3시간 안일 때</td><td>"○○ 측정소 · 9시 기준"</td><td>초미세먼지·미세먼지 ㎍/㎥·등급 + 나쁨 이상이면 할 일</td><td>새 정보</td></tr>
|
||||
<tr><td>13 당일치기</td><td>내 지역에서 20~200km 후보 도시 중 이번 주말 나들이 점수 1위가 50점 이상일 때</td><td>"다음은 ○○, 토요일 75점이에요." (2위 도시)</td><td>도시·거리·날씨 근거·기온·볼거리 + 그 도시 행사 1~2개(사진)</td><td>새 정보</td></tr>
|
||||
</tbody>
|
||||
</table></div>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<h2>타입별 자세히</h2>
|
||||
<div class="types">
|
||||
|
||||
<article class="type">
|
||||
<header><span class="no">5 EVENT</span><h3>축제·행사</h3></header>
|
||||
<dl>
|
||||
<dt>켜지는 조건</dt><dd>내 지역 중심에서 30km 안(시도 상관없음, 좌표 없는 행사는 같은 시도)에서 오늘부터 7일 안에 열려 있는 행사가 순위만큼 있을 때. 피드에 최대 3장이 무작위 자리에 끼워집니다 (<code>feed_service.py:353</code>).</dd>
|
||||
<dt>슬라이드</dt><dd>행사 사진(없으면 아이콘), 머리말 "가까운 행사 · 진행 중/곧 시작", 행사 이름, 표(장소 — 비어 있으면 뺌, 기간 <code>10.5~10.11</code>).</dd>
|
||||
<dt>본문</dt><dd>진행 상태·거리(<code>distance_km</code>)·그날 날씨(<code>fit</code>) 중 있는 것을 이어 붙임: "지금 진행 중 · 여기서 12km · 토요일 맑음 22°". 진행 중이 아니고 거리·날씨가 다 없으면 "일정이 확정됐어요." 또는 "올해 정확한 일정은 공식 안내로 확인해 주세요." (<code>feed_service.py</code> <code>_event_caption</code>)</dd>
|
||||
<dt>데이터</dt><dd>TourAPI 행사·문화정보원 전시(<code>event</code> 테이블): 이름·장소·시작일·종료일·사진·좌표·일정 확정 여부. 시도 단위로 받으므로 반경에 걸칠 수 있는 주변 시도(구 중심 50km 안)까지 같이 받습니다 (<code>week_service.py</code> <code>nearby_sidos</code>). 그날 날씨는 기상청 중기예보.</dd>
|
||||
</dl>
|
||||
<div class="issue"><b>남은 것:</b> 행사 소개글은 <code>event</code> 테이블에 칸이 없어서 지금은 보여 줄 수 없습니다. TourAPI 상세 조회에는 소개글이 있습니다.</div>
|
||||
</article>
|
||||
|
||||
<article class="type">
|
||||
<header><span class="no">1 WEATHER</span><h3>오늘·내일 날씨</h3></header>
|
||||
<dl>
|
||||
<dt>켜지는 조건</dt><dd>오늘 예보가 있으면 항상. 히어로 바로 아래 고정 (특보가 있으면 생활 알림 다음).</dd>
|
||||
<dt>슬라이드</dt><dd>"오늘 하루 · 3시간마다", "내일 · 3시간마다" 두 장. 0·3·6…21시 8칸에 아이콘·기온, 기온 높이만큼 칸 배경을 채웁니다.</dd>
|
||||
<dt>본문</dt><dd>슬라이드에 없는 앞으로 2시간 비 소식: "앞으로 2시간, 우산 없어도 돼요". 미세먼지는 12 미세먼지 포스트로 옮김.</dd>
|
||||
<dt>데이터</dt><dd>기상청 단기예보(<code>weather_hourly</code>), 일출·일몰 계산으로 밤·노을 칸 구분 (<code>weather_service.py:83</code>).</dd>
|
||||
</dl>
|
||||
<div class="issue">노을 그림은 맑은 날 해 지는 칸에만 나오고, 흐리거나 구름 많으면 구름 그림입니다. 예보가 없는 칸은 그림 없이 비웁니다.</div>
|
||||
</article>
|
||||
|
||||
<article class="type">
|
||||
<header><span class="no">2 GAK</span><h3>각 (1~3위)</h3></header>
|
||||
<dl>
|
||||
<dt>켜지는 조건</dt><dd>항상 3장. 하기 좋은 시간이 가까운 각을 앞에 둡니다 (<code>feed_service.py:109</code>).</dd>
|
||||
<dt>슬라이드</dt><dd>"오늘의 각 · N위", 각 설명, 각 그림, 큰 점수, "계산 근거 보기" 버튼.</dd>
|
||||
<dt>본문</dt><dd>내일 점수와 오늘 대비: "내일은 72점, 오늘보다 13점 낮아요." 내일 점수가 없으면 하기 좋은 시간 "하기 좋은 때는 10~16시예요." 제목·공유 문구는 "피크닉각 85점".</dd>
|
||||
<dt>데이터</dt><dd>각 정의(<code>index_definition</code>)와 그날 점수(<code>index_score</code>). 점수는 기상청 예보·에어코리아 미세먼지로 계산.</dd>
|
||||
</dl>
|
||||
<div class="issue"><b>순위 문제:</b> 점수만으로 순위를 매겨 환기각·세차각 같은 가벼운 각이 1~3위에 듭니다. 중요도 반영 계획은 별도 보고.</div>
|
||||
</article>
|
||||
|
||||
<article class="type">
|
||||
<header><span class="no">3 SUNSET</span><h3>노을</h3></header>
|
||||
<dl>
|
||||
<dt>켜지는 조건</dt><dd>노을 점수가 있을 때. 해 지기 전엔 오늘, 진 뒤엔 내일 노을.</dd>
|
||||
<dt>슬라이드</dt><dd>60점 이상: 점수·등급·가장 붉은 시각과 촬영 시각들, 가까운 노을 명소와 거리. 60점 미만: 슬라이드 없이 한 줄 카드 "오늘 노을은 쉬어요".</dd>
|
||||
<dt>본문</dt><dd>다음 날 노을 점수 "내일 노을은 N점이에요." (내일 노을 카드면 모레). 없으면 "가장 붉은 때 앞뒤 20분이 골든타임이에요." / 한 줄 카드는 "구름에 가려요. 내일 노을 N점이에요." 명소 슬라이드는 "해 지는 서쪽이 트인 곳"처럼 방위 이름으로.</dd>
|
||||
<dt>데이터</dt><dd>노을 점수(<code>sky_score</code>): 기상청 하늘 상태 + Open-Meteo 높이별 구름양. 명소는 자체 목록.</dd>
|
||||
</dl>
|
||||
</article>
|
||||
|
||||
<article class="type">
|
||||
<header><span class="no">4 SEASON · 6 TIP</span><h3>계절 소식 · 날씨 상식</h3></header>
|
||||
<dl>
|
||||
<dt>켜지는 조건</dt><dd>그날 날짜에 맞는 글이 있을 때. 날짜마다 돌아가며 한 편.</dd>
|
||||
<dt>슬라이드</dt><dd>머리말 "계절 소식"/"날씨 상식", 글 첫 문단, 아이콘.</dd>
|
||||
<dt>본문</dt><dd>글 둘째 문단 (없으면 첫 문단).</dd>
|
||||
<dt>데이터</dt><dd>직접 쓴 글(<code>article</code>). 절기는 KASI.</dd>
|
||||
</dl>
|
||||
</article>
|
||||
|
||||
<article class="type">
|
||||
<header><span class="no">7 WEEK</span><h3>주말 예보</h3></header>
|
||||
<dl>
|
||||
<dt>켜지는 조건</dt><dd>예보가 닿는 주말이 있을 때. 금요일 저녁엔 앞쪽으로.</dd>
|
||||
<dt>슬라이드</dt><dd>이번 주말·다음 주말 각 한 장: 토·일 아이콘·최저/최고·비 확률, 옷차림·우산 팁.</dd>
|
||||
<dt>본문</dt><dd>"이번 주말은 ○○만 챙기면 돼요. 토·일 플랜은 피드에 따로 올려둘게요."</dd>
|
||||
<dt>데이터</dt><dd>기상청 단기·중기예보(<code>weather_daily</code>).</dd>
|
||||
</dl>
|
||||
</article>
|
||||
|
||||
<article class="type">
|
||||
<header><span class="no">8 ALERT</span><h3>생활 알림</h3></header>
|
||||
<dl>
|
||||
<dt>켜지는 조건</dt><dd>오늘 남은 시간 비 40% 이상, 내일 출근 8시·퇴근 7시 비 40% 이상, 특보 중 하나라도 있을 때.</dd>
|
||||
<dt>슬라이드</dt><dd>"생활 알림 · 동네", 한 줄, 표(특보 문구, "오늘 15시부터 비 60%", "내일 출근 8시 비 50%").</dd>
|
||||
<dt>본문</dt><dd>특보: 종류별 할 일 (폭염 "낮 12시~5시엔 그늘에서 쉬어 가요.", 한파 "장갑·목도리 챙기고 수도관 얼지 않게 해요." 등) / 비: 비 확률 60% 이상이면 "큰 우산이 든든해요.", 아니면 "접는 우산이면 충분해요." 아이콘·공유 문구도 특보 종류별 (비만 우산·"☔ 우산 챙겨!").</dd>
|
||||
<dt>데이터</dt><dd>기상청 단기예보 비 확률, 기상청 특보.</dd>
|
||||
</dl>
|
||||
</article>
|
||||
|
||||
<article class="type">
|
||||
<header><span class="no">9 TOMORROW</span><h3>내일 미리보기</h3></header>
|
||||
<dl>
|
||||
<dt>켜지는 조건</dt><dd>지금 날씨를 받았을 때. 저녁·밤 시간대에만 보입니다.</dd>
|
||||
<dt>슬라이드</dt><dd>"내일 · 동네", 내일 한 줄, 표(출퇴근 날씨, 내일 1위 각과 점수).</dd>
|
||||
<dt>본문</dt><dd>내일 낮 최고기온을 오늘과 비교: "내일 낮 최고 19°, 오늘보다 4° 쌀쌀해요." 비교할 예보가 없으면 "출근 전에 한 번 더 확인해 주세요."</dd>
|
||||
<dt>데이터</dt><dd>기상청 단기예보, 내일 각 점수.</dd>
|
||||
</dl>
|
||||
</article>
|
||||
|
||||
<article class="type">
|
||||
<header><span class="no">10 QUOTE</span><h3>한 문장</h3></header>
|
||||
<dl>
|
||||
<dt>켜지는 조건</dt><dd>오늘 날씨(비·흐림·맑음, 밤)에 맞는 문장이 있을 때. 밤엔 맨 뒤.</dd>
|
||||
<dt>슬라이드</dt><dd>"오늘의 한 문장", 문장, 출처(작가가 있는 문장만).</dd>
|
||||
<dt>본문</dt><dd>왜 이 문장인지: "비 오는 오늘·흐린 오늘·맑은 오늘에 어울리는 한 문장이에요.", 밤 문장은 "잠들기 전에 어울리는 한 문장이에요."</dd>
|
||||
<dt>데이터</dt><dd>직접 고른 문장(<code>article</code>, 코드 앞머리로 날씨 구분).</dd>
|
||||
</dl>
|
||||
</article>
|
||||
|
||||
<article class="type">
|
||||
<header><span class="no">11 WEEKEND_PLAN</span><h3>주말 플랜 (토·일 각 한 장)</h3></header>
|
||||
<dl>
|
||||
<dt>켜지는 조건</dt><dd>이번 주말 예보가 있을 때 날마다 한 장.</dd>
|
||||
<dt>슬라이드</dt><dd>시간대별 동선: 아침이 쌀쌀하면 겉옷, 비 오는 시간엔 실내, 12~16시 바깥, 행사 1~2개(사진), 토요일은 노을 보고 저녁·일요일은 일찍 귀가.</dd>
|
||||
<dt>본문</dt><dd>그날 끝나는 축제가 있으면 "끝나는 축제부터 챙기기", 비면 "우산 필수", 맑으면 "12시부터 16시까지는 무조건 밖으로!", 흐리거나 구름 많으면 "비 소식 없어요. 12시부터 16시까지 바깥 일정 잡기 좋아요!"</dd>
|
||||
<dt>데이터</dt><dd>기상청 예보(비 오는 시간·기온), 일몰 계산, 30km 안 행사 (<code>weekend_plan.py:100</code>).</dd>
|
||||
</dl>
|
||||
</article>
|
||||
|
||||
<article class="type">
|
||||
<header><span class="no">12 AIR</span><h3>미세먼지</h3></header>
|
||||
<dl>
|
||||
<dt>켜지는 조건</dt><dd>가까운 측정소 값이 있고 3시간 안에 잰 것일 때. 아침엔 생활 알림 다음, 낮엔 셋째쯤, 저녁엔 내일 미리보기 앞, 밤엔 뒤쪽.</dd>
|
||||
<dt>슬라이드</dt><dd>"지금 공기 · <i>구</i>", 등급별 큰 줄("공기 맑아요, 창문 활짝 열어도 돼요" 등), 표(초미세먼지·미세먼지 <code>12㎍/㎥ · 좋음</code>, 나쁨 이상이면 "이렇게 해요" — KF80/KF94 마스크·외출 줄이기). 제목은 둘 중 나쁜 쪽 등급.</dd>
|
||||
<dt>본문</dt><dd>측정소와 시각: "○○ 측정소 · 9시 기준".</dd>
|
||||
<dt>데이터</dt><dd>에어코리아 실시간 측정(<code>air_quality</code>), 등급은 수치로 환경부 기준(초미세 15·35·75, 미세 30·80·150)에 맞춰 계산 (<code>air_service.py</code>, <code>feed_service.py</code> <code>_air</code>).</dd>
|
||||
</dl>
|
||||
<div class="issue"><b>남은 것:</b> 오늘 시간대별 미세먼지 예보는 아직 받지 않아 슬라이드에 없습니다. 마스크 아이콘이 없어 좋음·보통은 환기, 나쁨 이상은 구름 아이콘을 씁니다.</div>
|
||||
</article>
|
||||
|
||||
<article class="type">
|
||||
<header><span class="no">13 DAY_TRIP</span><h3>당일치기</h3></header>
|
||||
<dl>
|
||||
<dt>켜지는 조건</dt><dd>후보 도시(<code>backend/seed/trip_city.csv</code>, 지금 강릉·속초·춘천·가평·양평·인천·대전·전주·태안·단양 10곳) 중 내 지역에서 직선 20~200km 안인 곳의 이번 주말(토·일, 오늘 이후) 나들이 점수 1위가 50점 이상일 때. 주말 플랜 바로 뒤.</dd>
|
||||
<dt>슬라이드</dt><dd>첫 장 "당일치기 · 토요일 10.10", 큰 줄 "토요일엔 강릉, 나들이 86점", 표(거리 "여기서 약 160km", 날씨 근거 "비 10% · 체감 21° · 맑음" — 중기예보로 어림하면 "예상 날씨", 기온, 볼거리). 뒤로 그날 그 도시 30km 안 행사 최대 2장(사진 + 장소·기간).</dd>
|
||||
<dt>본문</dt><dd>2위 도시: "다음은 춘천, 일요일 75점이에요." 후보가 하나뿐이면 "아침 일찍 출발하면 하루가 넉넉해요."</dd>
|
||||
<dt>데이터</dt><dd>나들이 날씨 점수(<code>index_calc.py</code> <code>outing</code>·<code>outing_estimate</code>: 낮 10~17시 비 40%·기온 35%(체감 17~24°, 21° 최적)·하늘 15%·바람 10%, 비 확률 60% 이상이거나 비 소식이면 최대 30점). 단기예보 안이면 시간별, 밖이면 중기예보. 워커가 06:40·18:40에 계산해 Redis(<code>weekend_rank:<i>토요일</i></code>)에 둔 값만 쓰고, 없으면 카드를 끄고 피드를 60초만 캐시. 행사는 <code>WeekService.events</code>를 그 도시 기준으로 (<code>weekend_rank.py</code>, <code>feed_service.py</code> <code>_day_trip</code>).</dd>
|
||||
</dl>
|
||||
</article>
|
||||
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="note">
|
||||
피드에 같이 나오지만 포스트가 아닌 것: 히어로(지금 기온·체감·불쾌지수·2시간 비·1위 각), 오늘의 각 줄(전체 순위), 띠 3종(행사 4개, TOP5, 계절 글 목록).
|
||||
</section>
|
||||
</div>
|
||||
@@ -112,7 +112,7 @@ td .note{display:block;color:var(--muted);font-size:12px;margin-top:3px;line-hei
|
||||
|
||||
<article class="card">
|
||||
<header><h3>오늘의 각 1·2·3위</h3><span class="kind">핵심 콘텐츠 · 3장</span><span class="state always">항상</span></header>
|
||||
<dl><dt>보여 주는 것</dt><dd>그날 하루 기준 순위(확정). 100점은 완벽한 조건(예: 기온 22°·습도 30%·미풍)에만 주고, 편한 범위 안이라도 최적값에서 멀면 깎이며 가장 나쁜 요인이 전체를 끌어내립니다(확정, 10/6). 점수, 하기 좋은 시간, 이유 한 줄, 보낼 문구("치맥 한잔 할래?").</dd></dl>
|
||||
<dl><dt>보여 주는 것</dt><dd>그날 하루 기준 순위(확정). 100점은 완벽한 조건(예: 기온 22°·습도 30%·미풍)에만 주고, 편한 범위 안이라도 최적값에서 멀면 깎이며 가장 나쁜 요인이 전체를 끌어내립니다(확정, 10/2). 점수, 하기 좋은 시간, 이유 한 줄, 보낼 문구("치맥 한잔 할래?").</dd></dl>
|
||||
<dl><dt>① 유저</dt><dd>날씨 숫자 대신 "오늘 뭐 하면 좋은지"를 받습니다.</dd></dl>
|
||||
<dl><dt>② 운영</dt><dd>다른 날씨 서비스에 없는 우리만의 콘텐츠. 각마다 상세 페이지가 검색에 걸립니다.</dd></dl>
|
||||
</article>
|
||||
@@ -132,15 +132,22 @@ td .note{display:block;color:var(--muted);font-size:12px;margin-top:3px;line-hei
|
||||
</article>
|
||||
|
||||
<article class="card">
|
||||
<header><h3>주말 추천</h3><span class="kind">계획</span><span class="state always">매일</span></header>
|
||||
<dl><dt>켜지는 때</dt><dd>평일에도 매일(확정, 10/6). 첫 장은 이번 주말, 다음 주말은 예보가 닿는 날(오늘+10일, 수요일쯤)부터 두 번째 장으로 붙습니다. "이번 주말 야장 추천: 성수동" 수준으로 단순하게(확정).</dd></dl>
|
||||
<dl><dt>① 유저</dt><dd>주말 약속 장소와 날을 정하는 근거가 됩니다.</dd></dl>
|
||||
<header><h3>주말 예보</h3><span class="kind">계획</span><span class="state always">매일</span></header>
|
||||
<dl><dt>켜지는 때</dt><dd>평일에도 매일(확정, 10/2). 첫 장은 이번 주말, 다음 주말은 예보가 닿는 날(오늘+10일, 수요일쯤)부터 두 번째 장으로 붙습니다. 토·일 최저→최고 기온, 비 확률, 일교차를 나란히 비교하고 "토·일 둘 다 맑음! 나들이 확정각"처럼 한 줄로 정리합니다. 아래에 옷차림·우산 팁 하나(비 > 더위 > 추위 > 일교차 순으로 하나만, 10/6 변경).</dd></dl>
|
||||
<dl><dt>① 유저</dt><dd>주말 약속 날을 정하는 근거가 됩니다.</dd></dl>
|
||||
<dl><dt>② 운영</dt><dd>단톡방에 공유되는 카드. 목·금 방문이 늘어납니다.</dd></dl>
|
||||
</article>
|
||||
|
||||
<article class="card">
|
||||
<header><h3>주말 플랜</h3><span class="kind">계획 · 날마다 1장</span><span class="state always">매일</span></header>
|
||||
<dl><dt>켜지는 때</dt><dd>이번 주말 토·일 각각 독립 카드(포스트는 최대한 나눈다, 10/6). 그날 시간대별 동선: 아침 기온(일교차 크면 겉옷) → 12~16시 바깥 골든타임(비 오는 시간이 있으면 그 시간은 실내, 앞뒤로 바깥) → 그날 열리는 행사 최대 2곳(사진·장소) → 토요일은 일몰 시각에 노을, 일요일은 월요일 아침 기온과 함께 일찍 귀가. 행사는 가까운 순, 일요일은 그날 끝나는 행사 먼저("마지막 날 찬스"). 토요일에 고른 행사는 일요일에 다시 안 나옵니다.</dd></dl>
|
||||
<dl><dt>① 유저</dt><dd>"주말에 뭐 하지"에 시간표째로 답을 얻습니다.</dd></dl>
|
||||
<dl><dt>② 운영</dt><dd>날마다 내용이 달라 주말 직전까지 볼 이유가 생기고, "토요일 이렇게 놀자" 공유 카드가 됩니다.</dd></dl>
|
||||
</article>
|
||||
|
||||
<article class="card">
|
||||
<header><h3>행사·축제</h3><span class="kind">나들이 · 최대 3장</span><span class="state cond">조건부</span></header>
|
||||
<dl><dt>켜지는 때</dt><dd>그 시도에서 7일 안에 열리는 행사가 있을 때. 가까운 순으로 최대 3장을 각각 독립 카드로, 다른 카드 사이사이 무작위 자리에 넣습니다. 자리는 하루 동안 그대로입니다(확정, 10/6). 그날 날씨와 같이 보여 줍니다("토요일 맑음, 갈 만해요").</dd></dl>
|
||||
<dl><dt>켜지는 때</dt><dd>그 시도에서 7일 안에 열리는 행사가 있을 때. 가까운 순으로 최대 3장을 각각 독립 카드로, 다른 카드 사이사이 무작위 자리에 넣습니다. 자리는 하루 동안 그대로입니다(확정, 10/2). 그날 날씨와 같이 보여 줍니다("토요일 맑음, 갈 만해요").</dd></dl>
|
||||
<dl><dt>① 유저</dt><dd>날씨 좋은 날 갈 곳을 얻습니다.</dd></dl>
|
||||
<dl><dt>② 운영</dt><dd>"○○ 축제 날씨" 검색 유입.</dd></dl>
|
||||
</article>
|
||||
@@ -186,11 +193,12 @@ td .note{display:block;color:var(--muted);font-size:12px;margin-top:3px;line-hei
|
||||
<tr><td class="name">각 1·2·3위</td><td><span class="pos">2–4</span><span class="note">하기 좋은 시간이 가까운 각이 앞</span></td><td><span class="pos top">1–3</span></td><td><span class="pos">2–4</span><span class="note">시간이 지난 각은 뒤로</span></td><td><span class="pos">5–7</span><span class="note">오늘 순위 그대로(확정). 내일 순위는 내일 미리보기에서</span></td></tr>
|
||||
<tr><td class="name">노을<small>60점 미만은 한 줄</small></td><td><span class="pos">6</span><span class="note">"오늘 저녁 노을 예쁠 예정"</span></td><td><span class="pos">4</span></td><td><span class="pos top">1</span><span class="note">일몰 전까지</span></td><td><span class="pos">3</span><span class="note">내일 일출로 바뀜</span></td></tr>
|
||||
<tr><td class="name">내일 미리보기</td><td><span class="pos off">꺼짐</span></td><td><span class="pos off">꺼짐</span></td><td><span class="pos">5</span></td><td><span class="pos top">1</span></td></tr>
|
||||
<tr><td class="name">주말 추천<small>매일</small></td><td><span class="pos">8</span></td><td><span class="pos">6</span></td><td><span class="pos">6</span><span class="note">금요일은 2</span></td><td><span class="pos">4</span></td></tr>
|
||||
<tr><td class="name">주말 예보<small>매일</small></td><td><span class="pos">8</span></td><td><span class="pos">6</span></td><td><span class="pos">7</span><span class="note">금요일은 2</span></td><td><span class="pos">4</span></td></tr>
|
||||
<tr><td class="name">주말 플랜<small>토·일 2장</small></td><td><span class="pos">9·10</span><span class="note">같은 종류가 붙으면 떨어뜨림</span></td><td><span class="pos">7·9</span></td><td><span class="pos">8·10</span></td><td><span class="pos">6·9</span></td></tr>
|
||||
<tr><td class="name">행사<small>7일 안 · 최대 3장</small></td><td><span class="pos">무작위</span><span class="note">사이사이, 하루 같은 자리</span></td><td><span class="pos">무작위</span></td><td><span class="pos">무작위</span></td><td><span class="pos">무작위</span><span class="note">한 문장보다는 앞</span></td></tr>
|
||||
<tr><td class="name">계절 소식</td><td><span class="pos">5</span></td><td><span class="pos">7</span></td><td><span class="pos">8</span></td><td><span class="pos">6</span></td></tr>
|
||||
<tr><td class="name">날씨 상식</td><td><span class="pos">7</span></td><td><span class="pos">8</span></td><td><span class="pos">9</span></td><td><span class="pos">9</span></td></tr>
|
||||
<tr><td class="name">한 문장·시</td><td><span class="pos">10</span></td><td><span class="pos">9</span></td><td><span class="pos">10</span></td><td><span class="pos top">맨 끝 고정</span><span class="note">하루 마감 문장(확정)</span></td></tr>
|
||||
<tr><td class="name">계절 소식</td><td><span class="pos">5</span></td><td><span class="pos">8</span></td><td><span class="pos">9</span></td><td><span class="pos">10</span></td></tr>
|
||||
<tr><td class="name">날씨 상식</td><td><span class="pos">7</span></td><td><span class="pos">10</span></td><td><span class="pos">11</span></td><td><span class="pos">11</span></td></tr>
|
||||
<tr><td class="name">한 문장·시</td><td><span class="pos">11</span></td><td><span class="pos">11</span></td><td><span class="pos">12</span></td><td><span class="pos top">맨 끝 고정</span><span class="note">하루 마감 문장(확정)</span></td></tr>
|
||||
</tbody>
|
||||
</table></div>
|
||||
<div class="legend"><span><span class="pos top">1</span> 그 시간대의 주인공</span><span><span class="pos">5</span> 순서</span><span><span class="pos off">꺼짐</span> 그 시간대엔 안 보임</span><span>조건부 카드는 조건이 안 맞으면 시간대와 상관없이 빠지고 뒤 카드가 올라옵니다. 행사 카드가 끼면 그 뒤 카드는 한 칸씩 밀립니다.</span></div>
|
||||
@@ -205,10 +213,10 @@ td .note{display:block;color:var(--muted);font-size:12px;margin-top:3px;line-hei
|
||||
<div><span class="n">4</span><p>좋아요·댓글은 카드에 붙고, 전국 사용자가 같이 봅니다. 순서가 바뀌어도 같은 카드면 좋아요가 이어집니다.</p></div>
|
||||
<div><span class="n">5</span><p>시간대가 바뀌는 순간(05·11·16·21시)과 일몰 시각, 예보 갱신 때 피드가 새로 짜입니다.<small>앞에서 문제가 됐던 "새 칸이 늦게 보이는 문제"가 생기지 않습니다.</small></p></div>
|
||||
<div><span class="n">6</span><p>카드마다 보낼 문구가 있고, 보내면 카드 그대로 이미지+링크로 갑니다(확정).</p></div>
|
||||
<div><span class="n">7</span><p>UI는 따로 고민하지 않고 인스타그램·페이스북 방식을 그대로 따릅니다(확정, 10/6).</p></div>
|
||||
<div><span class="n">8</span><p>지역은 날씨를 가져오는 시군구 단위 그대로입니다. 수원시 장안구 같은 일반구도 따로 봅니다(확정, 10/6, 256곳).</p></div>
|
||||
<div><span class="n">7</span><p>UI는 따로 고민하지 않고 인스타그램·페이스북 방식을 그대로 따릅니다(확정, 10/2).</p></div>
|
||||
<div><span class="n">8</span><p>지역은 날씨를 가져오는 시군구 단위 그대로입니다. 수원시 장안구 같은 일반구도 따로 봅니다(확정, 10/2, 256곳).</p></div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<p class="foot">근거: docs/콘텐츠설계서.md, docs/콘텐츠구현기획.md 8장, 2026-09-30·2026-10-06 회의 확정 사항(docs/meetings/2026-10-06.md). 버전 v2.3, 2026-10-06. 카드 10종으로 진행, 추가 카드는 나중에.</p>
|
||||
<p class="foot">근거: docs/콘텐츠설계서.md, docs/콘텐츠구현기획.md 8장, 2026-09-30·2026-10-02 회의 확정 사항(docs/meetings/2026-10-02.md). 버전 v2.3, 2026-10-06. 카드 10종으로 진행, 추가 카드는 나중에.</p>
|
||||
</div>
|
||||
@@ -84,7 +84,7 @@ code{font-family:var(--mono);font-size:12.5px;background:var(--soft);padding:1px
|
||||
<div class="scroll"><table>
|
||||
<thead><tr><th>콘텐츠</th><th>출처</th><th>언제 새로</th></tr></thead>
|
||||
<tbody>
|
||||
<tr><td>1~3위 · 분야별 목록</td><td><div class="chips"><span class="chip calc">계산</span></div><small>오늘·내일·모레, 각마다 하기 좋은 시간대 예보로</small></td><td class="when">예보·미세먼지 바뀔 때</td></tr>
|
||||
<tr><td>1~3위 · 분야별 목록</td><td><div class="chips"><span class="chip calc">계산</span></div><small>오늘·내일·모레와 이번 주말, 각마다 하기 좋은 시간대 예보로. 시간별 예보가 없는 주말 날은 중기예보로 낸 예상 점수</small></td><td class="when">예보·미세먼지 바뀔 때</td></tr>
|
||||
<tr><td>계산 근거 (방사형 그래프)</td><td><div class="chips"><span class="chip calc">요소 6개 점수</span><span class="chip seed">각 정의 27개</span></div><small>기온·비·바람·습도·공기·시간대</small></td><td class="when">위와 같음</td></tr>
|
||||
<tr><td>각 점수는 어떻게 매길까?</td><td><div class="chips"><span class="chip seed">글</span></div></td><td class="when">—</td></tr>
|
||||
</tbody>
|
||||
@@ -147,5 +147,5 @@ code{font-family:var(--mono);font-size:12.5px;background:var(--soft);padding:1px
|
||||
<p>좋아요·댓글·프로필은 사용자가 만든 실제 값입니다.</p>
|
||||
</section>
|
||||
|
||||
<p class="foot">기준: main a7220b2, 2026-10-06. 상세 흐름은 docs/데이터지도.html.</p>
|
||||
<p class="foot">기준: main a7220b2, 2026-10-06. 상세 흐름은 docs/데이터흐름.html.</p>
|
||||
</div>
|
||||
@@ -1 +1 @@
|
||||
{"version":1,"sessions":{"8dca1a79-a5f0-4a96-a6a0-46a1ea37b382":{"updatedAt":1790727492068,"files":{"/Users/minachoi/orca/workspaces/o2o-weather/main-2/frontend/src/a/APages.tsx":{"editCount":2,"findings":[],"stopBaseline":{"version":1,"engine":"0.1.5","counts":{}},"cleanAcked":true}},"footerShown":true},"9c398292-16d6-4b79-a132-a0f1dcfae041":{"updatedAt":1790905454036,"files":{"/Users/minachoi/orca/workspaces/o2o-weather/main-2/frontend/src/b/b.css":{"editCount":1,"findings":[],"stopBaseline":{"version":1,"engine":"0.1.5","counts":{}},"cleanAcked":true},"/Users/minachoi/orca/workspaces/o2o-weather/main-2/frontend/src/b/ui.tsx":{"editCount":1,"findings":[],"stopBaseline":{"version":1,"engine":"0.1.5","counts":{}},"cleanAcked":true},"/Users/minachoi/orca/workspaces/o2o-weather/main-2/frontend/src/b/mock/feed.ts":{"editCount":1,"findings":[],"stopBaseline":{"version":1,"engine":"0.1.5","counts":{}}},"/Users/minachoi/orca/workspaces/o2o-weather/main-2/frontend/src/b/mock/week.ts":{"editCount":1,"findings":[],"stopBaseline":{"version":1,"engine":"0.1.5","counts":{}}},"/Users/minachoi/orca/workspaces/o2o-weather/main-2/frontend/src/b/mock/season.ts":{"editCount":1,"findings":[],"stopBaseline":{"version":1,"engine":"0.1.5","counts":{}}},"/Users/minachoi/orca/workspaces/o2o-weather/main-2/frontend/src/b/data.ts":{"editCount":1,"findings":[],"stopBaseline":{"version":1,"engine":"0.1.5","counts":{}}},"/Users/minachoi/orca/workspaces/o2o-weather/main-2/frontend/src/b/Sheets.tsx":{"editCount":1,"findings":[],"stopBaseline":{"version":1,"engine":"0.1.5","counts":{}},"cleanAcked":true},"/Users/minachoi/orca/workspaces/o2o-weather/main-2/frontend/src/b/svg.tsx":{"editCount":1,"findings":[],"stopBaseline":{"version":1,"engine":"0.1.5","counts":{}},"cleanAcked":true},"/Users/minachoi/orca/workspaces/o2o-weather/main-2/frontend/src/b/BLayout.tsx":{"editCount":1,"findings":[],"stopBaseline":{"version":1,"engine":"0.1.5","counts":{}},"cleanAcked":true},"/Users/minachoi/orca/workspaces/o2o-weather/main-2/frontend/src/b/Post.tsx":{"editCount":1,"findings":[],"stopBaseline":{"version":1,"engine":"0.1.5","counts":{}},"cleanAcked":true},"/Users/minachoi/orca/workspaces/o2o-weather/main-2/frontend/src/b/realPosts.ts":{"editCount":1,"findings":[],"stopBaseline":{"version":1,"engine":"0.1.5","counts":{}}},"/Users/minachoi/orca/workspaces/o2o-weather/main-2/frontend/src/b/TodayPage.tsx":{"editCount":1,"findings":[],"stopBaseline":{"version":1,"engine":"0.1.5","counts":{}},"cleanAcked":true},"/Users/minachoi/orca/workspaces/o2o-weather/main-2/frontend/src/b/GakPage.tsx":{"editCount":1,"findings":[],"stopBaseline":{"version":1,"engine":"0.1.5","counts":{}},"cleanAcked":true},"/Users/minachoi/orca/workspaces/o2o-weather/main-2/frontend/src/b/SkyPage.tsx":{"editCount":1,"findings":[],"stopBaseline":{"version":1,"engine":"0.1.5","counts":{}},"cleanAcked":true},"/Users/minachoi/orca/workspaces/o2o-weather/main-2/frontend/src/b/WeekPage.tsx":{"editCount":1,"findings":[],"stopBaseline":{"version":1,"engine":"0.1.5","counts":{}},"cleanAcked":true},"/Users/minachoi/orca/workspaces/o2o-weather/main-2/frontend/src/b/SeasonPage.tsx":{"editCount":2,"findings":[],"stopBaseline":{"version":1,"engine":"0.1.5","counts":{}},"cleanAcked":true},"/Users/minachoi/orca/workspaces/o2o-weather/main-2/frontend/src/api/mutator/custom-fetch.ts":{"editCount":1,"findings":[],"stopBaseline":{"version":1,"engine":"0.1.5","counts":{}}}}}}}
|
||||
{"version":1,"sessions":{"8dca1a79-a5f0-4a96-a6a0-46a1ea37b382":{"updatedAt":1790727492068,"files":{"/Users/minachoi/orca/workspaces/o2o-weather/main-2/frontend/src/a/APages.tsx":{"editCount":2,"findings":[],"stopBaseline":{"version":1,"engine":"0.1.5","counts":{}},"cleanAcked":true}},"footerShown":true},"9c398292-16d6-4b79-a132-a0f1dcfae041":{"updatedAt":1790905454036,"files":{"/Users/minachoi/orca/workspaces/o2o-weather/main-2/frontend/src/b/b.css":{"editCount":1,"findings":[],"stopBaseline":{"version":1,"engine":"0.1.5","counts":{}},"cleanAcked":true},"/Users/minachoi/orca/workspaces/o2o-weather/main-2/frontend/src/b/ui.tsx":{"editCount":1,"findings":[],"stopBaseline":{"version":1,"engine":"0.1.5","counts":{}},"cleanAcked":true},"/Users/minachoi/orca/workspaces/o2o-weather/main-2/frontend/src/b/mock/feed.ts":{"editCount":1,"findings":[],"stopBaseline":{"version":1,"engine":"0.1.5","counts":{}}},"/Users/minachoi/orca/workspaces/o2o-weather/main-2/frontend/src/b/mock/week.ts":{"editCount":1,"findings":[],"stopBaseline":{"version":1,"engine":"0.1.5","counts":{}}},"/Users/minachoi/orca/workspaces/o2o-weather/main-2/frontend/src/b/mock/season.ts":{"editCount":1,"findings":[],"stopBaseline":{"version":1,"engine":"0.1.5","counts":{}}},"/Users/minachoi/orca/workspaces/o2o-weather/main-2/frontend/src/b/data.ts":{"editCount":1,"findings":[],"stopBaseline":{"version":1,"engine":"0.1.5","counts":{}}},"/Users/minachoi/orca/workspaces/o2o-weather/main-2/frontend/src/b/Sheets.tsx":{"editCount":1,"findings":[],"stopBaseline":{"version":1,"engine":"0.1.5","counts":{}},"cleanAcked":true},"/Users/minachoi/orca/workspaces/o2o-weather/main-2/frontend/src/b/svg.tsx":{"editCount":1,"findings":[],"stopBaseline":{"version":1,"engine":"0.1.5","counts":{}},"cleanAcked":true},"/Users/minachoi/orca/workspaces/o2o-weather/main-2/frontend/src/b/BLayout.tsx":{"editCount":1,"findings":[],"stopBaseline":{"version":1,"engine":"0.1.5","counts":{}},"cleanAcked":true},"/Users/minachoi/orca/workspaces/o2o-weather/main-2/frontend/src/b/Post.tsx":{"editCount":1,"findings":[],"stopBaseline":{"version":1,"engine":"0.1.5","counts":{}},"cleanAcked":true},"/Users/minachoi/orca/workspaces/o2o-weather/main-2/frontend/src/b/realPosts.ts":{"editCount":1,"findings":[],"stopBaseline":{"version":1,"engine":"0.1.5","counts":{}}},"/Users/minachoi/orca/workspaces/o2o-weather/main-2/frontend/src/b/TodayPage.tsx":{"editCount":1,"findings":[],"stopBaseline":{"version":1,"engine":"0.1.5","counts":{}},"cleanAcked":true},"/Users/minachoi/orca/workspaces/o2o-weather/main-2/frontend/src/b/GakPage.tsx":{"editCount":1,"findings":[],"stopBaseline":{"version":1,"engine":"0.1.5","counts":{}},"cleanAcked":true},"/Users/minachoi/orca/workspaces/o2o-weather/main-2/frontend/src/b/SkyPage.tsx":{"editCount":1,"findings":[],"stopBaseline":{"version":1,"engine":"0.1.5","counts":{}},"cleanAcked":true},"/Users/minachoi/orca/workspaces/o2o-weather/main-2/frontend/src/b/WeekPage.tsx":{"editCount":1,"findings":[],"stopBaseline":{"version":1,"engine":"0.1.5","counts":{}},"cleanAcked":true},"/Users/minachoi/orca/workspaces/o2o-weather/main-2/frontend/src/b/SeasonPage.tsx":{"editCount":2,"findings":[],"stopBaseline":{"version":1,"engine":"0.1.5","counts":{}},"cleanAcked":true},"/Users/minachoi/orca/workspaces/o2o-weather/main-2/frontend/src/api/mutator/custom-fetch.ts":{"editCount":1,"findings":[],"stopBaseline":{"version":1,"engine":"0.1.5","counts":{}}}}},"aaff183a-d0d1-42b6-860a-c2c2b6ccc89a":{"updatedAt":1791268588092,"files":{"/Users/minachoi/orca/workspaces/o2o-weather/main-2/frontend/src/b/GakPage.tsx":{"editCount":3,"findings":[],"stopBaseline":{"version":1,"engine":"0.1.5","counts":{}},"cleanAcked":true},"/Users/minachoi/orca/workspaces/o2o-weather/main-2/frontend/src/b/Post.tsx":{"editCount":2,"findings":[],"stopBaseline":{"version":1,"engine":"0.1.5","counts":{}},"cleanAcked":true},"/Users/minachoi/orca/workspaces/o2o-weather/main-2/frontend/src/b/SkyPage.tsx":{"editCount":1,"findings":[],"stopBaseline":{"version":1,"engine":"0.1.5","counts":{}},"cleanAcked":true},"/Users/minachoi/orca/workspaces/o2o-weather/main-2/frontend/src/b/Sheets.tsx":{"editCount":1,"findings":[],"stopBaseline":{"version":1,"engine":"0.1.5","counts":{}},"cleanAcked":true},"/Users/minachoi/orca/workspaces/o2o-weather/main-2/frontend/src/b/ui.tsx":{"editCount":1,"findings":[],"stopBaseline":{"version":1,"engine":"0.1.5","counts":{}},"cleanAcked":true}}}}}
|
||||
@@ -14,6 +14,8 @@ CMD ["npm", "run", "dev", "--", "--host", "0.0.0.0", "--port", "5173"]
|
||||
|
||||
# ---- build: 타입체크 후 정적 파일 생성 ----
|
||||
FROM deps AS build
|
||||
ARG VITE_API_BASE_URL=""
|
||||
ENV VITE_API_BASE_URL=$VITE_API_BASE_URL
|
||||
COPY . .
|
||||
RUN npm run build
|
||||
|
||||
|
||||
@@ -20,6 +20,17 @@ server {
|
||||
try_files $uri =404;
|
||||
}
|
||||
|
||||
# API 는 같은 주소로 받아 backend 컨테이너로 넘긴다
|
||||
location /v1/ {
|
||||
# 백엔드 컨테이너가 다시 뜨면 IP 가 바뀌므로 docker DNS 로 매번 다시 찾는다
|
||||
resolver 127.0.0.11 valid=10s ipv6=off;
|
||||
set $api http://backend:9800;
|
||||
proxy_pass $api;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
}
|
||||
|
||||
# SPA: /indices, /sky 같은 주소로 새로고침해도 index.html을 돌려준다
|
||||
location / {
|
||||
add_header Cache-Control "no-cache";
|
||||
|
||||
|
After Width: | Height: | Size: 260 KiB |
|
After Width: | Height: | Size: 227 KiB |
|
After Width: | Height: | Size: 45 KiB |
|
After Width: | Height: | Size: 217 KiB |
|
After Width: | Height: | Size: 193 KiB |
|
After Width: | Height: | Size: 227 KiB |
|
After Width: | Height: | Size: 258 KiB |
|
After Width: | Height: | Size: 168 KiB |
|
After Width: | Height: | Size: 142 KiB |
@@ -0,0 +1,106 @@
|
||||
[
|
||||
{
|
||||
"code": "maple",
|
||||
"file": "maple.jpg",
|
||||
"title": "Seoraksan in the Fall 2- 설악산 단풍.jpg",
|
||||
"source_url": "https://commons.wikimedia.org/wiki/File:Seoraksan_in_the_Fall_2-_%EC%84%A4%EC%95%85%EC%82%B0_%EB%8B%A8%ED%92%8D.jpg",
|
||||
"author_or_org": "Joycekim77",
|
||||
"license": "CC BY-SA 3.0 (https://creativecommons.org/licenses/by-sa/3.0)"
|
||||
},
|
||||
{
|
||||
"code": "reed",
|
||||
"file": "reed.jpg",
|
||||
"title": "억새 군락지 (5).JPG",
|
||||
"source_url": "https://commons.wikimedia.org/wiki/File:%EC%96%B5%EC%83%88_%EA%B5%B0%EB%9D%BD%EC%A7%80_(5).JPG",
|
||||
"author_or_org": "Jocelyndurrey",
|
||||
"license": "CC BY-SA 4.0 (https://creativecommons.org/licenses/by-sa/4.0)"
|
||||
},
|
||||
{
|
||||
"code": "frost",
|
||||
"file": "frost.jpg",
|
||||
"title": "Autumn leaves with hoarfrost.jpg",
|
||||
"source_url": "https://commons.wikimedia.org/wiki/File:Autumn_leaves_with_hoarfrost.jpg",
|
||||
"author_or_org": "Sally V",
|
||||
"license": "CC BY-SA 4.0 (https://creativecommons.org/licenses/by-sa/4.0)"
|
||||
},
|
||||
{
|
||||
"code": "di",
|
||||
"file": "di.jpg",
|
||||
"title": "KOCIS Korea Malbok Cicada 01 (9490579049).jpg",
|
||||
"source_url": "https://commons.wikimedia.org/wiki/File:KOCIS_Korea_Malbok_Cicada_01_(9490579049).jpg",
|
||||
"author_or_org": "Korea.net / Korean Culture and Information Service (Jeon Han)",
|
||||
"license": "CC BY-SA 2.0 (https://creativecommons.org/licenses/by-sa/2.0)"
|
||||
},
|
||||
{
|
||||
"code": "sunset",
|
||||
"file": "sunset.jpg",
|
||||
"title": "Red sky in evening.jpg",
|
||||
"source_url": "https://commons.wikimedia.org/wiki/File:Red_sky_in_evening.jpg",
|
||||
"author_or_org": "Madhumitha Tamil",
|
||||
"license": "CC0 (http://creativecommons.org/publicdomain/zero/1.0/deed.en)"
|
||||
},
|
||||
{
|
||||
"code": "umbrella",
|
||||
"file": "umbrella.jpg",
|
||||
"title": "Clear Umbrella Rain Liverpool (Unsplash).jpg",
|
||||
"source_url": "https://commons.wikimedia.org/wiki/File:Clear_Umbrella_Rain_Liverpool_(Unsplash).jpg",
|
||||
"author_or_org": "freddie marriage fredmarriage",
|
||||
"license": "CC0 (http://creativecommons.org/publicdomain/zero/1.0/deed.en)"
|
||||
},
|
||||
{
|
||||
"code": "chestnut_new",
|
||||
"file": "chestnut_new.jpg",
|
||||
"title": "Korean chestnut (Castanea crenata).jpg",
|
||||
"source_url": "https://commons.wikimedia.org/wiki/File:Korean_chestnut_(Castanea_crenata).jpg",
|
||||
"author_or_org": "yihyejin",
|
||||
"license": "CC0 (http://creativecommons.org/publicdomain/zero/1.0/deed.en)"
|
||||
},
|
||||
{
|
||||
"code": "peanut_new",
|
||||
"file": "peanut_new.jpg",
|
||||
"title": "Boiled big peanuts & normal peanuts, Katori City, Japan.jpg",
|
||||
"source_url": "https://commons.wikimedia.org/wiki/File:Boiled_big_peanuts_%26_normal_peanuts,_Katori_City,_Japan.jpg",
|
||||
"author_or_org": "katorisi",
|
||||
"license": "CC BY 3.0 (https://creativecommons.org/licenses/by/3.0)"
|
||||
},
|
||||
{
|
||||
"code": "ginkgo",
|
||||
"file": "ginkgo.jpg",
|
||||
"title": "Korea October 01 (8124104915).jpg",
|
||||
"source_url": "https://commons.wikimedia.org/wiki/File:Korea_October_01_(8124104915).jpg",
|
||||
"author_or_org": "Korea.net / Korean Culture and Information Service (Jeon Han)",
|
||||
"license": "CC BY-SA 2.0 (https://creativecommons.org/licenses/by-sa/2.0)"
|
||||
},
|
||||
{
|
||||
"code": "sweet_potato",
|
||||
"file": "sweet_potato.jpg",
|
||||
"title": "Gungoguma (roasted sweet potatoes) 2.jpg",
|
||||
"source_url": "https://commons.wikimedia.org/wiki/File:Gungoguma_(roasted_sweet_potatoes)_2.jpg",
|
||||
"author_or_org": "국립국어원",
|
||||
"license": "CC BY-SA 2.0 kr (https://creativecommons.org/licenses/by-sa/2.0/kr/deed.en)"
|
||||
},
|
||||
{
|
||||
"code": "tangerine",
|
||||
"file": "tangerine.jpg",
|
||||
"title": "Citrus unshiu 20101127 a.jpg",
|
||||
"source_url": "https://commons.wikimedia.org/wiki/File:Citrus_unshiu_20101127_a.jpg",
|
||||
"author_or_org": "Batholith",
|
||||
"license": "Public domain"
|
||||
},
|
||||
{
|
||||
"code": "apple_fuji",
|
||||
"file": "apple_fuji.jpg",
|
||||
"title": "Malus domestica Fuji Apple Hirosaki Aomori Japan 20161016b.jpg",
|
||||
"source_url": "https://commons.wikimedia.org/wiki/File:Malus_domestica_Fuji_Apple_Hirosaki_Aomori_Japan_20161016b.jpg",
|
||||
"author_or_org": "あおもりくま,Aomorikuma",
|
||||
"license": "CC BY-SA 4.0 (https://creativecommons.org/licenses/by-sa/4.0)"
|
||||
},
|
||||
{
|
||||
"code": "kimjang",
|
||||
"file": "kimjang.jpg",
|
||||
"title": "김치 김장 Making kimchi IMG 2919.jpg",
|
||||
"source_url": "https://commons.wikimedia.org/wiki/File:%EA%B9%80%EC%B9%98_%EA%B9%80%EC%9E%A5_Making_kimchi_IMG_2919.jpg",
|
||||
"author_or_org": "Anattadairy",
|
||||
"license": "CC0 (http://creativecommons.org/publicdomain/zero/1.0/deed.en)"
|
||||
}
|
||||
]
|
||||
|
After Width: | Height: | Size: 72 KiB |
|
After Width: | Height: | Size: 82 KiB |
|
After Width: | Height: | Size: 140 KiB |
|
After Width: | Height: | Size: 118 KiB |
@@ -3,8 +3,8 @@
|
||||
import { type DefaultError, type InfiniteData, infiniteQueryOptions, queryOptions, type UseMutationOptions } from '@tanstack/react-query';
|
||||
|
||||
import { client } from '../client.gen';
|
||||
import { addComment, deleteComment, getArticle, getFeed, getIndex, getPost, getSeasonWeek, getSky, getSkyRanking, getWeatherNow, getWeatherToday, getWeek, healthzHealthzGet, likeComment, likePost, listArticles, listComments, listEvents, listIndices, listPlaces, listRegions, listSaved, login, logout, me, nearestRegion, type Options, refresh, savePost, signup, unlikeComment, unlikePost, unsavePost, updateMe } from '../sdk.gen';
|
||||
import type { AddCommentData, AddCommentError, AddCommentResponse, DeleteCommentData, DeleteCommentError, DeleteCommentResponse, GetArticleData, GetArticleError, GetArticleResponse, GetFeedData, GetFeedError, GetFeedResponse, GetIndexData, GetIndexError, GetIndexResponse, GetPostData, GetPostError, GetPostResponse, GetSeasonWeekData, GetSeasonWeekResponse, GetSkyData, GetSkyError, GetSkyRankingData, GetSkyRankingResponse, GetSkyResponse, GetWeatherNowData, GetWeatherNowError, GetWeatherNowResponse, GetWeatherTodayData, GetWeatherTodayError, GetWeatherTodayResponse, GetWeekData, GetWeekError, GetWeekResponse, HealthzHealthzGetData, HealthzHealthzGetResponse, LikeCommentData, LikeCommentError, LikeCommentResponse, LikePostData, LikePostError, LikePostResponse, ListArticlesData, ListArticlesError, ListArticlesResponse, ListCommentsData, ListCommentsError, ListCommentsResponse, ListEventsData, ListEventsError, ListEventsResponse, ListIndicesData, ListIndicesError, ListIndicesResponse, ListPlacesData, ListPlacesError, ListPlacesResponse, ListRegionsData, ListRegionsError, ListRegionsResponse, ListSavedData, ListSavedError, ListSavedResponse, LoginData, LoginError, LoginResponse, LogoutData, LogoutError, LogoutResponse, MeData, MeError, MeResponse, NearestRegionData, NearestRegionError, NearestRegionResponse, RefreshData, RefreshError, RefreshResponse, SavePostData, SavePostError, SavePostResponse, SignupData, SignupError, SignupResponse, UnlikeCommentData, UnlikeCommentError, UnlikeCommentResponse, UnlikePostData, UnlikePostError, UnlikePostResponse, UnsavePostData, UnsavePostError, UnsavePostResponse, UpdateMeData, UpdateMeError, UpdateMeResponse } from '../types.gen';
|
||||
import { addComment, deleteComment, getArticle, getFeed, getIndex, getPost, getSeasonWeek, getSky, getSkyRanking, getWeatherNow, getWeatherToday, getWeek, getWeekRanking, healthzHealthzGet, likeComment, likePost, listArticles, listComments, listEvents, listIndices, listPlaces, listRegions, listSaved, login, logout, me, nearestRegion, type Options, refresh, savePost, signup, unlikeComment, unlikePost, unsavePost, updateMe } from '../sdk.gen';
|
||||
import type { AddCommentData, AddCommentError, AddCommentResponse, DeleteCommentData, DeleteCommentError, DeleteCommentResponse, GetArticleData, GetArticleError, GetArticleResponse, GetFeedData, GetFeedError, GetFeedResponse, GetIndexData, GetIndexError, GetIndexResponse, GetPostData, GetPostError, GetPostResponse, GetSeasonWeekData, GetSeasonWeekResponse, GetSkyData, GetSkyError, GetSkyRankingData, GetSkyRankingResponse, GetSkyResponse, GetWeatherNowData, GetWeatherNowError, GetWeatherNowResponse, GetWeatherTodayData, GetWeatherTodayError, GetWeatherTodayResponse, GetWeekData, GetWeekError, GetWeekRankingData, GetWeekRankingResponse, GetWeekResponse, HealthzHealthzGetData, HealthzHealthzGetResponse, LikeCommentData, LikeCommentError, LikeCommentResponse, LikePostData, LikePostError, LikePostResponse, ListArticlesData, ListArticlesError, ListArticlesResponse, ListCommentsData, ListCommentsError, ListCommentsResponse, ListEventsData, ListEventsError, ListEventsResponse, ListIndicesData, ListIndicesError, ListIndicesResponse, ListPlacesData, ListPlacesError, ListPlacesResponse, ListRegionsData, ListRegionsError, ListRegionsResponse, ListSavedData, ListSavedError, ListSavedResponse, LoginData, LoginError, LoginResponse, LogoutData, LogoutError, LogoutResponse, MeData, MeError, MeResponse, NearestRegionData, NearestRegionError, NearestRegionResponse, RefreshData, RefreshError, RefreshResponse, SavePostData, SavePostError, SavePostResponse, SignupData, SignupError, SignupResponse, UnlikeCommentData, UnlikeCommentError, UnlikeCommentResponse, UnlikePostData, UnlikePostError, UnlikePostResponse, UnsavePostData, UnsavePostError, UnsavePostResponse, UpdateMeData, UpdateMeError, UpdateMeResponse } from '../types.gen';
|
||||
|
||||
export type QueryKey<TOptions extends Options> = [
|
||||
Pick<TOptions, 'baseUrl' | 'body' | 'headers' | 'path' | 'query'> & {
|
||||
@@ -114,7 +114,7 @@ export const getWeatherNowOptions = (options: Options<GetWeatherNowData>) => que
|
||||
export const getSkyQueryKey = (options: Options<GetSkyData>) => createQueryKey('getSky', options);
|
||||
|
||||
/**
|
||||
* 노을·일출 점수, 3컷, 가까운 명소, 앞으로 3일
|
||||
* 노을 결론(나가 볼 만한지·왜·언제 어디로), 시간표, 앞으로 3일, 가까운 명소
|
||||
*/
|
||||
export const getSkyOptions = (options: Options<GetSkyData>) => queryOptions<GetSkyResponse, GetSkyError, GetSkyResponse, ReturnType<typeof getSkyQueryKey>>({
|
||||
queryFn: async ({ queryKey, signal }) => {
|
||||
@@ -201,6 +201,24 @@ export const getWeekOptions = (options: Options<GetWeekData>) => queryOptions<Ge
|
||||
queryKey: getWeekQueryKey(options)
|
||||
});
|
||||
|
||||
export const getWeekRankingQueryKey = (options?: Options<GetWeekRankingData>) => createQueryKey('getWeekRanking', options);
|
||||
|
||||
/**
|
||||
* 이번 주말 전국 나들이 날씨 순위 (대표 30곳)
|
||||
*/
|
||||
export const getWeekRankingOptions = (options?: Options<GetWeekRankingData>) => queryOptions<GetWeekRankingResponse, DefaultError, GetWeekRankingResponse, ReturnType<typeof getWeekRankingQueryKey>>({
|
||||
queryFn: async ({ queryKey, signal }) => {
|
||||
const { data } = await getWeekRanking({
|
||||
...options,
|
||||
...queryKey[0],
|
||||
signal,
|
||||
throwOnError: true
|
||||
});
|
||||
return data;
|
||||
},
|
||||
queryKey: getWeekRankingQueryKey(options)
|
||||
});
|
||||
|
||||
export const listPlacesQueryKey = (options: Options<ListPlacesData>) => createQueryKey('listPlaces', options);
|
||||
|
||||
/**
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
// This file is auto-generated by @hey-api/openapi-ts
|
||||
|
||||
export { addComment, deleteComment, getArticle, getFeed, getIndex, getPost, getSeasonWeek, getSky, getSkyRanking, getWeatherNow, getWeatherToday, getWeek, healthzHealthzGet, likeComment, likePost, listArticles, listComments, listEvents, listIndices, listPlaces, listRegions, listSaved, login, logout, me, nearestRegion, type Options, refresh, savePost, signup, unlikeComment, unlikePost, unsavePost, updateMe } from './sdk.gen';
|
||||
export { type AddCommentData, type AddCommentError, type AddCommentErrors, type AddCommentResponse, type AddCommentResponses, type AirData, AirGrade, ArticleCategory, type ArticleSummary, AuthProvider, type BandArticle, type BandEvent, type Bands, type BestTime, type ClientOptions, type CommentData, type CommuteData, Confidence, type Cut, type DayData, type DeleteCommentData, type DeleteCommentError, type DeleteCommentErrors, type DeleteCommentResponse, type DeleteCommentResponses, type ErrorInfo, type EventData, type Factor, type GakSlide, type GetArticleData, type GetArticleError, type GetArticleErrors, type GetArticleResponse, type GetArticleResponses, type GetFeedData, type GetFeedError, type GetFeedErrors, type GetFeedResponse, type GetFeedResponses, type GetIndexData, type GetIndexError, type GetIndexErrors, type GetIndexResponse, type GetIndexResponses, type GetPostData, type GetPostError, type GetPostErrors, type GetPostResponse, type GetPostResponses, type GetSeasonWeekData, type GetSeasonWeekResponse, type GetSeasonWeekResponses, type GetSkyData, type GetSkyError, type GetSkyErrors, type GetSkyRankingData, type GetSkyRankingResponse, type GetSkyRankingResponses, type GetSkyResponse, type GetSkyResponses, type GetWeatherNowData, type GetWeatherNowError, type GetWeatherNowErrors, type GetWeatherNowResponse, type GetWeatherNowResponses, type GetWeatherTodayData, type GetWeatherTodayError, type GetWeatherTodayErrors, type GetWeatherTodayResponse, type GetWeatherTodayResponses, type GetWeekData, type GetWeekError, type GetWeekErrors, type GetWeekResponse, type GetWeekResponses, type HealthzHealthzGetData, type HealthzHealthzGetResponse, type HealthzHealthzGetResponses, type Hero, type HourCell, type HoursSlide, type HttpValidationError, IndexCategory, type IndexSummary, type LikeCommentData, type LikeCommentError, type LikeCommentErrors, type LikeCommentResponse, type LikeCommentResponses, type LikePostData, type LikePostError, type LikePostErrors, type LikePostResponse, type LikePostResponses, type ListArticlesData, type ListArticlesError, type ListArticlesErrors, type ListArticlesResponse, type ListArticlesResponses, type ListCommentsData, type ListCommentsError, type ListCommentsErrors, type ListCommentsResponse, type ListCommentsResponses, type ListEventsData, type ListEventsError, type ListEventsErrors, type ListEventsResponse, type ListEventsResponses, type ListIndicesData, type ListIndicesError, type ListIndicesErrors, type ListIndicesResponse, type ListIndicesResponses, type ListPlacesData, type ListPlacesError, type ListPlacesErrors, type ListPlacesResponse, type ListPlacesResponses, type ListRegionsData, type ListRegionsError, type ListRegionsErrors, type ListRegionsResponse, type ListRegionsResponses, type ListSavedData, type ListSavedError, type ListSavedErrors, type ListSavedResponse, type ListSavedResponses, type LoginData, type LoginError, type LoginErrors, type LoginResponse, type LoginResponses, type LogoutData, type LogoutError, type LogoutErrors, type LogoutResponse, type LogoutResponses, type Me, type MeData, type MeError, type MeErrors, type MeResponse, type MeResponses, type NearestRegionData, type NearestRegionError, type NearestRegionErrors, type NearestRegionResponse, type NearestRegionResponses, type PlaceData, type PostData, PostType, type Rain2h, type RainHourData, RainType, type RankData, type RefreshData, type RefreshError, type RefreshErrors, type RefreshResponse, type RefreshResponses, type RegionData, type ReqComment, type ReqLogin, type ReqRefresh, type ReqSignup, type ReqUpdateMe, type ResArticle, type ResArticleList, type ResAuth, type ResComment, type ResCommentLike, type ResCommentList, type ResEventList, type ResFeed, type ResHealth, type ResIndexDetail, type ResIndexList, type ResLogout, type ResMe, type ResPlaceList, type ResPost, type ResPostLike, type ResPostSave, type ResRegion, type ResRegionList, type ResSavedList, type ResSeasonWeek, type ResSky, type ResSkyRanking, type ResWeatherNow, type ResWeatherToday, type ResWebPacketProtocol, type ResWeek, type Row, type RowsSlide, type SavedPost, type SavePostData, type SavePostError, type SavePostErrors, type SavePostResponse, type SavePostResponses, type SignupData, type SignupError, type SignupErrors, type SignupResponse, type SignupResponses, Sky, SkyGrade, type SkyScoreData, SkyType, SlotTone, type SpotData, type SunsetSlide, type TermData, type Tomorrow, type TopIndex, type TrendPoint, type UnlikeCommentData, type UnlikeCommentError, type UnlikeCommentErrors, type UnlikeCommentResponse, type UnlikeCommentResponses, type UnlikePostData, type UnlikePostError, type UnlikePostErrors, type UnlikePostResponse, type UnlikePostResponses, type UnsavePostData, type UnsavePostError, type UnsavePostErrors, type UnsavePostResponse, type UnsavePostResponses, type UpdateMeData, type UpdateMeError, type UpdateMeErrors, type UpdateMeResponse, type UpdateMeResponses, type ValidationError, type WarningData, WarningLevel, WarnLine truncated
|
||||
export { addComment, deleteComment, getArticle, getFeed, getIndex, getPost, getSeasonWeek, getSky, getSkyRanking, getWeatherNow, getWeatherToday, getWeek, getWeekRanking, healthzHealthzGet, likeComment, likePost, listArticles, listComments, listEvents, listIndices, listPlaces, listRegions, listSaved, login, logout, me, nearestRegion, type Options, refresh, savePost, signup, unlikeComment, unlikePost, unsavePost, updateMe } from './sdk.gen';
|
||||
export { type AddCommentData, type AddCommentError, type AddCommentErrors, type AddCommentResponse, type AddCommentResponses, type AirData, AirGrade, ArticleCategory, type ArticleSummary, AuthProvider, type BandArticle, type BandEvent, type Bands, type BestTime, type ClientOptions, type CommentData, type CommuteData, Confidence, type Cut, type DayData, type DeleteCommentData, type DeleteCommentError, type DeleteCommentErrors, type DeleteCommentResponse, type DeleteCommentResponses, type ErrorInfo, type EventData, type Factor, type GakSlide, type GetArticleData, type GetArticleError, type GetArticleErrors, type GetArticleResponse, type GetArticleResponses, type GetFeedData, type GetFeedError, type GetFeedErrors, type GetFeedResponse, type GetFeedResponses, type GetIndexData, type GetIndexError, type GetIndexErrors, type GetIndexResponse, type GetIndexResponses, type GetPostData, type GetPostError, type GetPostErrors, type GetPostResponse, type GetPostResponses, type GetSeasonWeekData, type GetSeasonWeekResponse, type GetSeasonWeekResponses, type GetSkyData, type GetSkyError, type GetSkyErrors, type GetSkyRankingData, type GetSkyRankingResponse, type GetSkyRankingResponses, type GetSkyResponse, type GetSkyResponses, type GetWeatherNowData, type GetWeatherNowError, type GetWeatherNowErrors, type GetWeatherNowResponse, type GetWeatherNowResponses, type GetWeatherTodayData, type GetWeatherTodayError, type GetWeatherTodayErrors, type GetWeatherTodayResponse, type GetWeatherTodayResponses, type GetWeekData, type GetWeekError, type GetWeekErrors, type GetWeekRankingData, type GetWeekRankingResponse, type GetWeekRankingResponses, type GetWeekResponse, type GetWeekResponses, type HealthzHealthzGetData, type HealthzHealthzGetResponse, type HealthzHealthzGetResponses, type Hero, type HourCell, type HoursSlide, type HttpValidationError, IndexCategory, type IndexSummary, type LikeCommentData, type LikeCommentError, type LikeCommentErrors, type LikeCommentResponse, type LikeCommentResponses, type LikePostData, type LikePostError, type LikePostErrors, type LikePostResponse, type LikePostResponses, type ListArticlesData, type ListArticlesError, type ListArticlesErrors, type ListArticlesResponse, type ListArticlesResponses, type ListCommentsData, type ListCommentsError, type ListCommentsErrors, type ListCommentsResponse, type ListCommentsResponses, type ListEventsData, type ListEventsError, type ListEventsErrors, type ListEventsResponse, type ListEventsResponses, type ListIndicesData, type ListIndicesError, type ListIndicesErrors, type ListIndicesResponse, type ListIndicesResponses, type ListPlacesData, type ListPlacesError, type ListPlacesErrors, type ListPlacesResponse, type ListPlacesResponses, type ListRegionsData, type ListRegionsError, type ListRegionsErrors, type ListRegionsResponse, type ListRegionsResponses, type ListSavedData, type ListSavedError, type ListSavedErrors, type ListSavedResponse, type ListSavedResponses, type LoginData, type LoginError, type LoginErrors, type LoginResponse, type LoginResponses, type LogoutData, type LogoutError, type LogoutErrors, type LogoutResponse, type LogoutResponses, type Me, type MeData, type MeError, type MeErrors, type MeResponse, type MeResponses, type NearestRegionData, type NearestRegionError, type NearestRegionErrors, type NearestRegionResponse, type NearestRegionResponses, type PlaceData, type PlanSlide, type PlanSpot, type PlanStep, type PostData, PostType, type Rain2h, type RainHourData, RainType, type RankData, type RefreshData, type RefreshError, type RefreshErrors, type RefreshResponse, type RefreshResponses, type RegionData, type ReqComment, type ReqLogin, type ReqRefresh, type ReqSignup, type ReqUpdateMe, type ResArticle, type ResArticleList, type ResAuth, type ResComment, type ResCommentLike, type ResCommentList, type ResEventList, type ResFeed, type ResHealth, type ResIndexDetail, type ResIndexList, type ResLogout, type ResMe, type ResPlaceList, type ResPost, type ResPostLike, type ResPostSave, type ResRegion, type ResRegionList, type ResSavedList, type ResSeasonWeek, type ResSky, type ResSkyRanking, type ResWeatherNow, type ResWeatherToday, type ResWebPacketProtocol, type ResWeek, type ResWeekRanking, type Row, type RowsSlide, type SavedPost, type SavePostData, type SavePostError, type SavePostErrors, type SavePostResponse, type SavePostResponses, type SignupData, type SignupError, type SignupErrors, type SignupResponse, type SignupResponses, Sky, SkyGrade, type SkyPlanData, type SkyScoreData, SkyType, SlotTone, type SpotData, type SunsetSlide, type TermData, type Tomorrow, type TopIndex, type TrendPoint, type UnlikeCommentData, type UnlikeCommentError, type UnlikeCommentErrors, type UnlikeCommentResponse, type UnlikeCommentResponses, type UnlikePostData, type UnlikePostError, type UnlikePostErrors, type UnlikePostResponse, type UnlikePostResponses, type UnsavePostData, type UnsavePostError, type UnsavePostErrors, type UnsavePostResponse, type UnsavePostResponsLine truncated
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
import type { Client, ClientMeta, Options as Options2, RequestResult, TDataShape } from './client';
|
||||
import { client } from './client.gen';
|
||||
import type { AddCommentData, AddCommentErrors, AddCommentResponses, DeleteCommentData, DeleteCommentErrors, DeleteCommentResponses, GetArticleData, GetArticleErrors, GetArticleResponses, GetFeedData, GetFeedErrors, GetFeedResponses, GetIndexData, GetIndexErrors, GetIndexResponses, GetPostData, GetPostErrors, GetPostResponses, GetSeasonWeekData, GetSeasonWeekResponses, GetSkyData, GetSkyErrors, GetSkyRankingData, GetSkyRankingResponses, GetSkyResponses, GetWeatherNowData, GetWeatherNowErrors, GetWeatherNowResponses, GetWeatherTodayData, GetWeatherTodayErrors, GetWeatherTodayResponses, GetWeekData, GetWeekErrors, GetWeekResponses, HealthzHealthzGetData, HealthzHealthzGetResponses, LikeCommentData, LikeCommentErrors, LikeCommentResponses, LikePostData, LikePostErrors, LikePostResponses, ListArticlesData, ListArticlesErrors, ListArticlesResponses, ListCommentsData, ListCommentsErrors, ListCommentsResponses, ListEventsData, ListEventsErrors, ListEventsResponses, ListIndicesData, ListIndicesErrors, ListIndicesResponses, ListPlacesData, ListPlacesErrors, ListPlacesResponses, ListRegionsData, ListRegionsErrors, ListRegionsResponses, ListSavedData, ListSavedErrors, ListSavedResponses, LoginData, LoginErrors, LoginResponses, LogoutData, LogoutErrors, LogoutResponses, MeData, MeErrors, MeResponses, NearestRegionData, NearestRegionErrors, NearestRegionResponses, RefreshData, RefreshErrors, RefreshResponses, SavePostData, SavePostErrors, SavePostResponses, SignupData, SignupErrors, SignupResponses, UnlikeCommentData, UnlikeCommentErrors, UnlikeCommentResponses, UnlikePostData, UnlikePostErrors, UnlikePostResponses, UnsavePostData, UnsavePostErrors, UnsavePostResponses, UpdateMeData, UpdateMeErrors, UpdateMeResponses } from './types.gen';
|
||||
import type { AddCommentData, AddCommentErrors, AddCommentResponses, DeleteCommentData, DeleteCommentErrors, DeleteCommentResponses, GetArticleData, GetArticleErrors, GetArticleResponses, GetFeedData, GetFeedErrors, GetFeedResponses, GetIndexData, GetIndexErrors, GetIndexResponses, GetPostData, GetPostErrors, GetPostResponses, GetSeasonWeekData, GetSeasonWeekResponses, GetSkyData, GetSkyErrors, GetSkyRankingData, GetSkyRankingResponses, GetSkyResponses, GetWeatherNowData, GetWeatherNowErrors, GetWeatherNowResponses, GetWeatherTodayData, GetWeatherTodayErrors, GetWeatherTodayResponses, GetWeekData, GetWeekErrors, GetWeekRankingData, GetWeekRankingResponses, GetWeekResponses, HealthzHealthzGetData, HealthzHealthzGetResponses, LikeCommentData, LikeCommentErrors, LikeCommentResponses, LikePostData, LikePostErrors, LikePostResponses, ListArticlesData, ListArticlesErrors, ListArticlesResponses, ListCommentsData, ListCommentsErrors, ListCommentsResponses, ListEventsData, ListEventsErrors, ListEventsResponses, ListIndicesData, ListIndicesErrors, ListIndicesResponses, ListPlacesData, ListPlacesErrors, ListPlacesResponses, ListRegionsData, ListRegionsErrors, ListRegionsResponses, ListSavedData, ListSavedErrors, ListSavedResponses, LoginData, LoginErrors, LoginResponses, LogoutData, LogoutErrors, LogoutResponses, MeData, MeErrors, MeResponses, NearestRegionData, NearestRegionErrors, NearestRegionResponses, RefreshData, RefreshErrors, RefreshResponses, SavePostData, SavePostErrors, SavePostResponses, SignupData, SignupErrors, SignupResponses, UnlikeCommentData, UnlikeCommentErrors, UnlikeCommentResponses, UnlikePostData, UnlikePostErrors, UnlikePostResponses, UnsavePostData, UnsavePostErrors, UnsavePostResponses, UpdateMeData, UpdateMeErrors, UpdateMeResponses } from './types.gen';
|
||||
|
||||
export type Options<TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown> = Options2<TData, ThrowOnError, TResponse> & {
|
||||
/**
|
||||
@@ -39,7 +39,7 @@ export const getWeatherToday = <ThrowOnError extends boolean = true>(options: Op
|
||||
export const getWeatherNow = <ThrowOnError extends boolean = true>(options: Options<GetWeatherNowData, ThrowOnError>): RequestResult<GetWeatherNowResponses, GetWeatherNowErrors, ThrowOnError> => (options.client ?? client).get<GetWeatherNowResponses, GetWeatherNowErrors, ThrowOnError>({ url: '/v1/weather/now', ...options });
|
||||
|
||||
/**
|
||||
* 노을·일출 점수, 3컷, 가까운 명소, 앞으로 3일
|
||||
* 노을 결론(나가 볼 만한지·왜·언제 어디로), 시간표, 앞으로 3일, 가까운 명소
|
||||
*/
|
||||
export const getSky = <ThrowOnError extends boolean = true>(options: Options<GetSkyData, ThrowOnError>): RequestResult<GetSkyResponses, GetSkyErrors, ThrowOnError> => (options.client ?? client).get<GetSkyResponses, GetSkyErrors, ThrowOnError>({ url: '/v1/sky', ...options });
|
||||
|
||||
@@ -63,6 +63,11 @@ export const getIndex = <ThrowOnError extends boolean = true>(options: Options<G
|
||||
*/
|
||||
export const getWeek = <ThrowOnError extends boolean = true>(options: Options<GetWeekData, ThrowOnError>): RequestResult<GetWeekResponses, GetWeekErrors, ThrowOnError> => (options.client ?? client).get<GetWeekResponses, GetWeekErrors, ThrowOnError>({ url: '/v1/week', ...options });
|
||||
|
||||
/**
|
||||
* 이번 주말 전국 나들이 날씨 순위 (대표 30곳)
|
||||
*/
|
||||
export const getWeekRanking = <ThrowOnError extends boolean = true>(options?: Options<GetWeekRankingData, ThrowOnError>): RequestResult<GetWeekRankingResponses, unknown, ThrowOnError> => (options?.client ?? client).get<GetWeekRankingResponses, unknown, ThrowOnError>({ url: '/v1/week/ranking', ...options });
|
||||
|
||||
/**
|
||||
* 날씨 맞춤 데이트 명소
|
||||
*/
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// This file is auto-generated by @hey-api/openapi-ts
|
||||
|
||||
export type ClientOptions = {
|
||||
baseUrl: 'http://localhost:9810' | (string & {});
|
||||
baseUrl: `${string}://openapi.gen.json` | (string & {});
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -170,6 +170,14 @@ export type BandEvent = {
|
||||
* Icon
|
||||
*/
|
||||
icon: string;
|
||||
/**
|
||||
* Image
|
||||
*/
|
||||
image?: string | null;
|
||||
/**
|
||||
* Image Credit
|
||||
*/
|
||||
image_credit?: string | null;
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -433,6 +441,14 @@ export type EventData = {
|
||||
* Fit
|
||||
*/
|
||||
fit?: string | null;
|
||||
/**
|
||||
* Image
|
||||
*/
|
||||
image?: string | null;
|
||||
/**
|
||||
* Image Credit
|
||||
*/
|
||||
image_credit?: string | null;
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -736,6 +752,74 @@ export type PlaceData = {
|
||||
is_good: boolean;
|
||||
};
|
||||
|
||||
/**
|
||||
* PlanSlide
|
||||
*
|
||||
* 주말 플랜: 그날 시간대별 동선.
|
||||
*/
|
||||
export type PlanSlide = {
|
||||
/**
|
||||
* Kind
|
||||
*/
|
||||
kind: 'plan';
|
||||
/**
|
||||
* Eyebrow
|
||||
*/
|
||||
eyebrow: string;
|
||||
/**
|
||||
* Line
|
||||
*/
|
||||
line: string;
|
||||
/**
|
||||
* Steps
|
||||
*/
|
||||
steps: Array<PlanStep>;
|
||||
};
|
||||
|
||||
/**
|
||||
* PlanSpot
|
||||
*/
|
||||
export type PlanSpot = {
|
||||
/**
|
||||
* Name
|
||||
*/
|
||||
name: string;
|
||||
/**
|
||||
* Distance Km
|
||||
*/
|
||||
distance_km: number;
|
||||
};
|
||||
|
||||
/**
|
||||
* PlanStep
|
||||
*/
|
||||
export type PlanStep = {
|
||||
/**
|
||||
* Time
|
||||
*/
|
||||
time: string;
|
||||
/**
|
||||
* Icon
|
||||
*/
|
||||
icon: string;
|
||||
/**
|
||||
* Title
|
||||
*/
|
||||
title: string;
|
||||
/**
|
||||
* Sub
|
||||
*/
|
||||
sub: string;
|
||||
/**
|
||||
* Image
|
||||
*/
|
||||
image?: string | null;
|
||||
/**
|
||||
* Image Credit
|
||||
*/
|
||||
image_credit?: string | null;
|
||||
};
|
||||
|
||||
/**
|
||||
* PostData
|
||||
*/
|
||||
@@ -760,7 +844,7 @@ export type PostData = {
|
||||
/**
|
||||
* Slides
|
||||
*/
|
||||
slides: Array<HoursSlide | RowsSlide | GakSlide | SunsetSlide | WeekSlide>;
|
||||
slides: Array<HoursSlide | RowsSlide | GakSlide | SunsetSlide | WeekSlide | PlanSlide>;
|
||||
/**
|
||||
* Share Messages
|
||||
*/
|
||||
@@ -834,7 +918,19 @@ export const PostType = {
|
||||
/**
|
||||
* QUOTE
|
||||
*/
|
||||
QUOTE: 10
|
||||
QUOTE: 10,
|
||||
/**
|
||||
* WEEKEND_PLAN
|
||||
*/
|
||||
WEEKEND_PLAN: 11,
|
||||
/**
|
||||
* AIR
|
||||
*/
|
||||
AIR: 12,
|
||||
/**
|
||||
* DAY_TRIP
|
||||
*/
|
||||
DAY_TRIP: 13
|
||||
} as const;
|
||||
|
||||
/**
|
||||
@@ -1482,6 +1578,7 @@ export type ResSky = {
|
||||
* Spots
|
||||
*/
|
||||
spots?: Array<SpotData>;
|
||||
plan?: SkyPlanData | null;
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -1590,6 +1687,21 @@ export type ResWeek = {
|
||||
days?: Array<DayData>;
|
||||
};
|
||||
|
||||
/**
|
||||
* Res_WeekRanking
|
||||
*/
|
||||
export type ResWeekRanking = {
|
||||
result?: ErrorInfo;
|
||||
/**
|
||||
* Msg
|
||||
*/
|
||||
msg?: string | null;
|
||||
/**
|
||||
* Days
|
||||
*/
|
||||
days?: Array<WeekRankDay>;
|
||||
};
|
||||
|
||||
/**
|
||||
* Row
|
||||
*/
|
||||
@@ -1630,6 +1742,14 @@ export type RowsSlide = {
|
||||
* Rows
|
||||
*/
|
||||
rows?: Array<Row>;
|
||||
/**
|
||||
* Image
|
||||
*/
|
||||
image?: string | null;
|
||||
/**
|
||||
* Image Credit
|
||||
*/
|
||||
image_credit?: string | null;
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -1701,6 +1821,53 @@ export const SkyGrade = {
|
||||
*/
|
||||
export type SkyGrade = typeof SkyGrade[keyof typeof SkyGrade];
|
||||
|
||||
/**
|
||||
* SkyPlanData
|
||||
*/
|
||||
export type SkyPlanData = {
|
||||
/**
|
||||
* Day
|
||||
*/
|
||||
day: string;
|
||||
/**
|
||||
* When
|
||||
*/
|
||||
when: string;
|
||||
/**
|
||||
* Verdict
|
||||
*/
|
||||
verdict: 'go' | 'maybe' | 'rest';
|
||||
/**
|
||||
* Headline
|
||||
*/
|
||||
headline: string;
|
||||
/**
|
||||
* Reason
|
||||
*/
|
||||
reason: string;
|
||||
/**
|
||||
* Score
|
||||
*/
|
||||
score: number;
|
||||
/**
|
||||
* Grade Label
|
||||
*/
|
||||
grade_label: string;
|
||||
/**
|
||||
* Best At
|
||||
*/
|
||||
best_at?: string | null;
|
||||
spot?: PlanSpot | null;
|
||||
/**
|
||||
* Timeline
|
||||
*/
|
||||
timeline?: Array<BestTime>;
|
||||
/**
|
||||
* Outlook
|
||||
*/
|
||||
outlook?: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* SkyScoreData
|
||||
*/
|
||||
@@ -1899,10 +2066,22 @@ export type TrendPoint = {
|
||||
* Day
|
||||
*/
|
||||
day: string;
|
||||
/**
|
||||
* Label
|
||||
*
|
||||
* 칸 이름: 오늘 / 내일 / 토 10.10
|
||||
*/
|
||||
label: string;
|
||||
/**
|
||||
* Score
|
||||
*/
|
||||
score: number;
|
||||
/**
|
||||
* Estimated
|
||||
*
|
||||
* 시간별 예보가 없어 중기예보로 낸 예상 점수
|
||||
*/
|
||||
estimated: boolean;
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -2080,10 +2259,88 @@ export type WeekDay = {
|
||||
* Text
|
||||
*/
|
||||
text: string;
|
||||
/**
|
||||
* Temp Min C
|
||||
*/
|
||||
temp_min_c?: number | null;
|
||||
/**
|
||||
* Temp Max C
|
||||
*/
|
||||
temp_max_c?: number | null;
|
||||
/**
|
||||
* Rain Prob
|
||||
*/
|
||||
rain_prob?: number | null;
|
||||
};
|
||||
|
||||
/**
|
||||
* WeekRankDay
|
||||
*/
|
||||
export type WeekRankDay = {
|
||||
/**
|
||||
* Day
|
||||
*/
|
||||
day: string;
|
||||
/**
|
||||
* Weekday
|
||||
*/
|
||||
weekday: string;
|
||||
/**
|
||||
* Items
|
||||
*/
|
||||
items?: Array<WeekRankItem>;
|
||||
};
|
||||
|
||||
/**
|
||||
* WeekRankItem
|
||||
*/
|
||||
export type WeekRankItem = {
|
||||
/**
|
||||
* Rank
|
||||
*/
|
||||
rank: number;
|
||||
/**
|
||||
* Region Code
|
||||
*/
|
||||
region_code: string;
|
||||
/**
|
||||
* Name
|
||||
*/
|
||||
name: string;
|
||||
/**
|
||||
* Score
|
||||
*/
|
||||
score: number;
|
||||
/**
|
||||
* Reason
|
||||
*/
|
||||
reason: string;
|
||||
/**
|
||||
* Icon
|
||||
*/
|
||||
icon: string;
|
||||
/**
|
||||
* Temp Min C
|
||||
*/
|
||||
temp_min_c?: number | null;
|
||||
/**
|
||||
* Temp Max C
|
||||
*/
|
||||
temp_max_c?: number | null;
|
||||
/**
|
||||
* Rain Prob
|
||||
*/
|
||||
rain_prob: number;
|
||||
/**
|
||||
* Estimated
|
||||
*/
|
||||
estimated: boolean;
|
||||
};
|
||||
|
||||
/**
|
||||
* WeekSlide
|
||||
*
|
||||
* 주말 예보: 토·일 비교 + 옷차림·우산 팁.
|
||||
*/
|
||||
export type WeekSlide = {
|
||||
/**
|
||||
@@ -2102,6 +2359,10 @@ export type WeekSlide = {
|
||||
* Days
|
||||
*/
|
||||
days: Array<WeekDay>;
|
||||
/**
|
||||
* Tip
|
||||
*/
|
||||
tip?: string | null;
|
||||
};
|
||||
|
||||
export type ListRegionsData = {
|
||||
@@ -2393,6 +2654,22 @@ export type GetWeekResponses = {
|
||||
|
||||
export type GetWeekResponse = GetWeekResponses[keyof GetWeekResponses];
|
||||
|
||||
export type GetWeekRankingData = {
|
||||
body?: never;
|
||||
path?: never;
|
||||
query?: never;
|
||||
url: '/v1/week/ranking';
|
||||
};
|
||||
|
||||
export type GetWeekRankingResponses = {
|
||||
/**
|
||||
* Successful Response
|
||||
*/
|
||||
200: ResWeekRanking;
|
||||
};
|
||||
|
||||
export type GetWeekRankingResponse = GetWeekRankingResponses[keyof GetWeekRankingResponses];
|
||||
|
||||
export type ListPlacesData = {
|
||||
body?: never;
|
||||
path?: never;
|
||||
|
||||
@@ -11,7 +11,7 @@ import { useSheet } from './sheetContext'
|
||||
import { SheetProvider } from './Sheets'
|
||||
import { SkyContext, useSky } from './skyContext'
|
||||
import { PinIcon, TabIcon } from './svg'
|
||||
import { Avatar } from './ui'
|
||||
import { Avatar, Skel } from './ui'
|
||||
|
||||
const TABS = [
|
||||
{ to: '/', key: 'today', label: '오늘', title: null },
|
||||
@@ -23,9 +23,9 @@ const TABS = [
|
||||
|
||||
function TopBar() {
|
||||
const { pathname } = useLocation()
|
||||
const { region } = useRegion()
|
||||
const { region, locateStatus } = useRegion()
|
||||
const { open } = useSheet()
|
||||
const { me } = useAuth()
|
||||
const { me, mePending } = useAuth()
|
||||
const tab = TABS.find((t) => t.to !== '/' && pathname.startsWith(t.to))
|
||||
|
||||
return (
|
||||
@@ -35,12 +35,14 @@ function TopBar() {
|
||||
type="button"
|
||||
onClick={() => open({ type: 'region' })}
|
||||
aria-label={`위치 바꾸기, 지금 ${region.name}`}
|
||||
className="ml-auto flex cursor-pointer items-center gap-1 rounded-full bg-white px-3 py-1.5 text-[13.5px] font-bold shadow-[inset_0_-4px_0_var(--shade),0_6px_12px_rgb(40_48_74/0.07)]"
|
||||
className="ml-auto flex cursor-pointer items-center gap-1 rounded-full bg-white px-3 pt-1 pb-2 text-[13.5px] font-bold shadow-[inset_0_-4px_0_var(--shade),0_6px_12px_rgb(40_48_74/0.07)]"
|
||||
>
|
||||
<PinIcon className="size-3.5" />
|
||||
{region.name}
|
||||
{locateStatus === 'locating' ? <Skel className="w-[72px]" /> : region.name}
|
||||
</button>
|
||||
{me ? (
|
||||
{mePending ? (
|
||||
<Skel shape className="size-9 shrink-0 rounded-full" />
|
||||
) : me ? (
|
||||
<button type="button" onClick={() => open({ type: 'me' })} aria-label={`내 정보, ${me.nickname}`} className="shrink-0 cursor-pointer rounded-full shadow-[0_6px_12px_rgb(40_48_74/0.12)]">
|
||||
<Avatar character={me.character} color={me.color} mood={me.mood} size={36} />
|
||||
</button>
|
||||
@@ -61,6 +63,16 @@ const STARS = Array.from({ length: 46 }, (_, i) => ({
|
||||
'--dl': `-${(i * 0.7) % 6}s`,
|
||||
}))
|
||||
|
||||
// 별똥별: 위치·길이·주기를 엇갈려 몇 초마다 하나씩 떨어지게
|
||||
const SHOOTS = [
|
||||
{ top: '8%', left: '78%', '--len': '110px', '--dur': '7s', '--dl': '1s' },
|
||||
{ top: '22%', left: '46%', '--len': '80px', '--dur': '9s', '--dl': '3.5s' },
|
||||
{ top: '5%', left: '30%', '--len': '95px', '--dur': '8s', '--dl': '5.5s' },
|
||||
{ top: '36%', left: '88%', '--len': '70px', '--dur': '10s', '--dl': '2.2s' },
|
||||
{ top: '52%', left: '62%', '--len': '90px', '--dur': '11s', '--dl': '7s' },
|
||||
{ top: '14%', left: '96%', '--len': '120px', '--dur': '12s', '--dl': '9s' },
|
||||
]
|
||||
|
||||
/** 화면 전체 하늘: 시간대별 색, 아주 느리게 일렁이는 색 덩어리, 밤에는 별 */
|
||||
function SkyBg() {
|
||||
const { kind } = useSky()
|
||||
@@ -82,7 +94,9 @@ function SkyBg() {
|
||||
{STARS.map((s, i) => (
|
||||
<i key={i} style={s} />
|
||||
))}
|
||||
<span className="b-shoot" />
|
||||
{SHOOTS.map((s, i) => (
|
||||
<span key={i} className="b-shoot" style={s} />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
|
||||
@@ -3,10 +3,10 @@ import { useQuery } from '@tanstack/react-query'
|
||||
import { listArticlesOptions, listIndicesOptions } from '../api/client/@tanstack/react-query.gen'
|
||||
import { ArticleCategory, IndexCategory } from '../api/client/types.gen'
|
||||
import { cx } from '../lib/utils'
|
||||
import { MEDALS } from './lib'
|
||||
import { loadOf, MEDALS } from './lib'
|
||||
import { useRegion } from './regionContext'
|
||||
import { useSheet } from './sheetContext'
|
||||
import { Chips, Ic, Sec, StateBox } from './ui'
|
||||
import { Chips, Ic, Sec, Skel, StateBox } from './ui'
|
||||
|
||||
type Cat = 'all' | 'out' | 'food' | 'home' | 'life' | 'core'
|
||||
|
||||
@@ -21,6 +21,54 @@ const CATS = [
|
||||
|
||||
const CAT_PARAM: Partial<Record<Cat, IndexCategory>> = { out: IndexCategory.OUTSIDE, food: IndexCategory.FOOD, home: IndexCategory.HOME, life: IndexCategory.LIFE }
|
||||
|
||||
const GRID_SKELS = Array.from({ length: 9 }, (_, i) => i)
|
||||
|
||||
/** 1~3위 받침대와 같은 칸(가운데가 높은 3칸)의 스켈레톤 */
|
||||
function PodiumSkel() {
|
||||
return (
|
||||
<div className="grid grid-cols-[1fr_1.15fr_1fr] items-end gap-1.5 px-3 pt-3" aria-hidden="true">
|
||||
{[1, 0, 2].map((k) => (
|
||||
<span key={k} className={cx('flex flex-col items-center rounded-3xl bg-white px-1.5 text-center shadow-[inset_0_-6px_0_var(--shade)]', k === 0 ? 'py-4' : 'py-3')}>
|
||||
<Skel shape className={cx('aspect-square rounded-full', k === 0 ? 'w-20' : 'w-[62px]')} />
|
||||
<b className="mt-1.5 font-jua text-base font-normal">
|
||||
<Skel className="w-16" />
|
||||
</b>
|
||||
<em className="font-bagel text-[30px] leading-[1.05] not-italic">
|
||||
<Skel className="w-10" />
|
||||
</em>
|
||||
<small className="w-full text-[11.5px] font-semibold">
|
||||
<Skel className="w-full" />
|
||||
</small>
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function GakCellSkel() {
|
||||
return (
|
||||
<span className="flex flex-col items-center rounded-[22px] bg-white px-1.5 pt-3 pb-2.5 shadow-[inset_0_-5px_0_var(--shade)]" aria-hidden="true">
|
||||
<Skel shape className="aspect-square w-[50px] rounded-full" />
|
||||
<b className="mt-1 font-jua text-[15px] font-normal">
|
||||
<Skel className="w-14" />
|
||||
</b>
|
||||
<em className="font-bagel text-[22px] leading-[1.1] not-italic">
|
||||
<Skel className="w-8" />
|
||||
</em>
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
function GridSkel() {
|
||||
return (
|
||||
<div className="grid grid-cols-3 gap-2 p-3">
|
||||
{GRID_SKELS.map((i) => (
|
||||
<GakCellSkel key={i} />
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export function GakPage() {
|
||||
const { region } = useRegion()
|
||||
const { open } = useSheet()
|
||||
@@ -29,13 +77,20 @@ export function GakPage() {
|
||||
const top = q.data?.top3 ?? []
|
||||
const items = q.data?.items ?? []
|
||||
const day = q.data?.day?.split('-').map(Number)
|
||||
const load = loadOf(q)
|
||||
const howto = useQuery(listArticlesOptions({ query: { category: ArticleCategory.GAK } })).data?.articles?.find((a) => a.code === 'howgak')
|
||||
|
||||
return (
|
||||
<section aria-label="각">
|
||||
<Sec title="오늘 1~3위" sub={`${day ? `${day[1]}월 ${day[2]}일 기준 · ` : ''}${region.name} · 칸 아래 막대는 오늘·내일·모레 점수`} />
|
||||
{top.length === 3 && (
|
||||
<div className="grid grid-cols-[1fr_1.15fr_1fr] items-end gap-1.5 px-3 pt-3">
|
||||
<section aria-label="각" aria-busy={load === 'loading'}>
|
||||
<Sec title="오늘 1~3위" sub={`${day ? `${day[1]}월 ${day[2]}일 기준 · ` : ''}${region.name}`} />
|
||||
{top.length !== 3 ? (
|
||||
load === 'loading' ? (
|
||||
<PodiumSkel />
|
||||
) : (
|
||||
<StateBox load={load} onRetry={() => q.refetch()} empty="오늘 1~3위를 아직 못 정했어요." hold={<PodiumSkel />} className="inset-x-3 top-3 bottom-0" />
|
||||
)
|
||||
) : (
|
||||
<div className={cx('grid grid-cols-[1fr_1.15fr_1fr] items-end gap-1.5 px-3 pt-3 transition-opacity', q.isPlaceholderData && 'opacity-60')}>
|
||||
{[1, 0, 2].map((k) => {
|
||||
const g = top[k]
|
||||
return (
|
||||
@@ -60,11 +115,14 @@ export function GakPage() {
|
||||
</div>
|
||||
)}
|
||||
<Chips items={CATS} value={cat} onChange={setCat} label="분야" />
|
||||
<StateBox loading={q.isPending} error={q.error} onRetry={() => q.refetch()} empty={q.isSuccess && !items.length ? '이 분야는 오늘 계산된 각이 없어요.' : undefined} />
|
||||
<div className="grid grid-cols-3 gap-2 p-3">
|
||||
{load === 'loading' ? (
|
||||
<GridSkel />
|
||||
) : !items.length ? (
|
||||
// 실패 안내·다시 시도는 위 받침대 자리에 한 번만
|
||||
<StateBox load="ready" empty={load === 'ready' ? '이 분야는 오늘 계산된 각이 없어요.' : '각 목록을 불러오지 못했어요.'} hold={<GridSkel />} className="inset-3" />
|
||||
) : (
|
||||
<div className={cx('grid grid-cols-3 gap-2 p-3 transition-opacity', q.isPlaceholderData && 'opacity-60')}>
|
||||
{items.map((g) => {
|
||||
const trend = g.trend ?? []
|
||||
const mx = Math.max(1, ...trend.map((t) => t.score))
|
||||
return (
|
||||
<button key={g.index_id} type="button" onClick={() => open({ type: 'gak', indexId: g.index_id })} aria-label={`${g.rank}위 ${g.name} ${g.score}점`} className="relative flex cursor-pointer flex-col items-center rounded-[22px] bg-white px-1.5 pt-3 pb-2.5 shadow-[inset_0_-5px_0_var(--shade)]">
|
||||
<span className="absolute top-[7px] left-[9px] font-jua text-[13px] text-(--ink3)">{g.rank}</span>
|
||||
@@ -72,16 +130,13 @@ export function GakPage() {
|
||||
<Ic name={g.icon} className="w-[50px]" />
|
||||
<b className="mt-1 font-jua text-[15px] font-normal">{g.name}</b>
|
||||
<em className={cx('font-bagel text-[22px] leading-[1.1] not-italic', g.score < 50 ? 'text-(--ink3)' : 'text-(--orange)')}>{g.score}</em>
|
||||
<span className="mt-1 flex h-[18px] items-end gap-[3px]" aria-hidden="true">
|
||||
{trend.map((t, j) => (
|
||||
<i key={t.day} className={cx('w-[9px] rounded-[3px]', j ? 'bg-[#dbe4ef]' : 'bg-(--orange)')} style={{ height: Math.max(4, (t.score / mx) * 18) }} />
|
||||
))}
|
||||
</span>
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
{howto && (
|
||||
)}
|
||||
{/* 목록 칸 수가 정해진 뒤에 붙여 목록이 늘어날 때 밀리지 않게 */}
|
||||
{howto && load !== 'loading' && (
|
||||
<button type="button" onClick={() => open({ type: 'article', articleId: howto.article_id })} className="mx-3 mt-1.5 flex w-[calc(100%-24px)] cursor-pointer items-center gap-3 rounded-[22px] bg-[#ece7ff] p-3.5 text-left">
|
||||
<Ic name="bulb" className="w-11" />
|
||||
<span>
|
||||
|
||||
@@ -1,32 +1,34 @@
|
||||
import { useRef, useState, type CSSProperties, type MouseEvent, type ReactNode } from 'react'
|
||||
import { PostType, SlotTone, type GakSlide, type HoursSlide, type PostData, type ResFeed, type RowsSlide, type SunsetSlide, type WeekSlide } from '../api/client/types.gen'
|
||||
import { useEffect, useRef, useState, type CSSProperties, type MouseEvent, type ReactNode } from 'react'
|
||||
import { PostType, SlotTone, type GakSlide, type HoursSlide, type PlanSlide, type PostData, type ResFeed, type RowsSlide, type SunsetSlide, type WeekSlide } from '../api/client/types.gen'
|
||||
import { cx } from '../lib/utils'
|
||||
import { cardBg, clockShort, fall } from './lib'
|
||||
import type { SlideBg } from './types'
|
||||
import { deg } from './weatherText'
|
||||
import { useMutation, useQueryClient, type QueryClient } from '@tanstack/react-query'
|
||||
import { likePostMutation, savePostMutation, unlikePostMutation, unsavePostMutation } from '../api/client/@tanstack/react-query.gen'
|
||||
import { likePostMutation, unlikePostMutation } from '../api/client/@tanstack/react-query.gen'
|
||||
import { useAuth } from './authContext'
|
||||
import { useRegion } from './regionContext'
|
||||
import { useSheet } from './sheetContext'
|
||||
import { CommentIcon, HeartIcon, MoreIcon, SaveIcon, SendIcon } from './svg'
|
||||
import { CommentIcon, HeartIcon, SendIcon } from './svg'
|
||||
import { useCarousel } from './carousel'
|
||||
import { Arrows, Ic, Rows } from './ui'
|
||||
import { Arrows, Credit, Ic, Rows, Skel, Thumb } from './ui'
|
||||
|
||||
const ACCOUNTS: Record<PostType, readonly [string, string]> = {
|
||||
[PostType.WEATHER]: ['오늘 날씨', 'sun'],
|
||||
[PostType.GAK]: ['오늘의 각', 'rabbit'],
|
||||
[PostType.SUNSET]: ['노을', 'sunset'],
|
||||
[PostType.SEASON]: ['계절 소식', 'maple'],
|
||||
[PostType.EVENT]: ['행사', 'fireworks'],
|
||||
[PostType.EVENT]: ['가까운 행사', 'fireworks'],
|
||||
[PostType.TIP]: ['날씨 상식', 'bulb'],
|
||||
[PostType.WEEK]: ['주말 추천', 'calendar'],
|
||||
[PostType.WEEK]: ['주말 예보', 'calendar'],
|
||||
[PostType.ALERT]: ['생활 알림', 'umbrella'],
|
||||
[PostType.TOMORROW]: ['내일 미리보기', 'moon'],
|
||||
[PostType.QUOTE]: ['오늘의 한 문장', 'letter'],
|
||||
[PostType.WEEKEND_PLAN]: ['주말 플랜', 'calendar'],
|
||||
[PostType.AIR]: ['미세먼지', 'vent'],
|
||||
[PostType.DAY_TRIP]: ['당일치기', 'picnic'],
|
||||
}
|
||||
|
||||
type Slide = HoursSlide | RowsSlide | GakSlide | SunsetSlide | WeekSlide
|
||||
type Slide = HoursSlide | RowsSlide | GakSlide | SunsetSlide | WeekSlide | PlanSlide
|
||||
|
||||
const GAK_BG: SlideBg[] = ['butter', 'peach', 'lilac']
|
||||
const ROW_ICON_BG: Record<string, SlideBg> = { umbrella: 'lilac', vent: 'mint', sunset: 'peach', thermo: 'sky', maple: 'peach' }
|
||||
@@ -36,9 +38,12 @@ function slideBg(post: PostData, slide: Slide): SlideBg {
|
||||
if (slide.kind === 'hours') return 'sky'
|
||||
if (slide.kind === 'sunset') return 'dusk'
|
||||
if (slide.kind === 'week') return 'mint'
|
||||
if (slide.kind === 'plan') return slide.eyebrow.startsWith('일') ? 'peach' : 'butter'
|
||||
if (slide.kind === 'gak') return GAK_BG[post.post_id % GAK_BG.length]
|
||||
if (post.post_type === PostType.EVENT) return 'night'
|
||||
if (post.post_type === PostType.TIP) return 'sky'
|
||||
if (post.post_type === PostType.AIR) return slide.icon === 'vent' ? 'mint' : 'lilac'
|
||||
if (post.post_type === PostType.DAY_TRIP) return slide.image ? 'night' : 'mint'
|
||||
return ROW_ICON_BG[slide.icon] ?? cardBg(slide.icon, post.post_id)
|
||||
}
|
||||
|
||||
@@ -73,7 +78,10 @@ const slideBase = 'relative flex h-full w-full shrink-0 flex-col px-5 py-[22px]'
|
||||
|
||||
function SlideView({ slide, bg }: { slide: Slide; bg: SlideBg }) {
|
||||
const { open } = useSheet()
|
||||
if (slide.kind === 'hours')
|
||||
if (slide.kind === 'hours') {
|
||||
const temps = slide.hours.flatMap((h) => (h.temp_c == null ? [] : [h.temp_c]))
|
||||
const lo = Math.min(...temps)
|
||||
const span = Math.max(...temps) - lo || 1
|
||||
return (
|
||||
<div className={cx(slideBase, 'b-bg-sky')}>
|
||||
<Eyebrow>{slide.eyebrow}</Eyebrow>
|
||||
@@ -85,10 +93,13 @@ function SlideView({ slide, bg }: { slide: Slide; bg: SlideBg }) {
|
||||
<div
|
||||
key={h.label}
|
||||
className={cx(
|
||||
'flex flex-col items-center justify-between rounded-[18px] px-1 pt-2.5 pb-[9px] text-xs font-bold text-(--ink2)',
|
||||
'relative flex flex-col items-center justify-between overflow-hidden rounded-[18px] px-1 pt-2.5 pb-[9px] text-xs font-bold text-(--ink2) [&>*]:relative',
|
||||
h.tone === SlotTone.NIGHT ? 'bg-[#e3e7ff] shadow-[inset_0_-5px_0_#c7cff5]' : h.tone === SlotTone.SUNSET ? 'bg-[#ffe3d2] shadow-[inset_0_-5px_0_#ffc19f]' : 'bg-white shadow-[inset_0_-5px_0_var(--shade)]',
|
||||
)}
|
||||
>
|
||||
{h.temp_c != null && (
|
||||
<i className="absolute! inset-x-0 bottom-0 bg-linear-to-t from-[rgb(255_122_69/0.34)] to-[rgb(255_122_69/0.1)]" style={{ height: `${20 + ((h.temp_c - lo) / span) * 70}%` }} aria-hidden="true" />
|
||||
)}
|
||||
<span>{h.label}</span>
|
||||
<Ic name={h.icon} className="w-[34px]" />
|
||||
<b className="font-bagel text-[21px] font-normal text-(--ink)">{deg(h.temp_c)}</b>
|
||||
@@ -97,6 +108,7 @@ function SlideView({ slide, bg }: { slide: Slide; bg: SlideBg }) {
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
if (slide.kind === 'gak')
|
||||
return (
|
||||
<div className={cx(slideBase, `b-bg-${bg}`)}>
|
||||
@@ -107,14 +119,14 @@ function SlideView({ slide, bg }: { slide: Slide; bg: SlideBg }) {
|
||||
<p className="m-0 font-jua text-[29px] leading-tight">{slide.name}</p>
|
||||
<Eyebrow className="mt-1">{slide.summary}</Eyebrow>
|
||||
<button type="button" onClick={() => open({ type: 'gak', indexId: slide.index_id })} className="mt-3 cursor-pointer self-start rounded-full bg-(--orange) px-4 py-[9px] font-jua text-[15px] text-white shadow-[inset_0_-5px_0_var(--orange-deep)]">
|
||||
계산 근거 보기 ⬡
|
||||
계산 근거 보기
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
if (slide.kind === 'sunset')
|
||||
return (
|
||||
<div className={cx(slideBase, 'b-bg-dusk')}>
|
||||
<Eyebrow className="opacity-90">{slide.eyebrow}</Eyebrow>
|
||||
<Eyebrow>{slide.eyebrow}</Eyebrow>
|
||||
<Big>
|
||||
<Lines text={slide.line} />
|
||||
</Big>
|
||||
@@ -140,15 +152,59 @@ function SlideView({ slide, bg }: { slide: Slide; bg: SlideBg }) {
|
||||
</Big>
|
||||
<div className="mt-auto grid grid-cols-2 gap-2.5">
|
||||
{slide.days.map((d) => (
|
||||
<div key={d.day} className="rounded-[18px] bg-white/80 px-3 py-2.5 shadow-[inset_0_-5px_0_rgb(217_229_244/0.9)]">
|
||||
<Ic name={d.icon} className="w-[38px]" />
|
||||
<b className="block font-jua text-lg font-normal">
|
||||
<div key={d.day} className="flex flex-col gap-0.5 rounded-[18px] bg-white/85 px-3 py-2.5 shadow-[inset_0_-5px_0_rgb(217_229_244/0.9)]">
|
||||
<Ic name={d.icon} className="w-[34px]" />
|
||||
<b className="font-jua text-lg font-normal">
|
||||
{d.weekday} {d.day.split('-').slice(1).map(Number).join('.')}
|
||||
</b>
|
||||
<small className="text-[12.5px] font-bold text-(--ink2)">{d.text}</small>
|
||||
<span className="font-jua text-[22px]">
|
||||
<span className="text-(--rain)">{deg(d.temp_min_c)}</span> → <span className="text-(--orange)">{deg(d.temp_max_c)}</span>
|
||||
</span>
|
||||
<small className="text-xs font-bold text-(--ink2)">
|
||||
비 {d.rain_prob ?? '?'}%{d.temp_min_c != null && d.temp_max_c != null && ` · 일교차 ${Math.round(d.temp_max_c - d.temp_min_c)}°`}
|
||||
</small>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
{slide.tip && <p className="mt-3 rounded-[14px] bg-(--ink) px-3 py-2.5 text-[13px] leading-snug font-bold text-white">{slide.tip}</p>}
|
||||
</div>
|
||||
)
|
||||
if (slide.kind === 'plan') {
|
||||
const credits = [...new Set(slide.steps.flatMap((st) => (st.image && st.image_credit ? [st.image_credit] : [])))]
|
||||
return (
|
||||
<div className={cx(slideBase, `b-bg-${bg}`)}>
|
||||
<Eyebrow>{slide.eyebrow}</Eyebrow>
|
||||
<Big className="text-[24px]!">
|
||||
<Lines text={slide.line} />
|
||||
</Big>
|
||||
<ol className="mt-auto flex flex-col gap-2">
|
||||
{slide.steps.map((st, i) => (
|
||||
<li key={i} className="grid grid-cols-[52px_26px_minmax(0,1fr)_auto] items-center gap-1.5 rounded-[14px] bg-white/80 px-2 py-1.5">
|
||||
<time className="font-jua text-sm text-(--ink2) tabular-nums">{st.time}</time>
|
||||
<Ic name={st.icon} className="w-[22px] justify-self-center" />
|
||||
<span className="min-w-0">
|
||||
<b className="block truncate text-[13.5px]">{st.title}</b>
|
||||
<small className="block truncate text-[11.5px] font-semibold text-(--ink2)">{st.sub}</small>
|
||||
</span>
|
||||
{st.image && <Thumb image={st.image} icon={st.icon} className="size-[46px] rounded-[10px]" iconClassName="w-[26px]" />}
|
||||
</li>
|
||||
))}
|
||||
</ol>
|
||||
{credits.length > 0 && <small className="mt-1.5 block text-right text-[10px] font-semibold text-(--ink2)">사진 {credits.join(' · ')}</small>}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
if (slide.kind === 'rows' && slide.image)
|
||||
return (
|
||||
<div className={'relative flex h-full w-full shrink-0 flex-col justify-end bg-cover bg-center text-white'} style={{ backgroundImage: `url(${slide.image})` }}>
|
||||
{slide.image_credit && <Credit text={slide.image_credit} className="top-2.5 right-2.5" />}
|
||||
<div className="bg-linear-to-b from-transparent via-[rgb(16_20_34/0.55)] via-35% to-[rgb(16_20_34/0.85)] px-5 pt-20 pb-3.5">
|
||||
<Eyebrow>{slide.eyebrow}</Eyebrow>
|
||||
<Big>
|
||||
<Lines text={slide.line} />
|
||||
</Big>
|
||||
<Rows rows={slide.rows ?? []} dark />
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
return (
|
||||
@@ -176,7 +232,7 @@ const BURST: [number, number, number, string][] = [
|
||||
[52, -100, 12, '#ffc86e'],
|
||||
]
|
||||
|
||||
/** 받아 둔 피드 데이터에도 좋아요·저장을 반영한다. 안 하면 다른 탭에 다녀왔을 때 예전 값으로 다시 그려진다 */
|
||||
/** 받아 둔 피드 데이터에도 좋아요를 반영한다. 안 하면 다른 탭에 다녀왔을 때 예전 값으로 다시 그려진다 */
|
||||
function patchFeed(queryClient: QueryClient, postId: number, patch: Partial<PostData>) {
|
||||
queryClient.setQueriesData<ResFeed>({ predicate: (q) => (q.queryKey[0] as { _id?: string } | undefined)?._id === 'getFeed' }, (feed) =>
|
||||
feed?.posts ? { ...feed, posts: feed.posts.map((p) => (p.post_id === postId ? { ...p, ...patch } : p)) } : feed,
|
||||
@@ -202,58 +258,88 @@ export function PostCard({ post }: PostProps) {
|
||||
return post.size === 'line' ? <LineCard post={post} /> : <FullCard post={post} />
|
||||
}
|
||||
|
||||
/** FullCard 와 같은 틀(머리줄·4:5 그림·버튼줄·글 한 줄)의 스켈레톤 */
|
||||
export function PostCardSkel() {
|
||||
return (
|
||||
<div className="mt-3.5 border-y border-(--line) bg-white" aria-hidden="true">
|
||||
<div className="flex items-center gap-2.5 px-3 py-2.5">
|
||||
<Skel shape className="size-[34px] shrink-0 rounded-full" />
|
||||
<span>
|
||||
<b className="block text-sm leading-tight font-extrabold">
|
||||
<Skel className="w-12" />
|
||||
</b>
|
||||
<small className="text-xs font-semibold">
|
||||
<Skel className="w-16" />
|
||||
</small>
|
||||
</span>
|
||||
</div>
|
||||
<Skel shape className="aspect-[4/5]" />
|
||||
<div className="flex items-center gap-3.5 px-3 pt-2.5 pb-1">
|
||||
<Skel shape className="size-7 rounded-full" />
|
||||
<Skel shape className="size-7 rounded-full" />
|
||||
<Skel shape className="size-7 rounded-full" />
|
||||
</div>
|
||||
<p className="px-3 py-0.5 text-sm">
|
||||
<Skel className="w-20" />
|
||||
</p>
|
||||
<p className="px-3 py-0.5 text-sm">
|
||||
<Skel className="w-4/5" />
|
||||
</p>
|
||||
<p className="px-3 pt-[3px] text-sm">
|
||||
<Skel className="w-32" />
|
||||
</p>
|
||||
<p className="px-3 pt-1 pb-3 text-[11.5px]">
|
||||
<Skel className="w-8" />
|
||||
</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function FullCard({ post }: PostProps) {
|
||||
const { open } = useSheet()
|
||||
const { region } = useRegion()
|
||||
const { loggedIn } = useAuth()
|
||||
const liked = !!post.liked
|
||||
const likeCount = post.like_count
|
||||
const saved = !!post.saved
|
||||
const queryClient = useQueryClient()
|
||||
const like = useMutation(likePostMutation())
|
||||
const unlike = useMutation(unlikePostMutation())
|
||||
const save = useMutation(savePostMutation())
|
||||
const unsave = useMutation(unsavePostMutation())
|
||||
const { ref: sliderRef, api: slider, prev: canPrev, next: canNext, index } = useCarousel({ align: 'start' })
|
||||
const { ref: sliderRef, api: slider, prev: canPrev, next: canNext, index } = useCarousel({ align: 'start', active: post.slides.length > 1 })
|
||||
const [pop, setPop] = useState(0)
|
||||
const [likeFailed, setLikeFailed] = useState(0)
|
||||
const lastTap = useRef(0)
|
||||
const cardRef = useRef<HTMLDivElement>(null)
|
||||
const [account, avatar] = ACCOUNTS[post.post_type]
|
||||
const n = post.slides.length
|
||||
const bgs = post.slides.map((sl) => slideBg(post, sl))
|
||||
const accountName = post.post_type === PostType.EVENT ? `${region.name.split(' ')[0]} ${account}` : account
|
||||
const share = () => open({ type: 'share', share: { title: post.title, icon: post.icon, bg: bgs[0] ?? 'sky', messages: post.share_messages ?? [], card: cardRef.current } })
|
||||
const comments = () => open({ type: 'comments', postId: post.post_id })
|
||||
const patch = (values: Partial<PostData>) => patchFeed(queryClient, post.post_id, values)
|
||||
|
||||
useEffect(() => {
|
||||
if (!likeFailed) return
|
||||
const t = setTimeout(() => setLikeFailed(0), 2500)
|
||||
return () => clearTimeout(t)
|
||||
}, [likeFailed])
|
||||
|
||||
// 화면을 먼저 바꾸고, 실패하면 되돌린다 (서버는 실패도 200 + result.success=false 로 준다)
|
||||
const setLike = (on: boolean) => {
|
||||
if (!loggedIn) return open({ type: 'login' })
|
||||
if (on === liked || like.isPending || unlike.isPending) return
|
||||
if (on) setPop((p) => p + 1)
|
||||
setLikeFailed(0)
|
||||
patch({ liked: on, like_count: likeCount + (on ? 1 : -1) })
|
||||
const revert = () => {
|
||||
patch({ liked, like_count: likeCount })
|
||||
setLikeFailed(Date.now())
|
||||
}
|
||||
;(on ? like : unlike).mutate(
|
||||
{ path: { post_id: post.post_id } },
|
||||
{
|
||||
onSuccess: (res) =>
|
||||
res.result?.success
|
||||
? patch({ liked: res.liked ?? on, ...(res.like_count != null ? { like_count: res.like_count } : {}) })
|
||||
: patch({ liked, like_count: likeCount }),
|
||||
onError: () => patch({ liked, like_count: likeCount }),
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
const toggleSave = () => {
|
||||
if (!loggedIn) return open({ type: 'login' })
|
||||
if (save.isPending || unsave.isPending) return
|
||||
const on = !saved
|
||||
patch({ saved: on })
|
||||
;(on ? save : unsave).mutate(
|
||||
{ path: { post_id: post.post_id } },
|
||||
{
|
||||
onSuccess: (res) => patch({ saved: res.result?.success ? (res.saved ?? on) : saved }),
|
||||
onError: () => patch({ saved }),
|
||||
: revert(),
|
||||
onError: revert,
|
||||
},
|
||||
)
|
||||
}
|
||||
@@ -278,11 +364,8 @@ function FullCard({ post }: PostProps) {
|
||||
</span>
|
||||
<span>
|
||||
<b className="block text-sm leading-tight font-extrabold">날씨각</b>
|
||||
<small className="text-xs font-semibold text-(--ink2)">{accountName}</small>
|
||||
<small className="text-xs font-semibold text-(--ink2)">{account}</small>
|
||||
</span>
|
||||
<button type="button" onClick={share} aria-label="더 보기" className="ml-auto grid size-7 cursor-pointer place-items-center text-(--ink)">
|
||||
<MoreIcon />
|
||||
</button>
|
||||
</div>
|
||||
<div ref={cardRef} className="relative aspect-[4/5] overflow-hidden" onClick={onTap}>
|
||||
{n > 1 && (
|
||||
@@ -327,8 +410,11 @@ function FullCard({ post }: PostProps) {
|
||||
<span className="b-like-toast absolute top-[62%] rounded-full bg-white px-4 py-2 font-jua text-[17px] text-(--heart) opacity-0 shadow-[0_8px_18px_rgb(40_48_74/0.18)]">좋아요했어요!</span>
|
||||
</div>
|
||||
)}
|
||||
<p data-noshot role="status" className="pointer-events-none absolute inset-x-0 bottom-4 z-[5] m-0 flex justify-center px-4">
|
||||
{likeFailed > 0 && <span className="rounded-full bg-[rgb(30_36_56/0.82)] px-3.5 py-2 text-[13px] font-bold text-white">{liked ? '좋아요를 취소하지 못했어요' : '좋아요를 반영하지 못했어요'}. 다시 해 주세요.</span>}
|
||||
</p>
|
||||
</div>
|
||||
<div className="relative flex items-center gap-3.5 px-3 pt-2.5 pb-1 [&_svg]:size-[26px] [&_svg]:stroke-[1.9]">
|
||||
<div className="flex items-center gap-3.5 px-3 pt-2.5 pb-1 [&_svg]:size-[26px] [&_svg]:stroke-[1.9]">
|
||||
<button type="button" onClick={() => setLike(!liked)} aria-pressed={liked} aria-label="좋아요" className="grid size-7 cursor-pointer place-items-center">
|
||||
<HeartIcon className={liked ? 'fill-(--heart) stroke-(--heart)' : 'fill-none stroke-(--ink)'} />
|
||||
</button>
|
||||
@@ -338,16 +424,6 @@ function FullCard({ post }: PostProps) {
|
||||
<button type="button" onClick={share} aria-label="보내기" className="grid size-7 cursor-pointer place-items-center">
|
||||
<SendIcon className="fill-none stroke-(--ink) [stroke-linecap:round] [stroke-linejoin:round]" />
|
||||
</button>
|
||||
{n > 1 && (
|
||||
<span className="absolute left-1/2 flex -translate-x-1/2 gap-1" aria-hidden="true">
|
||||
{post.slides.map((_, k) => (
|
||||
<i key={k} className={cx('size-1.5 rounded-full', k === index ? 'bg-(--rain)' : 'bg-[#cfd8e6]')} />
|
||||
))}
|
||||
</span>
|
||||
)}
|
||||
<button type="button" onClick={toggleSave} aria-pressed={saved} aria-label="저장" className="ml-auto grid size-7 cursor-pointer place-items-center">
|
||||
<SaveIcon className={cx('stroke-(--ink) [stroke-linejoin:round]', saved ? 'fill-(--ink)' : 'fill-none')} />
|
||||
</button>
|
||||
</div>
|
||||
<p className="px-3 py-0.5 text-sm font-extrabold">좋아요 {likeCount.toLocaleString()}개</p>
|
||||
<p className="px-3 py-0.5 text-sm">
|
||||
|
||||
@@ -3,9 +3,9 @@ import { useQuery } from '@tanstack/react-query'
|
||||
import { getSeasonWeekOptions, listArticlesOptions } from '../api/client/@tanstack/react-query.gen'
|
||||
import { ArticleCategory } from '../api/client/types.gen'
|
||||
import { cx } from '../lib/utils'
|
||||
import { ARTICLE_CAT, cardBg, fall, shortDay } from './lib'
|
||||
import { ARTICLE_CAT, cardBg, dateRange, fall, loadOf, shortDay } from './lib'
|
||||
import { useSheet } from './sheetContext'
|
||||
import { Chips, Ic, StateBox } from './ui'
|
||||
import { Chips, Ic, Skel, StateBox } from './ui'
|
||||
|
||||
const CATS = [
|
||||
['all', '전체'],
|
||||
@@ -16,6 +16,54 @@ const CATS = [
|
||||
|
||||
const CAT_PARAM = { season: ArticleCategory.SEASON, tip: ArticleCategory.TIP, gak: ArticleCategory.GAK } as const
|
||||
|
||||
const HEAD_BOX = 'relative mx-3 mt-3 flex min-h-[250px] w-[calc(100%-24px)] flex-col overflow-hidden rounded-[28px] p-5 text-left'
|
||||
const ROW = 'grid w-full grid-cols-[1fr_84px] items-center gap-3 border-b-[1.5px] border-(--line) px-4 py-3.5 text-left'
|
||||
const ROW_SKELS = [0, 1, 2, 3]
|
||||
|
||||
/** 특집 상자와 같은 틀: 머리말 · 제목 두 줄 · 시 한 줄 · 절기 막대 (최소 높이 250px 안) */
|
||||
function HeadSkel() {
|
||||
return (
|
||||
<div className={cx(HEAD_BOX, 'bg-white')} aria-hidden="true">
|
||||
<p className="m-0 text-[13px] font-extrabold">
|
||||
<Skel className="w-36" />
|
||||
</p>
|
||||
<p className="mt-1 max-w-[62%] font-jua text-[29px] leading-tight">
|
||||
<Skel className="w-full" />
|
||||
<br />
|
||||
<Skel className="w-2/3" />
|
||||
</p>
|
||||
<p className="mt-auto max-w-[72%] pt-3 font-batang text-[22px] leading-[1.7]">
|
||||
<Skel className="w-full" />
|
||||
</p>
|
||||
<div className="mt-2.5 max-w-[70%]">
|
||||
<div className="text-xs font-extrabold">
|
||||
<Skel className="w-full" />
|
||||
</div>
|
||||
<Skel shape className="mt-1 h-[7px] rounded-full" />
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function RowSkel() {
|
||||
return (
|
||||
<div className={ROW} aria-hidden="true">
|
||||
<span>
|
||||
<span className="text-xs font-extrabold">
|
||||
<Skel className="w-12" />
|
||||
</span>
|
||||
<b className="mt-0.5 block font-jua text-[17.5px] leading-snug font-normal">
|
||||
<Skel className="w-48" />
|
||||
</b>
|
||||
<small className="mt-1 block text-xs font-semibold">
|
||||
<Skel className="w-14" />
|
||||
</small>
|
||||
</span>
|
||||
<Skel shape className="h-[84px] rounded-[18px]" />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export function SeasonPage() {
|
||||
const { open } = useSheet()
|
||||
const [cat, setCat] = useState<(typeof CATS)[number][0]>('all')
|
||||
@@ -24,12 +72,14 @@ export function SeasonPage() {
|
||||
const w = week.data
|
||||
const list = arts.data?.articles ?? []
|
||||
const progress = Math.round((w?.progress ?? 0) * 100)
|
||||
const weekLoad = loadOf(week)
|
||||
const artLoad = loadOf(arts)
|
||||
|
||||
return (
|
||||
<section aria-label="계절·상식">
|
||||
<section aria-label="계절·상식" aria-busy={weekLoad === 'loading' || artLoad === 'loading'}>
|
||||
{w?.headline ? (
|
||||
<button type="button" onClick={() => open({ type: 'seasonWeek' })} className="relative mx-3 mt-3 flex min-h-[250px] w-[calc(100%-24px)] cursor-pointer flex-col overflow-hidden rounded-[28px] bg-[linear-gradient(180deg,#ffd2bb,#fff2ea)] p-5 text-left">
|
||||
<p className="m-0 text-[13px] font-extrabold opacity-75">이번 주 특집 · {w.week}번째 주</p>
|
||||
<button type="button" onClick={() => open({ type: 'seasonWeek' })} className={cx(HEAD_BOX, 'cursor-pointer bg-[linear-gradient(180deg,#ffd2bb,#fff2ea)]')}>
|
||||
<p className="m-0 text-[13px] font-extrabold opacity-75">이번 주 특집{w.start && w.end ? ` · ${dateRange(w.start, w.end)}` : ''}</p>
|
||||
<p className="mt-1 max-w-[62%] font-jua text-[29px] leading-tight">{w.headline}</p>
|
||||
<span className="b-fall pointer-events-none absolute top-[18%] right-3.5 w-[38%]" style={fall('.1s')}>
|
||||
<Ic name="maple" className="w-full drop-shadow-[0_16px_18px_rgb(40_48_74/0.18)]" />
|
||||
@@ -60,14 +110,17 @@ export function SeasonPage() {
|
||||
</div>
|
||||
)}
|
||||
</button>
|
||||
) : weekLoad === 'loading' ? (
|
||||
<HeadSkel />
|
||||
) : (
|
||||
<StateBox loading={week.isPending} error={week.error} onRetry={() => week.refetch()} empty="이번 주 특집이 아직 없어요." />
|
||||
<StateBox load={weekLoad} onRetry={() => week.refetch()} empty="이번 주 특집이 아직 없어요." hold={<HeadSkel />} className="inset-x-3 top-3 bottom-0" />
|
||||
)}
|
||||
<Chips items={CATS} value={cat} onChange={setCat} label="분류" />
|
||||
<div className="mt-1.5">
|
||||
<StateBox loading={arts.isPending} error={arts.error} onRetry={() => arts.refetch()} empty={arts.isSuccess && !list.length ? '읽을거리가 아직 없어요.' : undefined} />
|
||||
<div className={cx('mt-1.5 transition-opacity', arts.isPlaceholderData && 'opacity-60')}>
|
||||
{artLoad === 'loading' && ROW_SKELS.map((i) => <RowSkel key={i} />)}
|
||||
{artLoad !== 'loading' && !list.length && <StateBox load={artLoad} onRetry={() => arts.refetch()} empty="읽을거리가 아직 없어요." hold={ROW_SKELS.map((i) => <RowSkel key={i} />)} className="inset-3" />}
|
||||
{list.map((a) => (
|
||||
<button key={a.article_id} type="button" onClick={() => open({ type: 'article', articleId: a.article_id })} className="grid w-full cursor-pointer grid-cols-[1fr_84px] items-center gap-3 border-b-[1.5px] border-(--line) px-4 py-3.5 text-left">
|
||||
<button key={a.article_id} type="button" onClick={() => open({ type: 'article', articleId: a.article_id })} className={cx(ROW, 'cursor-pointer')}>
|
||||
<span>
|
||||
<span className={cx('text-xs font-extrabold', ARTICLE_CAT[a.category]?.[1])}>{ARTICLE_CAT[a.category]?.[0]}</span>
|
||||
<b className="mt-0.5 block font-jua text-[17.5px] leading-snug font-normal">{a.title}</b>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useInfiniteQuery, useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import { useInfiniteQuery, useMutation, useQuery, useQueryClient, type InfiniteData } from '@tanstack/react-query'
|
||||
import { useCallback, useDeferredValue, useEffect, useMemo, useRef, useState, type FormEvent, type ReactNode } from 'react'
|
||||
import { setTokens, subscribeAuth } from '../api/auth'
|
||||
import {
|
||||
@@ -18,16 +18,16 @@ import {
|
||||
unlikeCommentMutation,
|
||||
updateMeMutation,
|
||||
} from '../api/client/@tanstack/react-query.gen'
|
||||
import type { CommentData, Factor, ResAuth, ResIndexDetail } from '../api/client/types.gen'
|
||||
import type { CommentData, Factor, ResAuth, ResCommentList, ResIndexDetail } from '../api/client/types.gen'
|
||||
import { cx } from '../lib/utils'
|
||||
import { useAuth } from './authContext'
|
||||
import { AVATAR_COLORS, ago, ARTICLE_CAT, articleMeta, cardBg, CHARACTERS, dayLabel, MOODS, shortDay } from './lib'
|
||||
import { ago, ARTICLE_CAT, articleMeta, AVATAR_COLORS, cardBg, CHARACTERS, dateRange, loadOf, MOODS, shortDay } from './lib'
|
||||
import { useRegion } from './regionContext'
|
||||
import { useSky } from './skyContext'
|
||||
import { storyImage } from './storyImage'
|
||||
import { SheetContext, useSheet, type SharePayload, type SheetState } from './sheetContext'
|
||||
import { HeartIcon } from './svg'
|
||||
import { Avatar, Ic, StateBox } from './ui'
|
||||
import { Avatar, Ic, Skel, StateBox } from './ui'
|
||||
|
||||
export function SheetProvider({ children }: { children: ReactNode }) {
|
||||
const [state, setState] = useState<SheetState>(null)
|
||||
@@ -51,6 +51,7 @@ const TITLES = { article: '읽을거리', seasonWeek: '이번 주 특집', share
|
||||
/** 아래에서 올라오는 창: 네이티브 <dialog>라 ESC·포커스 가두기·포커스 되돌리기가 기본으로 된다 */
|
||||
function SheetHost({ state, onClose }: { state: SheetState; onClose: () => void }) {
|
||||
const ref = useRef<HTMLDialogElement>(null)
|
||||
const { kind } = useSky()
|
||||
const [gakTitle, setGakTitle] = useState('')
|
||||
const [articleTitle, setArticleTitle] = useState('')
|
||||
|
||||
@@ -79,6 +80,7 @@ function SheetHost({ state, onClose }: { state: SheetState; onClose: () => void
|
||||
<dialog
|
||||
ref={ref}
|
||||
aria-label={title}
|
||||
data-t={kind}
|
||||
onClose={onClose}
|
||||
onClick={(e) => {
|
||||
if (e.target === e.currentTarget) onClose()
|
||||
@@ -88,7 +90,7 @@ function SheetHost({ state, onClose }: { state: SheetState; onClose: () => void
|
||||
{state && (
|
||||
<div className="b-sheet flex max-h-[86dvh] flex-col rounded-t-[22px] bg-white">
|
||||
<div className="relative border-b border-(--line) px-4 pt-2 pb-2.5 text-center">
|
||||
<div className="mx-auto mb-2.5 h-1 w-10 rounded-full bg-[#d5dce7]" aria-hidden="true" />
|
||||
<div className="mx-auto mb-2.5 h-1 w-10 rounded-full bg-(--line)" aria-hidden="true" />
|
||||
<h3 className="m-0 text-[15px] font-extrabold">{title}</h3>
|
||||
<button type="button" onClick={onClose} aria-label="닫기" className="absolute right-3 bottom-2 grid size-[30px] cursor-pointer place-items-center text-xl text-(--ink2)">
|
||||
×
|
||||
@@ -112,10 +114,151 @@ function Body({ children, className }: { children: ReactNode; className?: string
|
||||
return <div className={cx('flex-1 overflow-auto overscroll-contain px-4 pt-3.5 pb-[18px]', className)}>{children}</div>
|
||||
}
|
||||
|
||||
/** 문구를 모두 같은 칸에 겹쳐 두고 하나만 보인다: 대기 문구로 바뀌어도 버튼 크기가 그대로다 */
|
||||
function Swap({ labels, at }: { labels: readonly ReactNode[]; at: number }) {
|
||||
return (
|
||||
<span className="inline-grid [&>*]:col-start-1 [&>*]:row-start-1">
|
||||
{labels.map((l, i) => (
|
||||
<span key={i} className={cx(i !== at && 'invisible')}>
|
||||
{l}
|
||||
</span>
|
||||
))}
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
/* ---------- 시트 스켈레톤: 완료 화면과 같은 틀·같은 줄 높이 ---------- */
|
||||
const N3 = [0, 1, 2]
|
||||
const N4 = [0, 1, 2, 3]
|
||||
const N6 = [0, 1, 2, 3, 4, 5]
|
||||
const N14 = Array.from({ length: 14 }, (_, i) => i)
|
||||
|
||||
function GakSkel() {
|
||||
return (
|
||||
<div aria-hidden="true">
|
||||
<div className="flex items-center gap-3">
|
||||
<Skel shape className="size-[58px] shrink-0 rounded-full" />
|
||||
<div className="flex-1">
|
||||
<h4 className="m-0 font-jua text-[22px] font-normal">
|
||||
<Skel className="w-28" />
|
||||
</h4>
|
||||
<p className="mt-0.5 text-[13.5px] font-semibold">
|
||||
<Skel className="w-4/5" />
|
||||
</p>
|
||||
</div>
|
||||
<b className="ml-auto font-bagel text-[42px] font-normal">
|
||||
<Skel className="w-14" />
|
||||
</b>
|
||||
</div>
|
||||
<Skel shape className="mx-auto mt-2 aspect-square w-full max-w-[250px] rounded-full" />
|
||||
<div className="mt-2.5 grid grid-cols-4 gap-1.5">
|
||||
{N4.map((i) => (
|
||||
<div key={i} className="rounded-2xl bg-[#f3f6fb] px-1 py-2.5 text-center">
|
||||
<small className="block text-xs font-extrabold">
|
||||
<Skel className="w-8" />
|
||||
</small>
|
||||
<b className="block font-bagel text-2xl font-normal">
|
||||
<Skel className="w-9" />
|
||||
</b>
|
||||
<small className="block text-[11px] leading-4 font-extrabold">
|
||||
<Skel className="w-6" />
|
||||
</small>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
<div className="mt-3.5 flex flex-col gap-2.5">
|
||||
{N6.map((i) => (
|
||||
<div key={i} className="grid grid-cols-[84px_1fr_52px] items-center gap-x-2.5 text-[13.5px] font-bold">
|
||||
<span>
|
||||
<Skel className="w-12" />
|
||||
</span>
|
||||
<Skel shape className="h-[9px] rounded-full" />
|
||||
<em className="text-right text-xs not-italic">
|
||||
<Skel className="w-10" />
|
||||
</em>
|
||||
<p className="col-start-2 col-end-4 -mt-0.5 text-[12.5px] font-semibold">
|
||||
<Skel className="w-3/4" />
|
||||
</p>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
<div className="mt-3.5 flex flex-col gap-1.5 text-[13px] font-semibold">
|
||||
<span>
|
||||
<Skel className="w-full" />
|
||||
<br />
|
||||
<Skel className="w-1/2" />
|
||||
</span>
|
||||
<span>
|
||||
<Skel className="w-4/5" />
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/** 읽을거리·이번 주 특집: 그림 150px · 머리말 · 제목 · 본문 */
|
||||
function ArticleSkel() {
|
||||
return (
|
||||
<div aria-hidden="true">
|
||||
<Skel shape className="mb-3.5 h-[150px] rounded-[20px]" />
|
||||
<p className="text-[13px] font-extrabold">
|
||||
<Skel className="w-24" />
|
||||
</p>
|
||||
<h4 className="mt-1.5 mb-2.5 font-jua text-2xl leading-tight font-normal">
|
||||
<Skel className="w-4/5" />
|
||||
</h4>
|
||||
{N3.map((k) => (
|
||||
<p key={k} className="mb-2.5 text-[15px] leading-[1.7]">
|
||||
<Skel className="w-full" />
|
||||
<br />
|
||||
<Skel className="w-2/3" />
|
||||
</p>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function CommentsSkel() {
|
||||
return (
|
||||
<div aria-hidden="true">
|
||||
{N3.map((i) => (
|
||||
<div key={i} className="grid grid-cols-[34px_1fr_24px] items-start gap-2.5 py-2">
|
||||
<Skel shape className="size-[34px] rounded-full" />
|
||||
<div>
|
||||
<p className="m-0 text-sm">
|
||||
<Skel className="w-3/4" />
|
||||
</p>
|
||||
<small className="mt-0.5 block text-xs font-bold">
|
||||
<Skel className="w-24" />
|
||||
</small>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function RegionsSkel() {
|
||||
return (
|
||||
<ul className="mt-2 flex flex-col" aria-hidden="true">
|
||||
{N14.map((i) => (
|
||||
<li key={i} className="border-b-[1.5px] border-(--line) px-1 py-3 font-jua text-[17px]">
|
||||
<Skel className="w-28" />
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)
|
||||
}
|
||||
|
||||
/* ---------- 각 계산 근거 ---------- */
|
||||
const labelLines = (label: string) => {
|
||||
const cut = label.indexOf(' ')
|
||||
return cut < 0 ? [label] : [label.slice(0, cut), label.slice(cut + 1)]
|
||||
}
|
||||
|
||||
function Radar({ name, factors, size = 250 }: { name: string; factors: Factor[]; size?: number }) {
|
||||
const c = size / 2
|
||||
const r = size / 2 - 34
|
||||
const r = size / 2 - 40
|
||||
const n = factors.length
|
||||
const pt = (i: number, v: number) => {
|
||||
const a = -Math.PI / 2 + (i * 2 * Math.PI) / n
|
||||
@@ -135,8 +278,12 @@ function Radar({ name, factors, size = 250 }: { name: string; factors: Factor[];
|
||||
<circle key={f.axis} cx={pt(i, f.value / 100)[0]} cy={pt(i, f.value / 100)[1]} r="4.5" fill="#fff" stroke="#ff7a45" strokeWidth="2.5" />
|
||||
))}
|
||||
{factors.map((f, i) => (
|
||||
<text key={f.axis} x={pt(i, 1.2)[0]} y={pt(i, 1.2)[1]} textAnchor="middle" dominantBaseline="middle" fontFamily="Jua,sans-serif" fontSize="14" fill="#28304a">
|
||||
{f.label}
|
||||
<text key={f.axis} x={pt(i, 1.24)[0]} y={pt(i, 1.24)[1]} textAnchor="middle" dominantBaseline="middle" fontFamily="Jua,sans-serif" fontSize="13" fill="#28304a">
|
||||
{labelLines(f.label).map((line, k, all) => (
|
||||
<tspan key={k} x={pt(i, 1.24)[0]} dy={k === 0 ? `${-(all.length - 1) * 0.55}em` : '1.1em'}>
|
||||
{line}
|
||||
</tspan>
|
||||
))}
|
||||
</text>
|
||||
))}
|
||||
</svg>
|
||||
@@ -153,7 +300,8 @@ function GakSheet({ indexId, onTitle }: { indexId: number; onTitle: (t: string)
|
||||
onTitle(g ? `${g.rank}위 ${g.name}` : '계산 근거')
|
||||
}, [g, onTitle])
|
||||
|
||||
if (!g) return <Body>{<StateBox loading={q.isPending} error={q.error} onRetry={() => q.refetch()} empty="이 각의 계산 근거가 아직 없어요." className="mx-0" />}</Body>
|
||||
const load = loadOf(q)
|
||||
if (!g) return <Body>{load === 'loading' ? <GakSkel /> : <StateBox load={load} onRetry={() => q.refetch()} empty="이 각의 계산 근거가 아직 없어요." hold={<GakSkel />} className="inset-0" />}</Body>
|
||||
const factors = d.factors ?? []
|
||||
return (
|
||||
<Body>
|
||||
@@ -167,18 +315,19 @@ function GakSheet({ indexId, onTitle }: { indexId: number; onTitle: (t: string)
|
||||
</div>
|
||||
{factors.length > 2 && <Radar name={g.name} factors={factors} />}
|
||||
{g.trend && g.trend.length > 0 && (
|
||||
<div className="mt-2.5 grid grid-cols-3 gap-2">
|
||||
{g.trend.map((t, j) => (
|
||||
<div key={t.day} className="rounded-2xl bg-[#f3f6fb] p-2.5 text-center">
|
||||
<small className="text-xs font-extrabold text-(--ink2)">{dayLabel(t.day, j)}</small>
|
||||
<div className="mt-2.5 grid grid-cols-4 gap-1.5">
|
||||
{g.trend.map((t) => (
|
||||
<div key={t.day} className="rounded-2xl bg-[#f3f6fb] px-1 py-2.5 text-center">
|
||||
<small className="block text-xs font-extrabold whitespace-nowrap text-(--ink2)">{t.label}</small>
|
||||
<b className="block font-bagel text-2xl font-normal text-(--orange)">{t.score}</b>
|
||||
<small className={cx('block text-[11px] leading-4 font-extrabold text-(--ink2)', !t.estimated && 'invisible')}>예상</small>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
<div className="mt-3.5 flex flex-col gap-2.5">
|
||||
{factors.map((f) => (
|
||||
<div key={f.axis} className="grid grid-cols-[50px_1fr_52px] items-center gap-x-2.5 text-[13.5px] font-bold">
|
||||
<div key={f.axis} className="grid grid-cols-[84px_1fr_52px] items-center gap-x-2.5 text-[13.5px] font-bold">
|
||||
<span>{f.label}</span>
|
||||
<i className="block h-[9px] overflow-hidden rounded-full bg-[#e3eaf4]">
|
||||
<s className="block h-full bg-[linear-gradient(90deg,#ffc86e,var(--orange))]" style={{ width: `${f.value}%` }} />
|
||||
@@ -191,12 +340,17 @@ function GakSheet({ indexId, onTitle }: { indexId: number; onTitle: (t: string)
|
||||
<div className="mt-3.5 flex flex-col gap-1.5 text-[13px] font-semibold text-(--ink2)">
|
||||
{d.zero_reason && (
|
||||
<span>
|
||||
<b className="text-(--heart)">오늘 0점인 이유:</b> {d.zero_reason}
|
||||
<b className="text-(--heart)">오늘 걸린 조건:</b> {d.zero_reason}
|
||||
</span>
|
||||
)}
|
||||
{factors.length > 0 && (
|
||||
<span>
|
||||
<b className="text-(--ink)">계산 방법:</b> 요소 점수에 비중을 곱해 더하고, 가장 낮은 요소가 낮을수록 최대 25%까지 더 깎아요
|
||||
</span>
|
||||
)}
|
||||
{d.zero_rules && (
|
||||
<span>
|
||||
<b className="text-(--ink)">바로 0점:</b> {d.zero_rules}
|
||||
<b className="text-(--ink)">점수 깎이는 조건:</b> {d.zero_rules}
|
||||
</span>
|
||||
)}
|
||||
{d.limit && (
|
||||
@@ -218,7 +372,8 @@ function ArticleSheet({ articleId, onTitle }: { articleId: number; onTitle: (t:
|
||||
onTitle(a ? (ARTICLE_CAT[a.category]?.[0] ?? '') : '')
|
||||
}, [a, onTitle])
|
||||
|
||||
if (!a) return <Body>{<StateBox loading={q.isPending} error={q.error} onRetry={() => q.refetch()} empty="글을 찾지 못했어요." className="mx-0" />}</Body>
|
||||
const load = loadOf(q)
|
||||
if (!a) return <Body>{load === 'loading' ? <ArticleSkel /> : <StateBox load={load} onRetry={() => q.refetch()} empty="글을 찾지 못했어요." hold={<ArticleSkel />} className="inset-0" />}</Body>
|
||||
return (
|
||||
<Body>
|
||||
<div className={cx('mb-3.5 grid h-[150px] place-items-center rounded-[20px]', `b-bg-${cardBg(a.icon, a.article_id)}`)}>
|
||||
@@ -240,13 +395,14 @@ function SeasonWeekSheet() {
|
||||
const { open } = useSheet()
|
||||
const q = useQuery(getSeasonWeekOptions())
|
||||
const w = q.data
|
||||
if (!w?.headline) return <Body>{<StateBox loading={q.isPending} error={q.error} onRetry={() => q.refetch()} empty="이번 주 특집이 아직 없어요." className="mx-0" />}</Body>
|
||||
const load = loadOf(q)
|
||||
if (!w?.headline) return <Body>{load === 'loading' ? <ArticleSkel /> : <StateBox load={load} onRetry={() => q.refetch()} empty="이번 주 특집이 아직 없어요." hold={<ArticleSkel />} className="inset-0" />}</Body>
|
||||
return (
|
||||
<Body>
|
||||
<div className="mb-3.5 grid h-[150px] place-items-center rounded-[20px] b-bg-peach">
|
||||
<Ic name="maple" className="w-24" />
|
||||
</div>
|
||||
<p className="text-[13px] font-extrabold text-(--ink2)">이번 주 특집 · {w.week}번째 주</p>
|
||||
<p className="text-[13px] font-extrabold text-(--ink2)">{w.start && w.end ? dateRange(w.start, w.end) : '이번 주'}</p>
|
||||
<h4 className="mt-1.5 mb-2.5 font-jua text-2xl leading-tight font-normal">{w.headline}</h4>
|
||||
{(w.poem_lines ?? []).length > 0 && (
|
||||
<p className="mb-2.5 font-batang text-[17px] leading-[1.7]">
|
||||
@@ -280,7 +436,7 @@ function ShareSheet({ share }: { share: SharePayload }) {
|
||||
const msg = isMine ? mine : opts[pick]
|
||||
|
||||
const url = window.location.origin
|
||||
const text = `${msg} — ${share.title} · 날씨각`
|
||||
const text = msg.trim() ? `${msg} — ${share.title} · 날씨각` : `${share.title} · 날씨각`
|
||||
const { kind } = useSky()
|
||||
const [image, setImage] = useState<{ blob: Blob; src: string } | null>(null)
|
||||
const [imageError, setImageError] = useState(false)
|
||||
@@ -450,22 +606,29 @@ function CommentRow({ c, postId }: { c: CommentData; postId: number }) {
|
||||
)
|
||||
}
|
||||
|
||||
const del = () =>
|
||||
// 지우는 동안은 흐리게 두고, 성공하면 다시 받기 전에 목록 캐시에서 바로 뺀다
|
||||
const del = () => {
|
||||
setRemoveFailed(false)
|
||||
remove.mutate(
|
||||
{ path: { comment_id: c.comment_id } },
|
||||
{
|
||||
onSuccess: (res) => {
|
||||
setRemoveFailed(!res.result?.success)
|
||||
if (!res.result?.success) return
|
||||
queryClient.invalidateQueries({ queryKey: listCommentsInfiniteQueryKey({ path: { post_id: postId } }) })
|
||||
onSuccess: async (res) => {
|
||||
if (!res.result?.success) return setRemoveFailed(true)
|
||||
const key = listCommentsInfiniteQueryKey({ path: { post_id: postId } })
|
||||
await queryClient.cancelQueries({ queryKey: key })
|
||||
queryClient.setQueryData<InfiniteData<ResCommentList>>(key, (data) =>
|
||||
data ? { ...data, pages: data.pages.map((p) => ({ ...p, comments: p.comments?.filter((x) => x.comment_id !== c.comment_id) })) } : data,
|
||||
)
|
||||
queryClient.invalidateQueries({ queryKey: key })
|
||||
queryClient.invalidateQueries({ queryKey: getFeedQueryKey({ query: { region: region.code } }) })
|
||||
},
|
||||
onError: () => setRemoveFailed(true),
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="grid grid-cols-[34px_1fr_24px] items-start gap-2.5 py-2">
|
||||
<div className={cx('grid grid-cols-[34px_1fr_24px] items-start gap-2.5 py-2 transition-opacity', remove.isPending && 'opacity-50')} aria-busy={remove.isPending}>
|
||||
<Avatar character={c.character} color={c.color} mood={c.mood} />
|
||||
<div>
|
||||
<p className="m-0 text-sm">
|
||||
@@ -477,13 +640,12 @@ function CommentRow({ c, postId }: { c: CommentData; postId: number }) {
|
||||
{c.mine && (
|
||||
<>
|
||||
{' · '}
|
||||
<button type="button" onClick={del} disabled={remove.isPending} className="cursor-pointer font-bold text-(--ink3) underline-offset-2 hover:underline">
|
||||
지우기
|
||||
<button type="button" onClick={del} disabled={remove.isPending} className={cx('cursor-pointer text-left font-bold underline-offset-2 hover:underline', removeFailed && !remove.isPending ? 'text-(--heart)' : 'text-(--ink3)')}>
|
||||
<Swap labels={['지우기', '지우는 중…', '못 지웠어요 · 다시']} at={remove.isPending ? 1 : removeFailed ? 2 : 0} />
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
</small>
|
||||
{removeFailed && <small className="block text-xs font-bold text-(--heart)">지우지 못했어요. 다시 해 주세요.</small>}
|
||||
</div>
|
||||
<button type="button" onClick={toggle} aria-pressed={liked} aria-label="댓글 좋아요" className="cursor-pointer pt-1">
|
||||
<HeartIcon className={cx('size-4 stroke-2', liked ? 'fill-(--heart) stroke-(--heart)' : 'fill-none stroke-(--ink3)')} />
|
||||
@@ -512,7 +674,8 @@ function CommentsSheet({ postId }: { postId: number }) {
|
||||
e.preventDefault()
|
||||
if (!loggedIn) return open({ type: 'login' })
|
||||
const body = text.trim()
|
||||
if (!body) return
|
||||
if (!body || add.isPending) return
|
||||
setAddFailed(false)
|
||||
add.mutate(
|
||||
{ path: { post_id: postId }, body: { body } },
|
||||
{
|
||||
@@ -541,21 +704,19 @@ function CommentsSheet({ postId }: { postId: number }) {
|
||||
</button>
|
||||
)}
|
||||
</>
|
||||
) : list.isSuccess ? (
|
||||
<p className="my-6 text-center font-semibold text-(--ink3)">
|
||||
아직 댓글이 없어요.
|
||||
<br />첫 댓글을 남겨 보세요.
|
||||
</p>
|
||||
) : loadOf(list) === 'loading' ? (
|
||||
<CommentsSkel />
|
||||
) : (
|
||||
<StateBox loading={list.isPending} error={list.error} onRetry={() => list.refetch()} className="mx-0" />
|
||||
<StateBox load={loadOf(list)} onRetry={() => list.refetch()} empty="아직 댓글이 없어요. 첫 댓글을 남겨 보세요." hold={<CommentsSkel />} className="inset-0" />
|
||||
)}
|
||||
</Body>
|
||||
<div className="flex justify-around pt-1 pb-2 text-[22px]" role="group" aria-label="빠른 이모지">
|
||||
<div className="flex justify-around pt-1 text-[22px]" role="group" aria-label="빠른 이모지">
|
||||
{EMOJIS.map((e) => (
|
||||
<button
|
||||
key={e}
|
||||
type="button"
|
||||
className="cursor-pointer"
|
||||
disabled={add.isPending}
|
||||
className="cursor-pointer disabled:opacity-40"
|
||||
onClick={() => {
|
||||
setText((t) => (t + e).slice(0, 60))
|
||||
inputRef.current?.focus()
|
||||
@@ -565,15 +726,13 @@ function CommentsSheet({ postId }: { postId: number }) {
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
{addFailed && (
|
||||
<p className="px-4 pb-1 text-center text-xs font-bold text-(--heart)" role="alert">
|
||||
댓글을 올리지 못했어요. 다시 해 주세요.
|
||||
</p>
|
||||
)}
|
||||
<p className="h-4 px-4 text-center text-xs leading-4 font-bold text-(--heart)" role="alert">
|
||||
{addFailed && '댓글을 올리지 못했어요. 다시 해 주세요.'}
|
||||
</p>
|
||||
<form onSubmit={submit} className="flex items-center gap-2.5 border-t border-(--line) px-3 pt-2.5 pb-[calc(10px+env(safe-area-inset-bottom,0px))]">
|
||||
<input ref={inputRef} value={text} onChange={(e) => setText(e.target.value)} maxLength={60} placeholder={me ? `${me.nickname}(으)로 댓글 달기…` : '댓글 달기…'} aria-label="댓글" className="flex-1 rounded-full border border-[#dfe5ee] bg-[#f7f9fc] px-3.5 py-2.5" />
|
||||
<input ref={inputRef} value={text} onChange={(e) => setText(e.target.value)} readOnly={add.isPending} maxLength={60} placeholder={me ? `${me.nickname}(으)로 댓글 달기…` : '댓글 달기…'} aria-label="댓글" className="min-w-0 flex-1 rounded-full border border-[#dfe5ee] bg-[#f7f9fc] px-3.5 py-2.5" />
|
||||
<button type="submit" disabled={add.isPending || (loggedIn && !text.trim())} className="cursor-pointer font-extrabold text-(--rain) disabled:opacity-40">
|
||||
게시
|
||||
<Swap labels={['게시', '올리는 중…']} at={add.isPending ? 1 : 0} />
|
||||
</button>
|
||||
</form>
|
||||
</>
|
||||
@@ -621,7 +780,7 @@ function LoginSheet({ onDone }: { onDone: () => void }) {
|
||||
return (
|
||||
<Body>
|
||||
<form onSubmit={submit} className="flex flex-col gap-2.5">
|
||||
<p className="text-center text-sm font-semibold text-(--ink2)">좋아요·저장·댓글은 로그인한 뒤에 할 수 있어요.</p>
|
||||
<p className="text-center text-sm font-semibold text-(--ink2)">좋아요·댓글은 로그인한 뒤에 할 수 있어요.</p>
|
||||
<div className="grid grid-cols-2 gap-1 rounded-full bg-[#f3f6fb] p-1" role="group" aria-label="로그인 또는 가입">
|
||||
{(
|
||||
[
|
||||
@@ -641,7 +800,7 @@ function LoginSheet({ onDone }: { onDone: () => void }) {
|
||||
{error}
|
||||
</p>
|
||||
<button type="submit" disabled={pending} className="cursor-pointer rounded-[14px] bg-(--orange) p-[13px] font-jua text-[17px] text-white shadow-[inset_0_-5px_0_var(--orange-deep)] disabled:opacity-60">
|
||||
{mode === 'login' ? '로그인' : '가입하고 시작하기'}
|
||||
<Swap labels={mode === 'login' ? ['로그인', '로그인 중…'] : ['가입하고 시작하기', '가입하는 중…']} at={pending ? 1 : 0} />
|
||||
</button>
|
||||
<button type="button" onClick={onDone} className="cursor-pointer rounded-[14px] p-[13px] text-[15px] font-extrabold text-(--ink2)">
|
||||
나중에 할게요
|
||||
@@ -676,6 +835,12 @@ function MeSheet({ onDone }: { onDone: () => void }) {
|
||||
)
|
||||
}
|
||||
|
||||
// 저장하는 동안은 고른 값을 바로 선택으로 보여 준다. 실패하면 me 값으로 돌아간다
|
||||
const saving = update.isPending ? update.variables?.body : undefined
|
||||
const character = saving?.character ?? me.character
|
||||
const color = saving?.color ?? me.color
|
||||
const mood = saving?.mood ?? me.mood
|
||||
|
||||
return (
|
||||
<Body className="flex flex-col gap-3">
|
||||
<div className="flex flex-col items-center gap-1.5">
|
||||
@@ -690,10 +855,10 @@ function MeSheet({ onDone }: { onDone: () => void }) {
|
||||
key={key}
|
||||
type="button"
|
||||
role="radio"
|
||||
aria-checked={me.character === key}
|
||||
aria-checked={character === key}
|
||||
disabled={update.isPending}
|
||||
onClick={() => save({ character: key })}
|
||||
className={cx('flex cursor-pointer flex-col items-center gap-1 rounded-[18px] border-2 bg-[#f7f9fc] py-2.5 font-jua text-[15px]', me.character === key ? 'border-(--orange) text-(--orange)' : 'border-transparent text-(--ink)')}
|
||||
className={cx('flex cursor-pointer flex-col items-center gap-1 rounded-[18px] border-2 bg-[#f7f9fc] py-2.5 font-jua text-[15px]', character === key ? 'border-(--orange) text-(--orange)' : 'border-transparent text-(--ink)')}
|
||||
>
|
||||
<Ic name={key} className="w-12" />
|
||||
{label}
|
||||
@@ -709,11 +874,11 @@ function MeSheet({ onDone }: { onDone: () => void }) {
|
||||
key={key}
|
||||
type="button"
|
||||
role="radio"
|
||||
aria-checked={me.color === key}
|
||||
aria-checked={color === key}
|
||||
aria-label={key}
|
||||
disabled={update.isPending}
|
||||
onClick={() => save({ color: key })}
|
||||
className={cx('size-9 cursor-pointer rounded-full border-[3px]', me.color === key ? 'border-(--ink)' : 'border-white shadow-[0_0_0_1px_var(--line)]')}
|
||||
className={cx('size-9 cursor-pointer rounded-full border-[3px]', color === key ? 'border-(--ink)' : 'border-white shadow-[0_0_0_1px_var(--line)]')}
|
||||
style={{ background: hex }}
|
||||
/>
|
||||
))}
|
||||
@@ -727,10 +892,10 @@ function MeSheet({ onDone }: { onDone: () => void }) {
|
||||
key={key}
|
||||
type="button"
|
||||
role="radio"
|
||||
aria-checked={me.mood === key}
|
||||
aria-checked={mood === key}
|
||||
disabled={update.isPending}
|
||||
onClick={() => save({ mood: me.mood === key ? '' : key })}
|
||||
className={cx('flex cursor-pointer flex-col items-center gap-0.5 rounded-[14px] border-2 bg-[#f7f9fc] py-2 text-xs font-bold', me.mood === key ? 'border-(--orange) text-(--orange)' : 'border-transparent text-(--ink2)')}
|
||||
onClick={() => save({ mood: mood === key ? '' : key })}
|
||||
className={cx('flex cursor-pointer flex-col items-center gap-0.5 rounded-[14px] border-2 bg-[#f7f9fc] py-2 text-xs font-bold', mood === key ? 'border-(--orange) text-(--orange)' : 'border-transparent text-(--ink2)')}
|
||||
>
|
||||
<span className="text-[22px] leading-none">{emoji}</span>
|
||||
{label}
|
||||
@@ -748,11 +913,11 @@ function MeSheet({ onDone }: { onDone: () => void }) {
|
||||
>
|
||||
<input value={nickname} onChange={(e) => setNickname(e.target.value)} required minLength={2} maxLength={12} aria-label="닉네임" placeholder="닉네임 (2~12자)" className="flex-1 rounded-[14px] border border-[#dfe5ee] bg-[#f7f9fc] px-3.5 py-3" />
|
||||
<button type="submit" disabled={update.isPending || nickname.trim() === me.nickname} className="cursor-pointer rounded-[14px] bg-(--ink) px-4 py-3 text-sm font-extrabold text-white disabled:opacity-40">
|
||||
바꾸기
|
||||
<Swap labels={['바꾸기', '저장 중…']} at={saving?.nickname != null ? 1 : 0} />
|
||||
</button>
|
||||
</form>
|
||||
<p className="m-0 min-h-5 text-center text-[13px] font-bold text-(--heart)" aria-live="polite">
|
||||
{error}
|
||||
<p className={cx('m-0 min-h-5 text-center text-[13px] font-bold', saving ? 'text-(--ink2)' : 'text-(--heart)')} aria-live="polite">
|
||||
{saving ? (saving.nickname == null ? '저장 중…' : '') : error}
|
||||
</p>
|
||||
<button
|
||||
type="button"
|
||||
@@ -779,6 +944,7 @@ function RegionSheet({ onDone }: { onDone: () => void }) {
|
||||
const deferred = useDeferredValue(q.trim())
|
||||
const list = useQuery(listRegionsOptions(deferred ? { query: { q: deferred } } : undefined))
|
||||
const regions = list.data?.regions ?? []
|
||||
const listLoad = loadOf(list)
|
||||
|
||||
return (
|
||||
<Body>
|
||||
@@ -789,8 +955,9 @@ function RegionSheet({ onDone }: { onDone: () => void }) {
|
||||
{LOCATE_TEXT[locateStatus]}
|
||||
</p>
|
||||
<input value={q} onChange={(e) => setQ(e.target.value)} placeholder="구 이름으로 찾기 (예: 마포)" aria-label="구 이름으로 찾기" className="mt-1 w-full rounded-full border border-[#dfe5ee] bg-[#f7f9fc] px-3.5 py-2.5" />
|
||||
<StateBox loading={list.isPending} error={list.error} onRetry={() => list.refetch()} empty={list.isSuccess && !regions.length ? '찾는 구가 없어요.' : undefined} className="mx-0" />
|
||||
<ul className="mt-2 flex flex-col">
|
||||
{listLoad === 'loading' && <RegionsSkel />}
|
||||
{listLoad !== 'loading' && !regions.length && (listLoad === 'ready' ? <StateBox load={listLoad} empty="찾는 구가 없어요." className="mt-3" /> : <StateBox load={listLoad} onRetry={() => list.refetch()} hold={<RegionsSkel />} className="inset-x-0 top-2 bottom-0" />)}
|
||||
<ul className={cx('mt-2 flex flex-col transition-opacity', list.isPlaceholderData && 'opacity-60')}>
|
||||
{regions.map((r) => (
|
||||
<li key={r.code}>
|
||||
<button
|
||||
@@ -809,7 +976,7 @@ function RegionSheet({ onDone }: { onDone: () => void }) {
|
||||
))}
|
||||
</ul>
|
||||
<p className="mt-4 flex items-center justify-center gap-2 text-[13px] font-bold text-(--ink2)">
|
||||
{me ? `${me.nickname}(으)로 로그인했어요` : '로그인하면 좋아요·저장·댓글을 쓸 수 있어요'}
|
||||
{me ? `${me.nickname}(으)로 로그인했어요` : '로그인하면 좋아요·댓글을 쓸 수 있어요'}
|
||||
<button type="button" onClick={me ? logout : () => open({ type: 'login' })} className="cursor-pointer font-extrabold text-(--rain)">
|
||||
{me ? '로그아웃' : '로그인'}
|
||||
</button>
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import type { ReactNode } from 'react'
|
||||
import { getSkyOptions, getSkyRankingOptions } from '../api/client/@tanstack/react-query.gen'
|
||||
import type { RegionData, SpotData } from '../api/client/types.gen'
|
||||
import type { BestTime, RegionData, SkyPlanData, SpotData } from '../api/client/types.gen'
|
||||
import { cx } from '../lib/utils'
|
||||
import { clockShort, dayLabel, timeWords } from './lib'
|
||||
import { clockShort, compass, dayLabel, loadOf } from './lib'
|
||||
import { useRegion } from './regionContext'
|
||||
import { Rail, Sec, StateBox } from './ui'
|
||||
import { Sec, Skel, StateBox } from './ui'
|
||||
|
||||
const W = 400
|
||||
const H = 260
|
||||
@@ -45,7 +46,7 @@ function SpotMap({ region, spots, azimuth }: { region: RegionData; spots: SpotDa
|
||||
<path d={`M${cx0} ${cy0} L${dir(260, -0.3).join(' ')} L${dir(260, 0.3).join(' ')} Z`} fill="#ff8e4e" opacity=".18" />
|
||||
<path d={`M${cx0} ${cy0} L${tip.join(' ')}`} stroke="#ff7a45" strokeWidth="3" strokeDasharray="7 6" />
|
||||
<text x={Math.min(W - 110, Math.max(8, label[0] - 50))} y={label[1] + 26} fontFamily="Jua,sans-serif" fontSize="14" fill="#d4552a">
|
||||
해 지는 쪽 {azimuth}°
|
||||
해 지는 {compass(azimuth)}쪽
|
||||
</text>
|
||||
</>
|
||||
)}
|
||||
@@ -67,21 +68,124 @@ function SpotMap({ region, spots, azimuth }: { region: RegionData; spots: SpotDa
|
||||
)
|
||||
}
|
||||
|
||||
function Li({ no, title, sub, right, meter, mine = false }: { no: number; title: string; sub?: string | null; right: string; meter?: number; mine?: boolean }) {
|
||||
function LiSkel({ ghost = false }: { ghost?: boolean }) {
|
||||
return (
|
||||
<li className={cx('grid grid-cols-[34px_1fr_auto] items-center gap-2.5 border-b-[1.5px] border-(--line) px-1 py-3 last:border-b-0', ghost && 'invisible')} aria-hidden="true">
|
||||
<span className="text-center font-bagel text-xl">
|
||||
<Skel className="w-5" />
|
||||
</span>
|
||||
<span>
|
||||
<b className="block font-jua text-[17px] font-normal">
|
||||
<Skel className="w-24" />
|
||||
</b>
|
||||
<small className="block truncate text-[12.5px] font-semibold">
|
||||
<Skel className="w-40" />
|
||||
</small>
|
||||
</span>
|
||||
<em className="font-jua text-base not-italic">
|
||||
<Skel className="w-9" />
|
||||
</em>
|
||||
</li>
|
||||
)
|
||||
}
|
||||
|
||||
const HERO = 'relative mx-3 mt-1 min-h-[350px] overflow-hidden rounded-[32px] bg-[linear-gradient(180deg,#7e6fe6,#f08aa2_58%,#ffc28a)] px-5 pt-5 pb-16 text-white'
|
||||
const THREE = [0, 1, 2]
|
||||
const FOUR = [0, 1, 2, 3]
|
||||
const RANK_SKELS = Array.from({ length: 8 }, (_, i) => i)
|
||||
|
||||
/** 결론 → 왜 → 몇 시에 어디로 → 점수(보조). 글자 줄 수를 고정해 스켈레톤과 크기가 같다 */
|
||||
function HeroBody({ plan }: { plan?: SkyPlanData }) {
|
||||
const v = (node: ReactNode, w: string) => (plan ? node : <Skel className={w} />)
|
||||
const place = plan && (plan.spot ? `${plan.spot.name} · ${plan.spot.distance_km}km` : plan.verdict === 'rest' ? '오늘은 나가지 않아도 돼요' : '30km 안에 등록된 명소가 없어요')
|
||||
return (
|
||||
<div aria-hidden={plan ? undefined : true}>
|
||||
<p className="relative m-0 mt-1.5 font-jua text-[38px] leading-[1.1]">{v(plan?.headline, 'w-[200px]')}</p>
|
||||
<div className="relative z-[1] mt-3 rounded-[20px] bg-[rgb(45_36_64/0.55)] px-4 py-3">
|
||||
<p className="m-0 line-clamp-2 h-[2lh] text-[14.5px] leading-snug font-bold">{v(plan?.reason, 'w-[250px]')}</p>
|
||||
<div className="mt-2.5 grid grid-cols-[auto_1fr] items-center gap-x-3 border-t border-white/25 pt-2.5">
|
||||
<b className="row-span-2 font-bagel text-[30px] leading-none font-normal">{v(plan?.best_at && clockShort(plan.best_at), 'w-[76px]')}</b>
|
||||
<span className="text-[13px] font-extrabold">{v(plan && '가장 붉을 때', 'w-20')}</span>
|
||||
<span className="truncate text-[13px] font-bold">{v(place, 'w-36')}</span>
|
||||
</div>
|
||||
<p className="m-0 mt-2.5 border-t border-white/25 pt-2 text-[12.5px] leading-snug font-bold">
|
||||
{v(plan && `노을 점수 ${plan.score}점 · ${plan.grade_label}`, 'w-32')}
|
||||
<small className="block text-[12px] font-semibold">{v(plan && '해 지는 쪽 구름 높이·양으로 매겨요. 60점부터 나가 볼 만해요', 'w-56')}</small>
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/** 일몰 전 골든아워 → 해 짐 → 가장 붉을 때 → 블루아워, 한 줄 */
|
||||
function Timeline({ rows }: { rows?: BestTime[] }) {
|
||||
return (
|
||||
<ol className="relative mx-3 mt-3 grid grid-cols-4 rounded-[22px] bg-white px-2 pt-4 pb-3 shadow-[inset_0_-5px_0_var(--shade)]" aria-hidden={rows ? undefined : true}>
|
||||
<span className="absolute inset-x-[12.5%] top-[22px] h-0.5 bg-(--line)" aria-hidden="true" />
|
||||
{(rows ?? FOUR.map(() => undefined)).map((t, i) => (
|
||||
<li key={t?.kind ?? i} className="relative flex flex-col items-center text-center">
|
||||
<span className={cx('size-3 rounded-full border-2 border-(--line) bg-white', t?.kind === 'peak' && 'border-[#d6457a] bg-[#d6457a]')} />
|
||||
<b className={cx('mt-1.5 font-bagel text-lg leading-tight font-normal', t?.kind === 'peak' && 'text-[#d6457a]')}>{t ? clockShort(t.at) : <Skel className="w-12" />}</b>
|
||||
<span className="text-[12px] font-bold text-(--ink2)">{t ? t.label : <Skel className="w-11" />}</span>
|
||||
</li>
|
||||
))}
|
||||
</ol>
|
||||
)
|
||||
}
|
||||
|
||||
function SpotsSkel() {
|
||||
return (
|
||||
<>
|
||||
<Skel shape className="mx-3 mt-3 aspect-[400/260] rounded-[26px]" />
|
||||
<ul className="mx-3 mt-1.5 flex flex-col">
|
||||
{THREE.map((i) => (
|
||||
<LiSkel key={i} />
|
||||
))}
|
||||
</ul>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
function DaysSkel() {
|
||||
return (
|
||||
<div className="grid grid-cols-3 gap-2 p-3" aria-hidden="true">
|
||||
{THREE.map((i) => (
|
||||
<div key={i} className="rounded-[20px] bg-white p-3 text-center shadow-[inset_0_-5px_0_var(--shade)]">
|
||||
<small className="block text-[12.5px] font-extrabold">
|
||||
<Skel className="w-10" />
|
||||
</small>
|
||||
<b className="block font-bagel text-[30px] font-normal">
|
||||
<Skel className="w-10" />
|
||||
</b>
|
||||
<span className="block text-xs font-bold">
|
||||
<Skel className="w-12" />
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function RankSkel() {
|
||||
return (
|
||||
<ul className="mx-3 mt-1.5 flex flex-col" aria-hidden="true">
|
||||
{RANK_SKELS.map((i) => (
|
||||
<LiSkel key={i} />
|
||||
))}
|
||||
</ul>
|
||||
)
|
||||
}
|
||||
|
||||
function Li({ no, title, sub, right, mine = false }: { no: number; title: string; sub?: string | null; right: string; mine?: boolean }) {
|
||||
return (
|
||||
<li className={cx('grid grid-cols-[34px_1fr_auto] items-center gap-2.5 border-b-[1.5px] border-(--line) px-1 py-3 last:border-b-0', mine && 'rounded-2xl bg-white')}>
|
||||
<span className="text-center font-bagel text-xl text-(--orange)">{no}</span>
|
||||
<span>
|
||||
<span className="min-w-0">
|
||||
<b className="block font-jua text-[17px] font-normal">
|
||||
{title}
|
||||
{mine && <small className="ml-1.5 font-sans text-xs font-extrabold text-(--rain)">내 지역</small>}
|
||||
</b>
|
||||
{sub && <small className="text-[12.5px] font-semibold text-(--ink2)">{sub}</small>}
|
||||
{meter != null && (
|
||||
<span className="mt-[5px] block h-1.5 overflow-hidden rounded-full bg-[#eef1f6]">
|
||||
<s className="block h-full bg-[linear-gradient(90deg,#ffc86e,#ff6f8e)]" style={{ width: `${meter}%` }} />
|
||||
</span>
|
||||
)}
|
||||
<small className="block truncate text-[12.5px] font-semibold text-(--ink2)">{sub || '\u00a0'}</small>
|
||||
</span>
|
||||
<em className="font-jua text-base not-italic">{right}</em>
|
||||
</li>
|
||||
@@ -92,57 +196,54 @@ export function SkyPage() {
|
||||
const { region } = useRegion()
|
||||
const sky = useQuery(getSkyOptions({ query: { region: region.code } }))
|
||||
const ranking = useQuery(getSkyRankingOptions())
|
||||
const s = sky.data?.sunset
|
||||
const times = s?.best_times ?? []
|
||||
const peak = times.find((t) => t.kind === 'peak')
|
||||
const spots = sky.data?.spots ?? []
|
||||
const load = loadOf(sky)
|
||||
const rankLoad = loadOf(ranking)
|
||||
const plan = sky.data?.plan ?? undefined
|
||||
const spots = (sky.data?.spots ?? []).slice(0, 3)
|
||||
const days = sky.data?.days ?? []
|
||||
const items = (ranking.data?.items ?? []).slice(0, 8)
|
||||
const target = Math.max(0, days.findIndex((d) => d.day === plan?.day))
|
||||
const best = days.reduce<number>((b, d, i) => (d.score > days[b].score ? i : b), target)
|
||||
// 서버 outlook 과 같은 기준: 10점 넘게 나을 때만 더 나은 날로 표시
|
||||
const better = days.length > 0 && days[best].score - days[target].score > 10 ? best : -1
|
||||
|
||||
return (
|
||||
<section aria-label="노을">
|
||||
{s ? (
|
||||
<div className="relative mx-3 mt-1 min-h-[300px] overflow-hidden rounded-[32px] bg-[linear-gradient(180deg,#7e6fe6,#f08aa2_58%,#ffc28a)] px-5 pt-5 pb-16 text-white">
|
||||
<div className="b-skyline pointer-events-none absolute inset-0 [--sky-h:22%]" aria-hidden="true" />
|
||||
<p className="relative m-0 text-[13px] font-extrabold opacity-90">오늘 노을 · {region.name}</p>
|
||||
<b className="relative mt-1.5 block font-bagel text-[96px] leading-[0.9] font-normal">{s.score}</b>
|
||||
<p className="relative m-0 font-jua text-[29px] leading-tight">
|
||||
{s.grade_label}
|
||||
{peak && ` · ${timeWords(peak.at)}이 절정`}
|
||||
</p>
|
||||
{times.length > 0 && (
|
||||
<div className="relative z-[1] mt-[18px]">
|
||||
<div className="h-2.5 rounded-full bg-[linear-gradient(90deg,#ffd27a,#ff7a6e_50%,#6a5bd6)]" />
|
||||
<div className="mt-1.5 flex justify-between text-[12.5px] font-extrabold">
|
||||
{times.map((t, i) => (
|
||||
<span key={t.kind} className={cx(i === 1 && 'text-center', i === times.length - 1 && i > 0 && 'text-right')}>
|
||||
<b className="block font-bagel text-lg font-normal">{clockShort(t.at)}</b>
|
||||
{t.label}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<section aria-label="노을" aria-busy={load === 'loading'} className={cx('transition-opacity', sky.isPlaceholderData && 'opacity-60')}>
|
||||
{/* 히어로 상자는 불러오는 중·실패·빈 값 모두 같은 크기 */}
|
||||
<div className={HERO}>
|
||||
<div className="b-skyline pointer-events-none absolute inset-0 [--sky-h:16%]" aria-hidden="true" />
|
||||
<p className="relative m-0 text-[13px] font-extrabold">
|
||||
{plan?.when ?? '오늘'} 노을 · {region.name}
|
||||
</p>
|
||||
{plan || load === 'loading' ? (
|
||||
<HeroBody plan={plan} />
|
||||
) : (
|
||||
<StateBox load={load} onRetry={() => sky.refetch()} empty="오늘 노을 정보가 없어요." hold={<HeroBody />} className="inset-x-0 top-1.5 bottom-0" />
|
||||
)}
|
||||
</div>
|
||||
<Sec title="언제 보면 좋을까" sub={plan ? `${plan.when} 해 지는 시간 기준` : '\u00a0'} />
|
||||
{plan?.timeline?.length || load === 'loading' ? (
|
||||
<Timeline rows={plan?.timeline} />
|
||||
) : (
|
||||
<StateBox loading={sky.isPending} error={sky.error} onRetry={() => sky.refetch()} empty="오늘 노을 정보가 없어요." />
|
||||
<StateBox load="ready" empty={load === 'ready' ? '노을 시간 정보가 없어요.' : '노을 시간을 불러오지 못했어요.'} hold={<Timeline />} className="inset-x-3 top-3 bottom-0" />
|
||||
)}
|
||||
{times.length > 0 && (
|
||||
<>
|
||||
<Sec title="오늘의 노을 3컷" sub="옆으로 넘겨 보세요" />
|
||||
<Rail label="오늘의 노을 3컷">
|
||||
{times.map((t, i) => (
|
||||
<div key={t.kind} className={cx('b-skyline relative h-[150px] w-[230px] overflow-hidden rounded-[22px] px-3.5 py-2.5 font-bagel text-2xl text-white [--sky-h:30%]', `b-cut-${Math.min(i + 1, 3)}`)}>
|
||||
<span className="relative z-[1]">
|
||||
{clockShort(t.at)}
|
||||
<small className="block font-jua text-sm">{t.label}</small>
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</Rail>
|
||||
</>
|
||||
<Sec title="내일·모레가 더 나을까" sub={plan?.outlook || '\u00a0'} />
|
||||
{days.length > 0 ? (
|
||||
<div className="grid grid-cols-3 gap-2 p-3">
|
||||
{days.map((d, i) => (
|
||||
<div key={d.day} className={cx('rounded-[20px] bg-white p-3 text-center shadow-[inset_0_-5px_0_var(--shade)]', i === better && 'ring-2 ring-[#d6457a] ring-inset')}>
|
||||
<small className="block text-[12.5px] font-extrabold text-(--ink2)">{dayLabel(d.day, i)}</small>
|
||||
<b className={cx('block font-bagel text-[30px] font-normal', d.score < 60 ? 'text-(--ink2)' : 'text-[#d6457a]')}>{d.score}</b>
|
||||
<span className="block text-xs font-bold text-(--ink2)">{d.grade_label}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
) : load === 'loading' ? (
|
||||
<DaysSkel />
|
||||
) : (
|
||||
<StateBox load="ready" empty={load === 'ready' ? '앞으로 3일 노을 정보가 없어요.' : '앞으로 3일 노을을 불러오지 못했어요.'} hold={<DaysSkel />} className="inset-3" />
|
||||
)}
|
||||
<Sec title="가까운 노을 명소" sub={sky.data?.sunset_azimuth != null ? `해 지는 쪽 ${sky.data.sunset_azimuth}° · 서쪽이 트인 곳` : '서쪽이 트인 곳'} />
|
||||
<Sec title="가까운 노을 명소" sub={sky.data?.sunset_azimuth != null ? `해 지는 ${compass(sky.data.sunset_azimuth)}쪽이 트인 곳, 가까운 순` : '서쪽이 트인 곳, 가까운 순'} />
|
||||
{spots.length ? (
|
||||
<>
|
||||
<SpotMap region={region} spots={spots} azimuth={sky.data?.sunset_azimuth} />
|
||||
@@ -150,34 +251,29 @@ export function SkyPage() {
|
||||
{spots.map((p) => (
|
||||
<Li key={p.no} no={p.no} title={p.name} sub={p.description} right={`${p.distance_km}km`} />
|
||||
))}
|
||||
{/* 3곳이 안 되면 빈 줄로 스켈레톤 높이를 지켜 아래 순위가 밀리지 않게 */}
|
||||
{THREE.slice(spots.length).map((i) => (
|
||||
<LiSkel key={`ghost-${i}`} ghost />
|
||||
))}
|
||||
</ul>
|
||||
</>
|
||||
) : load === 'loading' ? (
|
||||
<SpotsSkel />
|
||||
) : (
|
||||
<StateBox loading={sky.isPending} error={sky.error} empty="이 지역은 아직 등록된 노을 명소가 없어요." />
|
||||
// 실패 안내·다시 시도는 위 히어로에 한 번만. 여기는 지도·목록 자리만 지킨다
|
||||
<StateBox load="ready" empty={load === 'ready' ? '근처에 등록된 노을 명소가 없어요.' : '명소 정보를 불러오지 못했어요.'} hold={<SpotsSkel />} className="inset-x-3 top-3 bottom-0" />
|
||||
)}
|
||||
<Sec title="전국 노을 순위" sub={items[0] ? `오늘 기준 · 1위 ${items[0].name} ${items[0].score}점` : '오늘 기준'} />
|
||||
<Sec title="전국 노을 순위" sub="오늘 기준" />
|
||||
{items.length ? (
|
||||
<ul className="mx-3 mt-1.5 flex flex-col">
|
||||
{items.map((r) => (
|
||||
<Li key={r.region_code} no={r.rank} title={r.name} sub={r.note} right={String(r.score)} meter={r.score} mine={r.region_code === region.code} />
|
||||
<Li key={r.region_code} no={r.rank} title={r.name} sub={r.note} right={`${r.score}점`} mine={r.region_code === region.code} />
|
||||
))}
|
||||
</ul>
|
||||
) : rankLoad === 'loading' ? (
|
||||
<RankSkel />
|
||||
) : (
|
||||
<StateBox loading={ranking.isPending} error={ranking.error} onRetry={() => ranking.refetch()} empty="순위가 아직 없어요." />
|
||||
)}
|
||||
{days.length > 0 && (
|
||||
<>
|
||||
<Sec title="앞으로 3일" />
|
||||
<div className="grid grid-cols-3 gap-2 p-3">
|
||||
{days.map((d, i) => (
|
||||
<div key={d.day} className="rounded-[20px] bg-white p-3 text-center shadow-[inset_0_-5px_0_var(--shade)]">
|
||||
<small className="text-[12.5px] font-extrabold text-(--ink2)">{dayLabel(d.day, i)}</small>
|
||||
<b className={cx('block font-bagel text-[30px] font-normal', d.score < 50 ? 'text-(--ink3)' : 'text-[#d6457a]')}>{d.score}</b>
|
||||
<span className="text-xs font-bold text-(--ink2)">{d.grade_label}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</>
|
||||
<StateBox load={rankLoad} onRetry={() => ranking.refetch()} empty="순위가 아직 없어요." hold={<RankSkel />} className="inset-x-3 top-1.5 bottom-0" />
|
||||
)}
|
||||
</section>
|
||||
)
|
||||
|
||||
@@ -4,12 +4,12 @@ import { useQuery } from '@tanstack/react-query'
|
||||
import { getFeedOptions, getWeatherTodayOptions } from '../api/client/@tanstack/react-query.gen'
|
||||
import type { BandArticle, BandEvent, Hero as HeroData, ResWeatherToday, TopIndex } from '../api/client/types.gen'
|
||||
import { cx } from '../lib/utils'
|
||||
import { cardBg, fall, kindOfHour, kst, MEDALS, sidoOf, WEEKDAYS, type TimeKind } from './lib'
|
||||
import { PostCard } from './Post'
|
||||
import { cardBg, fall, kindOfHour, kst, type Load, loadOf, MEDALS, type TimeKind, WEEKDAYS } from './lib'
|
||||
import { PostCard, PostCardSkel } from './Post'
|
||||
import { useRegion } from './regionContext'
|
||||
import { useSheet } from './sheetContext'
|
||||
import { useSky } from './skyContext'
|
||||
import { Ic, Rail, Sec, StateBox } from './ui'
|
||||
import { Ic, Rail, Sec, Skel, SkelRail, StateBox, Thumb } from './ui'
|
||||
import { deg, skyText, slotAt } from './weatherText'
|
||||
|
||||
type Mode = 'now' | TimeKind
|
||||
@@ -31,6 +31,12 @@ const PREVIEW: Record<TimeKind, { label: string; clock: string; hour: number }>
|
||||
}
|
||||
|
||||
const STARS = Array.from({ length: 26 }, (_, i) => ({ left: `${(i * 37) % 100}%`, top: `${(i * 53) % 60}%`, opacity: 0.4 + ((i * 7) % 6) / 10 }))
|
||||
// 별똥별 셋: 위치·길이·주기를 엇갈려 하나씩 떨어지게
|
||||
const SHOOTS = [
|
||||
{ top: '6%', left: '80%', '--len': '90px', '--dur': '7s', '--dl': '1.5s' },
|
||||
{ top: '20%', left: '52%', '--len': '70px', '--dur': '9s', '--dl': '4s' },
|
||||
{ top: '34%', left: '94%', '--len': '80px', '--dur': '11s', '--dl': '6.5s' },
|
||||
]
|
||||
const ORB_POS = { left: '66%', top: '6px', d: '.5s', f: '4.4s' }
|
||||
|
||||
function useNow(ms = 20000) {
|
||||
@@ -42,9 +48,29 @@ function useNow(ms = 20000) {
|
||||
return now
|
||||
}
|
||||
|
||||
type HeroProps = { hero?: HeroData | null; today?: ResWeatherToday }
|
||||
// 값이 오기 전엔 그 글자 자리(같은 줄 높이)에 스켈레톤, 못 불러왔거나 값이 없으면 같은 글꼴의 '?'
|
||||
function heroVal(load: Load, v: ReactNode, skel: string) {
|
||||
if (v != null) return v
|
||||
if (load === 'loading')
|
||||
return (
|
||||
<>
|
||||
<Skel className={skel} />
|
||||
<span className="sr-only">불러오는 중</span>
|
||||
</>
|
||||
)
|
||||
return (
|
||||
<>
|
||||
<span className="opacity-50" aria-hidden="true">?</span>
|
||||
<span className="sr-only">{load === 'ready' ? '정보 없음' : '못 불러왔어요'}</span>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
function Hero({ hero, today }: HeroProps) {
|
||||
const failed = (load: Load) => load === 'error' || load === 'retrying'
|
||||
|
||||
type HeroProps = { hero?: HeroData | null; today?: ResWeatherToday; feedLoad: Load; todayLoad: Load }
|
||||
|
||||
function Hero({ hero, today, feedLoad, todayLoad }: HeroProps) {
|
||||
const { open } = useSheet()
|
||||
const [mode, setMode] = useState<Mode>('now')
|
||||
const clock = useNow()
|
||||
@@ -62,12 +88,19 @@ function Hero({ hero, today }: HeroProps) {
|
||||
const feels = mode === 'now' && hero ? hero.feels_c : slot?.feels_c
|
||||
const top1 = hero?.top1
|
||||
const who = kind === 'night' ? 'bear' : 'rabbit'
|
||||
const tempLoad = mode === 'now' ? feedLoad : todayLoad
|
||||
const feelsLine = temp != null ? `체감 ${deg(feels)}${slot ? ` · ${skyText(slot)}` : ''}` : failed(tempLoad) ? '날씨를 못 불러왔어요' : tempLoad === 'ready' ? '체감 ?°' : null
|
||||
const bubble = hero ? (hero.bubble ?? '오늘은 쉬어 가요') : failed(feedLoad) ? '앗, 날씨를 못 불러왔어요' : null
|
||||
|
||||
// 아래 값은 모두 로딩·완료·실패 사이 높이가 같다: 글자 자리 스켈레톤, 비 칸은 두 줄 높이로 고정
|
||||
return (
|
||||
<div className="b-hero relative mx-3 mt-1 overflow-hidden rounded-[32px] px-[18px] pt-4 pb-[18px]" data-t={kind}>
|
||||
<div className="b-stars pointer-events-none absolute inset-0" aria-hidden="true">
|
||||
{STARS.map((s, i) => (
|
||||
<i key={i} className="absolute size-[3px] rounded-full bg-white shadow-[0_0_6px_#fff]" style={s} />
|
||||
<i key={i} className="absolute size-[3px] rounded-full shadow-[0_0_6px_#fff]" style={s} />
|
||||
))}
|
||||
{SHOOTS.map((s, i) => (
|
||||
<span key={i} className="b-shoot" style={s} />
|
||||
))}
|
||||
</div>
|
||||
<div className="relative z-[3] flex flex-wrap gap-1.5" role="group" aria-label="시간대 배경 미리보기">
|
||||
@@ -85,36 +118,28 @@ function Hero({ hero, today }: HeroProps) {
|
||||
<div className="font-bagel text-[60px] leading-none">{mode === 'now' ? `${String(t.h).padStart(2, '0')}:${String(t.mi).padStart(2, '0')}` : PREVIEW[mode].clock}</div>
|
||||
</div>
|
||||
<div className="text-right">
|
||||
<b className="font-bagel text-[42px] leading-none font-normal">{temp != null ? deg(temp) : '--°'}</b>
|
||||
<span className="block text-[12.5px] font-bold opacity-85">{temp != null ? `체감 ${deg(feels)}${slot ? ` · ${skyText(slot)}` : ''}` : '날씨를 불러오는 중'}</span>
|
||||
<b className="block font-bagel text-[42px] leading-none font-normal">{heroVal(tempLoad, temp != null ? deg(temp) : null, 'w-[72px]')}</b>
|
||||
<span className="block text-[12.5px] font-bold opacity-85">{feelsLine ?? <Skel className="w-[118px]" />}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div className="relative z-[3] mt-3 grid grid-cols-2 gap-2.5">
|
||||
<div className="b-stat flex items-center gap-2.5 rounded-[20px] px-3 py-[9px]">
|
||||
<Ic name="thermo" className="w-9" />
|
||||
<div>
|
||||
<small className="block text-xs font-bold opacity-80">불쾌지수</small>
|
||||
<b className="font-jua text-lg font-normal">{hero?.discomfort != null ? `${hero.discomfort} · ${hero.discomfort_label ?? ''}` : '-'}</b>
|
||||
</div>
|
||||
</div>
|
||||
<div className="b-stat flex items-center gap-2.5 rounded-[20px] px-3 py-[9px]">
|
||||
<Ic name="umbrella" className="w-9" />
|
||||
<div>
|
||||
<small className="block text-xs font-bold opacity-80">지금 비</small>
|
||||
<b className="font-jua text-lg font-normal">{hero?.will_rain_2h == null ? '-' : hero.will_rain_2h ? '2시간 안에 비' : '2시간 없음'}</b>
|
||||
</div>
|
||||
</div>
|
||||
<HeroStat icon="thermo" label="불쾌지수">
|
||||
{heroVal(feedLoad, hero?.discomfort != null ? `${hero.discomfort} · ${hero.discomfort_label ?? ''}` : null, 'w-16')}
|
||||
</HeroStat>
|
||||
<HeroStat icon="umbrella" label="지금 비">
|
||||
{heroVal(feedLoad, hero?.will_rain_2h == null ? null : hero.will_rain_2h ? '2시간 안에 와요' : '2시간 동안 안 와요', 'w-16')}
|
||||
</HeroStat>
|
||||
</div>
|
||||
<div className="relative mt-5 h-[286px]">
|
||||
<span className="b-cloud b-fall top-6 left-[6%] h-[30px] w-[84px]" style={fall('.1s', '6s')} aria-hidden="true" />
|
||||
<div className="b-sun b-fall absolute top-10 left-1/2 -ml-[82px] grid aspect-square w-[164px] place-items-center rounded-full text-center" style={fall('0s', '5.6s', '8px')}>
|
||||
<span>
|
||||
<b className="block font-bagel text-[56px] leading-[0.9] font-normal">{hero?.weather_score ?? '-'}</b>
|
||||
<small className="mt-0.5 block font-jua text-[14.5px]">오늘 날씨 점수</small>
|
||||
<b className="block font-bagel text-[56px] leading-[0.9] font-normal">{heroVal(feedLoad, hero?.weather_score, 'w-[84px]')}</b>
|
||||
<small className="mt-0.5 block font-jua text-[14.5px]">{failed(feedLoad) ? '점수를 못 불러왔어요' : '오늘 날씨 점수'}</small>
|
||||
</span>
|
||||
</div>
|
||||
<span className="b-cloud b-fall top-[188px] left-[54%] h-10 w-[118px]" style={fall('.25s', '6.4s')} aria-hidden="true" />
|
||||
{top1 && (
|
||||
{top1 ? (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => open({ type: 'gak', indexId: top1.index_id })}
|
||||
@@ -130,14 +155,33 @@ function Hero({ hero, today }: HeroProps) {
|
||||
1위 {top1.name} <em className="font-bagel text-(--orange) not-italic">{top1.score}</em>
|
||||
</span>
|
||||
</button>
|
||||
) : (
|
||||
feedLoad === 'loading' && (
|
||||
<span className="absolute z-[2] flex w-24 flex-col items-center gap-1" style={{ left: ORB_POS.left, top: ORB_POS.top }} aria-hidden="true">
|
||||
<Skel shape className="size-[78px] rounded-full" />
|
||||
<span className="font-jua text-sm">
|
||||
<Skel className="w-[72px]" />
|
||||
</span>
|
||||
</span>
|
||||
)
|
||||
)}
|
||||
</div>
|
||||
{hero?.bubble && (
|
||||
<div className="relative z-[3] flex items-end gap-2">
|
||||
<Ic name={who} alt={who === 'rabbit' ? '토끼' : '곰'} className="w-[50px] drop-shadow-[0_8px_10px_rgb(40_48_74/0.15)]" />
|
||||
<span className="mb-3 rounded-[20px_20px_20px_6px] bg-white px-3.5 py-[9px] font-jua text-base text-(--ink) shadow-[0_8px_16px_rgb(40_48_74/0.1)]">{hero.bubble}</span>
|
||||
</div>
|
||||
)}
|
||||
<div className="relative z-[3] flex items-end gap-2">
|
||||
<Ic name={who} alt={who === 'rabbit' ? '토끼' : '곰'} className="w-[50px] drop-shadow-[0_8px_10px_rgb(40_48_74/0.15)]" />
|
||||
<span className="mb-3 rounded-[20px_20px_20px_6px] bg-white px-3.5 py-[9px] font-jua text-base text-(--ink) shadow-[0_8px_16px_rgb(40_48_74/0.1)]">{bubble ?? <Skel className="w-[120px]" />}</span>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function HeroStat({ icon, label, children }: { icon: string; label: string; children: ReactNode }) {
|
||||
return (
|
||||
<div className="b-stat flex min-h-[90px] items-center gap-2.5 rounded-[20px] px-3 py-[9px]">
|
||||
<Ic name={icon} className="w-9 shrink-0" />
|
||||
<div className="min-w-0">
|
||||
<small className="block text-xs font-bold opacity-80">{label}</small>
|
||||
<b className="block font-jua text-lg font-normal">{children}</b>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -162,6 +206,36 @@ function Stories({ items }: { items: TopIndex[] }) {
|
||||
)
|
||||
}
|
||||
|
||||
function PostsSkel() {
|
||||
return (
|
||||
<>
|
||||
<PostCardSkel />
|
||||
<PostCardSkel />
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
const STORY_SKELS = Array.from({ length: 6 }, (_, i) => i)
|
||||
|
||||
/** Stories 와 같은 칸(68px 동그라미 + 이름 + 점수)을 6개 */
|
||||
function StoriesSkel() {
|
||||
return (
|
||||
<SkelRail>
|
||||
{STORY_SKELS.map((i) => (
|
||||
<span key={i} className="flex w-[72px] flex-col items-center gap-1">
|
||||
<Skel shape className="size-[68px] rounded-full" />
|
||||
<b className="font-jua text-[13px] font-normal">
|
||||
<Skel className="w-12" />
|
||||
</b>
|
||||
<em className="font-bagel text-[12.5px] leading-none not-italic">
|
||||
<Skel className="w-6" />
|
||||
</em>
|
||||
</span>
|
||||
))}
|
||||
</SkelRail>
|
||||
)
|
||||
}
|
||||
|
||||
function Band({ tone, title, sub, to, children }: { tone: 1 | 2 | 3; title: string; sub: string; to: string; children: ReactNode }) {
|
||||
return (
|
||||
<section className={cx('mt-3.5 pt-4 pb-3.5', `b-band-${tone}`)} aria-label={title}>
|
||||
@@ -172,16 +246,14 @@ function Band({ tone, title, sub, to, children }: { tone: 1 | 2 | 3; title: stri
|
||||
}
|
||||
|
||||
function EventsBand({ events }: { events: BandEvent[] }) {
|
||||
const { region } = useRegion()
|
||||
return (
|
||||
<Band tone={1} title={`이번 주 ${sidoOf(region.name)} 행사`} sub="날씨까지 같이 보고 골라요" to="/week">
|
||||
<Band tone={1} title="이번 주 가까운 행사" sub="30km 안 · 날씨까지 같이 보고 골라요" to="/week">
|
||||
<Rail>
|
||||
{events.map((e, i) => (
|
||||
<Link key={e.event_id} to="/week" className="w-[200px] overflow-hidden rounded-[22px] bg-white shadow-[inset_0_-5px_0_var(--shade),0_8px_16px_rgb(40_48_74/0.06)]">
|
||||
<span className={cx('relative grid h-[116px] place-items-center', `b-bg-${cardBg(e.icon, i)}`)}>
|
||||
<Thumb image={e.image} icon={e.icon} credit={e.image_credit} className={cx('h-[116px]', `b-bg-${cardBg(e.icon, i)}`)} iconClassName="w-[76px]">
|
||||
<span className={cx('absolute top-2.5 left-2.5 rounded-full px-2 py-[3px] text-[11.5px] font-extrabold text-white', e.status_label === '진행 중' ? 'bg-[#1f9d62]' : 'bg-(--orange)')}>{e.status_label}</span>
|
||||
<Ic name={e.icon} className="w-[76px]" />
|
||||
</span>
|
||||
</Thumb>
|
||||
<span className="block px-3 pt-2.5 pb-3">
|
||||
<b className="block font-jua text-[16.5px] leading-snug font-normal">{e.name}</b>
|
||||
</span>
|
||||
@@ -241,6 +313,7 @@ export function TodayPage() {
|
||||
const stories = f?.stories ?? []
|
||||
const bands = f?.bands
|
||||
const nowAt = f?.hero?.now_at
|
||||
const load = loadOf(feed)
|
||||
|
||||
// 디자인대로 3·6·9번째 글 뒤에 띠를 넣고, 글이 모자라면 남은 띠는 맨 뒤에 붙인다
|
||||
const bandAt: [number, ReactNode][] = [
|
||||
@@ -250,12 +323,17 @@ export function TodayPage() {
|
||||
]
|
||||
|
||||
return (
|
||||
<section aria-label="오늘">
|
||||
<Hero hero={f?.hero} today={today.data} />
|
||||
<section aria-label="오늘" aria-busy={load === 'loading'} className={cx('transition-opacity', feed.isPlaceholderData && 'opacity-60')}>
|
||||
<Hero hero={f?.hero} today={today.data} feedLoad={load} todayLoad={loadOf(today)} />
|
||||
<Sec title="오늘의 각" sub="누르면 계산 근거를 보여 줘요" more={{ to: '/gak' }} />
|
||||
{stories.length ? <Stories items={stories} /> : <StateBox loading={feed.isPending} error={feed.error} onRetry={() => feed.refetch()} empty="오늘 계산된 각이 없어요." />}
|
||||
<StateBox loading={feed.isPending} error={feed.error} onRetry={() => feed.refetch()} empty={feed.isSuccess && !posts.length ? '오늘 올라온 글이 아직 없어요.' : undefined} />
|
||||
{/* 실패 안내는 여기 한 번만, 각 줄 스켈레톤과 같은 크기로 */}
|
||||
{stories.length ? <Stories items={stories} /> : load === 'loading' ? <StoriesSkel /> : <StateBox load={load} onRetry={() => feed.refetch()} empty="오늘 계산된 각이 없어요." hold={<StoriesSkel />} className="inset-x-3 top-3 bottom-1" />}
|
||||
<div>
|
||||
{load === 'loading' && <PostsSkel />}
|
||||
{/* 글이 없거나 못 받아도 스켈레톤 두 장 자리는 그대로 둔다 */}
|
||||
{load !== 'loading' && !posts.length && (
|
||||
<StateBox load="ready" empty={load === 'ready' ? '오늘 올라온 글이 아직 없어요.' : '글을 불러오지 못했어요.'} hold={<PostsSkel />} className="inset-x-3 top-3.5 bottom-auto" />
|
||||
)}
|
||||
{posts.map((p, i) => (
|
||||
<Fragment key={p.post_id}>
|
||||
<PostCard post={p} />
|
||||
|
||||
@@ -1,11 +1,138 @@
|
||||
import { useState } from 'react'
|
||||
import { useState, type ReactNode } from 'react'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { getWeekOptions, listEventsOptions, listPlacesOptions } from '../api/client/@tanstack/react-query.gen'
|
||||
import { getWeekOptions, getWeekRankingOptions, listEventsOptions, listPlacesOptions } from '../api/client/@tanstack/react-query.gen'
|
||||
import { cx } from '../lib/utils'
|
||||
import { cardBg, dateRange, sidoOf } from './lib'
|
||||
import { cardBg, dateRange, loadOf, shortDay, sidoOf } from './lib'
|
||||
import { useRegion } from './regionContext'
|
||||
import { useSheet } from './sheetContext'
|
||||
import { Ic, Rail, Sec, StateBox } from './ui'
|
||||
import { Arrows, Chips, Ic, Rail, Sec, Skel, SkelRail, StateBox, Thumb } from './ui'
|
||||
import { useCarousel } from './carousel'
|
||||
|
||||
const TEN = Array.from({ length: 10 }, (_, i) => i)
|
||||
const THREE = [0, 1, 2]
|
||||
const DAY_BTN = 'flex w-[calc((100%-24px)/7)] shrink-0 snap-start flex-col items-center gap-0.5 rounded-[18px] pt-[9px] pb-2 text-xs font-extrabold'
|
||||
const PLACE_CARD = 'w-[178px] overflow-hidden rounded-[22px] bg-white text-left shadow-[inset_0_-5px_0_var(--shade),0_8px_16px_rgb(40_48_74/0.06)]'
|
||||
const EVENT_CARD = 'mx-3 mt-2.5 grid grid-cols-[84px_1fr] items-center gap-3 rounded-[22px] bg-white p-3 shadow-[inset_0_-5px_0_var(--shade)]'
|
||||
|
||||
function DaysSkel() {
|
||||
return (
|
||||
<div className="flex gap-1 overflow-hidden px-3 pt-3" aria-hidden="true">
|
||||
{TEN.map((i) => (
|
||||
<span key={i} className={cx(DAY_BTN, 'bg-white shadow-[inset_0_-4px_0_var(--shade)]')}>
|
||||
<span>
|
||||
<Skel className="w-3" />
|
||||
</span>
|
||||
<Skel shape className="size-7 rounded-full" />
|
||||
<b className="font-jua text-sm font-normal">
|
||||
<Skel className="w-6" />
|
||||
</b>
|
||||
<span className="px-0.5 text-[9.5px]">
|
||||
<Skel className="w-5" />
|
||||
</span>
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function PickSkel() {
|
||||
return (
|
||||
<div className="mx-3 mt-3 flex items-center gap-3.5 rounded-3xl bg-white p-4 shadow-[inset_0_-5px_0_var(--shade)]" aria-hidden="true">
|
||||
<Skel shape className="size-16 shrink-0 rounded-full" />
|
||||
<div className="flex-1">
|
||||
<b className="block font-jua text-[19px] font-normal">
|
||||
<Skel className="w-32" />
|
||||
</b>
|
||||
<p className="mt-0.5 text-[13.5px] font-semibold">
|
||||
<Skel className="w-4/5" />
|
||||
</p>
|
||||
<p className="mt-2 font-jua text-base">
|
||||
<Skel className="w-36" />
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function PlacesSkel() {
|
||||
return (
|
||||
<SkelRail>
|
||||
{THREE.map((i) => (
|
||||
<span key={i} className={PLACE_CARD}>
|
||||
<Skel shape className="h-[104px]" />
|
||||
<span className="block px-3 pt-2.5 pb-3">
|
||||
<span className="text-[11.5px] font-extrabold">
|
||||
<Skel className="w-16" />
|
||||
</span>
|
||||
<b className="block font-jua text-[16.5px] font-normal">
|
||||
<Skel className="w-24" />
|
||||
</b>
|
||||
<small className="block text-[12.5px] leading-snug font-semibold">
|
||||
<Skel className="w-full" />
|
||||
<br />
|
||||
<Skel className="w-20" />
|
||||
</small>
|
||||
</span>
|
||||
</span>
|
||||
))}
|
||||
</SkelRail>
|
||||
)
|
||||
}
|
||||
|
||||
function EventSkel() {
|
||||
return (
|
||||
<div className={EVENT_CARD} aria-hidden="true">
|
||||
<Skel shape className="h-[84px] rounded-2xl" />
|
||||
<span className="min-w-0">
|
||||
<b className="block h-[2lh] font-jua text-[17px] leading-snug font-normal">
|
||||
<Skel className="w-40" />
|
||||
<br />
|
||||
<Skel className="w-20" />
|
||||
</b>
|
||||
<small className="block text-[12.5px] font-semibold">
|
||||
<Skel className="w-44" />
|
||||
</small>
|
||||
<span className="mt-[5px] block h-[1lh] text-xs font-extrabold">
|
||||
<Skel className="w-24" />
|
||||
</span>
|
||||
</span>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const RANK_ROW = 'grid grid-cols-[34px_1fr_auto] items-center gap-2.5 border-b-[1.5px] border-(--line) px-1 py-3 last:border-b-0'
|
||||
// 불러오는 동안에도 탭 줄 높이를 지키려고 같은 칩을 미리 그린다
|
||||
const RANK_TABS_HOLD = [
|
||||
['토', '토요일'],
|
||||
['일', '일요일'],
|
||||
] as const
|
||||
|
||||
function RankSkel() {
|
||||
return (
|
||||
<ul className="mx-3 mt-1.5 flex flex-col" aria-hidden="true">
|
||||
{TEN.map((i) => (
|
||||
<li key={i} className={RANK_ROW}>
|
||||
<span className="text-center font-bagel text-xl">
|
||||
<Skel className="w-5" />
|
||||
</span>
|
||||
<span className="min-w-0">
|
||||
<b className="block font-jua text-[17px] font-normal">
|
||||
<Skel className="w-24" />
|
||||
</b>
|
||||
<small className="block text-[12.5px] font-semibold">
|
||||
<Skel className="w-40" />
|
||||
</small>
|
||||
<Skel shape className="mt-[5px] h-1.5 rounded-full" />
|
||||
</span>
|
||||
<em className="flex items-center gap-1 font-jua text-base not-italic">
|
||||
<Skel shape className="size-6 rounded-full" />
|
||||
<Skel className="w-9" />
|
||||
</em>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)
|
||||
}
|
||||
|
||||
const PLACE_BG: Record<string, string> = { picnic: 'mint', walk: 'mint', sunset: 'dusk', chimaek: 'peach', photo: 'butter', bulb: 'lilac' }
|
||||
|
||||
@@ -22,11 +149,21 @@ export function WeekPage() {
|
||||
const sel = days.find((d) => d.day === picked) ?? days.find((d) => d.weekday === '토') ?? days[0]
|
||||
const places = useQuery({ ...listPlacesOptions({ query: { region: region.code, day: sel?.day, area: area === '전체' ? undefined : area } }), enabled: !!sel })
|
||||
const events = useQuery(listEventsOptions({ query: { region: region.code } }))
|
||||
const ranking = useQuery(getWeekRankingOptions())
|
||||
const rankDays = ranking.data?.days ?? []
|
||||
const [rankPick, setRankPick] = useState<string | null>(null)
|
||||
const rankDay = rankDays.find((d) => d.day === rankPick) ?? rankDays[0]
|
||||
const rankItems = (rankDay?.items ?? []).slice(0, 10)
|
||||
const rankLoad = loadOf(ranking)
|
||||
const sido = sidoOf(region.name)
|
||||
const areas = places.data?.areas ?? []
|
||||
const rainy = places.data?.rainy ?? sel?.is_rainy
|
||||
const placeList = places.data?.places ?? []
|
||||
const eventList = events.data?.events ?? []
|
||||
const weekLoad = loadOf(week)
|
||||
const eventLoad = loadOf(events)
|
||||
// 날씨(고른 날)가 와야 명소를 부를 수 있다
|
||||
const placeLoad = sel ? loadOf(places) : weekLoad === 'loading' ? 'loading' : 'ready'
|
||||
|
||||
const sendPlan = () => {
|
||||
if (!sel) return
|
||||
@@ -34,10 +171,10 @@ export function WeekPage() {
|
||||
}
|
||||
|
||||
return (
|
||||
<section aria-label="주말·행사">
|
||||
<section aria-label="주말·행사" aria-busy={weekLoad === 'loading'}>
|
||||
<Sec title="열흘 날씨" sub="날짜를 누르면 그날 추천이 바뀌어요" />
|
||||
{days.length ? (
|
||||
<div className="flex snap-x gap-1 overflow-x-auto px-3 pt-3 [scrollbar-width:none]" role="group" aria-label="날짜 고르기">
|
||||
<DayStrip dim={week.isPlaceholderData}>
|
||||
{days.map((d) => {
|
||||
const on = d.day === sel?.day
|
||||
const weekend = d.weekday === '토' || d.weekday === '일' || !!d.holiday
|
||||
@@ -47,18 +184,34 @@ export function WeekPage() {
|
||||
type="button"
|
||||
aria-pressed={on}
|
||||
onClick={() => setPicked(d.day)}
|
||||
className={cx('flex w-[calc((100%-24px)/7)] shrink-0 cursor-pointer snap-start flex-col items-center gap-0.5 rounded-[18px] pt-[9px] pb-2 text-xs font-extrabold', on ? 'bg-(--ink) text-white' : cx('bg-white shadow-[inset_0_-4px_0_var(--shade)]', weekend ? 'text-[#d6457a]' : 'text-(--ink2)'))}
|
||||
className={cx(DAY_BTN, 'cursor-pointer', on ? 'bg-(--ink) text-white' : cx('bg-white shadow-[inset_0_-4px_0_var(--shade)]', weekend ? 'text-[#d6457a]' : 'text-(--ink2)'))}
|
||||
>
|
||||
<span>{d.weekday}</span>
|
||||
<Ic name={d.icon} className="w-7" />
|
||||
<b className={cx('font-jua text-sm font-normal', on ? 'text-white' : 'text-(--ink)')}>{d.temp_max_c != null ? `${Math.round(d.temp_max_c)}°` : '-'}</b>
|
||||
<b className={cx('font-jua text-sm font-normal', on ? 'text-white' : 'text-(--ink)')}>{d.temp_max_c != null ? `${Math.round(d.temp_max_c)}°` : <span className="opacity-50" aria-label="기온 정보 없음">?</span>}</b>
|
||||
<span className={cx('max-w-full truncate px-0.5 text-[9.5px]', on ? 'text-[#ffb3c4]' : 'text-[#d6457a]')}>{d.holiday ? d.holiday.replace(/\(.*\)/, '') : `${Number(d.day.slice(8))}일`}</span>
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</DayStrip>
|
||||
) : weekLoad === 'loading' ? (
|
||||
<>
|
||||
<DaysSkel />
|
||||
<PickSkel />
|
||||
</>
|
||||
) : (
|
||||
<StateBox loading={week.isPending} error={week.error} onRetry={() => week.refetch()} empty="날씨가 아직 없어요." />
|
||||
<StateBox
|
||||
load={weekLoad}
|
||||
onRetry={() => week.refetch()}
|
||||
empty="날씨가 아직 없어요."
|
||||
hold={
|
||||
<>
|
||||
<DaysSkel />
|
||||
<PickSkel />
|
||||
</>
|
||||
}
|
||||
className="inset-x-3 top-3 bottom-0"
|
||||
/>
|
||||
)}
|
||||
{sel && (
|
||||
<div className="mx-3 mt-3 flex items-center gap-3.5 rounded-3xl bg-[linear-gradient(180deg,#e9fbf2,#fff)] p-4 shadow-[inset_0_-5px_0_var(--shade)]" aria-live="polite">
|
||||
@@ -66,27 +219,27 @@ export function WeekPage() {
|
||||
<div>
|
||||
<b className="block font-jua text-[19px] font-normal">{sel.headline}</b>
|
||||
<p className="mt-0.5 text-[13.5px] font-semibold text-(--ink2)">{sel.summary}</p>
|
||||
<p className="mt-2 font-jua text-base text-(--ink)">추천: {sel.pick}</p>
|
||||
<p className="mt-2 font-jua text-base text-(--ink)">{sel.pick}</p>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{areas.length > 0 && (
|
||||
{(sel || weekLoad !== 'ready') && (
|
||||
<div className="mx-3 mt-3.5 flex items-center justify-between">
|
||||
<label htmlFor="b-area" className="text-[13.5px] font-bold text-(--ink2)">
|
||||
{sido} · 데이트 명소
|
||||
</label>
|
||||
<select id="b-area" value={area} onChange={(e) => setAreaPick({ region: region.code, area: e.target.value })} className="rounded-full bg-white px-3 py-[7px] font-bold text-(--ink) shadow-[inset_0_-3px_0_var(--shade)]">
|
||||
<select id="b-area" value={area} onChange={(e) => setAreaPick({ region: region.code, area: e.target.value })} disabled={!areas.length} className="rounded-full bg-white px-3 py-[7px] font-bold text-(--ink) shadow-[inset_0_-3px_0_var(--shade)] disabled:opacity-60">
|
||||
{['전체', ...areas].map((a) => (
|
||||
<option key={a}>{a}</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
)}
|
||||
<Sec title="날씨 맞춤 데이트 명소" sub={sel ? `${sel.weekday}요일은 ${rainy ? '비가 와서 실내 명소를 먼저' : '맑아서 야외 명소를 먼저'} 보여 줘요` : undefined} className="pt-3" />
|
||||
<Sec title="날씨 맞춤 데이트 명소" sub={sel ? `${sel.weekday}요일은 ${rainy ? '비가 와서 실내 명소를 먼저' : sel.icon === 'sun' ? '맑아서 야외 명소를 먼저' : '비 소식이 없어 야외 명소를 먼저'} 보여 줘요` : weekLoad === 'loading' ? <Skel className="w-56" /> : '날씨에 맞춰 골라 보여 줘요'} className="pt-3" />
|
||||
{placeList.length ? (
|
||||
<Rail>
|
||||
<Rail className={cx('transition-opacity', places.isPlaceholderData && 'opacity-60')}>
|
||||
{placeList.map((p, i) => (
|
||||
<div key={p.place_id} className="w-[178px] overflow-hidden rounded-[22px] bg-white text-left shadow-[inset_0_-5px_0_var(--shade),0_8px_16px_rgb(40_48_74/0.06)]">
|
||||
<div key={p.place_id} className={PLACE_CARD}>
|
||||
<span className={cx('relative grid h-[104px] place-items-center', `b-bg-${PLACE_BG[p.icon] ?? (p.is_outdoor ? 'mint' : cardBg(p.icon, i))}`)}>
|
||||
{p.is_good && <span className={cx('absolute top-2.5 left-2.5 rounded-full px-2 py-[3px] text-[11.5px] font-extrabold text-white', p.is_outdoor ? 'bg-[#1f9d62]' : 'bg-(--rain)')}>{p.is_outdoor ? '오늘 딱' : '비 와도 OK'}</span>}
|
||||
<Ic name={p.icon} className="w-[62px]" />
|
||||
@@ -105,33 +258,95 @@ export function WeekPage() {
|
||||
</div>
|
||||
))}
|
||||
</Rail>
|
||||
) : placeLoad === 'loading' ? (
|
||||
<PlacesSkel />
|
||||
) : (
|
||||
<StateBox loading={places.isPending && !!sel} error={places.error} onRetry={() => places.refetch()} empty={`${sido} 데이트 명소는 아직 준비 중이에요.`} />
|
||||
<StateBox load={placeLoad} onRetry={() => places.refetch()} empty={sel ? `${sido} 데이트 명소는 아직 준비 중이에요.` : '날씨를 불러오면 명소를 골라 드려요.'} hold={<PlacesSkel />} className="inset-x-3 top-3 bottom-1" />
|
||||
)}
|
||||
<Sec title={`${sido} 축제·행사`} sub="앞으로 30일 · 그날 날씨까지 같이 봐요" className="pt-[18px]" />
|
||||
<Sec title="이번 주말 전국 날씨 순위" sub="낮 10~17시 나들이 날씨 · 대표 지역 30곳 중 10위까지" className="pt-[18px]" />
|
||||
{rankDays.length ? (
|
||||
<Chips label="순위 볼 날" items={rankDays.map((d) => [d.day, `${d.weekday}요일 ${shortDay(d.day)}`] as const)} value={rankDay?.day ?? ''} onChange={setRankPick} />
|
||||
) : (
|
||||
<Chips label="순위 볼 날" items={RANK_TABS_HOLD} value="토" onChange={() => {}} />
|
||||
)}
|
||||
{rankItems.length ? (
|
||||
<ul className={cx('mx-3 mt-1.5 flex flex-col transition-opacity', ranking.isPlaceholderData && 'opacity-60')}>
|
||||
{rankItems.map((r) => {
|
||||
const mine = r.region_code === region.code
|
||||
return (
|
||||
<li key={r.region_code} className={cx(RANK_ROW, mine && 'rounded-2xl bg-white')}>
|
||||
<span className="text-center font-bagel text-xl text-(--orange)">{r.rank}</span>
|
||||
<span className="min-w-0">
|
||||
<b className="block truncate font-jua text-[17px] font-normal">
|
||||
{r.name}
|
||||
{mine && <small className="ml-1.5 font-sans text-xs font-extrabold text-(--rain)">내 지역</small>}
|
||||
</b>
|
||||
<small className="block truncate text-[12.5px] font-semibold text-(--ink2)">
|
||||
{r.reason}
|
||||
{r.estimated && ' · 예상'}
|
||||
</small>
|
||||
<span className="mt-[5px] block h-1.5 overflow-hidden rounded-full bg-[#eef1f6]">
|
||||
<s className="block h-full bg-[linear-gradient(90deg,#9be7c4,#1f9d62)]" style={{ width: `${r.score}%` }} />
|
||||
</span>
|
||||
</span>
|
||||
<em className="flex items-center gap-1 font-jua text-base not-italic">
|
||||
<Ic name={r.icon} className="size-6" />
|
||||
{r.score}점
|
||||
</em>
|
||||
</li>
|
||||
)
|
||||
})}
|
||||
</ul>
|
||||
) : rankLoad === 'loading' ? (
|
||||
<RankSkel />
|
||||
) : (
|
||||
<StateBox load={rankLoad} onRetry={() => ranking.refetch()} empty="주말 예보가 아직 없어요." hold={<RankSkel />} className="inset-x-3 top-1.5 bottom-0" />
|
||||
)}
|
||||
<Sec title="가까운 축제·행사" sub="30km 안 · 앞으로 30일 · 그날 날씨까지 같이 봐요" className="pt-[18px]" />
|
||||
{eventList.length ? (
|
||||
eventList.map((e, i) => (
|
||||
<div key={e.event_id} className="mx-3 mt-2.5 grid grid-cols-[84px_1fr] items-center gap-3 rounded-[22px] bg-white p-3 shadow-[inset_0_-5px_0_var(--shade)]">
|
||||
<span className={cx('grid h-[84px] place-items-center rounded-2xl', `b-bg-${cardBg(e.icon, i)}`)}>
|
||||
<Ic name={e.icon} className="w-14" />
|
||||
</span>
|
||||
<span>
|
||||
<span className={cx('mr-1.5 inline-block rounded-full px-[7px] py-0.5 align-[2px] text-[11px] font-extrabold', e.status === 'live' ? 'bg-[#dff5ea] text-[#1f7a4f]' : 'bg-[#ffe8dc] text-[#c2471b]')}>{e.status_label}</span>
|
||||
<b className="inline font-jua text-[17px] leading-snug font-normal">{e.name}</b>
|
||||
<small className="block text-[12.5px] font-semibold text-(--ink2)">
|
||||
{dateRange(e.start_date, e.end_date)} · {e.place_name}
|
||||
<div key={e.event_id} className={cx(EVENT_CARD, 'transition-opacity', events.isPlaceholderData && 'opacity-60')}>
|
||||
<Thumb image={e.image} icon={e.icon} credit={e.image_credit} className={cx('h-[84px] rounded-2xl', `b-bg-${cardBg(e.icon, i)}`)} iconClassName="w-14" />
|
||||
{/* 이름 두 줄·정보 한 줄·날씨 한 줄로 고정해 카드 높이가 데이터와 무관하게 같다 */}
|
||||
<span className="min-w-0">
|
||||
<b className="line-clamp-2 h-[2lh] font-jua text-[17px] leading-snug font-normal">
|
||||
<span className={cx('mr-1.5 inline-block rounded-full px-[7px] py-0.5 align-[2px] font-sans text-[11px] leading-normal font-extrabold', e.status === 'live' ? 'bg-[#dff5ea] text-[#1f7a4f]' : 'bg-[#ffe8dc] text-[#c2471b]')}>{e.status_label}</span>
|
||||
{e.name}
|
||||
</b>
|
||||
<small className="block truncate text-[12.5px] font-semibold text-(--ink2)">
|
||||
{[dateRange(e.start_date, e.end_date), e.place_name].filter(Boolean).join(' · ')}
|
||||
{!e.is_confirmed && ' · 일정 확인 필요'}
|
||||
</small>
|
||||
{e.fit && <span className={cx('mt-[5px] inline-block text-xs font-extrabold', e.fit.includes('비') ? 'text-[#d6457a]' : 'text-[#1f9d62]')}>{e.fit}</span>}
|
||||
<span className={cx('mt-[5px] block h-[1lh] text-xs font-extrabold', e.fit?.includes('비') ? 'text-[#d6457a]' : 'text-[#1f9d62]')}>{e.fit}</span>
|
||||
</span>
|
||||
</div>
|
||||
))
|
||||
) : eventLoad === 'loading' ? (
|
||||
THREE.map((i) => <EventSkel key={i} />)
|
||||
) : (
|
||||
<StateBox loading={events.isPending} error={events.error} onRetry={() => events.refetch()} empty="이 지역 행사는 아직 없어요. 다른 지역을 골라 보세요." />
|
||||
<StateBox load={eventLoad} onRetry={() => events.refetch()} empty="30km 안에 열리는 행사가 아직 없어요. 다른 지역을 골라 보세요." hold={THREE.map((i) => <EventSkel key={i} />)} className="inset-x-3 top-2.5 bottom-0" />
|
||||
)}
|
||||
{/* 행사 수가 정해진 뒤에 붙여 목록이 늘어날 때 밀리지 않게 */}
|
||||
{eventLoad !== 'loading' && (
|
||||
<button type="button" onClick={sendPlan} disabled={!sel} className="mx-3 mt-4 block w-[calc(100%-24px)] cursor-pointer rounded-full bg-(--orange) p-[13px] font-jua text-[17px] text-white shadow-[inset_0_-5px_0_var(--orange-deep)] disabled:opacity-60">
|
||||
이번 주말 일정 보내기
|
||||
</button>
|
||||
)}
|
||||
</section>
|
||||
)
|
||||
}
|
||||
|
||||
const DAY_STRIP = { align: 'start', dragFree: true, containScroll: 'trimSnaps' } as const
|
||||
|
||||
/** 열흘 날짜 줄: 손가락·마우스로 끌어 넘기고, PC 에선 화살표도 */
|
||||
function DayStrip({ children, dim }: { children: ReactNode; dim: boolean }) {
|
||||
const { ref, api, prev, next } = useCarousel(DAY_STRIP)
|
||||
return (
|
||||
<div className="relative" role="group" aria-label="날짜 고르기">
|
||||
<div ref={ref} className="overflow-hidden">
|
||||
<div className={cx('flex gap-1 px-3 pt-3 transition-opacity *:shrink-0', dim && 'opacity-60')}>{children}</div>
|
||||
</div>
|
||||
<Arrows api={api} prev={prev} next={next} />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -17,9 +17,10 @@ export function AuthProvider({ children }: { children: ReactNode }) {
|
||||
const queryClient = useQueryClient()
|
||||
const me = useQuery({ ...meOptions(), enabled: !!token })
|
||||
|
||||
// 로그인·로그아웃하면 좋아요·저장 여부가 달라지니 받아 둔 데이터를 다시 받는다
|
||||
// 로그인·로그아웃하면 좋아요 여부가 달라지니 받아 둔 데이터를 다시 받는다
|
||||
useEffect(() => subscribeAuth((reason) => reason === 'change' && queryClient.invalidateQueries()), [queryClient])
|
||||
|
||||
const api = useMemo(() => ({ loggedIn: !!token, me: (token && me.data?.me) || null, logout }), [token, me.data])
|
||||
const mePending = !!token && me.isPending
|
||||
const api = useMemo(() => ({ loggedIn: !!token, me: (token && me.data?.me) || null, mePending, logout }), [token, me.data, mePending])
|
||||
return <AuthContext value={api}>{children}</AuthContext>
|
||||
}
|
||||
@@ -1,7 +1,8 @@
|
||||
import { createContext, use } from 'react'
|
||||
import type { Me } from '../api/client/types.gen'
|
||||
|
||||
export type AuthApi = { loggedIn: boolean; me: Me | null; logout: () => void }
|
||||
/** mePending: 토큰은 있고 내 정보를 받는 중 (아바타 자리를 비워 두지 않으려고) */
|
||||
export type AuthApi = { loggedIn: boolean; me: Me | null; mePending: boolean; logout: () => void }
|
||||
|
||||
export const AuthContext = createContext<AuthApi | null>(null)
|
||||
|
||||
|
||||
@@ -11,6 +11,8 @@
|
||||
--orange-deep: #d4552a;
|
||||
--rain: #4f97e3;
|
||||
--heart: #ff3b5c;
|
||||
/* 스켈레톤: 그 자리 글자색을 옅게 써서 낮·밤·노을 어디서든 보이게 */
|
||||
--skel: color-mix(in oklab, currentColor 13%, transparent);
|
||||
font-size: 15px;
|
||||
line-height: 1.5;
|
||||
}
|
||||
@@ -140,7 +142,7 @@
|
||||
}
|
||||
}
|
||||
|
||||
/* 히어로 시간대 배경 */
|
||||
/* 히어로 시간대 배경 (저녁은 흰 글자 대비 AA 4.5:1 이상이 되게 깊은 보라로) */
|
||||
.b-hero {
|
||||
transition: background 0.6s;
|
||||
}
|
||||
@@ -151,7 +153,7 @@
|
||||
background: linear-gradient(180deg, #9fd3ff, #cfe9ff 55%, #f1f8ff);
|
||||
}
|
||||
.b-hero[data-t='sunset'] {
|
||||
background: linear-gradient(180deg, #8e7cf0, #f28aa0 48%, #ffc38a);
|
||||
background: linear-gradient(180deg, #4c42b0, #6a48b0 45%, #9a4a88);
|
||||
color: #fff;
|
||||
}
|
||||
.b-hero[data-t='night'] {
|
||||
@@ -165,6 +167,9 @@
|
||||
.b-hero[data-t='night'] .b-stars {
|
||||
opacity: 1;
|
||||
}
|
||||
.b-stars i {
|
||||
background: #fff;
|
||||
}
|
||||
.b-stat {
|
||||
background: rgb(255 255 255 / 0.72);
|
||||
color: var(--ink);
|
||||
@@ -176,6 +181,9 @@
|
||||
color: #fff;
|
||||
box-shadow: inset 0 -5px 0 rgb(255 255 255 / 0.12);
|
||||
}
|
||||
.b-hero[data-t='sunset'] .b-stat {
|
||||
background: rgb(30 16 80 / 0.2);
|
||||
}
|
||||
.b-orb-label {
|
||||
text-shadow: 0 2px 0 rgb(255 255 255 / 0.7);
|
||||
}
|
||||
@@ -423,19 +431,17 @@
|
||||
}
|
||||
.b-shoot {
|
||||
position: absolute;
|
||||
top: 14%;
|
||||
left: 70%;
|
||||
width: 90px;
|
||||
width: var(--len, 90px);
|
||||
height: 1.5px;
|
||||
border-radius: 2px;
|
||||
background: linear-gradient(90deg, rgb(255 255 255 / 0), #fff);
|
||||
opacity: 0;
|
||||
animation: b-shoot 14s ease-in 6s infinite;
|
||||
animation: b-shoot var(--dur, 8s) ease-in var(--dl, 0s) infinite;
|
||||
}
|
||||
@keyframes b-shoot {
|
||||
0%, 92% { opacity: 0; transform: rotate(-24deg) translateX(0); }
|
||||
94% { opacity: 1; }
|
||||
100% { opacity: 0; transform: rotate(-24deg) translateX(-220px); }
|
||||
0%, 86% { opacity: 0; transform: rotate(-24deg) translateX(0); }
|
||||
89% { opacity: 1; }
|
||||
100% { opacity: 0; transform: rotate(-24deg) translateX(-240px); }
|
||||
}
|
||||
.b-paused * {
|
||||
animation-play-state: paused !important;
|
||||
@@ -467,18 +473,85 @@
|
||||
border-color: rgb(255 255 255 / 0.08);
|
||||
}
|
||||
|
||||
/* 밤: 하늘 위 글자는 밝게, 카드 안은 원래 색 */
|
||||
/* ===== 밤: 화면 전체를 어두운 테마로 (글자 대비 WCAG AA 4.5:1 이상) ===== */
|
||||
.b-app[data-t='night'] {
|
||||
--ink: #f1f3ff;
|
||||
--ink2: #bcc3ea;
|
||||
--ink3: #a3abdc;
|
||||
}
|
||||
.b-app[data-t='night'] :is(article, .bg-white, [class*='bg-white/'], [class*='b-bg-'], .b-stat, .b-sheet) {
|
||||
--ink: #28304a;
|
||||
--ink2: #5a6380;
|
||||
--ink3: #8a92aa;
|
||||
--ink: #eef1ff;
|
||||
--ink2: #c3c9ec;
|
||||
--ink3: #a1a9db;
|
||||
--line: rgb(255 255 255 / 0.1);
|
||||
--page: #1a2150;
|
||||
--shade: #141a42;
|
||||
--orange: #ff8a57;
|
||||
--heart: #ff6b85;
|
||||
--card: #222a5c;
|
||||
--chip: #2b3470;
|
||||
--skel: color-mix(in oklab, currentColor 17%, transparent);
|
||||
color-scheme: dark;
|
||||
}
|
||||
.b-app[data-t='night'] .b-tabbar {
|
||||
--ink: #fff;
|
||||
--ink3: #9aa2d4;
|
||||
}
|
||||
.b-app[data-t='night'] .bg-white {
|
||||
background-color: var(--card);
|
||||
}
|
||||
.b-app[data-t='night'] [class*='bg-white/'] {
|
||||
background-color: rgb(34 42 92 / 0.85);
|
||||
}
|
||||
.b-app[data-t='night'] :is([class*='bg-[#f'], [class*='bg-[#e'], [class*='bg-[#d'], [class*='bg-[#c'], [class*='bg-[linear-gradient']) {
|
||||
background: var(--chip);
|
||||
}
|
||||
.b-app[data-t='night'] [class*='border-[#dfe5ee]'] {
|
||||
border-color: rgb(255 255 255 / 0.12);
|
||||
}
|
||||
.b-app[data-t='night'] [class*='rgb(217_229_244'] {
|
||||
box-shadow: inset 0 -5px 0 var(--shade);
|
||||
}
|
||||
.b-app[data-t='night'] .bg-\(--ink\) {
|
||||
background-color: #4b56b5;
|
||||
color: #fff;
|
||||
}
|
||||
.b-app[data-t='night'] .bg-\(--ink\) .text-\[\#ffb3c4\] {
|
||||
color: #ffd0dc;
|
||||
}
|
||||
.b-app[data-t='night'] .text-\[\#28304a\] {
|
||||
color: var(--ink);
|
||||
}
|
||||
.b-app[data-t='night'] :is(.text-\[\#1f9d62\], .text-\[\#1f7a4f\]) {
|
||||
color: #4fd39a;
|
||||
}
|
||||
.b-app[data-t='night'] .text-\[\#d6457a\] {
|
||||
color: #ff8db5;
|
||||
}
|
||||
.b-app[data-t='night'] .text-\[\#c2471b\] {
|
||||
color: #ffab85;
|
||||
}
|
||||
.b-app[data-t='night'] .bg-\[\#dff5ea\] {
|
||||
background: rgb(79 211 154 / 0.16);
|
||||
}
|
||||
.b-app[data-t='night'] .bg-\[\#ffe8dc\] {
|
||||
background: rgb(255 138 87 / 0.16);
|
||||
}
|
||||
.b-app[data-t='night'] .b-bg-sky {
|
||||
background: linear-gradient(180deg, #2a4384, #1f2c62);
|
||||
}
|
||||
.b-app[data-t='night'] .b-bg-butter {
|
||||
background: linear-gradient(180deg, #4d4128, #2c2a3e);
|
||||
}
|
||||
.b-app[data-t='night'] .b-bg-peach {
|
||||
background: linear-gradient(180deg, #553632, #2e2840);
|
||||
}
|
||||
.b-app[data-t='night'] .b-bg-mint {
|
||||
background: linear-gradient(180deg, #1f4a45, #1d2d4a);
|
||||
}
|
||||
.b-app[data-t='night'] .b-bg-lilac {
|
||||
background: linear-gradient(180deg, #3d3480, #262a5e);
|
||||
}
|
||||
.b-app[data-t='night'] .b-band-1 {
|
||||
background: linear-gradient(180deg, rgb(255 160 110 / 0.12), rgb(255 255 255 / 0));
|
||||
}
|
||||
.b-app[data-t='night'] .b-band-2 {
|
||||
background: linear-gradient(180deg, rgb(255 214 110 / 0.12), rgb(255 255 255 / 0));
|
||||
}
|
||||
.b-app[data-t='night'] .b-band-3 {
|
||||
background: linear-gradient(180deg, rgb(110 230 180 / 0.12), rgb(255 255 255 / 0));
|
||||
}
|
||||
@@ -3,8 +3,9 @@ import type { CSSProperties } from 'react'
|
||||
const SHARED = new Set(['bear', 'bike', 'bronze', 'camping', 'carwash', 'chimaek', 'cloud', 'coldwind', 'delivery', 'dog', 'garden', 'glasses', 'gold', 'hiking', 'iced_hot', 'jjamppong', 'laundry', 'letter', 'makeup', 'makgeolli', 'maple', 'moon', 'muggy', 'naengmyeon', 'photo', 'picnic', 'rabbit', 'rain', 'running', 'silver', 'snow', 'stars', 'sun_cloud', 'sun', 'sunset', 'taxi', 'umbrella', 'vent', 'walk', 'yajang', 'baseball', 'study', 'netflix', 'chestnut', 'peanut', 'tangerine', 'sweet_potato', 'fallen_leaf', 'kimchi', 'apple'])
|
||||
const OWN = new Set(['fireworks', 'bulb', 'calendar', 'thermo', 'sheaf'])
|
||||
|
||||
/** 아이콘 이름 → 파일 경로 (공용 public/icons, B 전용 public/b/icons) */
|
||||
/** 아이콘 이름 → 파일 경로 (공용 public/icons, B 전용 public/b/icons). 'none'(데이터 없는 칸)은 그림 없음 */
|
||||
export function iconSrc(name: string) {
|
||||
if (name === 'none') return null
|
||||
if (OWN.has(name)) return `/b/icons/${name}.png`
|
||||
return `/icons/${SHARED.has(name) ? name : 'sun_cloud'}.png`
|
||||
}
|
||||
@@ -27,7 +28,7 @@ export const AVATAR_COLORS: Record<string, string> = { orange: '#ff8e4e', blue:
|
||||
/** 오늘 기분 (백엔드 MOODS 와 같아야 한다) */
|
||||
export const MOODS = [
|
||||
['clear', '☀️', '맑음'],
|
||||
['partly', '⛅', '구름조금'],
|
||||
['partly', '⛅', '구름 조금'],
|
||||
['cloudy', '☁️', '흐림'],
|
||||
['rain', '🌧️', '비'],
|
||||
['thunder', '⚡', '번개'],
|
||||
@@ -53,12 +54,17 @@ export function kst(input: string | Date) {
|
||||
|
||||
const h12 = (h: number) => h % 12 || 12
|
||||
|
||||
/** 18:25 → "6:25" */
|
||||
/** 18:25 → "18:25" (포스트·플랜과 같은 24시간제) */
|
||||
export function clockShort(iso: string) {
|
||||
const t = kst(iso)
|
||||
return `${h12(t.h)}:${String(t.mi).padStart(2, '0')}`
|
||||
return `${t.h}:${String(t.mi).padStart(2, '0')}`
|
||||
}
|
||||
|
||||
const COMPASS = ['북', '북북동', '북동', '동북동', '동', '동남동', '남동', '남남동', '남', '남남서', '남서', '서남서', '서', '서북서', '북서', '북북서']
|
||||
|
||||
/** 방위각 → 16방위 이름. 263 → "서" */
|
||||
export const compass = (deg: number) => COMPASS[Math.round(deg / 22.5) % 16]
|
||||
|
||||
/** 18:30 → "6시 반", 18:25 → "6시 25분" */
|
||||
export function timeWords(iso: string) {
|
||||
const t = kst(iso)
|
||||
@@ -119,3 +125,13 @@ export const ARTICLE_CAT: Record<number, [string, string]> = { 1: ['계절 소
|
||||
|
||||
/** 읽을거리 한 줄 정보: "계절 소식 · 3분" */
|
||||
export const articleMeta = (a: { category: number; read_minutes: number }) => `${ARTICLE_CAT[a.category]?.[0] ?? '읽을거리'} · ${a.read_minutes}분`
|
||||
|
||||
export type Load = 'loading' | 'error' | 'retrying' | 'ready'
|
||||
type QueryLike = { data?: unknown; isPending: boolean; isError: boolean; isFetching: boolean; errorUpdateCount: number }
|
||||
|
||||
/** 데이터가 있으면 ready. 실패 뒤 다시 받는 중(retrying)은 처음 불러오기(loading)와 구분한다 */
|
||||
export function loadOf(q: QueryLike): Load {
|
||||
if (q.data !== undefined) return 'ready'
|
||||
if (q.isError) return q.isFetching ? 'retrying' : 'error'
|
||||
return q.isFetching && q.errorUpdateCount > 0 ? 'retrying' : 'loading'
|
||||
}
|
||||