Merge branch 'main' into feat/open-meteo
This commit is contained in:
commit
aa05d870a2
80 files changed
+4893
-351
No files matched your search
+1
-1
@@ -5,7 +5,7 @@
|
||||
DATA_GO_KR_SERVICE_KEY=
|
||||
# 행사 수집(7일마다) 완료 알림 — Microsoft Teams Workflows 수신 webhook. 비우면 보내지 않는다.
|
||||
TEAMS_WEBHOOK_URL=
|
||||
IMAGE_PROXY_HOSTS=tong.visitkorea.or.kr,www.culture.go.kr
|
||||
IMAGE_PROXY_HOSTS=tong.visitkorea.or.kr,www.culture.go.kr,culture.seoul.go.kr
|
||||
|
||||
# ── 백엔드: DB·Redis (네이티브 실행 기준. compose 안에서는 compose.yaml 이 host·port 를 덮어쓴다)
|
||||
DB_HOST=localhost
|
||||
|
||||
@@ -1,5 +1,20 @@
|
||||
# TODO
|
||||
|
||||
## 출시 전 (10/8 확정)
|
||||
|
||||
| 상태 | 할 일 | 이유 | 관련 파일 |
|
||||
|---|---|---|---|
|
||||
| [x] | 계절 소식 사진 연결 (11장) | 출시 전 | `frontend/public/season/`, `backend/seed/article.json` |
|
||||
| [x] | 노을 명소 보강 — 30km 안 명소 없는 구 89 → 23 | 출시 전 | `backend/seed/sunset_spot.csv` |
|
||||
| [x] | 기능 QA 작성 (`docs/QA_체크리스트.md` 100항목) + 찾은 버그 수정 | 출시 전 | `docs/QA_체크리스트.md` |
|
||||
| [ ] | 모바일 실기기 테스트 (QA 체크리스트로) | 출시 전 | `docs/QA_체크리스트.md` |
|
||||
| [x] | 각 늘리기 27 → 34 + 순위에 중요도 반영 | 출시 전 | `backend/seed/index_definition.json` |
|
||||
| [x] | 노치 대응 — 상단 띠 불투명, 시간대별 `theme-color` | 출시 전 | `frontend/index.html`, `frontend/src/b/BLayout.tsx` |
|
||||
| [x] | 데이트 명소 전국 (2,445곳, 30km) | 출시 전 | `backend/seed/place_tourapi.csv` |
|
||||
| [x] | 좋아요·댓글 시도 단위로 나누기 | 출시 전 | `backend/services/feed_service.py` |
|
||||
| [x] | 노을 판정 확인 방법·SEO 방식 — 추천안을 아래 [결정 필요] 행에 정리 | 출시 전 | |
|
||||
| [ ] | `release/launch-1008` → main 병합, 킹서버 배포, 시드 재적재·`feed:*` 캐시 삭제, 운영 JWT 비밀키 교체 (운영 영향, 확인 받고) | 출시 | `deploy.sh`, `backend/scripts/load_seed.py` |
|
||||
|
||||
## 진행 순서
|
||||
|
||||
결정이 필요 없는 것부터, 사용자 눈에 틀린 정보가 보이는 것 → 기능 → 다듬기 순.
|
||||
@@ -22,9 +37,11 @@
|
||||
| [x] | 행사 독립 카드 최대 3장, 피드 무작위 노출 (하루 같은 자리) | 10/2 회의 | `backend/services/feed_service.py` |
|
||||
| [x] | 계절 소식 제철 7개 추가 (햇밤·햇땅콩·은행·고구마·귤·부사·김장) — 피드백 대기 | 10/2 회의 | `backend/seed/article.json` |
|
||||
| [x] | 새 각 추가 (야구·공부·넷플릭스·군밤) | 10/2 회의 | `backend/seed/index_definition.json` |
|
||||
| [x] | 각 늘리기 27→34 (골프·집콕·낚시·드라이브·연날리기·물놀이·김장), 집콕각은 미세먼지 탁할수록 좋게 | 사용자 요청 | `backend/seed/index_definition.json`, `backend/services/calc/index_calc.py` |
|
||||
| [x] | 주말 전국 지역 랭킹 — 노을 순위 대표 30곳의 토·일 '나들이 날씨 점수'(낮 10~17시 비 40·기온 35·하늘 15·바람 10, 비 60%↑면 최대 30점) 순위. `GET /v1/week/ranking`, 주말 화면 '이번 주말 전국 날씨 순위'(토/일 탭, 10위까지). 워커가 06:40·18:40에 계산해 Redis에 13시간 저장, 없으면 API가 그 자리에서 계산 | 10/2 회의 최종 그림 | `backend/services/weekend_rank.py`, `backend/services/calc/index_calc.py` (`outing`), `frontend/src/b/WeekPage.tsx` |
|
||||
| [x] | 노을 명소 지역별 목록 연결 — 지금 명소 데이터가 서울 마포구 3곳뿐이고 구 코드로만 찾아서 분당구 등은 하나도 안 나옴 | 10/2 회의 (추후), 사용자 지적 | `backend/seed/sunset_spot.csv`, `backend/services/sky_service.py` |
|
||||
| [ ] | 노을 명소 30km 안에 하나도 없는 구 89/256 — 광주·대전·세종·충북·강원·경북 내륙·전북 내륙 등. TourAPI 키워드로는 안 잡혀 직접 추가하거나 반경을 넓힐지 결정 필요 | 명소 확충 결과 | `backend/seed/sunset_spot.csv`, `backend/services/sky_service.py` |
|
||||
| [x] | 노을 명소 30km 안에 하나도 없는 구 89/256 — 광주·대전·세종·충북·강원·경북 내륙·전북 내륙 등. TourAPI 키워드로는 안 잡혀 직접 추가하거나 반경을 넓힐지 결정 필요 → 노을 근거를 확인한 21곳을 추가해 89 → 23 | 명소 확충 결과 | `backend/seed/sunset_spot.csv`, `backend/services/sky_service.py` |
|
||||
| [ ] | 노을 명소 30km 안에 없는 구 23/256(최대 51.8km, 지금은 가장 가까운 1곳을 거리와 함께 보여 줌) — 강원 동해·삼척·양구·인제·태백·횡성, 경남 거창·산청·함양, 경북 구미·김천·봉화·안동·울진·의성, 대구 군위, 전남 곡성·구례, 전북 남원·임실·장수·진안, 충북 보은. 노을 근거를 찾지 못함. 반경 밖이면 화면엔 '근처에 등록된 노을 명소가 없어요'만 나오고 가장 가까운 곳·거리는 안 나옴 | 명소 보강 결과 | `backend/seed/sunset_spot.csv`, `backend/services/sky_service.py` (`nearest_spots`), `frontend/src/b/SkyPage.tsx` |
|
||||
| [x] | 명소 '서쪽이 트임'(west_open)·설명 꼬리말은 TourAPI 개요를 보고 사람이 붙인 값 — 현장 확인 안 됨. 분당구는 가장 가까운 곳이 17~18km(일자산·반포·광나루)라 수도권 동남부 명소 보강 필요 → 화면에서 설명을 빼고 방향·거리만 보여줌. 현장 확인은 여전히 안 됨 | 명소 확충 결과 | `backend/seed/sunset_spot.csv` |
|
||||
| [ ] | TourAPI 좌표 오류로 뺀 곳: 기흥레스피아호수공원(용인)·급치산전망대(진도) — 좌표가 (19.69, 117.99). 좌표를 직접 넣어 추가할지 결정 | 명소 확충 결과 | `backend/seed/sunset_spot_tourapi.csv` |
|
||||
| [x] | 서울·경기 반영 범위 확인 — 서울 25구·경기 31시군(구 있는 시는 구 단위, 부천 3구·화성 4구 포함) 모두 있고 코드도 기상청 격자표(2607) 현행 코드와 일치 | 10/2 회의 확인 필요 | `backend/seed/region.csv` |
|
||||
@@ -47,11 +64,11 @@
|
||||
| [ ] | 월요일 0시~06:40엔 새 주말 점수가 아직 없어 당일치기 카드가 꺼짐 (주말 화면 순위는 그 자리에서 계산해 채움). 필요하면 03:00 작업에도 계산 추가 | 당일치기 작업 중 발견 | `backend/worker_main.py`, `backend/scheduler/jobs.py` |
|
||||
| [ ] | 주말 점수 계산이 대표 지역·후보 도시 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] | 각 순위에 중요도 반영 — 점수만으로 정해 환기·세차각이 상위권. 안: `index_definition.priority`(상/중/하) 추가, 정렬은 점수×가중치(상 1.0·중 0.85·하 0.7), 표시 점수는 그대로. 정할 것: 등급 배정(초안 — 상: 빨래·산책·피크닉·등산·캠핑·러닝·자전거 / 중: 야장·치맥·별보기·멍뭉산책·사진산책·김서림·화장붕괴·택시대란·배달폭주 / 하: 환기·세차·가드닝·야구·짬뽕·막걸리·뜨아·냉면·공부·넷플릭스·군밤), 가중치 값, 로컬·운영 DB `ALTER TABLE index_definition ADD COLUMN priority SMALLINT NOT NULL DEFAULT 2` 실행 | 사용자 지적 | `backend/services/index_service.py:119`, `backend/common/database/model/models.py`, `backend/postgres-init/init.sql`, `backend/seed/index_definition.json` |
|
||||
| [x] | 각 상세 창 점수 칸을 오늘/내일/토/일로 — 단기예보(시간별)는 약 4일 뒤까지라 월~수엔 주말 점수를 같은 방식으로 못 냄. 안: 범위 밖 주말은 중기예보(기온·비 확률)로 대략 점수 + "예상" 표시, 오늘·내일이 주말이면 다음 주말 표시 | 사용자 요청 | `backend/services/index_service.py` (`DAYS = 3`), `frontend/src/b/Sheets.tsx` |
|
||||
| [x] | 그날 밤 달 모양 — 밤 히어로에 달 모양·밝기, 보름·삭인 밤엔 '오늘 밤 달' 포스트 (사용자 결정 1·4안). 보름·삭 시각은 Meeus 계산(오차 2분 안) — 계산은 `moon.py`로 외부 API 없이 가능 | 사용자 질문 | `backend/services/calc/moon.py` |
|
||||
| [ ] | **[결정 필요]** 각과 상관없는 요소 비중 — 김서림각 바람, 택시대란·배달폭주·넷플릭스각 습도가 '상관없음'인데 비중 5%라 항상 50점으로 섞임. 0으로 할지 / 짬뽕·배달폭주각에 '공기 맑음' 5%가 좋은 쪽으로 들어가는 게 맞는지 | 6각 차트 수정 중 발견 | `backend/seed/index_definition.json` |
|
||||
| [ ] | **[결정 필요]** 계절 이야기 사진 — CC BY-SA 등 8장은 저작자·라이선스 표시 필요(표시 위치 정하기), `howgak` 글은 맞는 사진 없음(일러스트/아이콘), `tangerine`(퍼블릭 도메인) 사용 여부, `di`(매미)·`peanut_new`(일본 삶은 땅콩) 주제 적합성 | 사진 수집 중 발견 | `frontend/public/season/sources.json` |
|
||||
| [x] | **[결정 필요]** 계절 이야기 사진 — 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` |
|
||||
@@ -64,7 +81,8 @@
|
||||
| [ ] | 문화정보 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] | 계절 이야기 사진 연결 — 받은 13장(`frontend/public/season/`)을 `article`에 사진 칸 추가해 띠·목록·상세·피드에 표시, CC BY 계열은 저작자·라이선스 표시. 스켈레톤 작업 끝난 뒤 진행 | 사용자 요청 | `backend/common/database/model/models.py`, `backend/seed/article.json`, `frontend/src/b/SeasonPage.tsx`, `frontend/src/b/Sheets.tsx`, `frontend/src/b/TodayPage.tsx` |
|
||||
| [ ] | **[결정 필요]** 계절 이야기 사진 2장 안 씀 — `di.jpg`(매미)는 불쾌지수 글과 주제가 다르고, `peanut_new.jpg`(일본 가토리시 삶은 땅콩, 왼쪽은 일본 대립종)는 '국산 햇땅콩' 글과 맞지 않아 아이콘 유지. 맞는 사진을 새로 구할지 | 계절 이야기 사진 연결 중 판단 | `frontend/public/season/sources.json`, `backend/seed/article.json` |
|
||||
| [x] | (로컬 반영함, 운영 DB는 배포 때 같은 ALTER 필요) 로컬 DB 칼럼 추가 후 백엔드·워커 컨테이너 다시 빌드 — 지금 9810 백엔드는 이미지로 떠 있어 이번 백엔드 수정이 화면에 안 보임. 필요한 ALTER: `weather_daily.rain_prob_am`/`rain_prob_pm SMALLINT NULL`, `index_score.estimated BOOLEAN NOT NULL DEFAULT false`. 진행 중인 백엔드 작업이 끝난 뒤 실행 | 오늘/내일/토/일 작업 중 발견 | `backend/postgres-init/init.sql`, `compose.yaml` |
|
||||
| [ ] | **[결정 필요]** 확정 시안(`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` |
|
||||
@@ -72,7 +90,7 @@
|
||||
| [ ] | 한 문장 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` |
|
||||
| [x] | 주말 화면 '데이트 명소'는 아직 시도 기준(`places`) — 행사처럼 거리 기준으로 바꿀지. 지금 명소 데이터는 10곳뿐 | 행사 거리 기준 작업 중 발견 | `backend/services/week_service.py` (`places`), `frontend/src/b/WeekPage.tsx` |
|
||||
| [ ] | 행사 수집이 사용자 한 명당 주변 시도 2~4곳으로 늘어 TourAPI·문화정보 API 호출이 시도 수만큼 늘어남(시도별 하루 1회 캐시) — 운영 배포 때 일일 호출 한도 확인 | 행사 거리 기준 작업 중 발견 | `backend/services/week_service.py` (`_ensure_events`), `backend/docs/load-estimate.md` |
|
||||
| [ ] | 다른 문서의 포스트 종류 목록·행사 시도 기준 설명 갱신 (`PostType` 12 미세먼지, 30km 행사) — `docs/포스트_종류별_내용.html`만 고침 | 문서 점검 | `backend/docs/`, `docs/화면별_데이터_출처.html`, `docs/데이터_흐름.html`, `docs/콘텐츠_설계서.md` |
|
||||
| [ ] | **[결정 필요]** 스켈레톤 작업에서 바뀐 디자인 — 댓글 없음 안내가 글자 두 줄 → 상자(스켈레톤 3줄 크기) | 스켈레톤 작업 중 발견 | `frontend/src/b/Sheets.tsx` (`CommentsSheet`) |
|
||||
@@ -94,13 +112,40 @@
|
||||
| [x] | 문화정보원 API 가 `23 LIMITED_NUMBER_OF_SERVICE_REQUESTS_PER_SECOND_EXCEEDS_ERROR` 를 냄 — 쪽 사이 1초, 시도 사이 1초 간격을 둬 17개 시도 수집에서 오류 없음 | 콘서트 수집 점검 중 발견 | `backend/services/external/culture_api.py` |
|
||||
| [x] | `event.kind` 칸 추가(1=축제 2=전시 3=콘서트 4=팝업). 행사 종류(축제·전시·콘서트·팝업)를 구분하는 칸이 없음 — 지금은 `source_id` 접두어로만 구분하고 전시·콘서트는 둘 다 `kcis:` 라 섞임 | 콘서트 수집 | `backend/postgres-init/init.sql` (`event`) |
|
||||
| [x] | 히어로 두 칸을 상황별로 고름(비→미세먼지→자외선→일교차→체감→불쾌지수, 모자라면 기본값), 아이콘·색도 상태별 (시안 A, 사용자 결정). 히어로 내용 전체 다시 보기 — 아이콘이 뜻과 안 맞음: 불쾌지수에 온도계(불쾌지수는 기온+습도), '지금 비'는 비가 안 와도 우산. 칸마다 무엇을 보여줄지(불쾌지수가 필요한지 포함)부터 다시 정하기 | 사용자 지적 | `frontend/src/b/TodayPage.tsx` (`HeroStat`) |
|
||||
| [ ] | 검색 노출(SEO·AEO) 대응 빌드 방식 정하기 — 지금은 브라우저에서만 그리는 React(Vite)라 검색엔진·AI가 내용을 못 읽음. SSR 말고도 미리 그려 두는 방식(정적 사전 렌더링), 일부 페이지만 서버에서 그리기 등을 비교해 추천안 내기 | 지시 사항 (SEO·AEO 필요) | `frontend/vite.config.ts`, `frontend/nginx.conf` |
|
||||
| [x] | 검색 노출 1단계: 메타는 `index.html` 하나로 유지 + canonical, `robots.txt`·`sitemap.xml`(메인 한 줄) 추가 — 탭별 HTML로 나누는 안은 효과(탭별 공유 미리보기·탭별 색인)가 작아 보류. 도메인 `weather.o2o.kr` 고정이라 바뀌면 두 파일도 수정 | 10/8 논의 | `frontend/index.html`, `frontend/public/robots.txt`, `frontend/public/sitemap.xml` |
|
||||
| [ ] | **[보류]** AEO·일반 검색어 유입 — 본문이 HTML에 없어 네이버 Yeti·AI 크롤러(GPTBot 등)는 메타만 읽고, 일반 검색어("세차하기 좋은 날씨" 등)는 메타만으로 순위에 못 듦. 지금 탭 내용은 지역별·매일 바뀌는 값이라 색인돼도 금방 틀림. 하려면 검색어용 페이지(각 기준·월별 노을 시간·노을 명소·계절 글·월별 행사)를 새로 만들어야 함 → 기획 결정 필요. 계절 이야기 글은 지역 무관이라 글마다 주소만 붙이면 바로 후보 | 10/8 논의 | [검색 유입 기획](https://claude.ai/artifact/SKz9SipYyguERGF8weUpZs), [검색어 리서치](https://claude.ai/artifact/Eu5ax3DbR9SdnhKdMRzE3p) |
|
||||
| [ ] | 구글 서치 콘솔·네이버 서치어드바이저에 사이트 등록, `sitemap.xml` 제출 — 배포 뒤 | 등록·제출 없으면 새 도메인은 색인이 늦음 | https://search.google.com/search-console , https://searchadvisor.naver.com |
|
||||
| [x] | 세션 여러 개가 같은 테스트 DB·Redis를 쓰면 서로 지움 — `TEST_DB_NAME`·`TEST_REDIS_DB`로 폴더마다 다르게 줄 수 있게 함 | 테스트 충돌 (10/7 두 번) | `backend/tests/conftest.py` |
|
||||
| [x] | 피드 행사 카드·띠를 축제→팝업→전시→콘서트 차례로 돌아가며 고름 (사용자 결정). 피드 행사 카드(최대 3장)가 연주회로 채워짐 — 시작일이 오늘에 가까운 순이라 하루짜리 콘서트(서울 170건)가 위를 차지. 기획엔 "축제·행사"만 있고 콘서트·팝업을 어떻게 섞을지 없음. 안: 종류별 1장씩(축제·전시·팝업 우선) 또는 피드에서 콘서트 제외 | 사용자 지적 | `backend/services/week_service.py` (`events` 정렬), `backend/services/feed_service.py` (`PostType.EVENT`), `docs/피드_기획.html` |
|
||||
| [ ] | 노을 하늘 상황 판정이 실제와 맞는지 확인할 방법 정하기 — 기준값(중·높은 구름 25~75% 등)은 추정값. 사진 기록·사용자 반응 등 후보 | 노을 탭 다시 기획 (10/7) | `backend/services/calc/sky_score.py` (`situation`) |
|
||||
| [ ] | **[결정 필요]** 노을 하늘 상황 판정이 실제와 맞는지 확인할 방법 정하기 — 기준값(중·높은 구름 25~75% 등)은 추정값. 추천안: 서쪽이 트인 공개 웹캠·CCTV 6~8곳을 워커가 매일 '가장 붉을 때' 시각에 캡처하고, 같은 날 13시 기준 예보(상황·판정)를 따로 남김. 사람이 주 1회 사진에 잿빛/은은/고움/붉음 라벨(30분 내외) → 판정(나가 볼 만해요/애매/쉬어요) 3×3 적중표, 특히 '나가 볼 만해요' 적중률(목표 70%↑). 6~8주(약 300장)면 기준값 조정 가능. 비용 0원, 테이블 1개+워커 잡 1개+라벨 CSV로 2~3일. 결정할 것: 웹캠 출처·이용 조건, 라벨 담당 | 노을 탭 다시 기획 (10/7). 사용자 '예뻤어요/별로'는 출시 전엔 표본이 없고 출시 후 보조 지표로, 기상청 ASOS 운량은 전운량·중하층운량만이라 구름 입력 검증용이지 노을이 예뻤는지는 못 알려줌, 인스타 해시태그는 예쁜 날만 올라와 '쉬어요' 검증 불가·수집 약관 문제. `sky_score`는 갱신 때 덮어쓰고 7일 뒤 지워져 지금은 과거 예보가 안 남음 | `backend/services/calc/sky_score.py` (`situation`), `backend/services/sky_service.py`, `backend/scheduler/jobs.py` |
|
||||
| [x] | 공유 이미지: 행사 카드의 장소(지도 링크)가 빠짐 — 버튼과 함께 `<a>`도 빼서 생김. 링크는 남기고 버튼만 빼야 함 | 공유 이미지 점검 (10/7) | `frontend/src/b/storyImage.ts` (`keep`), `frontend/src/b/ui.tsx` (지도 링크) |
|
||||
| [x] | 공유 이미지: 행사 사진은 백엔드 `/v1/image`(허용 호스트만)로 대신 받음 (사용자 결정). 행사 사진(한국관광공사·문화정보원)이 CORS 차단으로 하얗게 빠짐. 안: 백엔드가 사진을 대신 받아 주기 / 공유 때만 사진 대신 아이콘 | 공유 이미지 점검 (10/7) | `frontend/src/b/storyImage.ts`, `backend` 이미지 응답 |
|
||||
| [x] | 공유 이미지: 2장 카드는 한 이미지에 엇갈려 묶음 (사용자 결정). 여러 장 카드는 보고 있는 1장만 나감(주말 예보는 2번째 장 내용이 빠짐). 1장만 / 장마다 이미지 여러 장 / 2장을 한 이미지에 중 정하기 | 공유 이미지 점검 (10/7) | `frontend/src/b/storyImage.ts`, `frontend/src/b/Post.tsx` (`share`) |
|
||||
| [x] | 공유 이미지: 카드 아래 긴 제목이 한 줄 폭에 눌려 찌그러짐 — 두 줄 나눔 또는 말줄임 | 공유 이미지 점검 (10/7) | `frontend/src/b/storyImage.ts` (`fillText`) |
|
||||
| [x] | 공유 이미지: 카드 아래 제목을 빼고 주소 알약으로 바꿈 (시안 A, 사용자 결정). 카드 안 제목과 카드 아래 제목이 같아 두 번 보임. 아래 줄을 뺄지, 다른 말(지역·날짜)로 바꿀지 정하기 | 공유 이미지 점검 (10/7) | `frontend/src/b/storyImage.ts` |
|
||||
| [ ] | 노치(아이폰 상단 카메라 영역) 대응 — 화면 위·아래가 노치·홈 막대에 가리지 않게 safe-area 여백 점검 | 사용자 요청 | `frontend/index.html`, `frontend/src/b/BLayout.tsx` |
|
||||
| [x] | 노치(아이폰 상단 카메라 영역) 대응 — 화면 위·아래가 노치·홈 막대에 가리지 않게 safe-area 여백 점검 | 사용자 요청 | `frontend/index.html`, `frontend/src/b/BLayout.tsx` |
|
||||
| [x] | 홈 화면 상태바 색(`theme-color`)이 낮 하늘색 고정 — 밤 테마 등 시간대 따라 바꿀지 → 시간대 따라 바꿈 | 노치 대응 중 발견 (10/8) | `frontend/index.html` |
|
||||
| [x] | 안드로이드 뒤로 가기: 시트가 열려 있을 때 시트만 닫히지 않고 페이지가 뒤로 감 (방문 기록 미사용) | QA 작성 중 발견 (10/8) | `frontend/src/b/Sheets.tsx:53` |
|
||||
| [x] | 로그아웃 상태에서 댓글 "게시" → 로그인 시트 → 로그인 후 시트가 닫혀 쓰던 댓글이 사라지고 댓글 화면으로 안 돌아옴 | QA 작성 중 발견 (10/8) | `frontend/src/b/Sheets.tsx:662`, `:753` |
|
||||
| [x] | 터치 영역 44px 미만 — 포스트 하트·댓글·보내기 28px, 댓글 하트 약 16px, 시트 × 30px | QA 작성 중 발견 (10/8) | `frontend/src/b/Post.tsx:426`, `frontend/src/b/Sheets.tsx:637`, `:96` |
|
||||
| [x] | 주말 순위 로드 실패 시 토/일 칩이 눌리는 것처럼 보이지만 동작 없음 | QA 작성 중 발견 (10/8) | `frontend/src/b/WeekPage.tsx:278` |
|
||||
| [x] | "지금 위치로 찾기" 성공 후 지역 시트가 안 닫힘 (목록에서 고르면 닫힘) — 닫을지 정하기 | QA 작성 중 발견 (10/8) | `frontend/src/b/region.tsx:44`, `frontend/src/b/Sheets.tsx:938` |
|
||||
| [ ] | **[결정 필요]** 데이트 명소: 서울 기존 10곳(직접 고른 곳)을 거리순과 상관없이 앞에 고정할지 | 데이트 명소 전국 확대 (10/8) | `backend/services/week_service.py` (`pick_places`) |
|
||||
| [ ] | 데이트 명소: 14개 구는 30km 안 실내 명소가 없어 비 오는 날에도 야외만 나옴 | 데이트 명소 전국 확대 (10/8) | `backend/seed/place_tourapi.csv` |
|
||||
| [ ] | 데이트 명소: 동네 고르기 목록에 기존 동네 이름(성수 등)과 새 구 이름이 섞이고 서울은 목록이 길어짐 | 데이트 명소 전국 확대 (10/8) | `frontend/src/b/WeekPage.tsx` |
|
||||
| [ ] | 각 문서: 강풍 특보 조건이 "wind 특보가 있으면"으로 찍힘 (등산·골프·낚시각) | 각 늘리기 중 발견 (10/8) | `backend/scripts/gen_gak_doc.py` |
|
||||
| [ ] | 각 문서: "한눈에 보기" 표에 자외선·햇빛·가시거리 비중이 빠져 합이 100%가 안 됨 (등산·드라이브·물놀이각) | 각 늘리기 중 발견 (10/8) | `backend/scripts/gen_gak_doc.py` |
|
||||
| [x] | 각 중요도: 새 각 7개 제안 — 드라이브 상 / 골프·낚시·물놀이 중 / 집콕·연날리기·김장 하 | 각 늘리기 (10/8) | `backend/seed/index_definition.json` |
|
||||
| [ ] | `tests/test_sky_api.py` 2개가 09시 직전(08:58 KST)에 실패 — 시간대 경계 의존, 재실행 시 통과 | 계절 사진 작업 중 발견 (10/8) | `backend/tests/test_sky_api.py` |
|
||||
| [ ] | 개인정보처리방침·이용약관 모달 (출시 후로 미룸) — `feat/legal` 브랜치(f6ddc67)에 구현 완료, 병합 전. 남은 것: `OPERATOR` 자리표시(회사명·대표자·사업자번호·주소·문의 이메일·보호책임자·호스팅 업체·로그 보유 기간), 탈퇴 기능 없음, 위치 좌표가 nginx 접속 로그에 남음, 만 14세 미만 확인 없음, 약관 열면 가입 입력값 사라짐, 위치정보법 신고 대상 법무 확인 | 사용자 결정 (10/8) | `frontend/src/b/legal/`, `frontend/src/b/Sheets.tsx` |
|
||||
| [x] | 좋아요·댓글이 전국 공통 — 포스트가 (날짜, 자리) 하나로 전국에 하나뿐이라, 구마다 내용이 다른 카드(오늘 날씨·각 1~3위·노을·미세먼지·행사)도 댓글·좋아요를 전국이 같이 씀. 예: 강남의 "1위 산책각"과 부산의 "1위 빨래각"이 같은 댓글창. 안: 지역 데이터 카드만 시도(17) 단위로 나누고 계절·상식·명언은 전국 공통 유지 | 사용자 질문 (10/8) | `backend/postgres-init/init.sql` (`uq_post_feed`), `backend/services/feed_service.py` (`build_day`, `_gak`) |
|
||||
| [ ] | **[결정 필요]** 포스트 시도 단위가 17이 아니라 16 — `region.code` 앞 2자리에서 광주·전남이 둘 다 `12`(전남광주통합특별시)라 같은 댓글창을 씀. 그대로 둘지, 이름 앞머리로 광주·전남을 나눌지 | 포스트 시도 나누기 (10/8) | `backend/services/feed_service.py` (`sido_of`), `backend/seed/region.csv` |
|
||||
| [ ] | 광주·전남 구는 행사가 안 잡힐 수 있음 — 구 코드 시도는 `12`인데 행사 수집·`event.sido_code`는 `29`(광주)·`46`(전남). 좌표 없는 행사는 `is_nearby`·`nearby_sidos`에서 빠짐 | 포스트 시도 나누기 중 발견 (10/8) | `backend/services/week_service.py:125,144`, `backend/services/external/culture_api.py:28` |
|
||||
| [x] | 전체 날씨 점수 기준 강화 — 100점은 '1년에 하루' 수준으로만 → 각과 같은 계산에 기준만 좁힘(체감 21±0.5°·습도 45~55%·해 90%↑·바람 1m/s↓·초미세먼지 10↓, 사용자 결정 '기준만 좁히기'). 실제 연 몇 번 나오는지는 미확인 (`docs/점수_계산식.md` 2) | 10/8 회의 결정 | `backend/services/index_service.py:203` |
|
||||
| [ ] | 각 점수를 아침·낮·저녁·밤 시간대별로 — 지금은 하루 중 가장 좋은 시간대 점수로 하루 고정이라 비가 와도 안 바뀜 | 10/8 회의 결정 | `backend/services/calc/index_calc.py:297` |
|
||||
| [ ] | 히어로에 습도·불쾌지수 항상 표시 — 지금은 상황별 두 칸이라 불쾌지수는 일정 수치 이상일 때만 | 10/8 회의 결정 | `frontend/src/b/TodayPage.tsx` (`HeroStat`) |
|
||||
| [ ] | 달 '밝기 %' 정의(밝기인지 보이는 면적인지) + 구름·달 모양 반영 산정 로직 | 10/8 회의 | `backend/services/calc/moon.py` |
|
||||
| [ ] | 노을: 하늘 상황 문구 대신 점수 강조(10/7 다시 기획에서 되돌림). 골든아워·블루아워 설명은 시간표 아래에 넣음 | 10/8 회의, 사용자 결정 | `frontend/src/b/SkyPage.tsx`, `backend/services/sky_service.py` |
|
||||
| [ ] | 주말 예보 UI 개선 — 회의에서 구체 내용 없음 | 10/8 회의 | `frontend/src/b/WeekPage.tsx` |
|
||||
| [ ] | AEO·SEO 메타데이터 + 구글·네이버 검색 등록 (금일 핵심 업무), 넣은 태그·키워드 정의서 작성, 매시간 갱신 콘텐츠 노출 방식 정리 → 대표 보고. 도메인은 별도 유지 | 10/8 회의 결정 | `frontend/index.html`, `docs/` |
|
||||
| [ ] | `docs/콘텐츠_구현기획.md` 2-1의 오늘 날씨 점수 식이 예전 기준(기온 40·비 30·바람 15·미세먼지 15) — 새 기준은 `docs/점수_계산식.md` | 점수 계산식 정리 중 발견 (10/8) | `docs/콘텐츠_구현기획.md` |
|
||||
@@ -183,6 +183,7 @@ class IndexDefinition(Base):
|
||||
limit_description: Mapped[Optional[str]] = mapped_column(String(200), nullable=True)
|
||||
sentences: Mapped[dict] = mapped_column(JSONB)
|
||||
sort_order: Mapped[int] = mapped_column(SmallInteger)
|
||||
priority: Mapped[int] = mapped_column(SmallInteger, default=2, server_default="2")
|
||||
|
||||
|
||||
class IndexScore(Base):
|
||||
@@ -205,6 +206,7 @@ class IndexScore(Base):
|
||||
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)
|
||||
slots: Mapped[dict] = mapped_column(JSONB, default=dict, server_default="{}")
|
||||
computed_at: Mapped[datetime] = mapped_column(DateTime(timezone=True))
|
||||
|
||||
|
||||
@@ -227,6 +229,9 @@ class Place(Base):
|
||||
reason: Mapped[str] = mapped_column(String(60))
|
||||
best_time: Mapped[str] = mapped_column(String(30))
|
||||
sort_order: Mapped[int] = mapped_column(SmallInteger, default=0)
|
||||
lat: Mapped[Optional[Decimal]] = mapped_column(Numeric(8, 5), nullable=True)
|
||||
lon: Mapped[Optional[Decimal]] = mapped_column(Numeric(8, 5), nullable=True)
|
||||
image_url: Mapped[Optional[str]] = mapped_column(String(500), nullable=True)
|
||||
|
||||
|
||||
class Event(Base):
|
||||
@@ -280,6 +285,8 @@ class Article(Base):
|
||||
show_from: Mapped[Optional[date]] = mapped_column(Date, nullable=True)
|
||||
show_until: Mapped[Optional[date]] = mapped_column(Date, nullable=True)
|
||||
sort_order: Mapped[int] = mapped_column(SmallInteger, default=0)
|
||||
image_url: Mapped[Optional[str]] = mapped_column(String(200), nullable=True)
|
||||
image_credit: Mapped[Optional[str]] = mapped_column(String(60), nullable=True)
|
||||
|
||||
|
||||
class Post(Base):
|
||||
@@ -288,6 +295,7 @@ class Post(Base):
|
||||
post_id: Mapped[int] = mapped_column(BigInteger, primary_key=True)
|
||||
feed_date: Mapped[date] = mapped_column(Date)
|
||||
position: Mapped[int] = mapped_column(SmallInteger)
|
||||
scope: Mapped[str] = mapped_column(String(2), default="00")
|
||||
post_type: Mapped[int] = mapped_column(SmallInteger)
|
||||
ref_type: Mapped[int] = mapped_column(SmallInteger, default=1)
|
||||
ref_id: Mapped[Optional[int]] = mapped_column(BigInteger, nullable=True)
|
||||
|
||||
@@ -29,7 +29,7 @@ class Settings(BaseSettings):
|
||||
data_go_kr_service_key: str = ""
|
||||
teams_webhook_url: str = ""
|
||||
# 공유 이미지용 사진 대신 받기를 허용할 호스트 (쉼표로 구분)
|
||||
image_proxy_hosts: str = "tong.visitkorea.or.kr,www.culture.go.kr"
|
||||
image_proxy_hosts: str = "tong.visitkorea.or.kr,www.culture.go.kr,culture.seoul.go.kr"
|
||||
|
||||
jwt_access_secret: str = ""
|
||||
jwt_refresh_secret: str = ""
|
||||
|
||||
@@ -9,13 +9,13 @@ from common.database.model.models import Post
|
||||
|
||||
|
||||
class FeedCRUD:
|
||||
async def day(self, s: AsyncSession, day: date) -> list[Post]:
|
||||
stmt = select(Post).where(Post.feed_date == day, Post.deleted.is_(False)).order_by(Post.position)
|
||||
async def day(self, s: AsyncSession, day: date, scopes: list[str]) -> list[Post]:
|
||||
stmt = select(Post).where(Post.feed_date == day, Post.scope.in_(scopes), Post.deleted.is_(False)).order_by(Post.position, Post.scope)
|
||||
return list((await s.scalars(stmt)).all())
|
||||
|
||||
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 positions(self, s: AsyncSession, day: date) -> set[tuple[str, int]]:
|
||||
"""그날 이미 만든 (scope, 카드 번호). 지운 카드도 넣어 다시 만들지 않게 한다."""
|
||||
return {(scope, pos) for scope, pos in (await s.execute(select(Post.scope, Post.position).where(Post.feed_date == day))).all()}
|
||||
|
||||
async def insert_day(self, s: AsyncSession, rows: list[dict]) -> None:
|
||||
if rows:
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
from datetime import date
|
||||
|
||||
from sqlalchemy import func, select
|
||||
from sqlalchemy import func, select, text
|
||||
from sqlalchemy.dialects.postgresql import insert
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
@@ -34,6 +34,13 @@ class IndexCRUD:
|
||||
stmt = select(func.min(IndexScore.computed_at)).where(IndexScore.region_code == region_code, IndexScore.score_date == day)
|
||||
return await s.scalar(stmt)
|
||||
|
||||
async def has_unslotted(self, s: AsyncSession, region_code: str, day: date) -> bool:
|
||||
"""그날 행 중 구간 점수가 비어 있는 행(구간 계산 전 행)이 있는지."""
|
||||
stmt = select(IndexScore.index_id).where(
|
||||
IndexScore.region_code == region_code, IndexScore.score_date == day, text("index_score.slots = '{}'::jsonb")
|
||||
).limit(1)
|
||||
return (await s.scalar(stmt)) is not None
|
||||
|
||||
async def upsert_scores(self, s: AsyncSession, rows: list[dict]) -> None:
|
||||
if not rows:
|
||||
return
|
||||
|
||||
@@ -26,14 +26,18 @@ class WeekCRUD:
|
||||
if rows:
|
||||
await s.execute(insert(Holiday).values(rows).on_conflict_do_nothing(index_elements=["holiday_date", "name"]))
|
||||
|
||||
async def places(self, s: AsyncSession, sido_code: str) -> list[Place]:
|
||||
stmt = select(Place).where(Place.region_code.startswith(sido_code)).order_by(Place.sort_order)
|
||||
async def places_in_box(self, s: AsyncSession, lat: float, lon: float, dlat: float, dlon: float) -> list[Place]:
|
||||
stmt = select(Place).where(Place.lat.between(lat - dlat, lat + dlat), Place.lon.between(lon - dlon, lon + dlon))
|
||||
return list((await s.scalars(stmt)).all())
|
||||
|
||||
async def all_places(self, s: AsyncSession) -> list[Place]:
|
||||
return list((await s.scalars(select(Place).where(Place.lat.is_not(None)))).all())
|
||||
|
||||
async def replace_places(self, s: AsyncSession, rows: list[dict]) -> None:
|
||||
await s.execute(delete(Place))
|
||||
if rows:
|
||||
await s.execute(insert(Place).values(rows))
|
||||
# asyncpg 는 한 문장에 인자 32767개까지라 나눠 넣는다.
|
||||
for i in range(0, len(rows), 1000):
|
||||
await s.execute(insert(Place).values(rows[i:i + 1000]))
|
||||
|
||||
async def events(self, s: AsyncSession, sido_codes: list[str], since: date, until: date) -> list[Event]:
|
||||
stmt = select(Event).where(Event.sido_code.in_(sido_codes), Event.end_date >= since, Event.start_date <= until)
|
||||
|
||||
@@ -153,12 +153,14 @@ CREATE TABLE IF NOT EXISTS public.index_score (
|
||||
zero_reason VARCHAR(100) NULL, -- 0점이 된 이유 (걸리지 않았으면 NULL)
|
||||
notes JSONB NOT NULL, -- 요소별 근거 문장 {"temp": "체감 21°, 편한 범위 18~24° 안", ...}
|
||||
estimated BOOLEAN NOT NULL DEFAULT false, -- 시간별 예보가 없어 중기예보로 낸 예상 점수
|
||||
slots JSONB NOT NULL DEFAULT '{}', -- 오늘만: 구간별 점수 {"morning"|"day"|"evening"|"night"|"early": {score, summary, factors, zero_reason, notes}}. 각 시간대와 안 겹치는 구간은 없음
|
||||
computed_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
PRIMARY KEY (region_code, score_date, index_id)
|
||||
);
|
||||
ALTER TABLE public.index_score ADD COLUMN IF NOT EXISTS uv_score SMALLINT NOT NULL DEFAULT 0;
|
||||
ALTER TABLE public.index_score ADD COLUMN IF NOT EXISTS sun_score SMALLINT NOT NULL DEFAULT 0;
|
||||
ALTER TABLE public.index_score ADD COLUMN IF NOT EXISTS view_score SMALLINT NOT NULL DEFAULT 0;
|
||||
ALTER TABLE public.index_score ADD COLUMN IF NOT EXISTS slots JSONB NOT NULL DEFAULT '{}';
|
||||
|
||||
-- 피드 카드. 매일 03:00 스케줄러가 그날 카드를 전부 만들고, 볼 때 시간대에 따라 켜고 끄고 순서를 정해 그 구 데이터로 채운다.
|
||||
CREATE TABLE IF NOT EXISTS public.post (
|
||||
@@ -175,7 +177,9 @@ CREATE TABLE IF NOT EXISTS public.post (
|
||||
end_at TIMESTAMPTZ NULL, -- NULL = 그날 끝까지
|
||||
deleted BOOLEAN NOT NULL DEFAULT FALSE
|
||||
);
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS uq_post_feed ON public.post (feed_date, position) WHERE deleted = FALSE;
|
||||
ALTER TABLE public.post ADD COLUMN IF NOT EXISTS scope VARCHAR(2) NOT NULL DEFAULT '00'; -- '00'=전국, 그 외 시도 코드(region.code 앞 2자리). 좋아요·댓글이 이 단위로 나뉜다
|
||||
DROP INDEX IF EXISTS public.uq_post_feed;
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS uq_post_feed_scope ON public.post (feed_date, position, scope) WHERE deleted = FALSE;
|
||||
|
||||
-- 사람·반응 (좋아요·저장·댓글은 로그인 필요, 보내기는 누구나)
|
||||
|
||||
@@ -286,11 +290,13 @@ CREATE TABLE IF NOT EXISTS public.index_definition (
|
||||
zero_rules JSONB NOT NULL DEFAULT '[]', -- 바로 0점 조건 [{"field": "rain_prob", "op": ">=", "value": 80}]. 화면 문장은 여기서 만든다
|
||||
limit_description VARCHAR(200) NULL, -- 반영 못 한 것
|
||||
sentences JSONB NOT NULL DEFAULT '{}', -- 문장 틀 {summary, headline, rabbit, bear, notes}
|
||||
sort_order SMALLINT NOT NULL DEFAULT 0
|
||||
sort_order SMALLINT NOT NULL DEFAULT 0,
|
||||
priority SMALLINT NOT NULL DEFAULT 2 -- 중요도: 1=상 2=중 3=하. 순위는 점수 × 가중치로 정한다
|
||||
);
|
||||
ALTER TABLE public.index_definition ADD COLUMN IF NOT EXISTS weight_uv SMALLINT NOT NULL DEFAULT 0;
|
||||
ALTER TABLE public.index_definition ADD COLUMN IF NOT EXISTS weight_sun SMALLINT NOT NULL DEFAULT 0;
|
||||
ALTER TABLE public.index_definition ADD COLUMN IF NOT EXISTS weight_view SMALLINT NOT NULL DEFAULT 0;
|
||||
ALTER TABLE public.index_definition ADD COLUMN IF NOT EXISTS priority SMALLINT NOT NULL DEFAULT 2;
|
||||
|
||||
-- 노을 명소.
|
||||
CREATE TABLE IF NOT EXISTS public.sunset_spot (
|
||||
@@ -303,18 +309,24 @@ CREATE TABLE IF NOT EXISTS public.sunset_spot (
|
||||
sort_order SMALLINT NOT NULL DEFAULT 0 -- 0 해 지는 쪽이 트인 곳(먼저), 1 그 밖
|
||||
);
|
||||
|
||||
-- 날씨 맞춤 데이트 명소 (주말·행사 탭).
|
||||
-- 날씨 맞춤 데이트 명소 (주말·행사 탭). 구 중심에서 가까운 곳을 고른다.
|
||||
CREATE TABLE IF NOT EXISTS public.place (
|
||||
place_id SERIAL PRIMARY KEY,
|
||||
region_code VARCHAR(10) NOT NULL,
|
||||
area VARCHAR(20) NOT NULL, -- 동네 묶음 ("성수", "연남·망원")
|
||||
area VARCHAR(20) NOT NULL, -- 동네 묶음 ("성수", "연남·망원") 또는 구 이름
|
||||
name VARCHAR(40) NOT NULL,
|
||||
is_outdoor BOOLEAN NOT NULL, -- 맑으면 야외, 비 오면 실내를 먼저
|
||||
icon VARCHAR(30) NOT NULL,
|
||||
reason VARCHAR(60) NOT NULL, -- "돗자리 펴고 낮 피크닉"
|
||||
best_time VARCHAR(30) NOT NULL, -- "낮 12시~4시"
|
||||
sort_order SMALLINT NOT NULL DEFAULT 0
|
||||
sort_order SMALLINT NOT NULL DEFAULT 0,
|
||||
lat NUMERIC(8,5) NULL, -- 시드가 늘 채운다
|
||||
lon NUMERIC(8,5) NULL,
|
||||
image_url VARCHAR(500) NULL -- TourAPI firstimage
|
||||
);
|
||||
ALTER TABLE public.place ADD COLUMN IF NOT EXISTS lat NUMERIC(8,5) NULL;
|
||||
ALTER TABLE public.place ADD COLUMN IF NOT EXISTS lon NUMERIC(8,5) NULL;
|
||||
ALTER TABLE public.place ADD COLUMN IF NOT EXISTS image_url VARCHAR(500) NULL;
|
||||
|
||||
-- 축제·행사.
|
||||
CREATE TABLE IF NOT EXISTS public.event (
|
||||
@@ -374,5 +386,9 @@ CREATE TABLE IF NOT EXISTS public.article (
|
||||
body JSONB NOT NULL, -- 문단 목록
|
||||
show_from DATE NULL, -- 계절 소식이 보이는 기간 (NULL = 늘)
|
||||
show_until DATE NULL,
|
||||
sort_order SMALLINT NOT NULL DEFAULT 0
|
||||
sort_order SMALLINT NOT NULL DEFAULT 0,
|
||||
image_url VARCHAR(200) NULL, -- 사진 (frontend/public/season/, NULL = 아이콘)
|
||||
image_credit VARCHAR(60) NULL -- 사진 출처 표기 ("ⓒ저작자 · CC BY-SA 4.0"), 표기가 필요 없으면 NULL
|
||||
);
|
||||
ALTER TABLE public.article ADD COLUMN IF NOT EXISTS image_url VARCHAR(200) NULL;
|
||||
ALTER TABLE public.article ADD COLUMN IF NOT EXISTS image_credit VARCHAR(60) NULL;
|
||||
@@ -131,6 +131,7 @@ class TopIndex(WebPacketProtocol):
|
||||
score: int
|
||||
rank: int
|
||||
summary: Optional[str] = None
|
||||
active: bool = Field(default=True, description="지금 구간이 이 각의 시간대와 겹침. false 면 순위 밖, score 는 하루 점수")
|
||||
|
||||
|
||||
class HeroStat(WebPacketProtocol):
|
||||
@@ -171,6 +172,8 @@ class BandArticle(WebPacketProtocol):
|
||||
title: str
|
||||
meta: str
|
||||
icon: str
|
||||
image: Optional[str] = None
|
||||
image_credit: Optional[str] = None
|
||||
|
||||
|
||||
class Bands(WebPacketProtocol):
|
||||
|
||||
@@ -5,7 +5,8 @@ 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, ScoreBand, TrendPoint
|
||||
from router.v1.index.protocol import Factor, IndexSummary, Res_IndexDetail, Res_IndexList, ScoreBand, SlotPoint, TrendPoint
|
||||
from services.calc.day_slot import SLOT_LABEL
|
||||
from services.calc.index_calc import AXES, axis_label, zero_rules_text
|
||||
from services.index_service import IndexItem, IndexService, slot_label
|
||||
|
||||
@@ -18,10 +19,11 @@ def _summary(i: IndexItem, today: date) -> IndexSummary:
|
||||
index_id=d.index_id, code=d.code, name=d.name, icon=d.icon, category=IndexCategory(d.category), is_fun=d.is_fun,
|
||||
is_core=d.is_core, score=i.score.score, rank=i.rank, summary=i.score.summary,
|
||||
trend=[TrendPoint(day=t.score_date, label=slot_label(t.score_date, today), score=t.score, estimated=t.estimated) for t in i.trend],
|
||||
active=i.active, slot=i.slot, slots=[SlotPoint(slot=k, label=SLOT_LABEL[k], score=v) for k, v in i.slots.items()],
|
||||
)
|
||||
|
||||
|
||||
@router.get("/list", response_model=Res_IndexList, response_model_exclude_none=True, summary="지수 목록 (점수순, 1~3위, 오늘 날씨 점수)")
|
||||
@router.get("/list", response_model=Res_IndexList, response_model_exclude_none=True, summary="지수 목록 (지금 구간 점수순, 1~3위, 지금 날씨 점수)")
|
||||
async def list_indices(
|
||||
region: str = Query(..., description="구 행정코드"),
|
||||
category: Optional[IndexCategory] = Query(None),
|
||||
@@ -32,8 +34,9 @@ async def list_indices(
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return Res_IndexList(result=error_info(err))
|
||||
items = [_summary(i, board.day) for i in board.items]
|
||||
top3 = [_summary(i, board.day) for i in board.ranked[:3]]
|
||||
filtered = [x for x in items if (category is None or x.category is category) and (not core or x.is_core)]
|
||||
return Res_IndexList(region_code=board.region.code, day=board.day, weather_score=board.weather_score, top3=items[:3], items=filtered)
|
||||
return Res_IndexList(region_code=board.region.code, day=board.day, weather_score=board.weather_score, top3=top3, items=filtered)
|
||||
|
||||
|
||||
@router.get("/{index_id}", response_model=Res_IndexDetail, response_model_exclude_none=True, summary="지수 계산 근거")
|
||||
|
||||
@@ -14,6 +14,12 @@ class TrendPoint(WebPacketProtocol):
|
||||
estimated: bool = Field(description="시간별 예보가 없어 중기예보로 낸 예상 점수")
|
||||
|
||||
|
||||
class SlotPoint(WebPacketProtocol):
|
||||
slot: str = Field(description="morning / day / evening / night")
|
||||
label: str = Field(description="아침 / 낮 / 저녁 / 밤")
|
||||
score: int
|
||||
|
||||
|
||||
class IndexSummary(WebPacketProtocol):
|
||||
index_id: int
|
||||
code: str
|
||||
@@ -26,12 +32,15 @@ class IndexSummary(WebPacketProtocol):
|
||||
rank: int
|
||||
summary: str
|
||||
trend: list[TrendPoint] = []
|
||||
active: bool = Field(default=True, description="지금 구간이 이 각의 시간대와 겹침. false 면 순위 밖, score 는 하루 점수")
|
||||
slot: Optional[str] = Field(default=None, description="score 가 어느 구간 점수인지 (지금 구간)")
|
||||
slots: list[SlotPoint] = Field(default=[], description="오늘 구간별 점수. 각 시간대와 안 겹치는 구간은 없음")
|
||||
|
||||
|
||||
class Res_IndexList(Res_WebPacketProtocol):
|
||||
region_code: Optional[str] = None
|
||||
day: Optional[date] = None
|
||||
weather_score: Optional[int] = None
|
||||
weather_score: Optional[int] = Field(default=None, description="지금 날씨 점수 (지금 구간 기준)")
|
||||
top3: list[IndexSummary] = []
|
||||
items: list[IndexSummary] = []
|
||||
|
||||
|
||||
@@ -17,6 +17,8 @@ class ArticleSummary(WebPacketProtocol):
|
||||
title: str
|
||||
read_minutes: int
|
||||
icon: str
|
||||
image: Optional[str] = None # 있으면 아이콘 대신 사진
|
||||
image_credit: Optional[str] = None # 사진 출처 표기 ("ⓒ저작자 · CC BY-SA 4.0")
|
||||
|
||||
|
||||
class Res_SeasonWeek(Res_WebPacketProtocol):
|
||||
|
||||
@@ -12,7 +12,8 @@ router = APIRouter(prefix="/v1/season", tags=["season"])
|
||||
|
||||
|
||||
def _summary(a: Article) -> ArticleSummary:
|
||||
return ArticleSummary(article_id=a.article_id, code=a.code, category=ArticleCategory(a.category), title=a.title, read_minutes=a.read_minutes, icon=a.icon)
|
||||
return ArticleSummary(article_id=a.article_id, code=a.code, category=ArticleCategory(a.category), title=a.title, read_minutes=a.read_minutes, icon=a.icon,
|
||||
image=a.image_url, image_credit=a.image_credit)
|
||||
|
||||
|
||||
@router.get("/week", response_model=Res_SeasonWeek, response_model_exclude_none=True, summary="이번 주 계절 책: 시, 절기, 계절 소식")
|
||||
|
||||
@@ -97,7 +97,7 @@ async def get_watch_summary(
|
||||
res.warning = now_w.warnings[0].text if now_w.warnings else None
|
||||
|
||||
if board is not None:
|
||||
res.top = [_top(i) for i in board.items[:TOP_N]]
|
||||
res.top = [_top(i) for i in board.ranked[:TOP_N]]
|
||||
codes = [c.strip() for c in (pick or "").split(",") if c.strip()][:MAX_PICKS]
|
||||
by_code = {i.definition.code: i for i in board.items}
|
||||
res.picks = [_top(by_code[c]) for c in codes if c in by_code]
|
||||
|
||||
@@ -32,6 +32,9 @@ class PlaceData(WebPacketProtocol):
|
||||
reason: str
|
||||
best_time: str
|
||||
is_good: bool
|
||||
distance_km: float # 구 중심에서 떨어진 거리
|
||||
image: Optional[str] = None
|
||||
image_credit: Optional[str] = None # 사진 출처 표기 ("ⓒ한국관광공사")
|
||||
|
||||
|
||||
class Res_PlaceList(Res_WebPacketProtocol):
|
||||
|
||||
@@ -9,7 +9,7 @@ from common.utils.kma_time import now_kst
|
||||
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.week_service import WeekService, image_credit, place_credit
|
||||
from services.weekend_rank import WeekendRank, rank_days, weekend_days
|
||||
|
||||
router = APIRouter(prefix="/v1/week", tags=["week"])
|
||||
@@ -45,20 +45,20 @@ async def get_week_ranking() -> Res_WeekRanking:
|
||||
])
|
||||
|
||||
|
||||
@router.get("/place/list", response_model=Res_PlaceList, response_model_exclude_none=True, summary="날씨 맞춤 데이트 명소")
|
||||
@router.get("/place/list", response_model=Res_PlaceList, response_model_exclude_none=True, summary="날씨 맞춤 데이트 명소 (구 중심 30km 안, 없으면 가장 가까운 곳)")
|
||||
async def list_places(
|
||||
region: str = Query(...), day: Optional[date] = Query(None, description="기본은 오늘"), area: Optional[str] = Query(None),
|
||||
service: WeekService = Depends(),
|
||||
) -> Res_PlaceList:
|
||||
target = day or now_kst().date()
|
||||
err, items, areas = await service.places(region, target, area)
|
||||
err, items, areas, rainy = await service.places(region, target, area)
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return Res_PlaceList(result=error_info(err))
|
||||
rainy = any(not i.place.is_outdoor and i.is_good for i in items)
|
||||
return Res_PlaceList(areas=areas, rainy=rainy, places=[
|
||||
PlaceData(
|
||||
place_id=i.place.place_id, area=i.place.area, name=i.place.name, is_outdoor=i.place.is_outdoor, icon=i.place.icon,
|
||||
reason=i.place.reason, best_time=i.place.best_time, is_good=i.is_good,
|
||||
reason=i.place.reason, best_time=i.place.best_time, is_good=i.is_good, distance_km=i.distance_km,
|
||||
image=i.place.image_url, image_credit=place_credit(i.place),
|
||||
)
|
||||
for i in items
|
||||
])
|
||||
|
||||
@@ -21,10 +21,10 @@ from services.external.culture_api import SIDO_NAME
|
||||
from services.external.data_go_kr import DataGoKrNotConfigured, DataGoKrRequestFailed
|
||||
from services.external.open_meteo import OpenMeteoRequestFailed, fetch_weather, parse_weather
|
||||
from services.feed_service import build_feed_day, clear_feed_cache
|
||||
from services.week_service import collect_events
|
||||
from services.week_service import collect_events, drop_known
|
||||
from services.weekend_rank import WeekendRank
|
||||
|
||||
_POPGA_SEEN = "popga:lastmod" # {팝업 id: 마지막으로 읽은 lastmod}, 바뀐 페이지만 다시 읽는다
|
||||
_POPGA_SEEN = "popga:lastmod:v2" # {팝업 id: 마지막으로 읽은 lastmod}, 바뀐 페이지만 다시 읽는다. 받는 분류가 바뀌면 이름을 바꿔 처음부터 읽는다
|
||||
_POPGA_BATCH = 100
|
||||
EVENTS_DONE = "events:collected" # 행사 수집을 마친 표시. 7일 유지, 없으면 worker 가 켜질 때 한 번 돈다
|
||||
_EVENTS_TTL_SEC = 7 * 86400
|
||||
@@ -98,13 +98,14 @@ async def refresh_openmeteo_weather() -> ErrorType:
|
||||
|
||||
|
||||
async def build_today_feed() -> ErrorType:
|
||||
"""그날 전국 공통 피드 칸을 넣고, 구별 피드 캐시를 비운다."""
|
||||
err = await build_feed_day(now_kst().date(), FeedCRUD(), SeasonCRUD())
|
||||
"""그날 피드 칸(전국·시도별)을 넣고, 구별 피드 캐시를 비운다."""
|
||||
err = await build_feed_day(now_kst().date(), FeedCRUD(), SeasonCRUD(), RegionCRUD())
|
||||
await clear_feed_cache()
|
||||
return err
|
||||
|
||||
|
||||
async def _save_popups(rows: list[dict], seen: dict[str, str]) -> ErrorType:
|
||||
rows = await drop_known(rows)
|
||||
err = await DB_SESSION_MNG.execute_lambda_run([lambda s: WeekCRUD().upsert_events(s, rows)])
|
||||
if err is ErrorType.SUCCESS and seen:
|
||||
await REDIS.conn.hset(_POPGA_SEEN, mapping=seen)
|
||||
@@ -147,7 +148,7 @@ async def refresh_popups() -> ErrorType:
|
||||
|
||||
|
||||
async def _popup_count() -> int:
|
||||
q = text("SELECT count(*) FROM public.event WHERE source_id LIKE 'popga:%' AND end_date >= (now() AT TIME ZONE 'Asia/Seoul')::date")
|
||||
q = text("SELECT count(*) FROM public.event WHERE source_id LIKE 'popga:%' AND kind = 4 AND end_date >= (now() AT TIME ZONE 'Asia/Seoul')::date")
|
||||
err, n = await DB_SESSION_MNG.execute_lambda(lambda s: s.scalar(q))
|
||||
return n if err is ErrorType.SUCCESS and n is not None else 0
|
||||
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
"""TourAPI 분류(lclsSystm3)에서 데이트에 맞는 관광지를 전국으로 모아 seed/place_tourapi.csv 로 쓴다 (일회성, 다시 돌리면 덮어씀).
|
||||
|
||||
손으로 고른 seed/place.csv 와 같은 곳(contentid)은 뺀다.
|
||||
실행: docker exec o2o-weather-backend-1 python scripts/fetch_date_places.py
|
||||
"""
|
||||
import asyncio
|
||||
import csv
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
|
||||
import httpx # noqa: E402
|
||||
|
||||
from common.utils.geo import haversine_km # noqa: E402
|
||||
from scripts.load_seed import SEED_DIR, read_regions # noqa: E402
|
||||
from services.external.data_go_kr import get_all_items # noqa: E402
|
||||
|
||||
LIST_URL = "https://apis.data.go.kr/B551011/KorService2/areaBasedList2"
|
||||
OUT = os.path.join(SEED_DIR, "place_tourapi.csv")
|
||||
_BASE = {"_type": "json", "MobileOS": "ETC", "MobileApp": "nalssigak", "arrange": "A"}
|
||||
# lclsSystm3 → (야외, 아이콘, 한 줄 이유, 추천 시간). 이유는 분류에서 나오는 말만 쓴다.
|
||||
CATEGORIES = {
|
||||
"VE030100": (True, "picnic", "공원 산책·피크닉", "낮 12시~4시"),
|
||||
"VE010200": (True, "stars", "전망대에서 보는 경치·야경", "해 진 뒤"),
|
||||
"VE010300": (True, "stars", "다리 위 야경 산책", "해 진 뒤"),
|
||||
"VE040300": (True, "walk", "둘레길 함께 걷기", "선선한 오후"),
|
||||
"NA010200": (True, "walk", "숲길 산책", "오전 10시~"),
|
||||
"NA020200": (True, "walk", "호숫가 산책", "선선한 저녁"),
|
||||
"NA040700": (True, "garden", "수목원·정원 꽃길 산책", "오전 10시~"),
|
||||
"VE040100": (True, "photo", "골목·카페거리 구경", "오후 2시~"),
|
||||
"NA020900": (True, "sunset", "바닷가 산책", "노을 무렵"),
|
||||
"VE020400": (False, "rain", "비 와도 실내 아쿠아리움", "비 오는 오후"),
|
||||
"VE070600": (False, "bulb", "비 오면 미술관으로", "비 오는 날"),
|
||||
}
|
||||
FIELDS = ["source", "region_name", "area", "name", "is_outdoor", "icon", "reason", "best_time", "lat", "lon", "image_url"]
|
||||
|
||||
|
||||
def _clean(text: str) -> str:
|
||||
return re.sub(r"\s+", " ", text or "").strip()
|
||||
|
||||
|
||||
def _manual_ids() -> set[str]:
|
||||
with open(os.path.join(SEED_DIR, "place.csv"), encoding="utf-8") as f:
|
||||
return {r["source"].removeprefix("tourapi:") for r in csv.DictReader(f) if r["source"].startswith("tourapi:")}
|
||||
|
||||
|
||||
async def main() -> int:
|
||||
regions = read_regions()
|
||||
skip = _manual_ids()
|
||||
rows: dict[str, dict] = {}
|
||||
async with httpx.AsyncClient(timeout=30) as client:
|
||||
for code, (outdoor, icon, reason, best_time) in CATEGORIES.items():
|
||||
params = {**_BASE, "lclsSystm1": code[:2], "lclsSystm2": code[:4], "lclsSystm3": code}
|
||||
items = await get_all_items(client, LIST_URL, params, page_size=500)
|
||||
kept = 0
|
||||
for it in items:
|
||||
cid, title = str(it["contentid"]), _clean(it.get("title", ""))
|
||||
if cid in skip or cid in rows or not title or not it.get("mapx") or not it.get("mapy"):
|
||||
continue
|
||||
lat, lon = round(float(it["mapy"]), 5), round(float(it["mapx"]), 5)
|
||||
if not (33 <= lat <= 39 and 124 <= lon <= 132):
|
||||
print(f"skip {cid} {title}: 좌표가 국내 밖 ({lat}, {lon})")
|
||||
continue
|
||||
near = min(regions, key=lambda r: haversine_km(lat, lon, r["lat"], r["lon"]))
|
||||
rows[cid] = {
|
||||
"source": f"tourapi:{cid}", "region_name": near["name"], "area": near["short_name"], "name": title[:60],
|
||||
"is_outdoor": int(outdoor), "icon": icon, "reason": reason, "best_time": best_time, "lat": lat, "lon": lon,
|
||||
"image_url": (it.get("firstimage") or "").replace("http://", "https://", 1),
|
||||
}
|
||||
kept += 1
|
||||
print(f"{code}: {len(items)} -> {kept}")
|
||||
out = sorted(rows.values(), key=lambda r: (r["region_name"], r["name"]))
|
||||
with open(OUT, "w", encoding="utf-8", newline="") as f:
|
||||
w = csv.DictWriter(f, fieldnames=FIELDS)
|
||||
w.writeheader()
|
||||
w.writerows(out)
|
||||
print(f"place {len(out)} -> {OUT}")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(asyncio.run(main()))
|
||||
@@ -1,11 +1,17 @@
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
|
||||
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
sys.path.insert(0, ROOT)
|
||||
|
||||
from services.calc.index_calc import PRIORITY_WEIGHT # noqa: E402
|
||||
|
||||
SEED = os.path.join(ROOT, "seed", "index_definition.json")
|
||||
OUT = os.path.join(os.path.dirname(ROOT), "docs", "각_계산기준.md")
|
||||
|
||||
CAT = {1: "밖에서 놀기", 2: "먹고 마시기", 3: "집안일", 4: "생활 고민"}
|
||||
PRIO = {1: "상", 2: "중", 3: "하"}
|
||||
WD = {"mon": "월", "tue": "화", "wed": "수", "thu": "목", "fri": "금", "sat": "토", "sun": "일", "holiday": "공휴일", "default": "그 외"}
|
||||
FIELD = {"rain_prob": ("비 확률", "%"), "wind_ms": ("바람", "m/s"), "feels_c": ("체감", "°"), "pm25": ("초미세먼지", "㎍/㎥"), "cloudy_ratio": ("흐린 시간 비율", "%"), "gust_ms": ("돌풍", "m/s"), "ground_c": ("지면 온도", "°")}
|
||||
|
||||
@@ -70,7 +76,13 @@ def zero(z):
|
||||
return s + (f" 최대 {z['cap']}점" if "cap" in z else " 0점")
|
||||
|
||||
|
||||
AX = [("temp", "기온", temp), ("rain", "비", rain), ("wind", "바람", wind), ("humidity", "습도", hum), ("air", "미세먼지", None),
|
||||
def air(r):
|
||||
if r["full"] > r["zero"]:
|
||||
return f"초미세먼지 높을수록 좋음 ({r['zero']}㎍/㎥=0점 → {r['full']}㎍/㎥=100점)"
|
||||
return "초미세먼지 낮을수록 좋음"
|
||||
|
||||
|
||||
AX = [("temp", "기온", temp), ("rain", "비", rain), ("wind", "바람", wind), ("humidity", "습도", hum), ("air", "미세먼지", air),
|
||||
("uv", "자외선", lambda r: f"자외선 {r['full']} 이하면 만점, {r['zero']} 이상이면 0점 (Open-Meteo)"),
|
||||
("sun", "햇빛", lambda r: f"해 난 비율 {round(r['full'] * 100)}% 이상이면 만점, {round(r['zero'] * 100)}% 이하면 0점 (Open-Meteo)"),
|
||||
("view", "가시거리", lambda r: f"{r['full']}km 이상이면 만점, {r['zero']}km 이하면 0점 (Open-Meteo)"),
|
||||
@@ -91,27 +103,28 @@ def main() -> None:
|
||||
P("- 최종 점수 = 비중대로 섞은 점수 × (0.75 + 0.25 × 가장 낮은 요소 점수 ÷ 100). 비중 0%인 요소는 '가장 낮은 요소'에서 뺍니다. 가장 낮은 요소가 0점이면 25%가 깎입니다.")
|
||||
P("- '0점 조건'에 걸리면 0점, '최대 N점' 조건에 걸리면 N점을 넘지 못합니다.")
|
||||
P("- 시간대가 여러 개면 그중 가장 좋은 시간대 점수를 씁니다.")
|
||||
P("- 미세먼지는 모든 각이 같은 규칙입니다: 초미세먼지 15㎍/㎥ 이하 100점 → 75㎍/㎥ 이상 0점.")
|
||||
P("- 바람·미세먼지·노을 정보가 없으면 70점으로 둡니다.\n")
|
||||
P("- 미세먼지는 초미세먼지 15㎍/㎥ 이하 100점 → 75㎍/㎥ 이상 0점입니다. 집콕각처럼 규칙을 따로 적은 각만 거꾸로(탁할수록 좋음) 셉니다.")
|
||||
P("- 바람·미세먼지·노을 정보가 없으면 70점으로 둡니다.")
|
||||
P("- 순위는 점수 × 중요도 가중치(" + " · ".join(f"{PRIO[k]} {v}" for k, v in PRIORITY_WEIGHT.items()) + ")로 정합니다. 화면에 보이는 점수는 그대로입니다.\n")
|
||||
P("## 한눈에 보기\n")
|
||||
P("| 순서 | 각 | 코드 | 분류 | 시간대 | 기온 | 비 | 바람 | 습도 | 미세먼지 | 시간 | 재미 각 | 계절 핵심 |")
|
||||
P("|---:|---|---|---|---|---:|---:|---:|---:|---:|---:|:---:|:---:|")
|
||||
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'])} | "
|
||||
P(f"| {x['sort_order']} | {x['name']} | `{x['code']}` | {CAT[x['category']]} | {PRIO[x['priority']]} | {' / '.join(win(w) for w in x['windows'])} | "
|
||||
+ " | ".join(f"{x['weight_' + a]}%" for a in ("temp", "rain", "wind", "humidity", "air", "time"))
|
||||
+ 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"- 분류: {CAT[x['category']]} · 중요도 {PRIO[x['priority']]} · 아이콘 `{x['icon']}` · 재미 각 {'예' if x['is_fun'] else '아니오'} · 계절 핵심 {'예' if x['is_core'] else '아니오'} · 계산 근거 화면 {'있음' if x['has_detail'] else '없음'}")
|
||||
P(f"- 시간대: {' / '.join(win(w) for w in x['windows'])}")
|
||||
P("- 요소별 규칙 (비중):")
|
||||
for key, label, fn in AX:
|
||||
w = x.get("weight_" + key, 0)
|
||||
if key in _OPTIONAL and not w:
|
||||
continue
|
||||
rule = "초미세먼지 낮을수록 좋음" if fn is None else fn(x["factor_rules"][key])
|
||||
rule = fn(x["factor_rules"].get(key, {"zero": 75, "full": 15}))
|
||||
P(f" - {label} {w}%: {rule}")
|
||||
zs = [zero(z) for z in x["zero_rules"]]
|
||||
P(f"- 점수 깎이는 조건: {', '.join(zs) if zs else '없음'}")
|
||||
|
||||
@@ -56,10 +56,12 @@ async def main() -> int:
|
||||
"lat": float(r["lat"]), "lon": float(r["lon"]), "sort_order": 0 if r["west_open"] == "1" else 1}
|
||||
for r in _read("sunset_spot.csv")
|
||||
]
|
||||
# 손으로 고른 place.csv 와 TourAPI 에서 모은 place_tourapi.csv (scripts/fetch_date_places.py). source 는 출처 기록용.
|
||||
places = [
|
||||
{"region_code": code_by_name[r["region_name"]], "area": r["area"], "name": r["name"], "is_outdoor": r["is_outdoor"] == "1",
|
||||
"icon": r["icon"], "reason": r["reason"], "best_time": r["best_time"], "sort_order": int(r["sort_order"])}
|
||||
for r in _read("place.csv")
|
||||
"icon": r["icon"], "reason": r["reason"], "best_time": r["best_time"], "sort_order": int(r.get("sort_order") or 0),
|
||||
"lat": float(r["lat"]), "lon": float(r["lon"]), "image_url": r.get("image_url") or None}
|
||||
for r in _read("place.csv") + _read("place_tourapi.csv")
|
||||
]
|
||||
# 직접 넣는 행사 (TourAPI 에 없는 것). source_id 가 없는 줄만 이 파일로 바꿔 넣는다.
|
||||
events = [
|
||||
@@ -70,7 +72,8 @@ async def main() -> int:
|
||||
]
|
||||
articles = [
|
||||
{**a, "show_from": date.fromisoformat(a["show_from"]) if a["show_from"] else None,
|
||||
"show_until": date.fromisoformat(a["show_until"]) if a["show_until"] else None}
|
||||
"show_until": date.fromisoformat(a["show_until"]) if a["show_until"] else None,
|
||||
"image_url": a.get("image_url"), "image_credit": a.get("image_credit")}
|
||||
for a in _json("article.json")
|
||||
]
|
||||
weeks = _json("season_week.json")
|
||||
|
||||
@@ -5,6 +5,8 @@
|
||||
"title": "설악산 첫 단풍, 절정은 언제?",
|
||||
"read_minutes": 3,
|
||||
"icon": "maple",
|
||||
"image_url": "/season/maple.jpg",
|
||||
"image_credit": "ⓒJoycekim77 · CC BY-SA 3.0",
|
||||
"show_from": "2026-09-20",
|
||||
"show_until": "2026-10-25",
|
||||
"body": [
|
||||
@@ -20,6 +22,8 @@
|
||||
"title": "하늘공원 억새가 반짝이는 시간",
|
||||
"read_minutes": 2,
|
||||
"icon": "sheaf",
|
||||
"image_url": "/season/reed.jpg",
|
||||
"image_credit": "ⓒJocelyndurrey · CC BY-SA 4.0",
|
||||
"show_from": "2026-09-25",
|
||||
"show_until": "2026-10-31",
|
||||
"body": [
|
||||
@@ -34,6 +38,8 @@
|
||||
"title": "대관령 첫서리, 서울은 한 달 뒤",
|
||||
"read_minutes": 2,
|
||||
"icon": "snow",
|
||||
"image_url": "/season/frost.jpg",
|
||||
"image_credit": "ⓒSally V · CC BY-SA 4.0",
|
||||
"show_from": "2026-10-01",
|
||||
"show_until": "2026-11-15",
|
||||
"body": [
|
||||
@@ -77,6 +83,7 @@
|
||||
"title": "노을은 왜 해 지고 15분 뒤가 더 붉을까?",
|
||||
"read_minutes": 3,
|
||||
"icon": "sunset",
|
||||
"image_url": "/season/sunset.jpg",
|
||||
"show_from": null,
|
||||
"show_until": null,
|
||||
"body": [
|
||||
@@ -91,6 +98,7 @@
|
||||
"title": "비 확률 30%면 우산을 챙겨야 할까?",
|
||||
"read_minutes": 2,
|
||||
"icon": "umbrella",
|
||||
"image_url": "/season/umbrella.jpg",
|
||||
"show_from": null,
|
||||
"show_until": null,
|
||||
"body": [
|
||||
@@ -251,6 +259,7 @@
|
||||
"title": "햇밤, 바로 먹을까 두었다 먹을까?",
|
||||
"read_minutes": 2,
|
||||
"icon": "chestnut",
|
||||
"image_url": "/season/chestnut_new.jpg",
|
||||
"show_from": "2026-09-15",
|
||||
"show_until": "2026-10-31",
|
||||
"body": [
|
||||
@@ -281,6 +290,8 @@
|
||||
"title": "은행 냄새 나는 길, 언제까지일까",
|
||||
"read_minutes": 2,
|
||||
"icon": "fallen_leaf",
|
||||
"image_url": "/season/ginkgo.jpg",
|
||||
"image_credit": "ⓒKorea.net · CC BY-SA 2.0",
|
||||
"show_from": "2026-10-10",
|
||||
"show_until": "2026-11-15",
|
||||
"body": [
|
||||
@@ -296,6 +307,8 @@
|
||||
"title": "군고구마가 생각나는 첫 추위",
|
||||
"read_minutes": 2,
|
||||
"icon": "sweet_potato",
|
||||
"image_url": "/season/sweet_potato.jpg",
|
||||
"image_credit": "ⓒ국립국어원 · CC BY-SA 2.0 KR",
|
||||
"show_from": "2026-10-15",
|
||||
"show_until": "2026-12-31",
|
||||
"body": [
|
||||
@@ -311,6 +324,7 @@
|
||||
"title": "노지 귤이 나오기 시작해요",
|
||||
"read_minutes": 2,
|
||||
"icon": "tangerine",
|
||||
"image_url": "/season/tangerine.jpg",
|
||||
"show_from": "2026-10-20",
|
||||
"show_until": "2026-12-31",
|
||||
"body": [
|
||||
@@ -326,6 +340,8 @@
|
||||
"title": "부사 사과가 나오는 때",
|
||||
"read_minutes": 2,
|
||||
"icon": "apple",
|
||||
"image_url": "/season/apple_fuji.jpg",
|
||||
"image_credit": "ⓒAomorikuma · CC BY-SA 4.0",
|
||||
"show_from": "2026-10-20",
|
||||
"show_until": "2026-11-30",
|
||||
"body": [
|
||||
@@ -341,6 +357,7 @@
|
||||
"title": "김장, 언제 하면 좋을까?",
|
||||
"read_minutes": 2,
|
||||
"icon": "kimchi",
|
||||
"image_url": "/season/kimjang.jpg",
|
||||
"show_from": "2026-11-01",
|
||||
"show_until": "2026-12-15",
|
||||
"body": [
|
||||
|
||||
@@ -70,7 +70,8 @@
|
||||
"60": "꽤 괜찮은 저녁! 바람만 살랑 불어 주면 딱이에요.",
|
||||
"80": "18~24°에 바람 살랑, 비 걱정 없음! 오늘은 무조건 바깥 자리 🍻"
|
||||
},
|
||||
"sort_order": 1
|
||||
"sort_order": 1,
|
||||
"priority": 2
|
||||
},
|
||||
{
|
||||
"code": "picnic",
|
||||
@@ -146,7 +147,8 @@
|
||||
"60": "돗자리 펴기 괜찮은 날! 바람막이 하나면 완벽해요.",
|
||||
"80": "20~26°에 바람 잔잔, 김밥 싸서 당장 출발! 🧺"
|
||||
},
|
||||
"sort_order": 2
|
||||
"sort_order": 2,
|
||||
"priority": 1
|
||||
},
|
||||
{
|
||||
"code": "chimaek",
|
||||
@@ -218,7 +220,8 @@
|
||||
"60": "바깥 테이블 괜찮아요! 얇은 겉옷 하나만 챙겨요.",
|
||||
"80": "20~27°의 선선한 저녁, 치킨에 맥주 부르는 날 🍗"
|
||||
},
|
||||
"sort_order": 3
|
||||
"sort_order": 3,
|
||||
"priority": 2
|
||||
},
|
||||
{
|
||||
"code": "walk",
|
||||
@@ -288,7 +291,8 @@
|
||||
"60": "한 바퀴 돌기 좋은 저녁! 이어폰 챙겨서 가볍게 나가요.",
|
||||
"80": "15~23°에 공기 맑고 바람 살랑, 동네 한 바퀴 무조건 🚶"
|
||||
},
|
||||
"sort_order": 4
|
||||
"sort_order": 4,
|
||||
"priority": 1
|
||||
},
|
||||
{
|
||||
"code": "vent",
|
||||
@@ -363,7 +367,8 @@
|
||||
"60": "열어도 괜찮아요. 맞바람 나게 10분이면 충분!",
|
||||
"80": "공기 맑고 바람도 적당, 창문 활짝 열 시간 🌬️"
|
||||
},
|
||||
"sort_order": 5
|
||||
"sort_order": 5,
|
||||
"priority": 3
|
||||
},
|
||||
{
|
||||
"code": "hiking",
|
||||
@@ -449,7 +454,8 @@
|
||||
"60": "오를 만해요! 바람막이 챙기고 일찍 출발해요.",
|
||||
"80": "산 위도 선선하고 바람 잔잔, 정상 인증각 ⛰️"
|
||||
},
|
||||
"sort_order": 6
|
||||
"sort_order": 6,
|
||||
"priority": 1
|
||||
},
|
||||
{
|
||||
"code": "carwash",
|
||||
@@ -521,7 +527,8 @@
|
||||
"60": "세차해도 괜찮아요. 먼지는 좀 붙을 수 있어요.",
|
||||
"80": "비 걱정 없고 공기도 맑아요. 반짝반짝 오래가는 날 ✨"
|
||||
},
|
||||
"sort_order": 7
|
||||
"sort_order": 7,
|
||||
"priority": 3
|
||||
},
|
||||
{
|
||||
"code": "camping",
|
||||
@@ -595,7 +602,8 @@
|
||||
"60": "하룻밤 괜찮아요. 새벽엔 쌀쌀하니 담요 챙기기!",
|
||||
"80": "밤새 12~22°에 바람 잔잔, 불멍하기 딱 좋은 밤 🔥"
|
||||
},
|
||||
"sort_order": 8
|
||||
"sort_order": 8,
|
||||
"priority": 1
|
||||
},
|
||||
{
|
||||
"code": "running",
|
||||
@@ -666,7 +674,8 @@
|
||||
"60": "뛸 만해요! 아침·저녁 중 시원한 쪽 고르기.",
|
||||
"80": "8~18°에 공기 보송, 기록 갱신각 🏃"
|
||||
},
|
||||
"sort_order": 9
|
||||
"sort_order": 9,
|
||||
"priority": 1
|
||||
},
|
||||
{
|
||||
"code": "stars",
|
||||
@@ -731,7 +740,8 @@
|
||||
"60": "꽤 보여요! 불빛 적은 곳으로 조금만 나가요.",
|
||||
"80": "달은 어둡고 공기는 맑아요. 은하수 노려볼 만한 밤 ✨"
|
||||
},
|
||||
"sort_order": 10
|
||||
"sort_order": 10,
|
||||
"priority": 2
|
||||
},
|
||||
{
|
||||
"code": "jjamppong",
|
||||
@@ -789,7 +799,8 @@
|
||||
"60": "쌀쌀하거나 비 와서 국물 각 잡혀요!",
|
||||
"80": "춥고 비까지! 얼큰한 짬뽕 한 그릇 무조건 🍜"
|
||||
},
|
||||
"sort_order": 11
|
||||
"sort_order": 11,
|
||||
"priority": 3
|
||||
},
|
||||
{
|
||||
"code": "makgeolli",
|
||||
@@ -845,7 +856,8 @@
|
||||
"60": "비 기운이 있어요. 파전 반죽 준비각!",
|
||||
"80": "비 오고 선선한 저녁, 파전에 막걸리 확정 🍶"
|
||||
},
|
||||
"sort_order": 12
|
||||
"sort_order": 12,
|
||||
"priority": 3
|
||||
},
|
||||
{
|
||||
"code": "iced_hot",
|
||||
@@ -899,7 +911,8 @@
|
||||
"60": "아침 공기가 차요. 오늘은 뜨아로 갈아탈 때!",
|
||||
"80": "아침이 한 자릿수, 따뜻한 커피 없인 못 버텨요 ☕"
|
||||
},
|
||||
"sort_order": 13
|
||||
"sort_order": 13,
|
||||
"priority": 3
|
||||
},
|
||||
{
|
||||
"code": "laundry",
|
||||
@@ -963,7 +976,8 @@
|
||||
"60": "잘 마르는 편이에요. 두꺼운 건 오후까지 두기!",
|
||||
"80": "따뜻하고 보송한데 바람까지 솔솔, 이불 빨래 가능한 날 ☀️"
|
||||
},
|
||||
"sort_order": 14
|
||||
"sort_order": 14,
|
||||
"priority": 1
|
||||
},
|
||||
{
|
||||
"code": "bike",
|
||||
@@ -1049,7 +1063,8 @@
|
||||
"60": "탈 만해요! 강변은 바람 좀 부니 바람막이 챙기기.",
|
||||
"80": "15~24°에 바람 잔잔, 멀리 달려도 좋은 날 🚲"
|
||||
},
|
||||
"sort_order": 15
|
||||
"sort_order": 15,
|
||||
"priority": 1
|
||||
},
|
||||
{
|
||||
"code": "dog",
|
||||
@@ -1128,7 +1143,8 @@
|
||||
"60": "산책 괜찮아요! 그늘 많은 길로 가요.",
|
||||
"80": "5~22°에 공기 맑음, 멍멍이 신나는 날 🐶"
|
||||
},
|
||||
"sort_order": 16
|
||||
"sort_order": 16,
|
||||
"priority": 2
|
||||
},
|
||||
{
|
||||
"code": "glasses",
|
||||
@@ -1182,7 +1198,8 @@
|
||||
"60": "출근길 안경에 김 서려요. 닦을 천 챙기기!",
|
||||
"80": "영하권 아침에 습하기까지, 문 열자마자 앞이 하얘져요 👓"
|
||||
},
|
||||
"sort_order": 17
|
||||
"sort_order": 17,
|
||||
"priority": 2
|
||||
},
|
||||
{
|
||||
"code": "makeup",
|
||||
@@ -1236,7 +1253,8 @@
|
||||
"60": "덥고 습해서 무너지기 쉬워요. 픽서 챙기기!",
|
||||
"80": "30° 넘는 찜통에 습도까지, 기름종이 필수 🫠"
|
||||
},
|
||||
"sort_order": 18
|
||||
"sort_order": 18,
|
||||
"priority": 2
|
||||
},
|
||||
{
|
||||
"code": "naengmyeon",
|
||||
@@ -1292,7 +1310,8 @@
|
||||
"60": "점심에 덥네요. 냉면 한 그릇 생각나요!",
|
||||
"80": "30° 넘는 한낮, 살얼음 동동 냉면 확정 🥶"
|
||||
},
|
||||
"sort_order": 19
|
||||
"sort_order": 19,
|
||||
"priority": 3
|
||||
},
|
||||
{
|
||||
"code": "taxi",
|
||||
@@ -1348,7 +1367,8 @@
|
||||
"60": "비나 추위로 택시 잡기 힘들어요. 막차 시간 확인!",
|
||||
"80": "비 오는 추운 밤, 택시 전쟁이에요. 막차 타세요 🚕"
|
||||
},
|
||||
"sort_order": 20
|
||||
"sort_order": 20,
|
||||
"priority": 2
|
||||
},
|
||||
{
|
||||
"code": "delivery",
|
||||
@@ -1405,7 +1425,8 @@
|
||||
"60": "비나 추위로 주문이 몰려요. 일찍 시키기!",
|
||||
"80": "비 오는 추운 저녁, 배달 한참 걸려요. 지금 바로 주문! 🛵"
|
||||
},
|
||||
"sort_order": 21
|
||||
"sort_order": 21,
|
||||
"priority": 2
|
||||
},
|
||||
{
|
||||
"code": "garden",
|
||||
@@ -1478,7 +1499,8 @@
|
||||
"60": "화분 돌보기 괜찮아요. 아침에 물 듬뿍!",
|
||||
"80": "12~25°의 보송한 아침, 분갈이까지 해도 되는 날 🌱"
|
||||
},
|
||||
"sort_order": 22
|
||||
"sort_order": 22,
|
||||
"priority": 3
|
||||
},
|
||||
{
|
||||
"code": "photo",
|
||||
@@ -1546,7 +1568,8 @@
|
||||
"60": "노을이 꽤 기대돼요. 해 지기 30분 전에 나가요.",
|
||||
"80": "노을 점수 높고 공기 맑음, 인생샷 각 📸"
|
||||
},
|
||||
"sort_order": 23
|
||||
"sort_order": 23,
|
||||
"priority": 2
|
||||
},
|
||||
{
|
||||
"code": "baseball",
|
||||
@@ -1612,7 +1635,8 @@
|
||||
"60": "직관 괜찮아요! 밤엔 선선하니 겉옷 하나.",
|
||||
"80": "15~25°에 비 걱정 없음, 응원가 목청껏 부르는 날 ⚾"
|
||||
},
|
||||
"sort_order": 24
|
||||
"sort_order": 24,
|
||||
"priority": 3
|
||||
},
|
||||
{
|
||||
"code": "study",
|
||||
@@ -1669,7 +1693,8 @@
|
||||
"60": "밖이 애매해서 책상에 앉을 만해요.",
|
||||
"80": "비 오고 춥거나 더워서 나갈 맛이 안 나요. 집중각 📚"
|
||||
},
|
||||
"sort_order": 25
|
||||
"sort_order": 25,
|
||||
"priority": 3
|
||||
},
|
||||
{
|
||||
"code": "netflix",
|
||||
@@ -1725,7 +1750,8 @@
|
||||
"60": "비 오거나 쌀쌀한 밤, 이불 속이 최고!",
|
||||
"80": "비 오는 주말 앞 밤, 정주행 시작각 🍿"
|
||||
},
|
||||
"sort_order": 26
|
||||
"sort_order": 26,
|
||||
"priority": 3
|
||||
},
|
||||
{
|
||||
"code": "chestnut",
|
||||
@@ -1779,6 +1805,524 @@
|
||||
"60": "손이 시려요. 따끈한 군밤 한 봉지!",
|
||||
"80": "영하 가까운 저녁, 군밤 품고 걷는 날 🌰"
|
||||
},
|
||||
"sort_order": 27
|
||||
"sort_order": 27,
|
||||
"priority": 3
|
||||
},
|
||||
{
|
||||
"code": "golf",
|
||||
"name": "골프각",
|
||||
"icon": "golf",
|
||||
"category": 1,
|
||||
"is_fun": false,
|
||||
"is_core": false,
|
||||
"has_detail": true,
|
||||
"description": "오전 7시~오후 5시, 필드에서 라운딩하기 좋은 정도",
|
||||
"windows": [
|
||||
{
|
||||
"from": 7,
|
||||
"to": 12
|
||||
},
|
||||
{
|
||||
"from": 12,
|
||||
"to": 17
|
||||
}
|
||||
],
|
||||
"weight_temp": 30,
|
||||
"weight_rain": 30,
|
||||
"weight_wind": 25,
|
||||
"weight_humidity": 5,
|
||||
"weight_air": 5,
|
||||
"weight_uv": 0,
|
||||
"weight_sun": 0,
|
||||
"weight_view": 0,
|
||||
"weight_time": 5,
|
||||
"factor_rules": {
|
||||
"temp": {
|
||||
"type": "range",
|
||||
"lo": 15,
|
||||
"hi": 24
|
||||
},
|
||||
"rain": {
|
||||
"dir": "dry"
|
||||
},
|
||||
"wind": {
|
||||
"type": "calm",
|
||||
"ok": 3,
|
||||
"limit": 9
|
||||
},
|
||||
"humidity": {
|
||||
"type": "range",
|
||||
"lo": 30,
|
||||
"hi": 60,
|
||||
"best": 35
|
||||
},
|
||||
"time": {
|
||||
"type": "weekday",
|
||||
"sat": 100,
|
||||
"sun": 100,
|
||||
"holiday": 100,
|
||||
"default": 70
|
||||
}
|
||||
},
|
||||
"zero_rules": [
|
||||
{
|
||||
"field": "rain_prob",
|
||||
"op": ">=",
|
||||
"value": 70
|
||||
},
|
||||
{
|
||||
"field": "wind_ms",
|
||||
"op": ">=",
|
||||
"value": 12
|
||||
},
|
||||
{
|
||||
"field": "warning",
|
||||
"op": "==",
|
||||
"value": "wind"
|
||||
}
|
||||
],
|
||||
"limit_description": "골프장 예약, 잔디 상태, 낙뢰는 반영하지 못해요",
|
||||
"sentences": {
|
||||
"0": "비 70% 넘거나 바람이 너무 세요. 오늘은 스크린으로!",
|
||||
"30": "춥거나 덥거나 바람이 공을 흔들어요. 타수는 기대 말기!",
|
||||
"60": "칠 만해요! 바람 방향만 잘 읽으면 돼요.",
|
||||
"80": "15~24°에 바람 잔잔, 인생 라운딩 노려볼 날 ⛳"
|
||||
},
|
||||
"sort_order": 28,
|
||||
"priority": 2
|
||||
},
|
||||
{
|
||||
"code": "jipkok",
|
||||
"name": "집콕각",
|
||||
"icon": "jipkok",
|
||||
"category": 3,
|
||||
"is_fun": true,
|
||||
"is_core": false,
|
||||
"has_detail": true,
|
||||
"description": "오전 10시~오후 6시, 나가기 싫어 집에 있고 싶은 정도",
|
||||
"windows": [
|
||||
{
|
||||
"from": 10,
|
||||
"to": 18
|
||||
}
|
||||
],
|
||||
"weight_temp": 30,
|
||||
"weight_rain": 30,
|
||||
"weight_wind": 10,
|
||||
"weight_humidity": 5,
|
||||
"weight_air": 20,
|
||||
"weight_uv": 0,
|
||||
"weight_sun": 0,
|
||||
"weight_view": 0,
|
||||
"weight_time": 5,
|
||||
"factor_rules": {
|
||||
"temp": {
|
||||
"type": "away",
|
||||
"lo": 15,
|
||||
"hi": 24
|
||||
},
|
||||
"rain": {
|
||||
"dir": "wet"
|
||||
},
|
||||
"wind": {
|
||||
"type": "strong"
|
||||
},
|
||||
"humidity": {
|
||||
"type": "higher"
|
||||
},
|
||||
"air": {
|
||||
"zero": 15,
|
||||
"full": 75
|
||||
},
|
||||
"time": {
|
||||
"type": "weekday",
|
||||
"sat": 100,
|
||||
"sun": 100,
|
||||
"holiday": 100,
|
||||
"default": 60
|
||||
}
|
||||
},
|
||||
"zero_rules": [],
|
||||
"limit_description": "재미로 보는 지수예요",
|
||||
"sentences": {
|
||||
"0": "밖이 너무 좋아요. 집에만 있기 아까운 날!",
|
||||
"30": "나갈까 말까, 소파와 밀당 중이에요.",
|
||||
"60": "덥거나 춥거나 공기가 탁해요. 집이 최고!",
|
||||
"80": "비 오고 공기까지 탁해요. 이불 밖은 위험해 🛋️"
|
||||
},
|
||||
"sort_order": 29,
|
||||
"priority": 3
|
||||
},
|
||||
{
|
||||
"code": "fishing",
|
||||
"name": "낚시각",
|
||||
"icon": "fishing",
|
||||
"category": 1,
|
||||
"is_fun": false,
|
||||
"is_core": false,
|
||||
"has_detail": true,
|
||||
"description": "새벽 5~9시·오후 4~7시, 물가에서 낚시하기 좋은 정도",
|
||||
"windows": [
|
||||
{
|
||||
"from": 5,
|
||||
"to": 9
|
||||
},
|
||||
{
|
||||
"from": 16,
|
||||
"to": 19
|
||||
}
|
||||
],
|
||||
"weight_temp": 25,
|
||||
"weight_rain": 25,
|
||||
"weight_wind": 35,
|
||||
"weight_humidity": 0,
|
||||
"weight_air": 5,
|
||||
"weight_uv": 0,
|
||||
"weight_sun": 0,
|
||||
"weight_view": 0,
|
||||
"weight_time": 10,
|
||||
"factor_rules": {
|
||||
"temp": {
|
||||
"type": "range",
|
||||
"lo": 12,
|
||||
"hi": 24
|
||||
},
|
||||
"rain": {
|
||||
"dir": "dry"
|
||||
},
|
||||
"wind": {
|
||||
"type": "calm",
|
||||
"ok": 4,
|
||||
"limit": 10
|
||||
},
|
||||
"humidity": {
|
||||
"type": "ignore"
|
||||
},
|
||||
"time": {
|
||||
"type": "weekday",
|
||||
"sat": 100,
|
||||
"sun": 100,
|
||||
"holiday": 100,
|
||||
"default": 60
|
||||
}
|
||||
},
|
||||
"zero_rules": [
|
||||
{
|
||||
"field": "rain_prob",
|
||||
"op": ">=",
|
||||
"value": 70
|
||||
},
|
||||
{
|
||||
"field": "wind_ms",
|
||||
"op": ">=",
|
||||
"value": 10
|
||||
},
|
||||
{
|
||||
"field": "warning",
|
||||
"op": "==",
|
||||
"value": "wind"
|
||||
}
|
||||
],
|
||||
"limit_description": "물때·수온·파도 높이는 반영하지 못해요",
|
||||
"sentences": {
|
||||
"0": "비 70% 넘거나 바람이 거세요. 물가는 위험, 오늘은 쉬어요!",
|
||||
"30": "바람에 찌가 흔들리거나 손이 시려요. 짧게 손맛만!",
|
||||
"60": "물가 나가볼 만해요! 새벽엔 쌀쌀하니 겉옷 챙기기.",
|
||||
"80": "12~24°에 물결 잔잔, 입질 기다리기 딱 좋은 날 🎣"
|
||||
},
|
||||
"sort_order": 30,
|
||||
"priority": 2
|
||||
},
|
||||
{
|
||||
"code": "drive",
|
||||
"name": "드라이브각",
|
||||
"icon": "drive",
|
||||
"category": 1,
|
||||
"is_fun": false,
|
||||
"is_core": false,
|
||||
"has_detail": true,
|
||||
"description": "오전 10시~오후 5시, 창문 열고 드라이브하기 좋은 정도",
|
||||
"windows": [
|
||||
{
|
||||
"from": 10,
|
||||
"to": 17
|
||||
}
|
||||
],
|
||||
"weight_temp": 20,
|
||||
"weight_rain": 30,
|
||||
"weight_wind": 5,
|
||||
"weight_humidity": 5,
|
||||
"weight_air": 15,
|
||||
"weight_uv": 0,
|
||||
"weight_sun": 0,
|
||||
"weight_view": 15,
|
||||
"weight_time": 10,
|
||||
"factor_rules": {
|
||||
"temp": {
|
||||
"type": "range",
|
||||
"lo": 15,
|
||||
"hi": 25
|
||||
},
|
||||
"rain": {
|
||||
"dir": "dry"
|
||||
},
|
||||
"wind": {
|
||||
"type": "calm",
|
||||
"ok": 6,
|
||||
"limit": 15
|
||||
},
|
||||
"humidity": {
|
||||
"type": "range",
|
||||
"lo": 30,
|
||||
"hi": 60,
|
||||
"best": 35
|
||||
},
|
||||
"time": {
|
||||
"type": "weekday",
|
||||
"sat": 100,
|
||||
"sun": 100,
|
||||
"holiday": 100,
|
||||
"default": 60
|
||||
},
|
||||
"view": {
|
||||
"zero": 5,
|
||||
"full": 20
|
||||
}
|
||||
},
|
||||
"zero_rules": [
|
||||
{
|
||||
"field": "rain_prob",
|
||||
"op": ">=",
|
||||
"value": 70,
|
||||
"cap": 20
|
||||
}
|
||||
],
|
||||
"limit_description": "길 막힘과 도로 공사는 반영하지 못해요",
|
||||
"sentences": {
|
||||
"0": "비가 쏟아져요. 와이퍼만 바쁜 날, 드라이브는 다음에!",
|
||||
"30": "하늘이 뿌옇거나 비 기운이 있어요. 가까운 곳만 슬쩍!",
|
||||
"60": "달릴 만해요! 창문 반쯤 열고 음악 크게.",
|
||||
"80": "공기 맑고 멀리까지 보여요. 해안도로 달리고 싶은 날 🚗"
|
||||
},
|
||||
"sort_order": 31,
|
||||
"priority": 1
|
||||
},
|
||||
{
|
||||
"code": "kite",
|
||||
"name": "연날리기각",
|
||||
"icon": "kite",
|
||||
"category": 1,
|
||||
"is_fun": false,
|
||||
"is_core": false,
|
||||
"has_detail": true,
|
||||
"description": "오전 11시~오후 4시, 연 날리기 좋은 정도",
|
||||
"windows": [
|
||||
{
|
||||
"from": 11,
|
||||
"to": 16
|
||||
}
|
||||
],
|
||||
"weight_temp": 20,
|
||||
"weight_rain": 25,
|
||||
"weight_wind": 45,
|
||||
"weight_humidity": 0,
|
||||
"weight_air": 5,
|
||||
"weight_uv": 0,
|
||||
"weight_sun": 0,
|
||||
"weight_view": 0,
|
||||
"weight_time": 5,
|
||||
"factor_rules": {
|
||||
"temp": {
|
||||
"type": "range",
|
||||
"lo": 8,
|
||||
"hi": 22
|
||||
},
|
||||
"rain": {
|
||||
"dir": "dry"
|
||||
},
|
||||
"wind": {
|
||||
"type": "moderate"
|
||||
},
|
||||
"humidity": {
|
||||
"type": "ignore"
|
||||
},
|
||||
"time": {
|
||||
"type": "weekday",
|
||||
"sat": 100,
|
||||
"sun": 100,
|
||||
"holiday": 100,
|
||||
"default": 70
|
||||
}
|
||||
},
|
||||
"zero_rules": [
|
||||
{
|
||||
"field": "rain_prob",
|
||||
"op": ">=",
|
||||
"value": 70
|
||||
},
|
||||
{
|
||||
"field": "gust_ms",
|
||||
"op": ">=",
|
||||
"value": 13
|
||||
},
|
||||
{
|
||||
"field": "wind_ms",
|
||||
"op": "<",
|
||||
"value": 1,
|
||||
"cap": 30
|
||||
}
|
||||
],
|
||||
"limit_description": "전깃줄·나무 없는 넓은 곳인지는 반영하지 못해요",
|
||||
"sentences": {
|
||||
"0": "비가 오거나 돌풍이 불어요. 연이 날아가 버려요!",
|
||||
"30": "바람이 너무 약하거나 너무 세요. 뛰어다녀야 겨우 떠요.",
|
||||
"60": "연 띄울 만해요! 실은 넉넉하게 감아 가요.",
|
||||
"80": "초속 2~5m 딱 좋은 바람, 연이 하늘 높이 쭉쭉 🪁"
|
||||
},
|
||||
"sort_order": 32,
|
||||
"priority": 3
|
||||
},
|
||||
{
|
||||
"code": "waterplay",
|
||||
"name": "물놀이각",
|
||||
"icon": "waterplay",
|
||||
"category": 1,
|
||||
"is_fun": false,
|
||||
"is_core": false,
|
||||
"has_detail": true,
|
||||
"description": "오전 11시~오후 5시, 바다·계곡에서 물놀이하기 좋은 정도",
|
||||
"windows": [
|
||||
{
|
||||
"from": 11,
|
||||
"to": 17
|
||||
}
|
||||
],
|
||||
"weight_temp": 40,
|
||||
"weight_rain": 25,
|
||||
"weight_wind": 10,
|
||||
"weight_humidity": 0,
|
||||
"weight_air": 0,
|
||||
"weight_uv": 0,
|
||||
"weight_sun": 20,
|
||||
"weight_view": 0,
|
||||
"weight_time": 5,
|
||||
"factor_rules": {
|
||||
"temp": {
|
||||
"type": "range",
|
||||
"lo": 27,
|
||||
"hi": 34,
|
||||
"best": 30
|
||||
},
|
||||
"rain": {
|
||||
"dir": "dry"
|
||||
},
|
||||
"wind": {
|
||||
"type": "calm",
|
||||
"ok": 4,
|
||||
"limit": 12
|
||||
},
|
||||
"humidity": {
|
||||
"type": "ignore"
|
||||
},
|
||||
"time": {
|
||||
"type": "weekday",
|
||||
"sat": 100,
|
||||
"sun": 100,
|
||||
"holiday": 100,
|
||||
"default": 60
|
||||
},
|
||||
"sun": {
|
||||
"zero": 0.2,
|
||||
"full": 0.8
|
||||
}
|
||||
},
|
||||
"zero_rules": [
|
||||
{
|
||||
"field": "rain_prob",
|
||||
"op": ">=",
|
||||
"value": 60
|
||||
},
|
||||
{
|
||||
"field": "feels_c",
|
||||
"op": "<",
|
||||
"value": 20
|
||||
}
|
||||
],
|
||||
"limit_description": "수온, 파도 높이, 계곡 물살은 반영하지 못해요",
|
||||
"sentences": {
|
||||
"0": "체감 20° 아래거나 비 소식이 있어요. 물놀이는 여름에!",
|
||||
"30": "물에 들어가면 으슬으슬해요. 발만 담그기!",
|
||||
"60": "물놀이 괜찮아요! 그늘막이랑 선크림 챙기기.",
|
||||
"80": "30° 안팎에 쨍쨍, 튜브 들고 풍덩 🏖️"
|
||||
},
|
||||
"sort_order": 33,
|
||||
"priority": 2
|
||||
},
|
||||
{
|
||||
"code": "kimjang",
|
||||
"name": "김장각",
|
||||
"icon": "kimchi",
|
||||
"category": 3,
|
||||
"is_fun": false,
|
||||
"is_core": false,
|
||||
"has_detail": true,
|
||||
"description": "오전 9시~오후 4시, 김장하기 좋은 정도",
|
||||
"windows": [
|
||||
{
|
||||
"from": 9,
|
||||
"to": 16
|
||||
}
|
||||
],
|
||||
"weight_temp": 50,
|
||||
"weight_rain": 25,
|
||||
"weight_wind": 10,
|
||||
"weight_humidity": 0,
|
||||
"weight_air": 5,
|
||||
"weight_uv": 0,
|
||||
"weight_sun": 0,
|
||||
"weight_view": 0,
|
||||
"weight_time": 10,
|
||||
"factor_rules": {
|
||||
"temp": {
|
||||
"type": "range",
|
||||
"lo": 0,
|
||||
"hi": 10,
|
||||
"best": 5
|
||||
},
|
||||
"rain": {
|
||||
"dir": "dry"
|
||||
},
|
||||
"wind": {
|
||||
"type": "calm",
|
||||
"ok": 4,
|
||||
"limit": 10
|
||||
},
|
||||
"humidity": {
|
||||
"type": "ignore"
|
||||
},
|
||||
"time": {
|
||||
"type": "weekday",
|
||||
"sat": 100,
|
||||
"sun": 100,
|
||||
"holiday": 100,
|
||||
"default": 50
|
||||
}
|
||||
},
|
||||
"zero_rules": [
|
||||
{
|
||||
"field": "feels_c",
|
||||
"op": ">=",
|
||||
"value": 18
|
||||
}
|
||||
],
|
||||
"limit_description": "배추 작황과 값, 집집마다 김장 날짜는 반영하지 못해요",
|
||||
"sentences": {
|
||||
"0": "아직 18° 넘어요. 지금 담그면 김치가 금방 쉬어요!",
|
||||
"30": "조금 이르거나 손이 꽁꽁 얼어요. 날을 다시 골라 봐요.",
|
||||
"60": "김장할 만해요! 고무장갑 안에 면장갑 하나 더.",
|
||||
"80": "0~10°에 비 없고 바람 잔잔, 김장 날 잡는 날 🥬"
|
||||
},
|
||||
"sort_order": 34,
|
||||
"priority": 3
|
||||
}
|
||||
]
|
||||
+11
-11
@@ -1,11 +1,11 @@
|
||||
region_name,area,name,is_outdoor,icon,reason,best_time,sort_order
|
||||
서울 성동구,성수,서울숲,1,picnic,돗자리 펴고 낮 피크닉,낮 12시~4시,1
|
||||
서울 성동구,성수,성수 갤러리 골목,0,photo,작은 전시와 팝업을 걸어서,비 오는 오후,2
|
||||
서울 마포구,연남·망원,경의선숲길,1,walk,해 질 녘 산책 데이트,저녁 6시 이후,3
|
||||
서울 마포구,연남·망원,망원한강공원,1,sunset,노을 명소 1위 강 건너 서쪽,노을 무렵,4
|
||||
서울 영등포구,여의도,여의도한강공원,1,chimaek,한강 치맥,저녁 7시,5
|
||||
서울 영등포구,여의도,더현대 서울,0,calendar,비 와도 하루 종일 실내,비 오는 날,6
|
||||
서울 송파구,잠실,석촌호수,1,walk,호수 한 바퀴 2.5km,선선한 저녁,7
|
||||
서울 송파구,잠실,롯데월드 아쿠아리움,0,rain,비 오는 날 실내 데이트,비 오는 오후,8
|
||||
서울 종로구,북촌·익선,북촌한옥마을,1,photo,맑은 날 한옥 골목 사진,오전 10시~,9
|
||||
서울 종로구,북촌·익선,국립현대미술관 서울관,0,bulb,비 오면 미술관으로,비 오는 날,10
|
||||
region_name,area,name,is_outdoor,icon,reason,best_time,sort_order,lat,lon,source
|
||||
서울 성동구,성수,서울숲,1,picnic,돗자리 펴고 낮 피크닉,낮 12시~4시,1,37.54307,127.04180,tourapi:128611
|
||||
서울 성동구,성수,성수 갤러리 골목,0,photo,작은 전시와 팝업을 걸어서,비 오는 오후,2,37.54320,127.05660,tourapi:2930901
|
||||
서울 마포구,연남·망원,경의선숲길,1,walk,해 질 녘 산책 데이트,저녁 6시 이후,3,37.56170,126.92306,tourapi:2553819
|
||||
서울 마포구,연남·망원,망원한강공원,1,sunset,노을 명소 1위 강 건너 서쪽,노을 무렵,4,37.55140,126.90050,tourapi:1059638
|
||||
서울 영등포구,여의도,여의도한강공원,1,chimaek,한강 치맥,저녁 7시,5,37.52640,126.93361,tourapi:1059479
|
||||
서울 영등포구,여의도,더현대 서울,0,calendar,비 와도 하루 종일 실내,비 오는 날,6,37.52710,126.92730,tourapi:2708109
|
||||
서울 송파구,잠실,석촌호수,1,walk,호수 한 바퀴 2.5km,선선한 저녁,7,37.50792,127.09894,tourapi:754052
|
||||
서울 송파구,잠실,롯데월드 아쿠아리움,0,rain,비 오는 날 실내 데이트,비 오는 오후,8,37.51417,127.10407,tourapi:2476731
|
||||
서울 종로구,북촌·익선,북촌한옥마을,1,photo,맑은 날 한옥 골목 사진,오전 10시~,9,37.57905,126.98671,tourapi:126537
|
||||
서울 종로구,북촌·익선,국립현대미술관 서울관,0,bulb,비 오면 미술관으로,비 오는 날,10,37.57865,126.98000,tourapi:1934593
|
||||
|
File diff suppressed because it is too large.
Load diff
@@ -154,3 +154,24 @@ region_name,name,description,lat,lon,west_open,source
|
||||
충남 홍성군,궁리포구,바다 너머 서쪽이 트임 · 충남 홍성군,36.58845,126.45721,1,tourapi:1937784
|
||||
충남 홍성군,남당노을전망대,바다 너머 서쪽이 트임 · 충남 홍성군,36.54428,126.4656,1,tourapi:3065226
|
||||
충남 홍성군,어사리 노을공원,바다 너머 서쪽이 트임 · 충남 홍성군,36.55615,126.46837,1,tourapi:2678991
|
||||
광주 동구,서석대,높은 곳에서 서쪽이 트임 · 광주 북구,35.14415,126.98900,1,tourapi:2614826
|
||||
세종 세종특별자치시,고운뜰공원,높은 곳에서 보는 도심 노을 · 세종,36.51255,127.23913,0,tourapi:2758467
|
||||
세종 세종특별자치시,청벽산,높은 곳에서 금강 너머 노을 · 충남 공주시,36.42857,127.22094,0,tourapi:2755172
|
||||
충남 금산군,대둔산도립공원(금산),낙조대까지 산행 · 충남 금산군,36.13746,127.34167,0,tourapi:128001
|
||||
충북 단양군,양방산전망대,높은 곳에서 남한강 너머 노을 · 충북 단양군,36.96837,128.38202,0,tourapi:1626685
|
||||
충북 음성군,백야둘레길,물가 노을 · 충북 음성군,36.96775,127.60332,0,tourapi:2782402
|
||||
강원 강릉시,강릉항여객터미널,육지 쪽 산으로 지는 해 · 강원 강릉시,37.77289,128.95289,0,tourapi:3546554
|
||||
경남 밀양시,낙동강철교전망대,물가 노을 · 경남 김해시,35.37512,128.82347,0,tourapi:2782619
|
||||
경북 영덕군,영덕조각공원,풍력단지 언덕 노을 · 경북 영덕군,36.42193,129.41761,0,tourapi:128718
|
||||
경기 연천군,임진강 주상절리,석양에 붉어지는 절벽 · 경기 연천군,38.01993,127.01545,0,tourapi:2569474
|
||||
강원 춘천시,구봉산 전망대 카페거리,높은 곳에서 서쪽이 트임 · 강원 춘천시,37.89250,127.77700,1,tourapi:129686
|
||||
경북 상주시,경천섬(경천섬공원),물가 노을 · 경북 상주시,36.45323,128.25506,0,tourapi:2756567
|
||||
강원 속초시,영랑호,물가 노을 · 강원 속초시,38.21422,128.58075,0,tourapi:127565;web:https://lady.khan.co.kr/finance/article/6492
|
||||
경남 함안군,함안 악양루,남강 절벽 위 노을 · 경남 함안군,35.33513,128.39847,0,tourapi:702331;web:https://www.knnews.co.kr/news/articleView.php?idxno=1425
|
||||
전북 완주군,비비정,만경강 낙조 · 전북 완주군,35.89901,127.06849,0,osm;web:https://jjan.kr/article/20251209500596
|
||||
경기 여주시,흥원창,남한강 물가 노을 · 강원 원주시,37.22665,127.75142,0,osm;web:https://xn--ok0b236bp0a.com/place/26309
|
||||
경북 영양군,선바위,강가 바위 위 석양 · 경북 영양군,36.60598,129.07461,0,osm;web:https://weekly.khan.co.kr/article/201111221629101
|
||||
경북 경주시,금장대,형산강 너머 서쪽 노을 · 경북 경주시,35.86066,129.20093,1,osm;web:https://www.telltrip.com/domestic-travel/gyeongju-geumjangdae-night-view-travel-tips/
|
||||
전남 강진군,강진만생태공원,물가 노을 · 전남 강진군,34.61961,126.77254,0,osm;web:https://m.seoul.co.kr/news/2022/11/24/20221124018005
|
||||
충북 영동군,함벽정,금강가 정자에서 보는 낙조 · 충북 영동군,36.13424,127.67067,0,osm;web:https://www.nhis.or.kr/static/alim/paper/oldpaper/202209/sub/14.html
|
||||
강원 평창군,육백마지기,높은 곳에서 서쪽이 트임 · 강원 평창군,37.41025,128.50836,1,osm;web:https://v.daum.net/v/Wr8Os0nbtv
|
||||
|
@@ -0,0 +1,27 @@
|
||||
from datetime import date, datetime, time, timedelta
|
||||
|
||||
from common.utils.kma_time import KST
|
||||
|
||||
SLOTS = ("morning", "day", "evening", "night")
|
||||
SLOT_LABEL = {"morning": "아침", "day": "낮", "evening": "저녁", "night": "밤"}
|
||||
NIGHT_AFTER_SUNSET = timedelta(hours=1) # 해 지고 이만큼 지나면 밤
|
||||
NIGHT_END_HOUR = 5
|
||||
|
||||
|
||||
def slot_of(now: datetime, sunset_at: datetime) -> str:
|
||||
"""아침 05–11 · 낮 11–일몰 2시간 전 · 저녁 일몰 2시간 전–일몰 1시간 뒤 · 밤 일몰 1시간 뒤–05. 밤은 계절 따라 18시대~21시대에 온다."""
|
||||
h = now.hour
|
||||
if NIGHT_END_HOUR <= h < 11:
|
||||
return "morning"
|
||||
if h >= 11 and now < sunset_at + NIGHT_AFTER_SUNSET:
|
||||
return "day" if now < sunset_at - timedelta(hours=2) else "evening"
|
||||
return "night"
|
||||
|
||||
|
||||
def slot_hours(day: date, sunset_at: datetime) -> dict[str, set[int]]:
|
||||
"""그날 5시~다음 날 5시를 구간별 시각으로 나눈다. 24 이상은 다음 날 시각. 한 시간은 그 30분 시점의 구간에 넣는다."""
|
||||
out: dict[str, set[int]] = {s: set() for s in SLOTS}
|
||||
start = datetime.combine(day, time(0), tzinfo=KST)
|
||||
for h in range(NIGHT_END_HOUR, 24 + NIGHT_END_HOUR):
|
||||
out[slot_of(start + timedelta(hours=h, minutes=30), sunset_at)].add(h)
|
||||
return out
|
||||
@@ -18,6 +18,13 @@ _FALL_FLOOR = exp(-0.5)
|
||||
# 편한 범위 안에서 최적값 ±이만큼은 100점 (기온 °, 습도 %p)
|
||||
_TEMP_PLATEAU = 2
|
||||
_HUMIDITY_PLATEAU = 5
|
||||
# 각 중요도(index_definition.priority)별 순위 가중치: 1=상 2=중 3=하. 순위만 바꾸고 보이는 점수는 그대로 둔다.
|
||||
PRIORITY_WEIGHT = {1: 1.0, 2: 0.85, 3: 0.7}
|
||||
|
||||
|
||||
def rank_score(score: int, priority: int) -> float:
|
||||
"""각 순위를 정하는 값 = 점수 × 중요도 가중치."""
|
||||
return score * PRIORITY_WEIGHT[priority]
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -108,7 +115,7 @@ def temp_score(rule: dict, feels: float) -> tuple[int, str]:
|
||||
shown = f"산 정상 기준 {round(t)}°" if rule.get("offset") else f"체감 {round(t)}°"
|
||||
if rule["type"] == "range":
|
||||
lo, hi = rule["lo"], rule["hi"]
|
||||
return _range(t, lo, hi, rule.get("best"), _TEMP_PLATEAU, 8), f"{shown}, 편한 범위 {lo}~{hi}° {'안' if lo <= t <= hi else '밖'}"
|
||||
return _range(t, lo, hi, rule.get("best"), rule.get("plateau", _TEMP_PLATEAU), 8), f"{shown}, 편한 범위 {lo}~{hi}° {'안' if lo <= t <= hi else '밖'}"
|
||||
if rule["type"] == "away":
|
||||
lo, hi = rule["lo"], rule["hi"]
|
||||
dist = 0 if lo <= t <= hi else min(abs(t - lo), abs(t - hi))
|
||||
@@ -154,10 +161,15 @@ def humidity_score(rule: dict, humidity: float) -> tuple[int, str]:
|
||||
return 50, f"{note}, 이 각엔 상관없어 50점으로 둬요"
|
||||
|
||||
|
||||
def air_score(pm25: Optional[int], label: Optional[str]) -> tuple[int, str]:
|
||||
_AIR_RULE = {"zero": 75, "full": 15}
|
||||
|
||||
|
||||
def air_score(pm25: Optional[int], label: Optional[str], rule: Optional[dict] = None) -> tuple[int, str]:
|
||||
"""rule 이 없으면 맑을수록 좋음. 집콕각처럼 탁할수록 좋은 각은 {"zero": 15, "full": 75} 로 뒤집는다."""
|
||||
if pm25 is None:
|
||||
return _UNKNOWN, f"미세먼지 정보가 없어 {_UNKNOWN}점으로 둬요"
|
||||
return _linear(pm25, 75, 15), f"초미세먼지 {pm25}㎍/㎥{', ' + label if label else ''}"
|
||||
rule = rule or _AIR_RULE
|
||||
return _linear(pm25, rule["zero"], rule["full"]), f"초미세먼지 {pm25}㎍/㎥{', ' + label if label else ''}"
|
||||
|
||||
|
||||
def uv_score(rule: dict, uv: Optional[float]) -> tuple[int, str]:
|
||||
@@ -208,7 +220,8 @@ def axis_label(axis: str, rules: dict) -> str:
|
||||
if axis == "rain":
|
||||
return "비 옴" if rules["rain"]["dir"] == "wet" else "비 안 옴"
|
||||
if axis == "air":
|
||||
return "공기 맑음"
|
||||
rule = rules.get("air", _AIR_RULE)
|
||||
return "공기 탁함" if rule["full"] > rule["zero"] else "공기 맑음"
|
||||
table = {"temp": _TEMP_LABEL, "wind": _WIND_LABEL, "humidity": _HUMIDITY_LABEL, "time": _TIME_LABEL}[axis]
|
||||
return table[rules[axis]["type"]]
|
||||
|
||||
@@ -304,7 +317,7 @@ def evaluate(definition, windows: list[list[Hour]], ctx: Context) -> Optional[Re
|
||||
"rain": rain_score(rules["rain"], max_prob, raining, until if max_prob > own_prob else ""),
|
||||
"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),
|
||||
"air": air_score(ctx.pm25, ctx.air_label, rules.get("air")),
|
||||
"uv": uv_score(rules["uv"], max(uvs, default=None)) if weights["uv"] else (0, ""),
|
||||
"sun": sun_score(rules["sun"], mean(suns) if suns else None) if weights["sun"] else (0, ""),
|
||||
"view": view_score(rules["view"], min(views, default=None)) if weights["view"] else (0, ""),
|
||||
|
||||
+4
-2
@@ -8,6 +8,8 @@ from services.external.data_go_kr import get_all_items
|
||||
|
||||
REALTIME_URL = "https://apis.data.go.kr/B552584/ArpltnInforInqireSvc/getCtprvnRltmMesureDnsty"
|
||||
STATION_URL = "https://apis.data.go.kr/B552584/MsrstnInfoInqireSvc/getMsrstnList"
|
||||
# 전국 조회는 한 번에 15~20초 걸린다. 갱신은 피드 응답과 따로 돌아 기다리게 하지 않는다.
|
||||
BUDGET_SEC = 45.0
|
||||
|
||||
|
||||
def _int(v) -> Optional[int]:
|
||||
@@ -26,11 +28,11 @@ def _measured_at(text: str) -> datetime:
|
||||
|
||||
|
||||
async def fetch_realtime(client: httpx.AsyncClient) -> list[dict]:
|
||||
return await get_all_items(client, REALTIME_URL, {"returnType": "json", "sidoName": "전국", "ver": "1.0"})
|
||||
return await get_all_items(client, REALTIME_URL, {"returnType": "json", "sidoName": "전국", "ver": "1.0"}, budget_sec=BUDGET_SEC)
|
||||
|
||||
|
||||
async def fetch_stations(client: httpx.AsyncClient) -> list[dict]:
|
||||
return await get_all_items(client, STATION_URL, {"returnType": "json"})
|
||||
return await get_all_items(client, STATION_URL, {"returnType": "json"}, budget_sec=BUDGET_SEC)
|
||||
|
||||
|
||||
def parse_realtime(items: list[dict]) -> list[dict]:
|
||||
|
||||
+5
-4
@@ -1,4 +1,5 @@
|
||||
import asyncio
|
||||
from typing import Optional
|
||||
|
||||
import httpx
|
||||
|
||||
@@ -17,12 +18,12 @@ class DataGoKrRequestFailed(RuntimeError):
|
||||
pass
|
||||
|
||||
|
||||
async def get_body(client: httpx.AsyncClient, url: str, params: dict) -> dict:
|
||||
async def get_body(client: httpx.AsyncClient, url: str, params: dict, budget_sec: Optional[float] = None) -> dict:
|
||||
"""data.go.kr 공통 호출. 가끔 오는 504(SERVICETIMEOUT)는 다시 시도하고, 응답이 없으면 잠시 그 API 를 쉰다. 로그·예외에 키를 남기지 않는다."""
|
||||
if not settings.data_go_kr_service_key:
|
||||
raise DataGoKrNotConfigured("DATA_GO_KR_SERVICE_KEY is empty")
|
||||
op = url.rsplit("/", 1)[-1]
|
||||
return await guarded(f"datagokr:{op}", lambda: _get_body(client, url, op, params), DataGoKrRequestFailed)
|
||||
return await guarded(f"datagokr:{op}", lambda: _get_body(client, url, op, params), DataGoKrRequestFailed, budget_sec)
|
||||
|
||||
|
||||
async def _get_body(client: httpx.AsyncClient, url: str, op: str, params: dict) -> dict:
|
||||
@@ -44,11 +45,11 @@ async def _get_body(client: httpx.AsyncClient, url: str, op: str, params: dict)
|
||||
raise Unreachable(f"failed after {_ATTEMPTS} attempts: {last or 'unexpected body'}")
|
||||
|
||||
|
||||
async def get_all_items(client: httpx.AsyncClient, url: str, params: dict, page_size: int = 1000) -> list[dict]:
|
||||
async def get_all_items(client: httpx.AsyncClient, url: str, params: dict, page_size: int = 1000, budget_sec: Optional[float] = None) -> list[dict]:
|
||||
items: list[dict] = []
|
||||
page = 1
|
||||
while True:
|
||||
body = await get_body(client, url, {**params, "numOfRows": page_size, "pageNo": page})
|
||||
body = await get_body(client, url, {**params, "numOfRows": page_size, "pageNo": page}, budget_sec)
|
||||
raw = body.get("items") or []
|
||||
chunk = raw.get("item", []) if isinstance(raw, dict) else raw
|
||||
chunk = [chunk] if isinstance(chunk, dict) else chunk
|
||||
|
||||
Vendored
+21
-7
@@ -13,9 +13,19 @@ from common.enums import EVENT_ICON, EventKind
|
||||
SITEMAP_URL = "https://popga.co.kr/sitemap.xml"
|
||||
POPUP_URL = "https://popga.co.kr/popup/{id}"
|
||||
SOURCE_PREFIX = "popga:"
|
||||
STORE = "STORE" # 팝가 분류: STORE=팝업스토어, PERFORMANCE=공연, FESTIVAL=축제
|
||||
# 팝가 분류(STORE=팝업스토어, PERFORMANCE=공연, FESTIVAL=축제) 중 받는 것. 공연은 문화정보원에서 따로 받는다
|
||||
_KINDS = {"STORE": EventKind.POPUP, "FESTIVAL": EventKind.FESTIVAL}
|
||||
REQUEST_GAP_SEC = 0.3
|
||||
|
||||
# 팝가 '축제' 중 연극제·음악제의 공연 한 편. 극장·홀에서 하거나 이름이 공연이면 공연으로 넣는다
|
||||
_SHOW_PLACE = ("극장", "홀", "아트센터", "예술의전당", "씨어터", "시어터", "문화회관", "공연장")
|
||||
_SHOW_NAME = ("연극", "뮤지컬", "오페라", "독주회", "리사이틀", "콘서트")
|
||||
|
||||
|
||||
def is_show(name: str, place: str) -> bool:
|
||||
return any(w in place for w in _SHOW_PLACE) or any(w in name for w in _SHOW_NAME)
|
||||
|
||||
|
||||
_LOC = re.compile(r"<loc>\s*([^<\s]+)\s*</loc>")
|
||||
_URL = re.compile(r"<url>(.*?)</url>", re.S)
|
||||
_LASTMOD = re.compile(r"<lastmod>\s*([^<\s]+)\s*</lastmod>")
|
||||
@@ -86,10 +96,11 @@ def _coord(v) -> Optional[float]:
|
||||
|
||||
|
||||
def parse_popup(page: str, popup_id: int, since: date) -> Optional[dict]:
|
||||
"""팝업스토어이고 since 이후에 끝나면 event 행, 아니면 None."""
|
||||
kind = re.search(rf'\\?"id\\?":{popup_id},\\?"type\\?":\\?"([A-Z_]+)', page)
|
||||
"""팝업스토어·축제이고 since 이후에 끝나면 event 행, 아니면 None."""
|
||||
found = re.search(rf'\\?"id\\?":{popup_id},\\?"type\\?":\\?"([A-Z_]+)', page)
|
||||
kind = _KINDS.get(found.group(1)) if found else None
|
||||
ld = _event_ld(page)
|
||||
if kind is None or kind.group(1) != STORE or ld is None:
|
||||
if kind is None or ld is None:
|
||||
return None
|
||||
start, end = _date(ld.get("startDate")), _date(ld.get("endDate"))
|
||||
if start is None or end is None or end < since:
|
||||
@@ -99,9 +110,12 @@ def parse_popup(page: str, popup_id: int, since: date) -> Optional[dict]:
|
||||
if sido is None:
|
||||
return None
|
||||
geo = loc.get("geo") or {}
|
||||
name, place = html.unescape(ld.get("name") or ""), html.unescape(loc.get("name") or "")
|
||||
if kind is EventKind.FESTIVAL and is_show(name, place):
|
||||
kind = EventKind.CONCERT
|
||||
return {
|
||||
"source_id": f"{SOURCE_PREFIX}{popup_id}", "sido_code": sido, "name": html.unescape(ld.get("name") or "")[:60],
|
||||
"place_name": html.unescape(loc.get("name") or "")[:60], "start_date": start, "end_date": end, "is_confirmed": True,
|
||||
"source_id": f"{SOURCE_PREFIX}{popup_id}", "sido_code": sido, "name": name[:60],
|
||||
"place_name": place[:60], "start_date": start, "end_date": end, "is_confirmed": True,
|
||||
"source_url": POPUP_URL.format(id=popup_id), "image_url": None,
|
||||
"lat": _coord(geo.get("latitude")), "lon": _coord(geo.get("longitude")), "kind": EventKind.POPUP, "icon": EVENT_ICON[EventKind.POPUP],
|
||||
"lat": _coord(geo.get("latitude")), "lon": _coord(geo.get("longitude")), "kind": kind, "icon": EVENT_ICON[kind],
|
||||
}
|
||||
+68
@@ -0,0 +1,68 @@
|
||||
import asyncio
|
||||
import html
|
||||
import re
|
||||
from datetime import date, timedelta
|
||||
from typing import Optional
|
||||
|
||||
import httpx
|
||||
|
||||
from common.enums import EVENT_ICON, EventKind
|
||||
|
||||
# 서울문화포털 문화행사 중 축제. 공개 API 는 키가 따로 있어 robots.txt 가 허용하는 /culture/culture/ 목록을 읽는다.
|
||||
LIST_URL = "https://culture.seoul.go.kr/culture/culture/cultureEvent/jsonList.json"
|
||||
VIEW_URL = "https://culture.seoul.go.kr/culture/culture/cultureEvent/view.do?cultcode={code}&menuNo=200010"
|
||||
IMAGE_URL = "https://culture.seoul.go.kr/cmmn/file/getImage.do?atchFileId={id}&thumb=Y"
|
||||
IMAGE_CREDIT = "ⓒ서울문화포털"
|
||||
SOURCE_PREFIX = "seoul:"
|
||||
SEOUL = "11"
|
||||
REQUEST_GAP_SEC = 0.3
|
||||
_MAX_PAGES = 30
|
||||
# 이름 앞 주최 기관 "[서울시청] ", "[마포문화재단] " 은 카드 제목에서 뗀다
|
||||
_HOST_PREFIX = re.compile(r"^(\s*\[[^\]]*\]\s*)+")
|
||||
|
||||
|
||||
async def fetch_seoul_festivals(client: httpx.AsyncClient, since: date, days: int) -> list[dict]:
|
||||
"""since 부터 days 일 안에 열리는 서울 축제. 한 쪽에 10개씩, 빈 쪽이 나올 때까지."""
|
||||
form = {"menuNo": "200010", "searchCate": "FESTIVAL", "sdate": since.isoformat(), "edate": (since + timedelta(days=days)).isoformat()}
|
||||
items: list[dict] = []
|
||||
for page in range(1, _MAX_PAGES + 1):
|
||||
res = await client.post(LIST_URL, data={**form, "pageIndex": str(page)})
|
||||
res.raise_for_status()
|
||||
chunk = res.json().get("resultList") or []
|
||||
if not chunk:
|
||||
break
|
||||
items.extend(chunk)
|
||||
await asyncio.sleep(REQUEST_GAP_SEC)
|
||||
return items
|
||||
|
||||
|
||||
def _date(v) -> Optional[date]:
|
||||
try:
|
||||
return date.fromisoformat(str(v)[:10])
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
|
||||
def _coord(v) -> Optional[float]:
|
||||
try:
|
||||
return round(float(v), 5) if v not in (None, "") else None
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
|
||||
|
||||
def parse_seoul_festivals(items: list[dict]) -> list[dict]:
|
||||
rows = []
|
||||
for it in items:
|
||||
start, end = _date(it.get("strtdate")), _date(it.get("endDate"))
|
||||
name = _HOST_PREFIX.sub("", html.unescape(it.get("title") or "")).strip()
|
||||
if start is None or end is None or not name or it.get("cultcode") is None:
|
||||
continue
|
||||
rows.append({
|
||||
"source_id": f"{SOURCE_PREFIX}{it['cultcode']}", "sido_code": SEOUL, "name": name[:60],
|
||||
"place_name": html.unescape(it.get("facName") or it.get("addr") or "")[:60], "start_date": start, "end_date": end, "is_confirmed": True,
|
||||
"source_url": VIEW_URL.format(code=it["cultcode"]),
|
||||
"image_url": IMAGE_URL.format(id=it["atchFileId"]) if it.get("atchFileId") else None,
|
||||
# 이 목록은 xCoord 가 위도, yCoord 가 경도다
|
||||
"lat": _coord(it.get("xCoord")), "lon": _coord(it.get("yCoord")), "kind": EventKind.FESTIVAL, "icon": EVENT_ICON[EventKind.FESTIVAL],
|
||||
})
|
||||
return rows
|
||||
@@ -25,6 +25,8 @@ from router.v1.feed.protocol import (
|
||||
)
|
||||
from services.air_service import GRADE_LABEL as AIR_GRADE_LABEL
|
||||
from services.air_service import pm10_grade, pm25_grade
|
||||
from services.calc.day_slot import NIGHT_AFTER_SUNSET, slot_of
|
||||
from services.calc.index_calc import rank_score
|
||||
from services.calc.moon import illumination, nearest, phase_name
|
||||
from services.calc.sky_score import GRADE_LABEL, SITUATION_LINE
|
||||
from services.calc.sun import sun_times
|
||||
@@ -62,6 +64,19 @@ LINEUP = [
|
||||
(19, PostType.MOON, RefType.NONE, None),
|
||||
(20, PostType.UV, RefType.NONE, None),
|
||||
]
|
||||
# 좋아요·댓글 단위. 이 종류들은 전국이 같은 카드 하나, 나머지는 그 구 데이터로 채우는 카드라 시도마다 따로 만든다.
|
||||
NATIONAL_SCOPE = "00"
|
||||
NATIONAL_TYPES = frozenset({PostType.SEASON, PostType.TIP, PostType.QUOTE, PostType.MOON})
|
||||
|
||||
|
||||
def sido_of(region_code: str) -> str:
|
||||
"""구 행정코드의 시도 부분(앞 2자리)."""
|
||||
return region_code[:2]
|
||||
|
||||
|
||||
def post_scope(post_type: PostType, region_code: str) -> str:
|
||||
return NATIONAL_SCOPE if post_type in NATIONAL_TYPES else sido_of(region_code)
|
||||
|
||||
# 시간대별 순서. 목록에 없는 종류는 그 시간대에 꺼진다. '오늘 하루 날씨'는 히어로 바로 아래 고정이라 따로 둔다. 행사는 사이사이 무작위.
|
||||
ORDER = {
|
||||
"morning": [PostType.ALERT, PostType.AIR, PostType.UV, PostType.GAK, PostType.GAK, PostType.GAK, PostType.SEASON, PostType.SUNSET, PostType.TIP, PostType.WEEK, PostType.WEEKEND_PLAN, PostType.WEEKEND_PLAN, PostType.DAY_TRIP, PostType.MOON, PostType.QUOTE],
|
||||
@@ -74,7 +89,6 @@ _CATEGORY_META = {ArticleCategory.SEASON.value: "계절 소식", ArticleCategory
|
||||
_FEED_TTL_MAX = 3600
|
||||
_PARTIAL_TTL = 60
|
||||
_SUNSET_HOUR = 18 # 노을 시간대 각의 대략적인 순서용
|
||||
_NIGHT_AFTER_SUNSET = timedelta(hours=1) # 해 지고 이만큼 지나면 밤
|
||||
_RAIN_PROB = 40
|
||||
_UV_SHOW = 3 # 자외선 포스트: 오늘 가장 셀 때 '보통' 이상이면 띄운다
|
||||
_HERO_RAIN_PROB = 60 # 히어로 '오늘 비': 오늘 남은 칸 중 비 형태가 있거나 확률이 이만큼 넘는 첫 칸
|
||||
@@ -140,22 +154,12 @@ def feed_day(now: datetime) -> date:
|
||||
return (now - timedelta(hours=_FEED_DAY_START)).date()
|
||||
|
||||
|
||||
def slot_of(now: datetime, sunset_at: datetime) -> str:
|
||||
"""아침 05–11 · 낮 11–일몰 2시간 전 · 저녁 일몰 2시간 전–일몰 1시간 뒤 · 밤 일몰 1시간 뒤–05. 밤은 계절 따라 18시대~21시대에 온다."""
|
||||
h = now.hour
|
||||
if 5 <= h < 11:
|
||||
return "morning"
|
||||
if h >= 11 and now < sunset_at + _NIGHT_AFTER_SUNSET:
|
||||
return "day" if now < sunset_at - timedelta(hours=2) else "evening"
|
||||
return "night"
|
||||
|
||||
|
||||
def feed_ttl_sec(now: datetime, sunset_at: datetime) -> int:
|
||||
"""다음에 피드가 달라지는 시각까지. 시간대 경계·일몰(노을 카드가 내일 것으로)·03:00·예보·미세먼지 갱신 중 가장 빠른 쪽."""
|
||||
day = now.date()
|
||||
at = lambda d, h: datetime.combine(d, time(h), tzinfo=KST) # noqa: E731
|
||||
sunset = sunset_at.astimezone(KST)
|
||||
changes = [at(day, _FEED_DAY_START), at(day, 5), at(day, 11), sunset - timedelta(hours=2), sunset, sunset + _NIGHT_AFTER_SUNSET,
|
||||
changes = [at(day, _FEED_DAY_START), at(day, 5), at(day, 11), sunset - timedelta(hours=2), sunset, sunset + NIGHT_AFTER_SUNSET,
|
||||
at(day + timedelta(days=1), _FEED_DAY_START), next_vilage_available(now)]
|
||||
air = now.replace(minute=20, second=0, microsecond=0)
|
||||
changes.append(air if air > now else air + timedelta(hours=1))
|
||||
@@ -223,17 +227,33 @@ def arrange(cards: list[PostData], slot: str, now: datetime, sunset_at: datetime
|
||||
return head + rest
|
||||
|
||||
|
||||
def _by_position(posts: list[Post]) -> list[Post]:
|
||||
"""번호마다 하나. 전국 행과 시도 행이 같이 있으면 전국 행을 쓴다 (지역 카드라도 그날 전국 행이 있으면 전국이 그 행을 같이 쓴다)."""
|
||||
out: dict[int, Post] = {}
|
||||
for p in sorted(posts, key=lambda p: (p.position, p.scope != NATIONAL_SCOPE)):
|
||||
out.setdefault(p.position, p)
|
||||
return list(out.values())
|
||||
|
||||
|
||||
def _top(i: IndexItem) -> TopIndex:
|
||||
d = i.definition
|
||||
return TopIndex(index_id=d.index_id, code=d.code, name=d.name, icon=d.icon, score=i.score.score, rank=i.rank, summary=i.score.summary)
|
||||
return TopIndex(index_id=d.index_id, code=d.code, name=d.name, icon=d.icon, score=i.score.score, rank=i.rank, summary=i.score.summary, active=i.active)
|
||||
|
||||
|
||||
async def build_feed_day(day: date, crud: FeedCRUD, season_crud: SeasonCRUD) -> ErrorType:
|
||||
"""그날 피드 카드를 넣는다. 이미 있는 번호는 그대로 두고, 새로 생긴 종류만 더한다. 모든 카드는 03:00 부터 다음 날 03:00 까지 유효하다."""
|
||||
async def build_feed_day(day: date, crud: FeedCRUD, season_crud: SeasonCRUD, regions: RegionCRUD) -> ErrorType:
|
||||
"""그날 피드 카드를 전국 1벌·시도마다 1벌 넣는다. 이미 있는 (scope, 번호)는 그대로 두고, 빠진 것만 더한다.
|
||||
전국 행이 있는 번호는 모든 시도가 그 행을 쓰므로 시도 행을 만들지 않는다. 모든 카드는 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]
|
||||
err, all_regions = await DB_SESSION_MNG.execute_lambda(lambda s: regions.search(s))
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return err
|
||||
sidos = sorted({sido_of(r.code) for r in all_regions})
|
||||
lineup = [
|
||||
(scope, *x) for x in LINEUP for scope in ([NATIONAL_SCOPE] if x[1] in NATIONAL_TYPES else sidos)
|
||||
if (scope, x[0]) not in made and (NATIONAL_SCOPE, x[0]) not in made
|
||||
]
|
||||
if not lineup:
|
||||
return err
|
||||
_, season = await DB_SESSION_MNG.execute_lambda(lambda s: season_crud.articles(s, day, ArticleCategory.SEASON.value))
|
||||
@@ -242,12 +262,12 @@ 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 scope, position, post_type, ref_type, rank in lineup:
|
||||
ref = refs.get(post_type)
|
||||
if ref_type is RefType.ARTICLE and ref is None:
|
||||
continue
|
||||
rows.append({
|
||||
"feed_date": day, "position": position, "post_type": post_type.value, "ref_type": ref_type.value,
|
||||
"feed_date": day, "position": position, "scope": scope, "post_type": post_type.value, "ref_type": ref_type.value,
|
||||
"ref_id": ref.article_id if ref is not None else None, "index_rank": rank,
|
||||
"published_at": start, "end_at": end,
|
||||
})
|
||||
@@ -301,7 +321,7 @@ class FeedService:
|
||||
|
||||
day = feed_day(now)
|
||||
async with redis_lock("lock:feed:build", ttl_sec=20):
|
||||
await build_feed_day(day, self.crud, self.season_crud)
|
||||
await build_feed_day(day, self.crud, self.season_crud, self.regions)
|
||||
res, partial = await self._assemble(region, now, day, slot, sunset_at)
|
||||
try:
|
||||
await REDIS.conn.set(key, res.model_dump_json(), ex=_PARTIAL_TTL if partial else feed_ttl_sec(now, sunset_at))
|
||||
@@ -332,7 +352,8 @@ class FeedService:
|
||||
_, 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)))
|
||||
)
|
||||
_, posts = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.day(s, day))
|
||||
_, posts = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.day(s, day, [NATIONAL_SCOPE, sido_of(region.code)]))
|
||||
posts = _by_position(posts or [])
|
||||
_, articles = await DB_SESSION_MNG.execute_lambda(lambda s: self.season_crud.articles(s, now.date(), None))
|
||||
by_article = {a.article_id: a for a in articles or []}
|
||||
quotes = [a for a in articles or [] if a.category == ArticleCategory.QUOTE.value]
|
||||
@@ -340,7 +361,7 @@ class FeedService:
|
||||
days=days, events=events, sunsets=sunsets, hourly=hourly or [], articles=by_article, quotes=quotes, trip=trip,
|
||||
uv=await self._uv_today(region.code, now))
|
||||
|
||||
gak = sorted(board.items[:3], key=lambda i: _gak_key(i, now.hour)) if board else []
|
||||
gak = sorted(board.ranked[:3], key=lambda i: _gak_key(i, now.hour)) if board else []
|
||||
cards = []
|
||||
for p in posts or []:
|
||||
if PostType(p.post_type) is PostType.GAK:
|
||||
@@ -360,9 +381,10 @@ class FeedService:
|
||||
bands=Bands(
|
||||
events=[BandEvent(event_id=e.event.event_id, name=e.event.name, status_label=e.status_label, icon=e.event.icon,
|
||||
image=e.event.image_url, image_credit=image_credit(e.event)) for e in mix_kinds(events)[:4]],
|
||||
top5=[_top(i) for i in items[:5]],
|
||||
top5=[_top(i) for i in board.ranked[:5]] if board else [],
|
||||
season=[
|
||||
BandArticle(article_id=a.article_id, title=a.title, meta=f"{_CATEGORY_META[a.category]} · {a.read_minutes}분", icon=a.icon)
|
||||
BandArticle(article_id=a.article_id, title=a.title, meta=f"{_CATEGORY_META[a.category]} · {a.read_minutes}분", icon=a.icon,
|
||||
image=a.image_url, image_credit=a.image_credit)
|
||||
for a in articles or [] if a.category == ArticleCategory.SEASON.value
|
||||
],
|
||||
),
|
||||
@@ -402,7 +424,7 @@ class FeedService:
|
||||
|
||||
def _hero(self, now: datetime, slot: str, cur: Optional[WeatherHourly], now_w: Optional[NowWeather], board: Optional[IndexBoard],
|
||||
today: Optional[TodayWeather] = None, uv: Optional[float] = None) -> Hero:
|
||||
top = board.items[0] if board and board.items else None
|
||||
top = board.ranked[0] if board and board.ranked else None
|
||||
bubble = None
|
||||
if top is not None:
|
||||
bubble = f"오늘은 {top.definition.name}!" if top.score.score >= 70 else "오늘은 쉬어 가요"
|
||||
@@ -450,7 +472,8 @@ class FeedService:
|
||||
if t in (PostType.SEASON, PostType.TIP) and p.ref_id in c.articles:
|
||||
a = c.articles[p.ref_id]
|
||||
return PostData(**base, title=a.title, icon=a.icon, caption=" ".join(a.body[1:2]) or a.body[0],
|
||||
slides=[RowsSlide(kind="rows", eyebrow=_CATEGORY_META[a.category], line=a.body[0], icon=a.icon)], share_messages=[a.title])
|
||||
slides=[RowsSlide(kind="rows", eyebrow=_CATEGORY_META[a.category], line=a.body[0], icon=a.icon, image=a.image_url, image_credit=a.image_credit)],
|
||||
share_messages=[a.title])
|
||||
if t is PostType.EVENT:
|
||||
soon = mix_kinds([e for e in c.events if e.event.start_date <= c.now.date() + timedelta(days=7) and e.event.end_date >= c.now.date()])
|
||||
rank = p.index_rank or 1
|
||||
@@ -656,7 +679,7 @@ class FeedService:
|
||||
best = None
|
||||
for i in c.board.items if c.board else []:
|
||||
s = next((x for x in i.trend if x.score_date == tomorrow), None)
|
||||
if s is not None and (best is None or s.score > best[1].score):
|
||||
if s is not None and (best is None or rank_score(s.score, i.definition.priority) > rank_score(best[1].score, best[0].definition.priority)):
|
||||
best = (i, s)
|
||||
if best is not None:
|
||||
rows.append(Row(label="내일 1위 각", value=f"{best[0].definition.name} {best[1].score}점"))
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import asyncio
|
||||
from dataclasses import dataclass, replace
|
||||
from dataclasses import dataclass, field, replace
|
||||
from datetime import date, datetime, time, timedelta
|
||||
from types import SimpleNamespace
|
||||
from typing import Optional
|
||||
@@ -16,7 +16,8 @@ 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, DayForecast, Hour, Result, estimate, evaluate
|
||||
from services.calc.day_slot import NIGHT_END_HOUR, SLOTS, slot_hours, slot_of
|
||||
from services.calc.index_calc import AXES, Context, DayForecast, Hour, Result, estimate, evaluate, rank_score
|
||||
from services.calc.moon import illumination
|
||||
from services.calc.sun import sun_times
|
||||
from services.external.open_meteo import is_dark_slot
|
||||
@@ -28,14 +29,15 @@ DAYS = 3
|
||||
_LOOKAHEAD_HOURS = (9, 18)
|
||||
_WEEKDAY_KO = ("월", "화", "수", "목", "금", "토", "일")
|
||||
|
||||
# 메인 하늘 영역의 '오늘 날씨 점수': 낮 9~21시 밖에 나가기 좋은 정도.
|
||||
# 메인 하늘 영역의 '지금 날씨 점수': 지금 구간(아침·낮·저녁·밤) 밖에 나가기 좋은 정도.
|
||||
WEATHER_SCORE_DEF = SimpleNamespace(
|
||||
weight_temp=40, weight_rain=30, weight_wind=15, weight_humidity=0, weight_air=15, weight_time=0,
|
||||
weight_temp=30, weight_rain=25, weight_wind=10, weight_humidity=10, weight_air=10, weight_sun=15, weight_time=0,
|
||||
factor_rules={
|
||||
"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},
|
||||
"temp": {"type": "range", "lo": 18, "hi": 24, "best": 21, "plateau": 0.5}, "rain": {"dir": "dry"},
|
||||
"wind": {"type": "calm", "ok": 2, "limit": 10}, "humidity": {"type": "range", "lo": 40, "hi": 60, "best": 50},
|
||||
"air": {"zero": 75, "full": 10}, "sun": {"zero": 0.2, "full": 0.9}, "time": {"type": "fixed", "value": 100},
|
||||
},
|
||||
zero_rules=[], windows=[{"from": 9, "to": 21}],
|
||||
zero_rules=[], windows=[{"from": NIGHT_END_HOUR, "to": 24 + NIGHT_END_HOUR}],
|
||||
)
|
||||
|
||||
|
||||
@@ -45,6 +47,9 @@ class IndexItem:
|
||||
score: IndexScore
|
||||
rank: int
|
||||
trend: list[IndexScore]
|
||||
slot: Optional[str] = None
|
||||
slots: dict[str, int] = field(default_factory=dict)
|
||||
active: bool = True # 지금 구간이 이 각의 시간대와 겹치는지. 아니면 순위·피드에서 빼고 목록 끝에 하루 점수로 둔다
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -54,6 +59,11 @@ class IndexBoard:
|
||||
weather_score: Optional[int]
|
||||
items: list[IndexItem]
|
||||
|
||||
@property
|
||||
def ranked(self) -> list[IndexItem]:
|
||||
"""지금 구간에 해당하는 각만 (순위·피드용)."""
|
||||
return [i for i in self.items if i.active]
|
||||
|
||||
|
||||
def _hour(r: WeatherHourly) -> Hour:
|
||||
return Hour(
|
||||
@@ -118,13 +128,17 @@ def _om_fields(instant: Optional[OpenMeteoHourly], covering: Optional[OpenMeteoH
|
||||
|
||||
|
||||
def windows_for(
|
||||
defn, day: date, region: Region, by_at: dict[datetime, WeatherHourly], by_om: Optional[dict[datetime, OpenMeteoHourly]] = None
|
||||
defn, day: date, region: Region, by_at: dict[datetime, WeatherHourly], by_om: Optional[dict[datetime, OpenMeteoHourly]] = None,
|
||||
only: Optional[set[int]] = None,
|
||||
) -> list[list[Hour]]:
|
||||
"""시간대 정의를 그날의 시간별 날씨 목록으로 바꾼다. 24시 이후는 다음 날로 넘어간다. 시간마다 Open-Meteo 3시간 구간 값을 붙인다 (순간값은 가장 가까운 구간, 일조는 덮는 구간)."""
|
||||
"""시간대 정의를 그날의 시간별 날씨 목록으로 바꾼다. 24시 이후는 다음 날로 넘어간다. 시간마다 Open-Meteo 3시간 구간 값을 붙인다 (순간값은 가장 가까운 구간, 일조는 덮는 구간).
|
||||
only 가 있으면 그 시각만 남긴다."""
|
||||
by_om = by_om or {}
|
||||
start = kst_midnight(day)
|
||||
out = []
|
||||
for hours in window_hours(defn, day, region):
|
||||
if only is not None:
|
||||
hours = [h for h in hours if h in only]
|
||||
rows = [by_at.get(start + timedelta(hours=h)) for h in hours]
|
||||
out.append([
|
||||
replace(_hour(r), hour=h, **_om_fields(
|
||||
@@ -135,6 +149,44 @@ def windows_for(
|
||||
return out
|
||||
|
||||
|
||||
EARLY = "early" # 0~5시: 전날 밤 구간
|
||||
|
||||
|
||||
def current_slot(now: datetime, sunset_at: datetime) -> str:
|
||||
return EARLY if now.hour < NIGHT_END_HOUR else slot_of(now, sunset_at)
|
||||
|
||||
|
||||
def shown_slot(key: str) -> str:
|
||||
return "night" if key == EARLY else key
|
||||
|
||||
|
||||
def slot_results(
|
||||
defn, day: date, region: Region, by_at: dict[datetime, WeatherHourly], by_om: dict[datetime, OpenMeteoHourly], ctx: Context, sunset_at: datetime,
|
||||
) -> dict[str, Result]:
|
||||
"""그날 아침·낮·저녁·밤과 0~5시(전날 밤) 점수. 각 시간대와 겹치지 않는 구간은 빠진다."""
|
||||
parts = {k: windows_for(defn, day, region, by_at, by_om, only=hours) for k, hours in slot_hours(day, sunset_at).items()}
|
||||
parts[EARLY] = windows_for(defn, day - timedelta(days=1), region, by_at, by_om, only=set(range(24, 24 + NIGHT_END_HOUR)))
|
||||
out = {}
|
||||
for key, windows in parts.items():
|
||||
result = evaluate(defn, windows, ctx)
|
||||
if result is not None:
|
||||
out[key] = result
|
||||
return out
|
||||
|
||||
|
||||
def _slot_json(r: Result) -> dict:
|
||||
return {"score": r.score, "summary": r.summary, "factors": r.factors, "zero_reason": r.zero_reason, "notes": r.notes}
|
||||
|
||||
|
||||
def _with_slot(row: IndexScore, data: dict) -> IndexScore:
|
||||
"""저장된 하루 점수 행을 구간 점수로 바꾼 사본 (DB에 붙지 않음)."""
|
||||
out = IndexScore(**{c.key: getattr(row, c.key) for c in IndexScore.__table__.columns})
|
||||
out.score, out.summary, out.zero_reason, out.notes = data["score"], data["summary"], data["zero_reason"], data["notes"]
|
||||
for a in AXES:
|
||||
setattr(out, f"{a}_score", data["factors"].get(a, 0))
|
||||
return out
|
||||
|
||||
|
||||
def day_forecast(d: WeatherDaily) -> DayForecast:
|
||||
return DayForecast(
|
||||
temp_min_c=float(d.temp_min_c) if d.temp_min_c is not None else None,
|
||||
@@ -204,20 +256,44 @@ class IndexService:
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return err, None
|
||||
today = now.date()
|
||||
cur = current_slot(now, sun_times(today, float(region.lat), float(region.lon)).sunset_at)
|
||||
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, 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}
|
||||
ranked = sorted((d for d in defs if (d.index_id, today) in by_key), key=lambda d: by_key[(d.index_id, today)].score, reverse=True)
|
||||
items = [
|
||||
IndexItem(
|
||||
definition=d, score=by_key[(d.index_id, today)], rank=i + 1,
|
||||
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)
|
||||
]
|
||||
# 오늘 점수는 지금 구간 점수. 구간 점수가 없는 행(예전 계산분)은 하루 점수 그대로, 지금 구간과 안 겹치는 각은 뺀다
|
||||
now_score: dict[int, IndexScore] = {}
|
||||
for d in defs:
|
||||
row = by_key.get((d.index_id, today))
|
||||
if row is None:
|
||||
continue
|
||||
if not row.slots:
|
||||
now_score[d.index_id] = row
|
||||
elif cur in row.slots:
|
||||
now_score[d.index_id] = _with_slot(row, row.slots[cur])
|
||||
ranked = sorted((d for d in defs if d.index_id in now_score), key=lambda d: rank_score(now_score[d.index_id].score, d.priority), reverse=True)
|
||||
items = []
|
||||
for i, d in enumerate(ranked):
|
||||
row = by_key[(d.index_id, today)]
|
||||
parts = {shown_slot(k): v["score"] for k, v in row.slots.items() if k != ("night" if cur == EARLY else EARLY)}
|
||||
items.append(IndexItem(
|
||||
definition=d, score=now_score[d.index_id], rank=i + 1,
|
||||
trend=[now_score[d.index_id] if day == today else by_key[(d.index_id, day)] for day in slots if (d.index_id, day) in by_key],
|
||||
slot=shown_slot(cur), slots={k: parts[k] for k in SLOTS if k in parts},
|
||||
))
|
||||
off = sorted(
|
||||
(d for d in defs if d.index_id not in now_score and (d.index_id, today) in by_key),
|
||||
key=lambda d: rank_score(by_key[(d.index_id, today)].score, d.priority), reverse=True,
|
||||
)
|
||||
for d in off:
|
||||
row = by_key[(d.index_id, today)]
|
||||
items.append(IndexItem(
|
||||
definition=d, score=row, rank=len(items) + 1,
|
||||
trend=[by_key[(d.index_id, day)] for day in slots if (d.index_id, day) in by_key],
|
||||
slots={shown_slot(k): v["score"] for k, v in row.slots.items() if k != ("night" if cur == EARLY else EARLY)}, active=False,
|
||||
))
|
||||
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]]:
|
||||
@@ -250,7 +326,8 @@ class IndexService:
|
||||
wind_warning=any(w.warning_type is WarningType.WIND for w in warnings or []),
|
||||
)
|
||||
today_ctx = Context(day=today, is_holiday=False, moon=0, sunset_score=None, lookahead_rain_prob=0, **base_ctx)
|
||||
weather_result = evaluate(WEATHER_SCORE_DEF, windows_for(WEATHER_SCORE_DEF, today, region, by_at, by_om), today_ctx)
|
||||
sunset_at = sun_times(today, float(region.lat), float(region.lon)).sunset_at
|
||||
weather_result = slot_results(WEATHER_SCORE_DEF, today, region, by_at, by_om, today_ctx, sunset_at).get(current_slot(now, sunset_at))
|
||||
|
||||
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
|
||||
@@ -258,8 +335,9 @@ class IndexService:
|
||||
inputs_at = max(inputs_at, max(r.fetched_at for r in by_om.values()))
|
||||
err, computed = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.last_computed(s, region.code, today))
|
||||
_, scored = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.score_dates(s, region.code, today, days[-1]))
|
||||
_, unslotted = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.has_unslotted(s, region.code, today))
|
||||
wanted = {d for d in days if d >= today + timedelta(days=DAYS) and d in daily and None not in (daily[d].temp_min_c, daily[d].temp_max_c)}
|
||||
if err is ErrorType.SUCCESS and computed is not None and computed >= inputs_at and wanted <= (scored or set()):
|
||||
if err is ErrorType.SUCCESS and computed is not None and computed >= inputs_at and wanted <= (scored or set()) and unslotted is False:
|
||||
return ErrorType.SUCCESS, weather_result.score if weather_result else None
|
||||
|
||||
err, defs = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.definitions(s))
|
||||
@@ -278,10 +356,12 @@ class IndexService:
|
||||
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
|
||||
parts = slot_results(d, day, region, by_at, by_om, ctx, sunset_at) if day == today else {}
|
||||
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,
|
||||
"estimated": result.estimated, "computed_at": now,
|
||||
"slots": {k: _slot_json(r) for k, r in parts.items()},
|
||||
})
|
||||
err = await DB_SESSION_MNG.execute_lambda_run([lambda s: self.crud.upsert_scores(s, out)])
|
||||
return err, weather_result.score if weather_result else None
|
||||
@@ -80,10 +80,12 @@ class RankItem:
|
||||
|
||||
|
||||
def nearest_spots(lat: float, lon: float, spots: list[SunsetSpot]) -> list[Spot]:
|
||||
"""반경 안에서 해 지는 쪽이 트인 곳(sort_order 0)을 먼저, 그 안에서는 가까운 순."""
|
||||
near = [Spot(spot=p, distance_km=round(haversine_km(lat, lon, float(p.lat), float(p.lon)), 1), direction=bearing_deg(lat, lon, float(p.lat), float(p.lon)))
|
||||
for p in spots]
|
||||
near = [x for x in near if x.distance_km <= SPOT_RADIUS_KM]
|
||||
"""반경 안에서 해 지는 쪽이 트인 곳(sort_order 0)을 먼저, 그 안에서는 가까운 순. 반경 안에 없으면 가장 가까운 한 곳."""
|
||||
every = [Spot(spot=p, distance_km=round(haversine_km(lat, lon, float(p.lat), float(p.lon)), 1), direction=bearing_deg(lat, lon, float(p.lat), float(p.lon)))
|
||||
for p in spots]
|
||||
near = [x for x in every if x.distance_km <= SPOT_RADIUS_KM]
|
||||
if not near:
|
||||
return sorted(every, key=lambda x: x.distance_km)[:1]
|
||||
return sorted(near, key=lambda x: (x.spot.sort_order, x.distance_km))[:SPOT_LIMIT]
|
||||
|
||||
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
import asyncio
|
||||
import math
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
from datetime import date, timedelta
|
||||
from typing import Optional
|
||||
@@ -20,11 +22,16 @@ 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.calc.index_calc import rank_score
|
||||
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 CONCERT, EXHIBITION, fetch_exhibitions, parse_exhibitions
|
||||
from services.external.data_go_kr import DataGoKrNotConfigured, DataGoKrRequestFailed
|
||||
from services.external.kasi import fetch_holidays
|
||||
from services.external.seoul_culture import IMAGE_CREDIT as SEOUL_CREDIT
|
||||
from services.external.seoul_culture import SEOUL
|
||||
from services.external.seoul_culture import SOURCE_PREFIX as SEOUL_PREFIX
|
||||
from services.external.seoul_culture import fetch_seoul_festivals, parse_seoul_festivals
|
||||
from services.external.tour_api import IMAGE_CREDIT as TOUR_CREDIT
|
||||
from services.external.tour_api import fetch_festivals, parse_festivals
|
||||
from services.index_service import IndexService
|
||||
@@ -36,6 +43,12 @@ MAX_EVENT_DAYS = 60
|
||||
EVENT_RADIUS_KM = 30
|
||||
# 행사는 시도 단위로 받는다. 구 중심이 이 거리 안에 있는 시도는 경계가 반경에 걸칠 수 있어 같이 받는다.
|
||||
_SIDO_REACH_KM = EVENT_RADIUS_KM + 20
|
||||
# 구 코드는 광주·전남을 한 시도(12)로 묶지만, 행사는 TourAPI·문화정보 시도 코드(광주 29 · 전남 46)로 받는다.
|
||||
_EVENT_SIDOS = {"12": ("29", "46")}
|
||||
PLACE_RADIUS_KM = EVENT_RADIUS_KM
|
||||
PLACE_LIMIT = 10
|
||||
# 반경 안에 명소가 하나도 없는 구는 가장 가까운 곳을 이만큼 거리와 함께 보여 준다.
|
||||
PLACE_FALLBACK = 3
|
||||
_ERRORS = (DataGoKrNotConfigured, DataGoKrRequestFailed, RedisError)
|
||||
_WEEKDAY_KO = ("월", "화", "수", "목", "금", "토", "일")
|
||||
_SKY_WORD = {Sky.CLEAR: "맑음", Sky.PARTLY: "구름 많음", Sky.CLOUDY: "흐림"}
|
||||
@@ -62,6 +75,7 @@ class DayPlan:
|
||||
class PlaceItem:
|
||||
place: Place
|
||||
is_good: bool
|
||||
distance_km: float
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -97,6 +111,8 @@ def image_credit(e: Event) -> Optional[str]:
|
||||
"""사진 출처 표기. 직접 넣은 행사(source_id 없음)는 출처를 모르니 None."""
|
||||
if not e.image_url or e.source_id is None:
|
||||
return None
|
||||
if e.source_id.startswith(SEOUL_PREFIX):
|
||||
return SEOUL_CREDIT
|
||||
return CULTURE_CREDIT if e.source_id.startswith(CULTURE_PREFIX) else TOUR_CREDIT
|
||||
|
||||
|
||||
@@ -115,11 +131,18 @@ def mix_kinds(items: list[EventItem]) -> list[EventItem]:
|
||||
return mixed
|
||||
|
||||
|
||||
def event_sidos(region_code: str) -> tuple[str, ...]:
|
||||
"""구가 속한 시도의 행사 시도 코드들."""
|
||||
sido = region_code[:2]
|
||||
return _EVENT_SIDOS.get(sido, (sido,))
|
||||
|
||||
|
||||
def nearby_sidos(region: Region, regions: list[Region]) -> list[str]:
|
||||
"""반경 안에 걸칠 수 있는 시도들. 자기 시도는 항상 앞에."""
|
||||
"""반경 안에 걸칠 수 있는 시도들(행사 시도 코드). 자기 시도는 항상 앞에."""
|
||||
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]})
|
||||
own = event_sidos(region.code)
|
||||
near = {s for r in regions if haversine_km(lat, lon, float(r.lat), float(r.lon)) <= _SIDO_REACH_KM for s in event_sidos(r.code)}
|
||||
return list(own) + sorted(near - set(own))
|
||||
|
||||
|
||||
def event_distance(region: Region, e: Event) -> Optional[float]:
|
||||
@@ -134,7 +157,23 @@ def is_nearby(region: Region, e: Event, distance_km: Optional[float]) -> bool:
|
||||
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]
|
||||
return e.sido_code in event_sidos(region.code)
|
||||
|
||||
|
||||
def pick_places(region: Region, places: list[Place], rainy: bool, area: Optional[str]) -> tuple[list[PlaceItem], list[str]]:
|
||||
"""구 중심에서 반경 안의 명소를 날씨에 맞는 것 먼저, 같으면 가까운 순으로. 반경 안에 없으면 가장 가까운 몇 곳."""
|
||||
lat, lon = float(region.lat), float(region.lon)
|
||||
dist = sorted(((p, round(haversine_km(lat, lon, float(p.lat), float(p.lon)), 1)) for p in places if p.lat is not None and p.lon is not None), key=lambda x: x[1])
|
||||
near = [x for x in dist if x[1] <= PLACE_RADIUS_KM] or dist[:PLACE_FALLBACK]
|
||||
areas = list(dict.fromkeys(p.area for p, _ in near))
|
||||
items = [PlaceItem(place=p, is_good=(not p.is_outdoor) if rainy else p.is_outdoor, distance_km=d) for p, d in near if area is None or p.area == area]
|
||||
items.sort(key=lambda i: (not i.is_good, i.distance_km))
|
||||
return items[:PLACE_LIMIT], areas
|
||||
|
||||
|
||||
def place_credit(p: Place) -> Optional[str]:
|
||||
"""명소 사진은 TourAPI 것만 넣는다."""
|
||||
return TOUR_CREDIT if p.image_url else None
|
||||
|
||||
|
||||
def _status(e: Event, today: date) -> tuple[str, str]:
|
||||
@@ -155,17 +194,59 @@ async def _culture(client: httpx.AsyncClient, sido: str, today: date, realm: str
|
||||
return []
|
||||
|
||||
|
||||
# 같은 축제를 두 출처가 다르게 적는다: "[성동문화재단] 2026 크리에이티브X성수" ↔ "2026 크리에이티브X성수"
|
||||
_NAME_NOISE = re.compile(r"\[[^\]]*\]|\([^)]*\)|20\d\d|제\s*\d+\s*회|[^\w]")
|
||||
|
||||
|
||||
def _name_key(name: str) -> str:
|
||||
return _NAME_NOISE.sub("", name).lower()
|
||||
|
||||
|
||||
async def drop_known(rows: list[dict]) -> list[dict]:
|
||||
"""다른 출처로 이미 들어 있는 행사(같은 시도, 이름이 같고 기간이 겹침)는 뺀다. 먼저 넣은 출처를 남긴다."""
|
||||
if not rows:
|
||||
return rows
|
||||
since, until = min(r["start_date"] for r in rows), max(r["end_date"] for r in rows)
|
||||
err, existing = await DB_SESSION_MNG.execute_lambda(lambda s: WeekCRUD().events(s, sorted({r["sido_code"] for r in rows}), since, until))
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return rows
|
||||
known: dict[tuple[str, str], list[Event]] = {}
|
||||
for e in existing or []:
|
||||
known.setdefault((e.sido_code, _name_key(e.name)), []).append(e)
|
||||
|
||||
def dup(r: dict) -> bool:
|
||||
key = _name_key(r["name"])
|
||||
return bool(key) and any(e.source_id != r["source_id"] and e.start_date <= r["end_date"] and r["start_date"] <= e.end_date
|
||||
for e in known.get((r["sido_code"], key), []))
|
||||
|
||||
return [r for r in rows if not dup(r)]
|
||||
|
||||
|
||||
async def _seoul(client: httpx.AsyncClient, sido: str, today: date, known: list[dict]) -> list[dict]:
|
||||
"""서울문화포털 축제(동네·구청·공원 행사). TourAPI 에 이미 있는 축제는 뺀다. 실패해도 다른 출처는 그대로 넣는다."""
|
||||
if sido != SEOUL:
|
||||
return []
|
||||
try:
|
||||
rows = parse_seoul_festivals(await fetch_seoul_festivals(client, today, EVENT_DAYS))
|
||||
except (httpx.HTTPError, ValueError) as e:
|
||||
LOG.error(f"[week] seoul festivals: {type(e).__name__} {e}")
|
||||
return []
|
||||
names = {_name_key(r["name"]) for r in known}
|
||||
return [r for r in rows if _name_key(r["name"]) not in names]
|
||||
|
||||
|
||||
async def collect_events(sido: str, today: date) -> tuple[ErrorType, dict[str, int]]:
|
||||
"""시도 하나의 축제·전시·콘서트를 받아 event 에 넣는다. 종류별 건수를 돌려준다."""
|
||||
try:
|
||||
async with httpx.AsyncClient(timeout=30) as client:
|
||||
festivals = parse_festivals(await fetch_festivals(client, sido, today), sido)
|
||||
festivals += await _seoul(client, sido, today, festivals)
|
||||
exhibitions = await _culture(client, sido, today, EXHIBITION)
|
||||
concerts = await _culture(client, sido, today, CONCERT)
|
||||
except (DataGoKrNotConfigured, DataGoKrRequestFailed) as e:
|
||||
LOG.error(f"[week] events {sido}: {e}")
|
||||
return ErrorType.EXTERNAL_API_ERROR, {}
|
||||
rows = list({r["source_id"]: r for r in festivals + exhibitions + concerts}.values())
|
||||
rows = await drop_known(list({r["source_id"]: r for r in festivals + exhibitions + concerts}.values()))
|
||||
err = await DB_SESSION_MNG.execute_lambda_run([lambda s: WeekCRUD().upsert_events(s, rows)])
|
||||
LOG.info(f"[week] events {sido} {len(rows)}: {err.name}")
|
||||
return err, {"festival": len(festivals), "exhibition": len(exhibitions), "concert": len(concerts)}
|
||||
@@ -205,11 +286,12 @@ class WeekService:
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return err, []
|
||||
names = {d.index_id: d.name for d in defs or []}
|
||||
priority = {d.index_id: d.priority for d in defs or []}
|
||||
plans = []
|
||||
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 and not x.estimated), key=lambda x: x.score, reverse=True)[:2]
|
||||
top = sorted((x for x in scores or [] if x.score_date == d.forecast_date and not x.estimated), key=lambda x: rank_score(x.score, priority.get(x.index_id, 2)), reverse=True)[:2]
|
||||
holiday = (holidays or {}).get(d.forecast_date)
|
||||
weekday = _WEEKDAY_KO[d.forecast_date.weekday()]
|
||||
word = _weather_word(d, rain_hours)
|
||||
@@ -229,19 +311,21 @@ class WeekService:
|
||||
))
|
||||
return ErrorType.SUCCESS, plans
|
||||
|
||||
async def places(self, region_code: str, day: date, area: Optional[str]) -> tuple[ErrorType, list[PlaceItem], list[str]]:
|
||||
async def places(self, region_code: str, day: date, area: Optional[str]) -> tuple[ErrorType, list[PlaceItem], list[str], bool]:
|
||||
err, region = await self._region(region_code)
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return err, [], []
|
||||
err, places = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.places(s, region.code[:2]))
|
||||
return err, [], [], False
|
||||
lat, lon = float(region.lat), float(region.lon)
|
||||
dlat, dlon = PLACE_RADIUS_KM / 111, PLACE_RADIUS_KM / (111 * math.cos(math.radians(lat)))
|
||||
err, places = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.places_in_box(s, lat, lon, dlat, dlon))
|
||||
if err is ErrorType.SUCCESS and not any(haversine_km(lat, lon, float(p.lat), float(p.lon)) <= PLACE_RADIUS_KM for p in places):
|
||||
err, places = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.all_places(s))
|
||||
_, daily = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.daily(s, region.code, day, day))
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return err, [], []
|
||||
return err, [], [], False
|
||||
rainy = bool(daily) and daily[0].rain_type != RainType.NONE.value
|
||||
areas = list(dict.fromkeys(p.area for p in places))
|
||||
picked = [p for p in places if area is None or p.area == area]
|
||||
picked.sort(key=lambda p: (p.is_outdoor if rainy else not p.is_outdoor, p.sort_order))
|
||||
return ErrorType.SUCCESS, [PlaceItem(place=p, is_good=(not p.is_outdoor) if rainy else p.is_outdoor) for p in picked], areas
|
||||
items, areas = pick_places(region, places, rainy, area)
|
||||
return ErrorType.SUCCESS, items, areas, rainy
|
||||
|
||||
async def events(self, region_code: str, area: Optional[str]) -> tuple[ErrorType, list[EventItem]]:
|
||||
err, region = await self._region(region_code)
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
from datetime import date, datetime
|
||||
from typing import Optional
|
||||
@@ -158,7 +159,7 @@ def _sort(steps: list[Step]) -> list[Step]:
|
||||
def key(s: Step) -> float:
|
||||
t = s.time
|
||||
if t[0].isdigit():
|
||||
h = int(t.split("~")[0].split(":")[0])
|
||||
h = int(re.match(r"\d+", t).group())
|
||||
return 5.5 if h >= 17 else 1.5 if h < 12 else 3
|
||||
if t.startswith("~"):
|
||||
return 0
|
||||
|
||||
@@ -65,6 +65,14 @@ async def _async(v):
|
||||
return v
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _no_seoul_crawl(monkeypatch):
|
||||
"""서울문화포털은 키 없이 바로 긁어 오므로, 테스트가 실제 사이트를 부르지 않게 기본으로 막는다."""
|
||||
import services.week_service as week_service
|
||||
|
||||
monkeypatch.setattr(week_service, "fetch_seoul_festivals", lambda *a: _async([]))
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def offline(monkeypatch):
|
||||
"""외부 API 를 모두 맑고 잔잔한 가짜 값으로 바꾼다."""
|
||||
|
||||
@@ -5,7 +5,8 @@ import httpx
|
||||
import pytest
|
||||
|
||||
from config.settings import settings
|
||||
from services.external import data_go_kr, guard, open_meteo
|
||||
from services.external import airkorea, data_go_kr, guard, open_meteo
|
||||
from services.external.airkorea import fetch_realtime
|
||||
from services.external.data_go_kr import DataGoKrRequestFailed, get_body
|
||||
from services.external.open_meteo import OpenMeteoRequestFailed, fetch_clouds
|
||||
|
||||
@@ -93,3 +94,16 @@ async def test_open_meteo_down_is_skipped(monkeypatch):
|
||||
with pytest.raises(OpenMeteoRequestFailed):
|
||||
await fetch_clouds(client, [(37.5, 127.0)])
|
||||
assert len(calls) == 1
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_airkorea_nationwide_call_waits_past_default_budget(fast, monkeypatch):
|
||||
"""전국 미세먼지 조회는 15~20초 걸려 기본 한도로는 늘 실패한다."""
|
||||
monkeypatch.setattr(airkorea, "BUDGET_SEC", 2.0)
|
||||
|
||||
async def slow(req: httpx.Request) -> httpx.Response:
|
||||
await asyncio.sleep(0.5)
|
||||
return httpx.Response(200, json={"response": {"header": {"resultCode": "00"}, "body": {"items": [{"stationName": "x"}], "totalCount": 1}}})
|
||||
|
||||
async with _client(slow) as client:
|
||||
assert await fetch_realtime(client) == [{"stationName": "x"}]
|
||||
@@ -0,0 +1,63 @@
|
||||
from datetime import date, datetime, timedelta
|
||||
from types import SimpleNamespace
|
||||
|
||||
from common.enums import RainType, Sky
|
||||
from common.utils.kma_time import KST, kst_midnight
|
||||
from services.calc.day_slot import slot_hours
|
||||
from services.calc.index_calc import Context
|
||||
from services.index_service import EARLY, WEATHER_SCORE_DEF, current_slot, slot_results
|
||||
|
||||
DAY = date(2026, 10, 8)
|
||||
SUNSET = datetime(2026, 10, 8, 18, 0, tzinfo=KST)
|
||||
REGION = SimpleNamespace(lat=37.5, lon=127.0)
|
||||
CTX = Context(day=DAY, is_holiday=False, pm25=10, air_label="좋음", moon=0, sunset_score=None, wind_warning=False, lookahead_rain_prob=0)
|
||||
|
||||
|
||||
def _rows(rain_from: int = 99):
|
||||
start = kst_midnight(DAY)
|
||||
return {
|
||||
start + timedelta(hours=h): SimpleNamespace(
|
||||
forecast_at=start + timedelta(hours=h), feels_c=21.0, rain_type=RainType.RAIN.value if h >= rain_from else RainType.NONE.value,
|
||||
rain_prob=90 if h >= rain_from else 0, wind_ms=1.0, humidity=50, sky=Sky.CLEAR.value,
|
||||
)
|
||||
for h in range(0, 30)
|
||||
}
|
||||
|
||||
|
||||
def _defn(windows):
|
||||
return SimpleNamespace(
|
||||
weight_temp=50, weight_rain=50, weight_wind=0, weight_humidity=0, weight_air=0, weight_time=0,
|
||||
factor_rules={"temp": {"type": "range", "lo": 18, "hi": 24}, "rain": {"dir": "dry"}, "wind": {"type": "ignore"},
|
||||
"humidity": {"type": "ignore"}, "time": {"type": "fixed", "value": 100}},
|
||||
zero_rules=[], windows=windows,
|
||||
)
|
||||
|
||||
|
||||
def test_slot_hours_split_by_sunset():
|
||||
hours = slot_hours(DAY, SUNSET)
|
||||
assert hours["morning"] == set(range(5, 11))
|
||||
assert hours["day"] == set(range(11, 16))
|
||||
assert hours["evening"] == {16, 17, 18}
|
||||
assert hours["night"] == set(range(19, 29))
|
||||
|
||||
|
||||
def test_current_slot_before_5_is_previous_night():
|
||||
assert current_slot(datetime(2026, 10, 8, 2, 0, tzinfo=KST), SUNSET) == EARLY
|
||||
assert current_slot(datetime(2026, 10, 8, 16, 30, tzinfo=KST), SUNSET) == "evening"
|
||||
|
||||
|
||||
def test_gak_hidden_in_slots_outside_its_window():
|
||||
parts = slot_results(_defn([{"from": 18, "to": 24}]), DAY, REGION, _rows(), {}, CTX, SUNSET)
|
||||
assert set(parts) == {"evening", "night"}
|
||||
|
||||
|
||||
def test_rain_in_evening_lowers_only_later_slots():
|
||||
parts = slot_results(_defn([{"from": 7, "to": 23}]), DAY, REGION, _rows(rain_from=16), {}, CTX, SUNSET)
|
||||
assert parts["morning"].score > 80
|
||||
assert parts["evening"].score < parts["morning"].score
|
||||
assert parts["night"].score < parts["morning"].score
|
||||
|
||||
|
||||
def test_weather_score_covers_every_slot():
|
||||
parts = slot_results(WEATHER_SCORE_DEF, DAY, REGION, _rows(), {}, CTX, SUNSET)
|
||||
assert set(parts) == {"morning", "day", "evening", "night", EARLY}
|
||||
@@ -8,6 +8,7 @@ from common.database.db_session_manager import DB_SESSION_MNG
|
||||
from common.enums import PostType
|
||||
from common.utils.kma_time import now_kst
|
||||
from crud.feed_crud import FeedCRUD
|
||||
from crud.region_crud import RegionCRUD
|
||||
from crud.season_crud import SeasonCRUD
|
||||
from router.router import app
|
||||
from services.feed_service import build_feed_day
|
||||
@@ -16,17 +17,19 @@ from services.week_service import collect_events
|
||||
REGION = "1114000000"
|
||||
|
||||
|
||||
async def _posts(day: date):
|
||||
_, rows = await DB_SESSION_MNG.execute_lambda(lambda s: s.execute(text(f"SELECT post_type FROM post WHERE feed_date='{day}' ORDER BY position")))
|
||||
async def _posts(day: date, sido: str = REGION[:2]):
|
||||
"""한 시도가 보는 그날 카드 (전국 + 그 시도)."""
|
||||
_, rows = await DB_SESSION_MNG.execute_lambda(lambda s: s.execute(text(
|
||||
f"SELECT post_type FROM post WHERE feed_date='{day}' AND scope IN ('00', '{sido}') ORDER BY position")))
|
||||
return [r[0] for r in rows]
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_build_day_adds_weekend_post_every_day():
|
||||
monday, thursday = date(2026, 10, 12), date(2026, 10, 15)
|
||||
await build_feed_day(monday, FeedCRUD(), SeasonCRUD())
|
||||
await build_feed_day(thursday, FeedCRUD(), SeasonCRUD())
|
||||
await build_feed_day(thursday, FeedCRUD(), SeasonCRUD())
|
||||
await build_feed_day(monday, FeedCRUD(), SeasonCRUD(), RegionCRUD())
|
||||
await build_feed_day(thursday, FeedCRUD(), SeasonCRUD(), RegionCRUD())
|
||||
await build_feed_day(thursday, FeedCRUD(), SeasonCRUD(), RegionCRUD())
|
||||
assert (await _posts(monday)).count(PostType.WEEK.value) == 1
|
||||
assert (await _posts(thursday)).count(PostType.WEEK.value) == 1
|
||||
assert (await _posts(thursday))[0] == PostType.WEATHER.value
|
||||
@@ -36,10 +39,10 @@ async def test_build_day_adds_weekend_post_every_day():
|
||||
async def test_build_day_adds_new_card_types_to_existing_day():
|
||||
"""이미 만든 날에 새 종류(미세먼지)가 생기면 빠진 카드만 더한다."""
|
||||
thursday = date(2026, 10, 15)
|
||||
await build_feed_day(thursday, FeedCRUD(), SeasonCRUD())
|
||||
await build_feed_day(thursday, FeedCRUD(), SeasonCRUD(), RegionCRUD())
|
||||
await DB_SESSION_MNG.execute_lambda_run([lambda s: s.execute(text(f"DELETE FROM post WHERE feed_date='{thursday}' AND post_type={PostType.AIR.value}"))])
|
||||
before = len(await _posts(thursday))
|
||||
await build_feed_day(thursday, FeedCRUD(), SeasonCRUD())
|
||||
await build_feed_day(thursday, FeedCRUD(), SeasonCRUD(), RegionCRUD())
|
||||
after = await _posts(thursday)
|
||||
assert len(after) == before + 1 and after.count(PostType.AIR.value) == 1
|
||||
|
||||
@@ -58,7 +61,7 @@ async def test_feed_assembles_hero_stories_posts_and_bands(offline):
|
||||
body = (await client.get("/v1/feed", params={"region": REGION})).json()
|
||||
assert body["result"]["success"] is True
|
||||
assert body["hero"]["temp_c"] == 20 and body["hero"]["top1"]["rank"] == 1 and "top3" not in body["hero"]
|
||||
assert len(body["stories"]) == 27
|
||||
assert len(body["stories"]) == 34
|
||||
weather = next(p for p in body["posts"] if p["post_type"] == PostType.WEATHER.value)
|
||||
assert [s["kind"] for s in weather["slides"]] == ["hours", "hours"]
|
||||
assert len(weather["slides"][0]["hours"]) == 8
|
||||
@@ -155,7 +158,7 @@ def test_arrange_scatters_up_to_three_events_same_spot_all_day():
|
||||
@pytest.mark.anyio
|
||||
async def test_build_day_makes_every_card_at_three():
|
||||
thursday = date(2026, 10, 15)
|
||||
await build_feed_day(thursday, FeedCRUD(), SeasonCRUD())
|
||||
await build_feed_day(thursday, FeedCRUD(), SeasonCRUD(), RegionCRUD())
|
||||
_, rows = await DB_SESSION_MNG.execute_lambda(lambda s: s.execute(text(f"SELECT post_type, published_at FROM post WHERE feed_date='{thursday}'")))
|
||||
rows = list(rows)
|
||||
assert {PostType.ALERT.value, PostType.TOMORROW.value, PostType.QUOTE.value} <= {r[0] for r in rows}
|
||||
|
||||
@@ -9,10 +9,13 @@ import services.warning_service as warning_service
|
||||
import services.weather_service as weather_service
|
||||
from common.database.db_session_manager import DB_SESSION_MNG
|
||||
from common.database.model.models import OpenMeteoHourly, WeatherHourly
|
||||
from common.enums import ErrorType
|
||||
from common.utils.kma_time import kst_midnight, now_kst
|
||||
from crud.region_crud import RegionCRUD
|
||||
from crud.weather_crud import WeatherCRUD
|
||||
from router.router import app
|
||||
from services.index_service import _nearest_slot_end_hour, _slot_end_hour, slot_days, slot_label, windows_for
|
||||
from services.calc.index_calc import rank_score
|
||||
from services.index_service import IndexService, _nearest_slot_end_hour, _slot_end_hour, slot_days, slot_label, windows_for
|
||||
|
||||
REGION = "1141000000"
|
||||
|
||||
@@ -51,13 +54,18 @@ def fakes(monkeypatch):
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_index_list_ranks_all_27_with_today_tomorrow_weekend_trend(fakes):
|
||||
async def test_index_list_ranks_all_34_with_today_tomorrow_weekend_trend(fakes):
|
||||
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
|
||||
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 len(body["items"]) == 34 and len(body["top3"]) == 3
|
||||
priority = {d["code"]: d["priority"] for d in _seed()}
|
||||
# 지금 구간에 해당하는 각이 먼저(순위), 해당 없는 각은 그 뒤. 각 묶음 안에서는 점수 × 중요도 순
|
||||
actives = [i["active"] for i in body["items"]]
|
||||
assert actives == sorted(actives, reverse=True) and all(i["active"] for i in body["top3"])
|
||||
for group in (True, False):
|
||||
weighted = [rank_score(i["score"], priority[i["code"]]) for i in body["items"] if i["active"] is group]
|
||||
assert weighted == sorted(weighted, reverse=True)
|
||||
today = now_kst().date()
|
||||
for i in body["items"]:
|
||||
assert [t["label"] for t in i["trend"]] == [slot_label(d, today) for d in slot_days(today)]
|
||||
@@ -95,13 +103,40 @@ async def test_index_detail_has_four_score_bands_with_today_marked(fakes):
|
||||
assert len(current) == 1 and current[0]["low"] <= body["index"]["score"] <= current[0]["high"]
|
||||
|
||||
|
||||
def test_every_index_has_four_band_sentences():
|
||||
def _seed() -> list[dict]:
|
||||
import json
|
||||
import os
|
||||
seed = json.load(open(os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "seed", "index_definition.json"), encoding="utf-8"))
|
||||
with open(os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "seed", "index_definition.json"), encoding="utf-8") as f:
|
||||
return json.load(f)
|
||||
|
||||
|
||||
def test_every_index_has_four_band_sentences():
|
||||
seed = _seed()
|
||||
assert all(sorted(d["sentences"], key=int) == ["0", "30", "60", "80"] and all(d["sentences"].values()) for d in seed)
|
||||
|
||||
|
||||
def test_every_index_has_priority():
|
||||
assert all(d["priority"] in (1, 2, 3) for d in _seed())
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_board_ranks_by_score_times_priority_weight(monkeypatch):
|
||||
today = now_kst().date()
|
||||
defs = [
|
||||
SimpleNamespace(index_id=1, code="low", priority=3),
|
||||
SimpleNamespace(index_id=2, code="mid", priority=2),
|
||||
SimpleNamespace(index_id=3, code="high", priority=1),
|
||||
]
|
||||
scores = [SimpleNamespace(index_id=x, score_date=today, score=v, slots={}) for x, v in ((1, 90), (2, 80), (3, 70))]
|
||||
crud = SimpleNamespace(definitions=lambda s: _async(defs), scores=lambda s, *a: _async(scores))
|
||||
service = IndexService(RegionCRUD(), crud, None, None, None, None, None, None)
|
||||
monkeypatch.setattr(service, "ensure", lambda *a: _async((ErrorType.SUCCESS, 50)))
|
||||
err, board = await service.board(REGION)
|
||||
assert err is ErrorType.SUCCESS
|
||||
# 하 90점(63) < 중 80점(68) < 상 70점(70). 보이는 점수는 그대로
|
||||
assert [(i.definition.code, i.score.score, i.rank) for i in board.items] == [("high", 70, 1), ("mid", 80, 2), ("low", 90, 3)]
|
||||
|
||||
|
||||
def _om_row(at, **over):
|
||||
row = {
|
||||
"region_code": REGION, "forecast_at": at, "fetched_at": now_kst(), "uv_index": 2.0, "uv_index_clear_sky": 2.0,
|
||||
|
||||
@@ -1,10 +1,14 @@
|
||||
import json
|
||||
from dataclasses import replace
|
||||
from datetime import date, datetime, timezone
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
from common.enums import RainType, Sky
|
||||
from services.calc.index_calc import (
|
||||
OUTING_HOURS, Context, DayForecast, Hour, axis_label, estimate, evaluate, hour_temp, outing, outing_estimate, rain_score, sun_score, temp_score,
|
||||
OUTING_HOURS, Context, DayForecast, Hour, air_score, axis_label, estimate, evaluate, hour_temp, outing, outing_estimate, rain_score, sun_score, temp_score,
|
||||
uv_score, view_score, zero_rules_text,
|
||||
)
|
||||
from services.calc.moon import illumination
|
||||
@@ -222,3 +226,51 @@ def test_outing_estimate_from_mid_forecast():
|
||||
assert r.reason.startswith("비 20% · 낮 ")
|
||||
assert outing_estimate(_fc(pm=60)).score <= 30
|
||||
assert outing_estimate(_fc(lo=None, hi=None)) is None
|
||||
|
||||
|
||||
def test_air_rule_can_reverse_so_dusty_air_scores_high():
|
||||
rule = {"zero": 15, "full": 75}
|
||||
assert air_score(80, None, rule)[0] == 100 and air_score(10, None, rule)[0] == 0
|
||||
assert air_score(10, None)[0] == 100
|
||||
assert axis_label("air", {"air": rule}) == "공기 탁함" and axis_label("air", {}) == "공기 맑음"
|
||||
|
||||
|
||||
_SEED = {x["code"]: SimpleNamespace(**x) for x in json.loads((Path(__file__).parents[1] / "seed" / "index_definition.json").read_text(encoding="utf-8"))}
|
||||
_SAT, _WED = date(2026, 10, 10), date(2026, 10, 7)
|
||||
|
||||
|
||||
def _seed_score(code, day=_SAT, pm25=10, **hour):
|
||||
d = _SEED[code]
|
||||
windows = [[_h(h, **hour) for h in range(w["from"], w["to"])] for w in d.windows]
|
||||
return evaluate(d, windows, replace(CTX, day=day, pm25=pm25)).score
|
||||
|
||||
|
||||
@pytest.mark.parametrize("code, good, bad", [
|
||||
("golf", dict(feels=19.0, wind=2.0, hum=45), dict(feels=18.0, prob=80, rain=RainType.RAIN)),
|
||||
("jipkok", dict(feels=4.0, prob=90, rain=RainType.RAIN, wind=7.0, hum=85), dict(feels=20.0, wind=1.0, hum=40)),
|
||||
("fishing", dict(feels=22.0, wind=3.0), dict(feels=17.0, wind=11.0)),
|
||||
("drive", dict(feels=23.0, wind=4.0, hum=45, visibility_km=18.0), dict(feels=18.0, prob=80, rain=RainType.RAIN, visibility_km=5.0)),
|
||||
("kite", dict(feels=19.0, wind=6.0), dict(feels=14.0, wind=0.5)),
|
||||
("waterplay", dict(feels=28.0, wind=3.0, sunshine_ratio=0.7), dict(feels=18.0, wind=2.0, sunshine_ratio=0.3)),
|
||||
("kimjang", dict(feels=9.0, wind=3.0), dict(feels=20.0, wind=2.0)),
|
||||
])
|
||||
def test_new_gak_good_day_high_bad_day_low(code, good, bad):
|
||||
assert 80 <= _seed_score(code, pm25=60 if code == "jipkok" else 10, **good) < 100
|
||||
assert _seed_score(code, **bad) <= 30
|
||||
|
||||
|
||||
def test_new_gak_100_only_when_every_factor_is_perfect():
|
||||
perfect = dict(feels=19.5, wind=1.0, hum=35)
|
||||
assert _seed_score("golf", **perfect) == 100
|
||||
assert _seed_score("golf", day=_WED, **perfect) < 100
|
||||
|
||||
|
||||
def test_weather_score_100_only_on_perfect_day():
|
||||
from services.index_service import WEATHER_SCORE_DEF
|
||||
|
||||
perfect = Context(day=date(2026, 10, 2), is_holiday=False, pm25=8, air_label="좋음", moon=0, sunset_score=None, wind_warning=False, lookahead_rain_prob=0)
|
||||
hours = [_h(h, feels=21.0, prob=0, wind=0.8, hum=50, sunshine_ratio=1.0) for h in range(9, 22)]
|
||||
assert evaluate(WEATHER_SCORE_DEF, [hours], perfect).score == 100
|
||||
|
||||
good = [_h(h, feels=22.5, prob=10, wind=2.5, hum=62, sunshine_ratio=0.7) for h in range(9, 22)]
|
||||
assert evaluate(WEATHER_SCORE_DEF, [good], replace(perfect, pm25=15)).score < 95
|
||||
@@ -28,6 +28,16 @@ def test_parse_popup_maps_store():
|
||||
}
|
||||
|
||||
|
||||
def test_parse_popup_maps_festival():
|
||||
row = parse_popup(_page(504, "FESTIVAL", "2026-10-02", "2026-10-11", "경기 수원시 팔달구 테스트로 1"), 504, date(2026, 10, 1))
|
||||
assert (row["kind"], row["icon"], row["sido_code"]) == (EventKind.FESTIVAL, "fireworks", "41")
|
||||
|
||||
|
||||
def test_parse_popup_moves_festival_shows_in_theaters_to_concert():
|
||||
page = _page(505, "FESTIVAL", "2026-10-02", "2026-10-11").replace("테스트 빌딩 1F", "대학로예술극장 소극장")
|
||||
assert parse_popup(page, 505, date(2026, 10, 1))["kind"] is EventKind.CONCERT
|
||||
|
||||
|
||||
@pytest.mark.parametrize("kind,end,address", [
|
||||
("PERFORMANCE", "2026-10-11", "서울 성동구 테스트로 1"),
|
||||
("STORE", "2026-09-30", "서울 성동구 테스트로 1"),
|
||||
|
||||
@@ -0,0 +1,112 @@
|
||||
import csv
|
||||
import os
|
||||
from collections import defaultdict
|
||||
from datetime import date
|
||||
|
||||
import pytest
|
||||
from httpx import ASGITransport, AsyncClient
|
||||
from sqlalchemy import text
|
||||
|
||||
from common.database.db_session_manager import DB_SESSION_MNG
|
||||
from common.enums import PostType
|
||||
from common.utils.kma_time import now_kst
|
||||
from crud.feed_crud import FeedCRUD
|
||||
from crud.region_crud import RegionCRUD
|
||||
from crud.season_crud import SeasonCRUD
|
||||
from router.router import app
|
||||
from services.feed_service import LINEUP, NATIONAL_SCOPE, NATIONAL_TYPES, build_feed_day, feed_day, sido_of
|
||||
|
||||
SEOUL_A, SEOUL_B, BUSAN = "1111000000", "1114000000", "2611000000"
|
||||
REGION_CSV = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "seed", "region.csv")
|
||||
|
||||
|
||||
def client():
|
||||
return AsyncClient(transport=ASGITransport(app=app), base_url="http://test")
|
||||
|
||||
|
||||
def _ids(feed: dict) -> dict[int, set[int]]:
|
||||
out: dict[int, set[int]] = defaultdict(set)
|
||||
for p in feed["posts"]:
|
||||
out[p["post_type"]].add(p["post_id"])
|
||||
return out
|
||||
|
||||
|
||||
def test_every_region_maps_to_one_sido():
|
||||
with open(REGION_CSV, encoding="utf-8") as f:
|
||||
regions = list(csv.DictReader(f))
|
||||
assert len(regions) == 256
|
||||
by_name: dict[str, set[str]] = defaultdict(set)
|
||||
for r in regions:
|
||||
by_name[r["name"].split()[0]].add(sido_of(r["code"]))
|
||||
assert all(len(codes) == 1 for codes in by_name.values()), by_name
|
||||
sidos = {sido_of(r["code"]) for r in regions}
|
||||
assert all(len(c) == 2 and c.isdigit() and c != NATIONAL_SCOPE for c in sidos)
|
||||
sejong = [r for r in regions if r["name"].startswith("세종")]
|
||||
assert len(sejong) == 1 and sido_of(sejong[0]["code"]) == "36"
|
||||
assert sum(1 for r in regions if sido_of(r["code"]) == "36") == 1
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_build_day_makes_national_once_and_regional_per_sido():
|
||||
day = date(2026, 10, 15)
|
||||
await build_feed_day(day, FeedCRUD(), SeasonCRUD(), RegionCRUD())
|
||||
await build_feed_day(day, FeedCRUD(), SeasonCRUD(), RegionCRUD())
|
||||
_, rows = await DB_SESSION_MNG.execute_lambda(lambda s: s.execute(text(f"SELECT scope, post_type FROM post WHERE feed_date='{day}'")))
|
||||
rows = list(rows)
|
||||
_, regions = await DB_SESSION_MNG.execute_lambda(lambda s: RegionCRUD().search(s))
|
||||
sidos = {sido_of(r.code) for r in regions}
|
||||
regional = [x for x in LINEUP if x[1] not in NATIONAL_TYPES]
|
||||
assert {scope for scope, t in rows if PostType(t) in NATIONAL_TYPES} == {NATIONAL_SCOPE}
|
||||
assert {scope for scope, t in rows if PostType(t) not in NATIONAL_TYPES} == sidos
|
||||
assert sum(1 for scope, t in rows if PostType(t) not in NATIONAL_TYPES) == len(regional) * len(sidos)
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_regional_posts_shared_within_sido_split_across_sido(offline):
|
||||
async with client() as c:
|
||||
a, b, busan = [(await c.get("/v1/feed", params={"region": r})).json() for r in (SEOUL_A, SEOUL_B, BUSAN)]
|
||||
ia, ib, ibusan = _ids(a), _ids(b), _ids(busan)
|
||||
regional = [t for t in ia if PostType(t) not in NATIONAL_TYPES]
|
||||
assert PostType.WEATHER.value in regional and PostType.GAK.value in regional
|
||||
for t in regional:
|
||||
if t in ib:
|
||||
assert ia[t] == ib[t], PostType(t)
|
||||
if t in ibusan:
|
||||
assert not ia[t] & ibusan[t], PostType(t)
|
||||
national = [t for t in ia if PostType(t) in NATIONAL_TYPES]
|
||||
assert PostType.MOON.value in national
|
||||
for t in national:
|
||||
assert ia[t] == ib[t] == ibusan[t], PostType(t)
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_like_in_one_sido_not_seen_in_another(offline):
|
||||
async with client() as c:
|
||||
token = (await c.post("/v1/auth/signup", json={"login_id": "scope_01", "password": "password1", "nickname": "시도테스트"})).json()["access_token"]
|
||||
h = {"Authorization": f"Bearer {token}"}
|
||||
seoul = (await c.get("/v1/feed", params={"region": SEOUL_A}, headers=h)).json()
|
||||
post_id = next(p["post_id"] for p in seoul["posts"] if p["post_type"] == PostType.WEATHER.value)
|
||||
assert (await c.post(f"/v1/reaction/post/{post_id}/like", headers=h)).json()["like_count"] == 1
|
||||
await c.post(f"/v1/reaction/post/{post_id}/comment", json={"body": "서울 맑음"}, headers=h)
|
||||
same = (await c.get("/v1/feed", params={"region": SEOUL_B}, headers=h)).json()
|
||||
busan = (await c.get("/v1/feed", params={"region": BUSAN}, headers=h)).json()
|
||||
mine = next(p for p in same["posts"] if p["post_id"] == post_id)
|
||||
assert mine["liked"] is True and mine["like_count"] == 1 and mine["comment_count"] == 1
|
||||
weather = next(p for p in busan["posts"] if p["post_type"] == PostType.WEATHER.value)
|
||||
assert weather["post_id"] != post_id and weather["like_count"] == 0 and weather["comment_count"] == 0 and not weather.get("liked")
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_day_built_before_split_keeps_national_rows_for_regional_cards(offline):
|
||||
"""그날 지역 카드가 이미 전국 행으로 있으면 시도 행을 만들지 않고, 모든 시도가 그 행(과 반응)을 같이 쓴다."""
|
||||
day = feed_day(now_kst())
|
||||
rows = ", ".join(f"('{day}', {pos}, '{NATIONAL_SCOPE}', {t.value}, {ref.value}, {rank if rank else 'NULL'}, now(), {5 if t is PostType.WEATHER else 0})"
|
||||
for pos, t, ref, rank in LINEUP if ref.value == 1)
|
||||
await DB_SESSION_MNG.execute_lambda_run([lambda s: s.execute(text(
|
||||
f"INSERT INTO post (feed_date, position, scope, post_type, ref_type, index_rank, published_at, like_count) VALUES {rows}"))])
|
||||
async with client() as c:
|
||||
seoul, busan = [(await c.get("/v1/feed", params={"region": r})).json() for r in (SEOUL_A, BUSAN)]
|
||||
_, n = await DB_SESSION_MNG.execute_lambda(lambda s: s.scalar(text(f"SELECT count(*) FROM post WHERE feed_date='{day}' AND scope <> '{NATIONAL_SCOPE}'")))
|
||||
assert n == 0
|
||||
ws, wb = [next(p for p in f["posts"] if p["post_type"] == PostType.WEATHER.value) for f in (seoul, busan)]
|
||||
assert ws["post_id"] == wb["post_id"] and ws["like_count"] == 5
|
||||
@@ -2,8 +2,10 @@ from datetime import timedelta
|
||||
|
||||
import pytest
|
||||
from httpx import ASGITransport, AsyncClient
|
||||
from sqlalchemy import text
|
||||
|
||||
import services.season_service as season_service
|
||||
from common.database.db_session_manager import DB_SESSION_MNG
|
||||
from common.utils.kma_time import now_kst
|
||||
from router.router import app
|
||||
|
||||
@@ -38,3 +40,15 @@ async def test_article_detail_and_not_found():
|
||||
missing = (await client.get("/v1/season/article/9999")).json()
|
||||
assert first["body"] and first["article"]["title"] == listed[0]["title"]
|
||||
assert missing["result"]["desc"] == "NOT_FOUND"
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_article_photo_only_when_seeded():
|
||||
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
|
||||
listed = {a["code"]: a for a in (await client.get("/v1/season/article/list")).json()["articles"]}
|
||||
umbrella = (await client.get(f"/v1/season/article/{listed['umbrella']['article_id']}")).json()["article"]
|
||||
_, maple_id = await DB_SESSION_MNG.execute_lambda(lambda s: s.scalar(text("SELECT article_id FROM article WHERE code = 'maple'")))
|
||||
maple = (await client.get(f"/v1/season/article/{maple_id}")).json()["article"]
|
||||
assert umbrella["image"] == "/season/umbrella.jpg" and "image_credit" not in umbrella
|
||||
assert maple["image"] == "/season/maple.jpg" and maple["image_credit"] == "ⓒJoycekim77 · CC BY-SA 3.0"
|
||||
assert "image" not in listed["howgak"] and "image" not in listed["di"]
|
||||
@@ -0,0 +1,83 @@
|
||||
from datetime import date
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
|
||||
import services.week_service as week_service
|
||||
from services.external.seoul_culture import LIST_URL, fetch_seoul_festivals, parse_seoul_festivals
|
||||
from services.week_service import _seoul
|
||||
|
||||
ITEM = {
|
||||
"cultcode": 159216, "title": "[중랑문화재단] 2026 중랑용마폭포축제", "strtdate": "2026-10-10", "endDate": "2026-10-10",
|
||||
"atchFileId": "abc", "xCoord": "37.5118239", "yCoord": "127.0591590", "facName": "용마폭포공원", "addr": "서울특별시 중랑구",
|
||||
}
|
||||
|
||||
|
||||
def test_parse_reads_lat_from_x_and_builds_image_and_link():
|
||||
[row] = parse_seoul_festivals([ITEM, {**ITEM, "cultcode": None}, {**ITEM, "cultcode": 2, "strtdate": ""}])
|
||||
assert row["source_id"] == "seoul:159216" and row["sido_code"] == "11"
|
||||
assert (row["lat"], row["lon"]) == (37.51182, 127.05916)
|
||||
assert row["name"] == "2026 중랑용마폭포축제"
|
||||
assert row["place_name"] == "용마폭포공원" and row["start_date"] == date(2026, 10, 10)
|
||||
assert row["image_url"].endswith("atchFileId=abc&thumb=Y") and "cultcode=159216" in row["source_url"]
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_fetch_pages_until_empty(monkeypatch):
|
||||
monkeypatch.setattr("services.external.seoul_culture.REQUEST_GAP_SEC", 0)
|
||||
pages = []
|
||||
|
||||
def handler(req: httpx.Request) -> httpx.Response:
|
||||
assert str(req.url) == LIST_URL
|
||||
page = int(dict(x.split("=") for x in req.content.decode().split("&"))["pageIndex"])
|
||||
pages.append(page)
|
||||
return httpx.Response(200, json={"resultList": [ITEM] * 10 if page < 3 else []})
|
||||
|
||||
async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
|
||||
items = await fetch_seoul_festivals(client, date(2026, 10, 8), 30)
|
||||
assert len(items) == 20 and pages == [1, 2, 3]
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_seoul_skips_festivals_tour_api_already_has_and_other_sidos(monkeypatch):
|
||||
other = {**ITEM, "cultcode": 2, "title": "2026 서울어텀페스타"}
|
||||
|
||||
async def fake(client, since, days):
|
||||
return [ITEM, other]
|
||||
|
||||
monkeypatch.setattr(week_service, "fetch_seoul_festivals", fake)
|
||||
known = [{"name": "제3회 중랑용마폭포축제"}]
|
||||
rows = await _seoul(None, "11", date(2026, 10, 8), known)
|
||||
assert [r["name"] for r in rows] == ["2026 서울어텀페스타"]
|
||||
assert await _seoul(None, "41", date(2026, 10, 8), known) == []
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_seoul_failure_keeps_other_sources(monkeypatch):
|
||||
async def broken(client, since, days):
|
||||
raise httpx.ConnectError("down")
|
||||
|
||||
monkeypatch.setattr(week_service, "fetch_seoul_festivals", broken)
|
||||
assert await _seoul(None, "11", date(2026, 10, 8), []) == []
|
||||
|
||||
|
||||
def _row(source_id, name, start, end, sido="11"):
|
||||
return {"source_id": source_id, "sido_code": sido, "name": name, "place_name": "", "start_date": start, "end_date": end,
|
||||
"is_confirmed": True, "source_url": None, "image_url": None, "lat": None, "lon": None, "kind": 1, "icon": "fireworks"}
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_drop_known_skips_same_festival_from_another_source():
|
||||
from common.database.db_session_manager import DB_SESSION_MNG
|
||||
from crud.week_crud import WeekCRUD
|
||||
from services.week_service import drop_known
|
||||
|
||||
tour = _row("9001", "경복궁 별빛야행", date(2026, 10, 1), date(2026, 10, 24))
|
||||
await DB_SESSION_MNG.execute_lambda_run([lambda s: WeekCRUD().upsert_events(s, [tour])])
|
||||
rows = [
|
||||
_row("popga:1", "2026 경복궁 별빛야행", date(2026, 10, 8), date(2026, 10, 10)),
|
||||
_row("popga:2", "경복궁 별빛야행", date(2026, 11, 1), date(2026, 11, 2)),
|
||||
_row("popga:3", "경복궁 별빛야행", date(2026, 10, 8), date(2026, 10, 10), sido="41"),
|
||||
_row("9001", "경복궁 별빛야행", date(2026, 10, 1), date(2026, 10, 25)),
|
||||
]
|
||||
assert [r["source_id"] for r in await drop_known(rows)] == ["popga:2", "popga:3", "9001"]
|
||||
@@ -93,7 +93,7 @@ async def test_sky_spots_by_distance(monkeypatch, clean, region, expected):
|
||||
assert [s["distance_km"] for s in spots] == sorted(s["distance_km"] for s in spots)
|
||||
|
||||
|
||||
def test_nearest_spots_west_first_and_empty_outside_radius():
|
||||
def test_nearest_spots_west_first_and_nearest_one_outside_radius():
|
||||
from decimal import Decimal
|
||||
|
||||
from common.database.model.models import SunsetSpot
|
||||
@@ -103,7 +103,7 @@ def test_nearest_spots_west_first_and_empty_outside_radius():
|
||||
|
||||
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) == []
|
||||
assert [x.spot.name for x in sky_service.nearest_spots(36.0, 127.0, spots)] == ["가까운 동쪽"]
|
||||
|
||||
|
||||
def test_outlook_only_when_a_later_day_has_a_better_verdict():
|
||||
|
||||
@@ -7,13 +7,13 @@ import services.air_service as air_service
|
||||
import services.warning_service as warning_service
|
||||
import services.weather_service as weather_service
|
||||
import services.week_service as week_service
|
||||
from common.database.model.models import Event
|
||||
from common.database.model.models import Event, Place, Region
|
||||
from common.enums import EventKind, RainType, Sky
|
||||
from common.utils.kma_time import KST, kst_midnight, now_kst
|
||||
from router.router import app
|
||||
from services.external.kma import latest_mid_base, mid_word, parse_mid
|
||||
from services.external.data_go_kr import DataGoKrRequestFailed
|
||||
from services.week_service import EventItem, _status, mix_kinds
|
||||
from services.week_service import PLACE_FALLBACK, PLACE_RADIUS_KM, EventItem, _status, mix_kinds, pick_places
|
||||
|
||||
REGION = "1144000000"
|
||||
|
||||
@@ -169,6 +169,22 @@ async def test_events_pick_within_30km_across_sido(fakes, monkeypatch):
|
||||
assert {e["name"] for e in body["events"]} == {"잠실 축제", "좌표 없는 경기 축제"}
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_gwangju_jeonnam_region_finds_events_saved_as_29_and_46(fakes, monkeypatch):
|
||||
"""구 코드는 광주·전남이 12로 묶이지만 행사는 광주 29 · 전남 46으로 저장된다. 광산구에서 둘 다 보여야 한다."""
|
||||
today = now_kst().date()
|
||||
span = {"eventstartdate": (today + timedelta(days=1)).strftime("%Y%m%d"), "eventenddate": (today + timedelta(days=3)).strftime("%Y%m%d")}
|
||||
by_sido = {
|
||||
"29": [{"contentid": "29", "title": "광주 축제", "addr1": "광주 광산구", "mapy": "35.1396", "mapx": "126.7937", **span}],
|
||||
"46": [{"contentid": "46", "title": "좌표 없는 전남 축제", "addr1": "전남", **span}],
|
||||
}
|
||||
monkeypatch.setattr(week_service, "fetch_festivals", lambda client, sido, since: _async(by_sido.get(sido, [])))
|
||||
await _collect("29", "46")
|
||||
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
|
||||
body = (await client.get("/v1/week/event/list", params={"region": "1233000000"})).json()
|
||||
assert {e["name"] for e in body["events"]} == {"광주 축제", "좌표 없는 전남 축제"}
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_places_put_indoor_first_on_rainy_day(fakes):
|
||||
rainy_day = (now_kst().date() + timedelta(days=2)).isoformat()
|
||||
@@ -179,6 +195,46 @@ async def test_places_put_indoor_first_on_rainy_day(fakes):
|
||||
assert body["places"][0]["is_outdoor"] is False and body["places"][0]["is_good"] is True
|
||||
|
||||
|
||||
def _place(name: str, lat: float, lon: float, outdoor: bool = True, area: str = "가") -> Place:
|
||||
return Place(name=name, lat=lat, lon=lon, is_outdoor=outdoor, area=area)
|
||||
|
||||
|
||||
def test_pick_places_within_radius_good_first_then_near():
|
||||
region = Region(lat=37.0, lon=127.0)
|
||||
places = [
|
||||
_place("먼 공원", 37.2, 127.0), _place("가까운 공원", 37.01, 127.0, area="나"),
|
||||
_place("미술관", 37.1, 127.0, outdoor=False), _place("반경 밖", 37.5, 127.0),
|
||||
]
|
||||
items, areas = pick_places(region, places, rainy=False, area=None)
|
||||
assert [i.place.name for i in items] == ["가까운 공원", "먼 공원", "미술관"]
|
||||
assert all(i.distance_km <= PLACE_RADIUS_KM for i in items) and items[0].distance_km == 1.1
|
||||
assert areas == ["나", "가"]
|
||||
items, _ = pick_places(region, places, rainy=True, area=None)
|
||||
assert [i.place.name for i in items][0] == "미술관" and items[0].is_good
|
||||
items, _ = pick_places(region, places, rainy=False, area="가")
|
||||
assert [i.place.name for i in items] == ["먼 공원", "미술관"]
|
||||
|
||||
|
||||
def test_pick_places_falls_back_to_nearest_when_none_in_radius():
|
||||
region = Region(lat=37.0, lon=127.0)
|
||||
places = [_place(f"{k}km", 37.0 + k / 111, 127.0) for k in (90, 40, 60, 200)]
|
||||
items, _ = pick_places(region, places, rainy=False, area=None)
|
||||
assert [i.place.name for i in items] == ["40km", "60km", "90km"][:PLACE_FALLBACK]
|
||||
assert items[0].distance_km > PLACE_RADIUS_KM
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
@pytest.mark.parametrize("region", ["2635000000", "5013000000", "4794000000"])
|
||||
async def test_places_outside_seoul_come_by_distance(fakes, region):
|
||||
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
|
||||
body = (await client.get("/v1/week/place/list", params={"region": region, "day": now_kst().date().isoformat()})).json()
|
||||
places = body["places"]
|
||||
assert places and all(p["distance_km"] <= PLACE_RADIUS_KM for p in places)
|
||||
good = [p["distance_km"] for p in places if p["is_good"]]
|
||||
assert good == sorted(good)
|
||||
assert all(p["image_credit"] == "ⓒ한국관광공사" for p in places if p.get("image"))
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_weekend_ranking_scores_30_spots_and_caches(fakes, monkeypatch):
|
||||
from services.weekend_rank import weekend_days
|
||||
|
||||
@@ -55,6 +55,11 @@ def test_afternoon_rain_moves_outdoor_time_before_it():
|
||||
assert card.line.startswith("비 오는 토요일")
|
||||
|
||||
|
||||
def test_morning_rain_then_outdoor_after_it_ends():
|
||||
card = day_plan(_day(SAT, rainy=True, rain_hours=(9, 14), prob=60), None, [], None)
|
||||
assert [s.time for s in card.steps] == ["9~14시", "14시~"]
|
||||
|
||||
|
||||
def test_saturday_ignores_ending_hook_and_sunday_skips_saturday_events():
|
||||
near = _event("가까운 축제", SAT, SUN, 3.0)
|
||||
ends_sat = _event("토요일 끝", SAT, SAT, 50.0)
|
||||
|
||||
@@ -0,0 +1,154 @@
|
||||
# 기능 QA 체크리스트 (휴대폰)
|
||||
|
||||
아이폰 Safari와 안드로이드 Chrome에서 http://172.30.1.36:30040 에 들어가 위에서부터 따라 하며 체크합니다. 기대 결과는 `frontend/src/b/` 코드 기준이고, 확실하지 않은 동작은 "(확인)"을 붙였습니다.
|
||||
|
||||
## 0. 처음 들어가기
|
||||
|
||||
- [ ] 사이트 데이터를 지우고 접속 → 위치 권한을 묻고, 상단 지역 버튼 자리에 스켈레톤 막대
|
||||
- [ ] 위치 허용 → 가장 가까운 구로 바뀐다 / 거부 → 기본 "서울 마포구"
|
||||
- [ ] 새로고침 → 위치를 다시 묻지 않고 마지막 지역 그대로
|
||||
|
||||
## 1. 공통: 상단 바·하단 탭
|
||||
|
||||
- [ ] 하단 탭이 노을 · 각 · 오늘(가운데 큰 주황 동그라미) · 주말·행사 · 계절·상식 순
|
||||
- [ ] 탭을 옮길 때마다 맨 위에서 시작하고, 제목이 오늘은 주황 "날씨각", 나머지는 노을 / 오늘의 각 / 주말·행사 / 계절·상식
|
||||
- [ ] 로그아웃 상태는 오른쪽 위 "로그인" 버튼, 로그인 상태는 내 캐릭터 동그라미(기분 이모지 포함)
|
||||
- [ ] 스크롤해도 상단 바·하단 탭이 고정되고 뒤 내용이 흐리게 비친다
|
||||
|
||||
## 2. 오늘 탭: 히어로
|
||||
|
||||
- [ ] 시간대 버튼 지금 · 아침 · 낮 · 저녁 · 밤, 처음엔 "지금", 날짜 줄은 "M월 D일 요일 · HH:MM"
|
||||
- [ ] 해 안에 "오늘 날씨 점수"와 큰 숫자, 아래 칩 한 줄: 첫 칸 "지금 + 기온·하늘", 나머지는 챙길 것(비·미세먼지 등)
|
||||
- [ ] "아침" → 시계 07:40, 첫 칩 이름 "아침", 기온이 7시 예보 값 (낮 13:20 · 저녁 18:25 · 밤 22:10도 같은 방식)
|
||||
- [ ] 저녁·밤 → 해 동그라미가 오늘 밤 달 모양으로 가려진다(달 정보가 있을 때), 밤은 캐릭터가 곰
|
||||
- [ ] 말풍선 누름 → 1위 각의 계산 근거 시트
|
||||
|
||||
## 3. 시간대 테마 (낮·노을·밤)
|
||||
|
||||
- [ ] 히어로에서 고른 시간대로 화면 전체 하늘 배경이 바뀐다
|
||||
- [ ] 밤 → 카드·시트·하단 탭까지 어두운 색, 글자 밝게, 별 반짝임과 별똥별
|
||||
- [ ] 저녁 → 노을색 배경, 히어로 칩 글자가 흰색으로 읽힌다
|
||||
- [ ] 고른 시간대가 다른 탭·새로고침에도 유지, 새 탭(새 창)에서 열면 "지금"으로 시작
|
||||
- [ ] "지금" → 실제 시각 기준(아침 05~11시, 일몰 2시간 전부터 저녁, 일몰 1시간 뒤부터 밤)
|
||||
|
||||
## 4. 오늘 탭: 각 줄·띠
|
||||
|
||||
- [ ] "오늘의 각" 동그라미 줄이 옆으로 밀리고, 1~3위 메달, 50점 미만은 회색 테두리, 누르면 계산 근거 시트
|
||||
- [ ] "전체 보기" → 각 탭
|
||||
- [ ] 3번째 글 뒤 "이번 주 가까운 행사"(카드 → 주말·행사 탭), 6번째 뒤 "지금 뜨는 각 TOP 5"(카드 → 계산 근거), 9번째 뒤 "이번 주 계절 이야기"(카드 → 읽을거리)
|
||||
- [ ] 글이 9개보다 적으면 남은 띠가 피드 맨 끝에 붙는다
|
||||
- [ ] 지역을 바꾸면 맨 위로 가고 넘겨 둔 슬라이드가 1장으로 돌아간다
|
||||
|
||||
## 5. 피드 포스트
|
||||
|
||||
- [ ] 머리줄 "날씨각" + 계정 이름(오늘 날씨, 오늘의 각, 노을, 계절 소식, 가까운 행사, 날씨 상식, 주말 예보, 생활 알림, 내일 미리보기, 오늘의 한 문장, 주말 플랜, 미세먼지, 당일치기, 오늘 밤 달, 자외선)
|
||||
- [ ] 2장 이상이면 오른쪽 위 "1/N", 밀면 숫자가 바뀐다. 1장짜리는 밀리지 않는다
|
||||
- [ ] 오늘 날씨: 시간별 4칸(주황 막대 높이가 기온 비례), 저녁 칸 살구색·밤 칸 보라색
|
||||
- [ ] 각: "오늘의 각 · N위", 큰 점수, "계산 근거 보기" → 계산 근거 시트
|
||||
- [ ] 노을: 노을 점수와 시각 칸들 / 주말 예보: 토·일 칸("비 N% · 일교차 N°") + 검은 팁 줄
|
||||
- [ ] 주말 플랜: 시간·아이콘·제목·설명 줄, 사진이 있으면 작은 사진과 맨 아래 "사진 출처"
|
||||
- [ ] 행사·당일치기 사진 슬라이드: 사진 위 글자, 오른쪽 위 출처
|
||||
- [ ] 점선 밑줄 장소 이름 → 네이버 지도 검색이 새 탭으로
|
||||
- [ ] 한 줄 카드(흐린 날 노을 등)는 아이콘·제목·설명만, 버튼 없음
|
||||
- [ ] 카드 아래 "좋아요 N개", 본문, "댓글 N개 모두 보기"(0개면 "첫 댓글 남기기")
|
||||
|
||||
## 6. 좋아요·댓글
|
||||
|
||||
- [ ] 로그아웃 상태에서 하트 또는 사진 두 번 탭 → 로그인 시트
|
||||
- [ ] 로그인 후 사진 두 번 탭 → 큰 하트 + 튀는 하트 + "좋아요했어요!", 하트 빨강, 숫자 +1
|
||||
- [ ] 이미 좋아요한 사진 두 번 탭 → 효과만 다시, 숫자 그대로 / 하트 버튼 → 취소, -1
|
||||
- [ ] 다른 탭에 다녀와도 하트·숫자 유지
|
||||
- [ ] (비행기 모드) 좋아요 → 원래대로 돌아가고 아래에 "좋아요를 반영하지 못했어요. 다시 해 주세요." 2.5초
|
||||
- [ ] 댓글 아이콘·"댓글 … 보기" → 댓글 시트, 없으면 "아직 댓글이 없어요. 첫 댓글을 남겨 보세요."
|
||||
- [ ] 빠른 이모지(☀️🌂🍻🌇😍👍) → 입력칸 끝에 붙고 포커스, 입력은 60자까지
|
||||
- [ ] 로그인 후 "게시" → "올리는 중…" 뒤 목록에 뜨고 입력칸이 비며, 피드 댓글 수도 늘어난다
|
||||
- [ ] 로그아웃 상태에서 "게시" → 로그인 시트로 바뀐다
|
||||
- [ ] 내 댓글에만 "지우기" → 흐려졌다 사라진다 / 댓글 작은 하트 → 좋아요 수 변경
|
||||
- [ ] 댓글이 많으면 "댓글 더 보기"로 더 불러온다 (확인: 한 번에 몇 개인지)
|
||||
|
||||
## 7. 로그인·내 정보
|
||||
|
||||
- [ ] 로그인 시트 "로그인 / 처음이에요" 전환, 처음이에요는 닉네임 칸 + "가입하고 시작하기"
|
||||
- [ ] 틀린 비밀번호 → "아이디나 비밀번호가 맞지 않아요." / 있는 아이디로 가입 → "이미 쓰고 있는 아이디예요."
|
||||
- [ ] 로그인 성공 → 시트가 닫히고 오른쪽 위가 내 캐릭터 / "나중에 할게요" → 닫힘
|
||||
- [ ] 캐릭터 누름 → "내 정보" 시트, "아이디(으)로 로그인했어요"
|
||||
- [ ] 캐릭터 6종·배경색 6개 누름 → 주황 테두리, 큰 캐릭터·상단 바 캐릭터가 바뀐다
|
||||
- [ ] 오늘 기분 8개 → 캐릭터 오른쪽 위 이모지, 같은 기분 다시 누르면 지워진다
|
||||
- [ ] 닉네임이 지금과 같으면 "바꾸기"가 막혀 있고, 바꾸면 "저장 중…" 뒤 저장, 댓글 목록에도 반영
|
||||
- [ ] "로그아웃" → 시트 닫힘, 오른쪽 위 "로그인", 좋아요 표시가 풀린다
|
||||
|
||||
## 8. 지역 바꾸기
|
||||
|
||||
- [ ] 지역 버튼 → "지역 바꾸기" 시트, 지금 지역은 주황 글자 + "지금 보는 곳"
|
||||
- [ ] "마포" 입력 → 목록이 걸러짐, 없는 이름 → "찾는 구가 없어요."
|
||||
- [ ] 다른 구 누름 → 시트가 닫히고 지역 이름·모든 탭 데이터가 바뀐다
|
||||
- [ ] "지금 위치로 찾기" → "위치를 찾는 중이에요…", 성공하면 지역이 바뀌고 시트는 열린 채 (확인)
|
||||
- [ ] 위치 권한 끈 상태 → "위치 권한이 꺼져 있어요. 아래 목록에서 골라 주세요."
|
||||
|
||||
## 9. 노을 탭
|
||||
|
||||
- [ ] 히어로 "오늘 노을 · 지역", 큰 해 지는 시각, 하늘 상황 한 줄, 상황에 따라 색이 다르고 아래 동네 실루엣
|
||||
- [ ] 흰 카드: 결론 + 이유, "예보 모델 N개 중 M개가 같은 예보 · 노을 점수 N"
|
||||
- [ ] "언제 보면 좋을까" 세 시각(해 짐 점만 주황), 더 나은 날이 있을 때만 분홍 안내 상자
|
||||
- [ ] 가까운 노을 명소 최대 3곳("방향쪽" · "Nkm", 이름 → 네이버 지도), 전국 노을 순위 8곳(내 지역 흰 바탕 + "내 지역")
|
||||
|
||||
## 10. 각 탭
|
||||
|
||||
- [ ] "오늘 1~3위" 부제 "M월 D일 기준 · 지역", 받침대 2위 · 1위(가장 크고 노란 바탕) · 3위, 누르면 계산 근거
|
||||
- [ ] 분야 칩 전체 · 밖에서 놀기 · 먹고 마시기 · 집안일 · 생활 고민 · 가을 각 → 3열 목록이 바뀐다
|
||||
- [ ] 목록 칸: 왼쪽 위 순위, 가을 핵심 각은 초록 "가을", 50점 미만 점수 회색
|
||||
- [ ] 맨 아래 "각 점수는 어떻게 매길까?" → 읽을거리 시트
|
||||
- [ ] 계산 근거 시트: 제목 "N위 이름", 지금 구간 설명, 레이더(요소 3개 이상), 날짜별 추이("예상" 표시), 구간 목록, 요소별 막대·비중, 계산 방법
|
||||
|
||||
## 11. 주말·행사 탭
|
||||
|
||||
- [ ] "열흘 날씨" 한 화면 7칸, 밀면 10일까지, 처음엔 이번 토요일 선택
|
||||
- [ ] 토·일·공휴일은 분홍 글자, 공휴일은 날짜 대신 이름
|
||||
- [ ] 날짜 누름 → 초록 추천 카드가 그날 것으로 바뀐다
|
||||
- [ ] 서울: 동네 고르기로 명소가 바뀌고, 부제가 날씨에 맞게("비가 와서 실내 명소를 먼저" / "맑아서 야외 명소를 먼저")
|
||||
- [ ] 명소 배지 "오늘 딱"(야외) / "비 와도 OK"(실내), 이름 → 네이버 지도
|
||||
- [ ] 서울이 아닌 지역 → 데이트 명소 칸이 통째로 숨는다, 지역을 바꾸면 동네 고르기가 "전체"로
|
||||
- [ ] 전국 날씨 순위: 토/일 칩 전환, 10위까지, 내 지역 표시, 추정은 "· 예상"
|
||||
- [ ] 축제·행사: 진행 중(초록)/곧 시작(주황) 배지, 기간·장소, 미확정 "· 일정 확인 필요", 날씨 줄(비면 분홍)
|
||||
- [ ] "이번 주말 일정 보내기" → 공유 시트(고른 날 추천 카드 이미지)
|
||||
|
||||
## 12. 계절·상식 탭
|
||||
|
||||
- [ ] 특집 상자: "이번 주 특집 · 기간", 제목, 시, 절기 막대
|
||||
- [ ] 특집 상자 → "이번 주 특집" 시트, 그 안 글 목록 → 읽을거리 시트로 바뀐다
|
||||
- [ ] 분류 칩 전체 · 계절 소식 · 날씨 상식 · 각 원리로 걸러지고, 줄 누름 → 읽을거리(제목이 분류 이름, "분류 · N분")
|
||||
|
||||
## 13. 공유하기
|
||||
|
||||
- [ ] 포스트 종이비행기 → "보내기" 시트, 9:16 선택된 채 "이미지 만드는 중" 뒤 미리보기
|
||||
- [ ] 4:5, 1:1로 바꾸면 비율이 바뀌고, 다시 돌아가면 바로 뜬다
|
||||
- [ ] 이미지: 위 "날씨각" + "지역 · 오늘 날짜", 슬라이드 최대 2장(2장이면 1·2 번호), 아래 "오늘 내 동네 각 보기 + 주소"
|
||||
- [ ] 이미지에 버튼("계산 근거 보기")·"1/N"·화살표가 빠져 있고, 밤 테마면 배경도 어두운 하늘
|
||||
- [ ] "공유하기" → 휴대폰 공유창에 이미지와 "제목 · 날씨각 주소" 글이 같이 넘어가고, 보내면 "보냈어요"(그냥 닫으면 안내 없음)
|
||||
- [ ] 카카오톡·인스타 스토리·사진 저장으로 실제 보내 본다 (확인: 앱마다 글이 빠질 수 있음)
|
||||
|
||||
## 14. 시트 공통
|
||||
|
||||
- [ ] 아래에서 올라오고 ×·바깥 어두운 곳 누름으로 닫힌다
|
||||
- [ ] 열린 동안 뒤 페이지가 스크롤되지 않고, 긴 내용은 시트 안에서만 스크롤된다
|
||||
- [ ] 안드로이드 뒤로 가기 → 시트만 닫힌다 (확인: 페이지가 뒤로 갈 수 있음)
|
||||
|
||||
## 15. 스켈레톤 · '?' · 실패
|
||||
|
||||
- [ ] 처음 열 때 각 화면·시트에 같은 틀의 회색 막대가 먼저 보이고, 데이터가 와도 덜컹이지 않는다
|
||||
- [ ] 값이 없는 칸은 흐린 '?'(히어로 점수·기온, 날짜 칸 기온, 시간별 "?°", 주말 "비 ?%")
|
||||
- [ ] 비행기 모드로 새로고침 → "정보를 불러오지 못했어요." + "다시 시도", 히어로 "앗, 날씨를 못 불러왔어요" / "점수를 못 불러왔어요"
|
||||
- [ ] 비행기 모드 해제 후 "다시 시도" → "다시 불러오는 중…" 뒤 정상 표시
|
||||
|
||||
## 16. 모바일에서 특히 볼 것
|
||||
|
||||
- [ ] 글자를 길게 눌러도 선택·돋보기·복사 메뉴가 안 뜬다, 사진·링크 길게 눌러도 미리보기 메뉴 없음(아이폰)
|
||||
- [ ] 입력칸(댓글·로그인·지역 검색·닉네임)은 글자 선택·붙여넣기가 되고, 눌러도 화면이 확대되지 않는다
|
||||
- [ ] 두 번 탭해도 확대되지 않는다, 두 손가락 확대 (확인: iOS는 막히지 않을 수 있음)
|
||||
- [ ] 아이폰 홈 막대가 하단 탭·댓글 입력줄을 가리지 않고, 좋아요 실패 알림은 하단 탭 위에 뜬다
|
||||
- [ ] 가로 모드에서 노치가 상단 바·카드 왼쪽 끝을 가리는지 (확인)
|
||||
- [ ] 어느 탭에서도 화면 전체가 옆으로 밀리지 않는다, 옆으로 미는 건 줄·슬라이드만
|
||||
- [ ] 슬라이드를 밀 때 페이지 위아래 스크롤이 같이 튀지 않는다
|
||||
- [ ] 작은 버튼이 잘 눌리는지: 포스트 하트·댓글·보내기, 댓글 하트, 시트 ×
|
||||
- [ ] 댓글 입력칸을 누르면 키보드 위로 입력칸·게시 버튼이 보인다 (확인)
|
||||
- [ ] 로그인 시트 비밀번호 칸·버튼, 지역 검색 목록이 키보드에 가려지지 않는다 (확인)
|
||||
+207
-57
@@ -8,47 +8,55 @@
|
||||
- 최종 점수 = 비중대로 섞은 점수 × (0.75 + 0.25 × 가장 낮은 요소 점수 ÷ 100). 비중 0%인 요소는 '가장 낮은 요소'에서 뺍니다. 가장 낮은 요소가 0점이면 25%가 깎입니다.
|
||||
- '0점 조건'에 걸리면 0점, '최대 N점' 조건에 걸리면 N점을 넘지 못합니다.
|
||||
- 시간대가 여러 개면 그중 가장 좋은 시간대 점수를 씁니다.
|
||||
- 미세먼지는 모든 각이 같은 규칙입니다: 초미세먼지 15㎍/㎥ 이하 100점 → 75㎍/㎥ 이상 0점.
|
||||
- 미세먼지는 초미세먼지 15㎍/㎥ 이하 100점 → 75㎍/㎥ 이상 0점입니다. 집콕각처럼 규칙을 따로 적은 각만 거꾸로(탁할수록 좋음) 셉니다.
|
||||
- 바람·미세먼지·노을 정보가 없으면 70점으로 둡니다.
|
||||
- 순위는 점수 × 중요도 가중치(상 1.0 · 중 0.85 · 하 0.7)로 정합니다. 화면에 보이는 점수는 그대로입니다.
|
||||
|
||||
## 한눈에 보기
|
||||
|
||||
| 순서 | 각 | 코드 | 분류 | 시간대 | 기온 | 비 | 바람 | 습도 | 미세먼지 | 시간 | 재미 각 | 계절 핵심 |
|
||||
|---:|---|---|---|---|---:|---:|---:|---:|---:|---:|:---:|:---:|
|
||||
| 1 | 야장각 | `yajang` | 먹고 마시기 | 18~24시 | 30% | 25% | 15% | 10% | 10% | 10% | ○ | |
|
||||
| 2 | 피크닉각 | `picnic` | 밖에서 놀기 | 11~16시 | 25% | 25% | 15% | 5% | 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시 | 25% | 25% | 20% | 5% | 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% | 15% | 10% | 5% | | |
|
||||
| 10 | 별보기각 | `stars` | 밖에서 놀기 | 21~다음 날 2시 | 5% | 10% | 5% | 5% | 15% | 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시 | 15% | 30% | 15% | 10% | 0% | 5% | | |
|
||||
| 15 | 자전거각 | `bike` | 밖에서 놀기 | 9~19시 | 25% | 25% | 25% | 5% | 10% | 5% | | |
|
||||
| 16 | 멍뭉산책각 | `dog` | 밖에서 놀기 | 7~9시 / 17~20시 | 35% | 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시 | 25% | 30% | 10% | 15% | 10% | 5% | | |
|
||||
| 23 | 사진산책각 | `photo` | 밖에서 놀기 | 일몰 앞뒤 1시간 | 10% | 25% | 10% | 5% | 10% | 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% | ○ | |
|
||||
| 순서 | 각 | 코드 | 분류 | 중요도 | 시간대 | 기온 | 비 | 바람 | 습도 | 미세먼지 | 시간 | 재미 각 | 계절 핵심 |
|
||||
|---:|---|---|---|:---:|---|---:|---:|---:|---:|---:|---:|:---:|:---:|
|
||||
| 1 | 야장각 | `yajang` | 먹고 마시기 | 중 | 18~24시 | 30% | 25% | 15% | 10% | 10% | 10% | ○ | |
|
||||
| 2 | 피크닉각 | `picnic` | 밖에서 놀기 | 상 | 11~16시 | 25% | 25% | 15% | 5% | 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시 | 25% | 25% | 20% | 5% | 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% | 15% | 10% | 5% | | |
|
||||
| 10 | 별보기각 | `stars` | 밖에서 놀기 | 중 | 21~다음 날 2시 | 5% | 10% | 5% | 5% | 15% | 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시 | 15% | 30% | 15% | 10% | 0% | 5% | | |
|
||||
| 15 | 자전거각 | `bike` | 밖에서 놀기 | 상 | 9~19시 | 25% | 25% | 25% | 5% | 10% | 5% | | |
|
||||
| 16 | 멍뭉산책각 | `dog` | 밖에서 놀기 | 중 | 7~9시 / 17~20시 | 35% | 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시 | 25% | 30% | 10% | 15% | 10% | 5% | | |
|
||||
| 23 | 사진산책각 | `photo` | 밖에서 놀기 | 중 | 일몰 앞뒤 1시간 | 10% | 25% | 10% | 5% | 10% | 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% | ○ | |
|
||||
| 28 | 골프각 | `golf` | 밖에서 놀기 | 중 | 7~12시 / 12~17시 | 30% | 30% | 25% | 5% | 5% | 5% | | |
|
||||
| 29 | 집콕각 | `jipkok` | 집안일 | 하 | 10~18시 | 30% | 30% | 10% | 5% | 20% | 5% | ○ | |
|
||||
| 30 | 낚시각 | `fishing` | 밖에서 놀기 | 중 | 5~9시 / 16~19시 | 25% | 25% | 35% | 0% | 5% | 10% | | |
|
||||
| 31 | 드라이브각 | `drive` | 밖에서 놀기 | 상 | 10~17시 | 20% | 30% | 5% | 5% | 15% | 10% | | |
|
||||
| 32 | 연날리기각 | `kite` | 밖에서 놀기 | 하 | 11~16시 | 20% | 25% | 45% | 0% | 5% | 5% | | |
|
||||
| 33 | 물놀이각 | `waterplay` | 밖에서 놀기 | 중 | 11~17시 | 40% | 25% | 10% | 0% | 0% | 5% | | |
|
||||
| 34 | 김장각 | `kimjang` | 집안일 | 하 | 9~16시 | 50% | 25% | 10% | 0% | 5% | 10% | | |
|
||||
|
||||
## 각별 자세히
|
||||
|
||||
### 야장각 (`yajang`)
|
||||
|
||||
- 설명: 저녁 6시~자정, 바깥 자리에 앉기 좋은 정도
|
||||
- 분류: 먹고 마시기 · 아이콘 `yajang` · 재미 각 예 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
||||
- 분류: 먹고 마시기 · 중요도 중 · 아이콘 `yajang` · 재미 각 예 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
||||
- 시간대: 18~24시
|
||||
- 요소별 규칙 (비중):
|
||||
- 기온 30%: 체감 18~24°가 좋음
|
||||
@@ -68,7 +76,7 @@
|
||||
### 피크닉각 (`picnic`)
|
||||
|
||||
- 설명: 낮 동안 돗자리 펴고 쉬기 좋은 정도
|
||||
- 분류: 밖에서 놀기 · 아이콘 `picnic` · 재미 각 아니오 · 계절 핵심 예 · 계산 근거 화면 있음
|
||||
- 분류: 밖에서 놀기 · 중요도 상 · 아이콘 `picnic` · 재미 각 아니오 · 계절 핵심 예 · 계산 근거 화면 있음
|
||||
- 시간대: 11~16시
|
||||
- 요소별 규칙 (비중):
|
||||
- 기온 25%: 체감 20~26°가 좋음
|
||||
@@ -89,7 +97,7 @@
|
||||
### 치맥각 (`chimaek`)
|
||||
|
||||
- 설명: 저녁에 바깥에서 치킨과 맥주가 당기는 정도
|
||||
- 분류: 먹고 마시기 · 아이콘 `chimaek` · 재미 각 예 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
||||
- 분류: 먹고 마시기 · 중요도 중 · 아이콘 `chimaek` · 재미 각 예 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
||||
- 시간대: 18~23시
|
||||
- 요소별 규칙 (비중):
|
||||
- 기온 30%: 체감 20~27°가 좋음
|
||||
@@ -109,7 +117,7 @@
|
||||
### 산책각 (`walk`)
|
||||
|
||||
- 설명: 걷기 좋은 정도 (해 진 뒤 기준)
|
||||
- 분류: 밖에서 놀기 · 아이콘 `walk` · 재미 각 아니오 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
||||
- 분류: 밖에서 놀기 · 중요도 상 · 아이콘 `walk` · 재미 각 아니오 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
||||
- 시간대: 18~22시
|
||||
- 요소별 규칙 (비중):
|
||||
- 기온 30%: 체감 15~23°가 좋음
|
||||
@@ -129,7 +137,7 @@
|
||||
### 환기각 (`vent`)
|
||||
|
||||
- 설명: 창문 열어 공기 바꾸기 좋은 정도
|
||||
- 분류: 집안일 · 아이콘 `vent` · 재미 각 아니오 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
||||
- 분류: 집안일 · 중요도 하 · 아이콘 `vent` · 재미 각 아니오 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
||||
- 시간대: 10~12시 / 12~14시 / 14~16시 / 16~18시
|
||||
- 요소별 규칙 (비중):
|
||||
- 기온 10%: 체감 15~26°가 좋음
|
||||
@@ -149,7 +157,7 @@
|
||||
### 등산각 (`hiking`)
|
||||
|
||||
- 설명: 산에 오르기 좋은 정도 (오전 기준)
|
||||
- 분류: 밖에서 놀기 · 아이콘 `hiking` · 재미 각 아니오 · 계절 핵심 예 · 계산 근거 화면 있음
|
||||
- 분류: 밖에서 놀기 · 중요도 상 · 아이콘 `hiking` · 재미 각 아니오 · 계절 핵심 예 · 계산 근거 화면 있음
|
||||
- 시간대: 7~12시
|
||||
- 요소별 규칙 (비중):
|
||||
- 기온 25%: 체감 10~20°가 좋음, 산 정상 보정 -6°
|
||||
@@ -171,7 +179,7 @@
|
||||
### 세차각 (`carwash`)
|
||||
|
||||
- 설명: 세차한 뒤 깨끗함이 오래가는 정도
|
||||
- 분류: 집안일 · 아이콘 `carwash` · 재미 각 아니오 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
||||
- 분류: 집안일 · 중요도 하 · 아이콘 `carwash` · 재미 각 아니오 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
||||
- 시간대: 9~18시 (비는 2일 뒤까지 봄)
|
||||
- 요소별 규칙 (비중):
|
||||
- 기온 5%: 체감 5~28°가 좋음
|
||||
@@ -191,7 +199,7 @@
|
||||
### 캠핑각 (`camping`)
|
||||
|
||||
- 설명: 하룻밤 캠핑하기 좋은 정도
|
||||
- 분류: 밖에서 놀기 · 아이콘 `camping` · 재미 각 아니오 · 계절 핵심 예 · 계산 근거 화면 있음
|
||||
- 분류: 밖에서 놀기 · 중요도 상 · 아이콘 `camping` · 재미 각 아니오 · 계절 핵심 예 · 계산 근거 화면 있음
|
||||
- 시간대: 18~다음 날 8시
|
||||
- 요소별 규칙 (비중):
|
||||
- 기온 30%: 체감 12~22°가 좋음
|
||||
@@ -211,7 +219,7 @@
|
||||
### 러닝각 (`running`)
|
||||
|
||||
- 설명: 뛰기 좋은 정도 (아침·저녁 중 좋은 쪽)
|
||||
- 분류: 밖에서 놀기 · 아이콘 `running` · 재미 각 아니오 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
||||
- 분류: 밖에서 놀기 · 중요도 상 · 아이콘 `running` · 재미 각 아니오 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
||||
- 시간대: 6~8시 / 19~22시
|
||||
- 요소별 규칙 (비중):
|
||||
- 기온 35%: 체감 8~18°가 좋음
|
||||
@@ -232,7 +240,7 @@
|
||||
### 별보기각 (`stars`)
|
||||
|
||||
- 설명: 밤하늘 별이 잘 보이는 정도
|
||||
- 분류: 밖에서 놀기 · 아이콘 `stars` · 재미 각 아니오 · 계절 핵심 예 · 계산 근거 화면 있음
|
||||
- 분류: 밖에서 놀기 · 중요도 중 · 아이콘 `stars` · 재미 각 아니오 · 계절 핵심 예 · 계산 근거 화면 있음
|
||||
- 시간대: 21~다음 날 2시
|
||||
- 요소별 규칙 (비중):
|
||||
- 기온 5%: 체감 5~25°가 좋음
|
||||
@@ -253,7 +261,7 @@
|
||||
### 짬뽕각 (`jjamppong`)
|
||||
|
||||
- 설명: 뜨끈한 국물이 당기는 정도
|
||||
- 분류: 먹고 마시기 · 아이콘 `jjamppong` · 재미 각 예 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
||||
- 분류: 먹고 마시기 · 중요도 하 · 아이콘 `jjamppong` · 재미 각 예 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
||||
- 시간대: 11~14시 / 17~20시
|
||||
- 요소별 규칙 (비중):
|
||||
- 기온 40%: 추울수록 좋음 (25°=0점 → 5°=100점)
|
||||
@@ -273,7 +281,7 @@
|
||||
### 막걸리각 (`makgeolli`)
|
||||
|
||||
- 설명: 비 오는 날 파전에 막걸리가 당기는 정도
|
||||
- 분류: 먹고 마시기 · 아이콘 `makgeolli` · 재미 각 예 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
||||
- 분류: 먹고 마시기 · 중요도 하 · 아이콘 `makgeolli` · 재미 각 예 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
||||
- 시간대: 17~22시
|
||||
- 요소별 규칙 (비중):
|
||||
- 기온 15%: 추울수록 좋음 (28°=0점 → 10°=100점)
|
||||
@@ -293,7 +301,7 @@
|
||||
### 뜨아각 (`iced_hot`)
|
||||
|
||||
- 설명: 아이스 대신 따뜻한 커피로 바꿀 때가 된 정도
|
||||
- 분류: 먹고 마시기 · 아이콘 `iced_hot` · 재미 각 예 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
||||
- 분류: 먹고 마시기 · 중요도 하 · 아이콘 `iced_hot` · 재미 각 예 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
||||
- 시간대: 7~10시
|
||||
- 요소별 규칙 (비중):
|
||||
- 기온 50%: 추울수록 좋음 (22°=0점 → 8°=100점)
|
||||
@@ -313,7 +321,7 @@
|
||||
### 빨래각 (`laundry`)
|
||||
|
||||
- 설명: 빨래가 잘 마르는 정도
|
||||
- 분류: 집안일 · 아이콘 `laundry` · 재미 각 아니오 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
||||
- 분류: 집안일 · 중요도 상 · 아이콘 `laundry` · 재미 각 아니오 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
||||
- 시간대: 9~16시
|
||||
- 요소별 규칙 (비중):
|
||||
- 기온 15%: 더울수록 좋음 (10°=0점 → 25°=100점)
|
||||
@@ -334,7 +342,7 @@
|
||||
### 자전거각 (`bike`)
|
||||
|
||||
- 설명: 자전거 타기 좋은 정도
|
||||
- 분류: 밖에서 놀기 · 아이콘 `bike` · 재미 각 아니오 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
||||
- 분류: 밖에서 놀기 · 중요도 상 · 아이콘 `bike` · 재미 각 아니오 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
||||
- 시간대: 9~19시
|
||||
- 요소별 규칙 (비중):
|
||||
- 기온 25%: 체감 15~24°가 좋음
|
||||
@@ -355,7 +363,7 @@
|
||||
### 멍뭉산책각 (`dog`)
|
||||
|
||||
- 설명: 반려견과 산책하기 좋은 정도
|
||||
- 분류: 밖에서 놀기 · 아이콘 `dog` · 재미 각 아니오 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
||||
- 분류: 밖에서 놀기 · 중요도 중 · 아이콘 `dog` · 재미 각 아니오 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
||||
- 시간대: 7~9시 / 17~20시
|
||||
- 요소별 규칙 (비중):
|
||||
- 기온 35%: 체감 5~22°가 좋음
|
||||
@@ -376,7 +384,7 @@
|
||||
### 김서림각 (`glasses`)
|
||||
|
||||
- 설명: 안경에 김이 서리기 쉬운 정도
|
||||
- 분류: 생활 고민 · 아이콘 `glasses` · 재미 각 아니오 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
||||
- 분류: 생활 고민 · 중요도 중 · 아이콘 `glasses` · 재미 각 아니오 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
||||
- 시간대: 7~9시
|
||||
- 요소별 규칙 (비중):
|
||||
- 기온 50%: 추울수록 좋음 (15°=0점 → -5°=100점)
|
||||
@@ -396,7 +404,7 @@
|
||||
### 화장붕괴각 (`makeup`)
|
||||
|
||||
- 설명: 화장이 무너지기 쉬운 정도
|
||||
- 분류: 생활 고민 · 아이콘 `makeup` · 재미 각 아니오 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
||||
- 분류: 생활 고민 · 중요도 중 · 아이콘 `makeup` · 재미 각 아니오 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
||||
- 시간대: 10~18시
|
||||
- 요소별 규칙 (비중):
|
||||
- 기온 40%: 더울수록 좋음 (20°=0점 → 32°=100점)
|
||||
@@ -416,7 +424,7 @@
|
||||
### 냉면각 (`naengmyeon`)
|
||||
|
||||
- 설명: 시원한 냉면이 당기는 정도
|
||||
- 분류: 먹고 마시기 · 아이콘 `naengmyeon` · 재미 각 예 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
||||
- 분류: 먹고 마시기 · 중요도 하 · 아이콘 `naengmyeon` · 재미 각 예 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
||||
- 시간대: 11~14시
|
||||
- 요소별 규칙 (비중):
|
||||
- 기온 55%: 더울수록 좋음 (18°=0점 → 32°=100점)
|
||||
@@ -436,7 +444,7 @@
|
||||
### 택시대란각 (`taxi`)
|
||||
|
||||
- 설명: 밤늦게 택시 잡기 어려운 정도
|
||||
- 분류: 생활 고민 · 아이콘 `taxi` · 재미 각 아니오 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
||||
- 분류: 생활 고민 · 중요도 중 · 아이콘 `taxi` · 재미 각 아니오 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
||||
- 시간대: 22~다음 날 2시
|
||||
- 요소별 규칙 (비중):
|
||||
- 기온 15%: 추울수록 좋음 (15°=0점 → -5°=100점)
|
||||
@@ -456,7 +464,7 @@
|
||||
### 배달폭주각 (`delivery`)
|
||||
|
||||
- 설명: 배달 주문이 몰리는 정도
|
||||
- 분류: 생활 고민 · 아이콘 `delivery` · 재미 각 아니오 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
||||
- 분류: 생활 고민 · 중요도 중 · 아이콘 `delivery` · 재미 각 아니오 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
||||
- 시간대: 17~21시
|
||||
- 요소별 규칙 (비중):
|
||||
- 기온 20%: 추울수록 좋음 (22°=0점 → 0°=100점)
|
||||
@@ -476,7 +484,7 @@
|
||||
### 가드닝각 (`garden`)
|
||||
|
||||
- 설명: 화분 돌보고 물 주기 좋은 정도
|
||||
- 분류: 집안일 · 아이콘 `garden` · 재미 각 아니오 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
||||
- 분류: 집안일 · 중요도 하 · 아이콘 `garden` · 재미 각 아니오 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
||||
- 시간대: 7~10시
|
||||
- 요소별 규칙 (비중):
|
||||
- 기온 25%: 체감 12~25°가 좋음
|
||||
@@ -497,7 +505,7 @@
|
||||
### 사진산책각 (`photo`)
|
||||
|
||||
- 설명: 노을 무렵 사진 찍으며 걷기 좋은 정도
|
||||
- 분류: 밖에서 놀기 · 아이콘 `photo` · 재미 각 아니오 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
||||
- 분류: 밖에서 놀기 · 중요도 중 · 아이콘 `photo` · 재미 각 아니오 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
||||
- 시간대: 일몰 앞뒤 1시간
|
||||
- 요소별 규칙 (비중):
|
||||
- 기온 10%: 체감 10~26°가 좋음
|
||||
@@ -518,7 +526,7 @@
|
||||
### 야구각 (`baseball`)
|
||||
|
||||
- 설명: 저녁 6~10시, 야구장 직관하기 좋은 정도
|
||||
- 분류: 밖에서 놀기 · 아이콘 `baseball` · 재미 각 예 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
||||
- 분류: 밖에서 놀기 · 중요도 하 · 아이콘 `baseball` · 재미 각 예 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
||||
- 시간대: 18~22시
|
||||
- 요소별 규칙 (비중):
|
||||
- 기온 25%: 체감 15~25°가 좋음
|
||||
@@ -538,7 +546,7 @@
|
||||
### 공부각 (`study`)
|
||||
|
||||
- 설명: 오후 1~6시, 밖에 나가기 싫어서 공부가 잘되는 정도
|
||||
- 분류: 집안일 · 아이콘 `study` · 재미 각 예 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
||||
- 분류: 집안일 · 중요도 하 · 아이콘 `study` · 재미 각 예 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
||||
- 시간대: 13~18시
|
||||
- 요소별 규칙 (비중):
|
||||
- 기온 35%: 체감이 15~24°에서 멀수록(덥거나 추울수록) 좋음
|
||||
@@ -558,7 +566,7 @@
|
||||
### 넷플릭스각 (`netflix`)
|
||||
|
||||
- 설명: 밤 8시~자정, 집에서 영화 보기 좋은 정도
|
||||
- 분류: 집안일 · 아이콘 `netflix` · 재미 각 예 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
||||
- 분류: 집안일 · 중요도 하 · 아이콘 `netflix` · 재미 각 예 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
||||
- 시간대: 20~24시
|
||||
- 요소별 규칙 (비중):
|
||||
- 기온 30%: 추울수록 좋음 (22°=0점 → 0°=100점)
|
||||
@@ -578,7 +586,7 @@
|
||||
### 군밤각 (`chestnut`)
|
||||
|
||||
- 설명: 저녁 5~9시, 길거리 군밤이 당기는 정도
|
||||
- 분류: 먹고 마시기 · 아이콘 `chestnut` · 재미 각 예 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
||||
- 분류: 먹고 마시기 · 중요도 하 · 아이콘 `chestnut` · 재미 각 예 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
||||
- 시간대: 17~21시
|
||||
- 요소별 규칙 (비중):
|
||||
- 기온 55%: 추울수록 좋음 (18°=0점 → 0°=100점)
|
||||
@@ -595,3 +603,145 @@
|
||||
- 60~79점: 손이 시려요. 따끈한 군밤 한 봉지!
|
||||
- 80~100점: 영하 가까운 저녁, 군밤 품고 걷는 날 🌰
|
||||
|
||||
### 골프각 (`golf`)
|
||||
|
||||
- 설명: 오전 7시~오후 5시, 필드에서 라운딩하기 좋은 정도
|
||||
- 분류: 밖에서 놀기 · 중요도 중 · 아이콘 `golf` · 재미 각 아니오 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
||||
- 시간대: 7~12시 / 12~17시
|
||||
- 요소별 규칙 (비중):
|
||||
- 기온 30%: 체감 15~24°가 좋음
|
||||
- 비 30%: 비 안 올수록 좋음
|
||||
- 바람 25%: 잔잔할수록 좋음 (초속 3m까지 괜찮음, 9m면 0점)
|
||||
- 습도 5%: 30~60%가 좋음 (최적 35%)
|
||||
- 미세먼지 5%: 초미세먼지 낮을수록 좋음
|
||||
- 시간·요일 5%: 요일별 점수: 토 100, 일 100, 공휴일 100, 그 외 70
|
||||
- 점수 깎이는 조건: 비 확률 70% 이상이면 0점, 바람 12m/s 이상이면 0점, wind 특보가 있으면
|
||||
- 반영 못 하는 것: 골프장 예약, 잔디 상태, 낙뢰는 반영하지 못해요
|
||||
- 점수 구간별 설명 (상세 창에 나옴):
|
||||
- 0~29점: 비 70% 넘거나 바람이 너무 세요. 오늘은 스크린으로!
|
||||
- 30~59점: 춥거나 덥거나 바람이 공을 흔들어요. 타수는 기대 말기!
|
||||
- 60~79점: 칠 만해요! 바람 방향만 잘 읽으면 돼요.
|
||||
- 80~100점: 15~24°에 바람 잔잔, 인생 라운딩 노려볼 날 ⛳
|
||||
|
||||
### 집콕각 (`jipkok`)
|
||||
|
||||
- 설명: 오전 10시~오후 6시, 나가기 싫어 집에 있고 싶은 정도
|
||||
- 분류: 집안일 · 중요도 하 · 아이콘 `jipkok` · 재미 각 예 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
||||
- 시간대: 10~18시
|
||||
- 요소별 규칙 (비중):
|
||||
- 기온 30%: 체감이 15~24°에서 멀수록(덥거나 추울수록) 좋음
|
||||
- 비 30%: 비 올수록 좋음
|
||||
- 바람 10%: 셀수록 좋음 (초속 8m=100점)
|
||||
- 습도 5%: 높을수록 좋음 (40%=0점 → 90%=100점)
|
||||
- 미세먼지 20%: 초미세먼지 높을수록 좋음 (15㎍/㎥=0점 → 75㎍/㎥=100점)
|
||||
- 시간·요일 5%: 요일별 점수: 토 100, 일 100, 공휴일 100, 그 외 60
|
||||
- 점수 깎이는 조건: 없음
|
||||
- 반영 못 하는 것: 재미로 보는 지수예요
|
||||
- 점수 구간별 설명 (상세 창에 나옴):
|
||||
- 0~29점: 밖이 너무 좋아요. 집에만 있기 아까운 날!
|
||||
- 30~59점: 나갈까 말까, 소파와 밀당 중이에요.
|
||||
- 60~79점: 덥거나 춥거나 공기가 탁해요. 집이 최고!
|
||||
- 80~100점: 비 오고 공기까지 탁해요. 이불 밖은 위험해 🛋️
|
||||
|
||||
### 낚시각 (`fishing`)
|
||||
|
||||
- 설명: 새벽 5~9시·오후 4~7시, 물가에서 낚시하기 좋은 정도
|
||||
- 분류: 밖에서 놀기 · 중요도 중 · 아이콘 `fishing` · 재미 각 아니오 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
||||
- 시간대: 5~9시 / 16~19시
|
||||
- 요소별 규칙 (비중):
|
||||
- 기온 25%: 체감 12~24°가 좋음
|
||||
- 비 25%: 비 안 올수록 좋음
|
||||
- 바람 35%: 잔잔할수록 좋음 (초속 4m까지 괜찮음, 10m면 0점)
|
||||
- 습도 0%: 상관없음 (50점 고정)
|
||||
- 미세먼지 5%: 초미세먼지 낮을수록 좋음
|
||||
- 시간·요일 10%: 요일별 점수: 토 100, 일 100, 공휴일 100, 그 외 60
|
||||
- 점수 깎이는 조건: 비 확률 70% 이상이면 0점, 바람 10m/s 이상이면 0점, wind 특보가 있으면
|
||||
- 반영 못 하는 것: 물때·수온·파도 높이는 반영하지 못해요
|
||||
- 점수 구간별 설명 (상세 창에 나옴):
|
||||
- 0~29점: 비 70% 넘거나 바람이 거세요. 물가는 위험, 오늘은 쉬어요!
|
||||
- 30~59점: 바람에 찌가 흔들리거나 손이 시려요. 짧게 손맛만!
|
||||
- 60~79점: 물가 나가볼 만해요! 새벽엔 쌀쌀하니 겉옷 챙기기.
|
||||
- 80~100점: 12~24°에 물결 잔잔, 입질 기다리기 딱 좋은 날 🎣
|
||||
|
||||
### 드라이브각 (`drive`)
|
||||
|
||||
- 설명: 오전 10시~오후 5시, 창문 열고 드라이브하기 좋은 정도
|
||||
- 분류: 밖에서 놀기 · 중요도 상 · 아이콘 `drive` · 재미 각 아니오 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
||||
- 시간대: 10~17시
|
||||
- 요소별 규칙 (비중):
|
||||
- 기온 20%: 체감 15~25°가 좋음
|
||||
- 비 30%: 비 안 올수록 좋음
|
||||
- 바람 5%: 잔잔할수록 좋음 (초속 6m까지 괜찮음, 15m면 0점)
|
||||
- 습도 5%: 30~60%가 좋음 (최적 35%)
|
||||
- 미세먼지 15%: 초미세먼지 낮을수록 좋음
|
||||
- 가시거리 15%: 20km 이상이면 만점, 5km 이하면 0점 (Open-Meteo)
|
||||
- 시간·요일 10%: 요일별 점수: 토 100, 일 100, 공휴일 100, 그 외 60
|
||||
- 점수 깎이는 조건: 비 확률 70% 이상이면 최대 20점
|
||||
- 반영 못 하는 것: 길 막힘과 도로 공사는 반영하지 못해요
|
||||
- 점수 구간별 설명 (상세 창에 나옴):
|
||||
- 0~29점: 비가 쏟아져요. 와이퍼만 바쁜 날, 드라이브는 다음에!
|
||||
- 30~59점: 하늘이 뿌옇거나 비 기운이 있어요. 가까운 곳만 슬쩍!
|
||||
- 60~79점: 달릴 만해요! 창문 반쯤 열고 음악 크게.
|
||||
- 80~100점: 공기 맑고 멀리까지 보여요. 해안도로 달리고 싶은 날 🚗
|
||||
|
||||
### 연날리기각 (`kite`)
|
||||
|
||||
- 설명: 오전 11시~오후 4시, 연 날리기 좋은 정도
|
||||
- 분류: 밖에서 놀기 · 중요도 하 · 아이콘 `kite` · 재미 각 아니오 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
||||
- 시간대: 11~16시
|
||||
- 요소별 규칙 (비중):
|
||||
- 기온 20%: 체감 8~22°가 좋음
|
||||
- 비 25%: 비 안 올수록 좋음
|
||||
- 바람 45%: 적당한 바람(초속 2~5m)이 좋음
|
||||
- 습도 0%: 상관없음 (50점 고정)
|
||||
- 미세먼지 5%: 초미세먼지 낮을수록 좋음
|
||||
- 시간·요일 5%: 요일별 점수: 토 100, 일 100, 공휴일 100, 그 외 70
|
||||
- 점수 깎이는 조건: 비 확률 70% 이상이면 0점, 돌풍 13m/s 이상이면 0점, 바람 1m/s 미만이면 최대 30점
|
||||
- 반영 못 하는 것: 전깃줄·나무 없는 넓은 곳인지는 반영하지 못해요
|
||||
- 점수 구간별 설명 (상세 창에 나옴):
|
||||
- 0~29점: 비가 오거나 돌풍이 불어요. 연이 날아가 버려요!
|
||||
- 30~59점: 바람이 너무 약하거나 너무 세요. 뛰어다녀야 겨우 떠요.
|
||||
- 60~79점: 연 띄울 만해요! 실은 넉넉하게 감아 가요.
|
||||
- 80~100점: 초속 2~5m 딱 좋은 바람, 연이 하늘 높이 쭉쭉 🪁
|
||||
|
||||
### 물놀이각 (`waterplay`)
|
||||
|
||||
- 설명: 오전 11시~오후 5시, 바다·계곡에서 물놀이하기 좋은 정도
|
||||
- 분류: 밖에서 놀기 · 중요도 중 · 아이콘 `waterplay` · 재미 각 아니오 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
||||
- 시간대: 11~17시
|
||||
- 요소별 규칙 (비중):
|
||||
- 기온 40%: 체감 27~34°가 좋음
|
||||
- 비 25%: 비 안 올수록 좋음
|
||||
- 바람 10%: 잔잔할수록 좋음 (초속 4m까지 괜찮음, 12m면 0점)
|
||||
- 습도 0%: 상관없음 (50점 고정)
|
||||
- 미세먼지 0%: 초미세먼지 낮을수록 좋음
|
||||
- 햇빛 20%: 해 난 비율 80% 이상이면 만점, 20% 이하면 0점 (Open-Meteo)
|
||||
- 시간·요일 5%: 요일별 점수: 토 100, 일 100, 공휴일 100, 그 외 60
|
||||
- 점수 깎이는 조건: 비 확률 60% 이상이면 0점, 체감 20° 미만이면 0점
|
||||
- 반영 못 하는 것: 수온, 파도 높이, 계곡 물살은 반영하지 못해요
|
||||
- 점수 구간별 설명 (상세 창에 나옴):
|
||||
- 0~29점: 체감 20° 아래거나 비 소식이 있어요. 물놀이는 여름에!
|
||||
- 30~59점: 물에 들어가면 으슬으슬해요. 발만 담그기!
|
||||
- 60~79점: 물놀이 괜찮아요! 그늘막이랑 선크림 챙기기.
|
||||
- 80~100점: 30° 안팎에 쨍쨍, 튜브 들고 풍덩 🏖️
|
||||
|
||||
### 김장각 (`kimjang`)
|
||||
|
||||
- 설명: 오전 9시~오후 4시, 김장하기 좋은 정도
|
||||
- 분류: 집안일 · 중요도 하 · 아이콘 `kimchi` · 재미 각 아니오 · 계절 핵심 아니오 · 계산 근거 화면 있음
|
||||
- 시간대: 9~16시
|
||||
- 요소별 규칙 (비중):
|
||||
- 기온 50%: 체감 0~10°가 좋음
|
||||
- 비 25%: 비 안 올수록 좋음
|
||||
- 바람 10%: 잔잔할수록 좋음 (초속 4m까지 괜찮음, 10m면 0점)
|
||||
- 습도 0%: 상관없음 (50점 고정)
|
||||
- 미세먼지 5%: 초미세먼지 낮을수록 좋음
|
||||
- 시간·요일 10%: 요일별 점수: 토 100, 일 100, 공휴일 100, 그 외 50
|
||||
- 점수 깎이는 조건: 체감 18° 이상이면 0점
|
||||
- 반영 못 하는 것: 배추 작황과 값, 집집마다 김장 날짜는 반영하지 못해요
|
||||
- 점수 구간별 설명 (상세 창에 나옴):
|
||||
- 0~29점: 아직 18° 넘어요. 지금 담그면 김치가 금방 쉬어요!
|
||||
- 30~59점: 조금 이르거나 손이 꽁꽁 얼어요. 날을 다시 골라 봐요.
|
||||
- 60~79점: 김장할 만해요! 고무장갑 안에 면장갑 하나 더.
|
||||
- 80~100점: 0~10°에 비 없고 바람 잔잔, 김장 날 잡는 날 🥬
|
||||
|
||||
+9
-15
@@ -1,22 +1,22 @@
|
||||
# 이벤트 추적 (GTM · GA4)
|
||||
# 이벤트 추적 (GA4)
|
||||
|
||||
기준: `frontend/index.html`, `frontend/src/lib/analytics.ts`, `frontend/src/b/Sheets.tsx`, `frontend/src/b/region.tsx` (2026-10-08)
|
||||
|
||||
## 한 줄 요약
|
||||
|
||||
GTM 컨테이너 `GTM-PKQMKPFC`를 `index.html`에 심고, 화면에서는 `track(이벤트, 값)`으로 `dataLayer`에 이벤트를 넣는다. GTM이 그 이벤트를 받아 GA4로 보낸다.
|
||||
GA4 태그(`gtag.js`, 측정 ID `G-D378J4X373`)를 `index.html`에 심고, 화면에서는 `track(이벤트, 값)`으로 GA4에 이벤트를 바로 보낸다. GTM은 쓰지 않는다.
|
||||
|
||||
```
|
||||
[화면] track('share', {...})
|
||||
└─ window.dataLayer.push({ event: 'share', ... })
|
||||
└─ [GTM] 맞춤 이벤트 트리거 → GA4 이벤트 태그 → GA4
|
||||
└─ window.gtag('event', 'share', {...}) → GA4
|
||||
```
|
||||
|
||||
- 개발 서버(`npm run dev`)에서는 보내지 않는다. 개발 트래픽이 집계에 섞이지 않게.
|
||||
- 왜 GTM이 아니라 GA4 직접인가: 이벤트를 코드(`analytics.ts`)에서 정하므로, GTM을 쓰면 이벤트마다 트리거·태그를 한 번 더 만들어야 한다. 광고 픽셀도, 마케터가 직접 손볼 일도 아직 없다.
|
||||
- 개발 서버(`npm run dev`)에서는 `track()`이 이벤트를 보내지 않는다. 단 `index.html`의 페이지 조회(`page_view`)는 개발 서버에서도 나가므로 GA4에서 `localhost`를 걸러 본다.
|
||||
- 이벤트 이름은 영어 snake_case. GA4 추천 이벤트(`share`, `login`, `sign_up`, `select_content`)는 이름을 그대로 써야 GA4 기본 보고서에 잡힌다.
|
||||
- 값은 사람이 읽을 수 있게 한글 그대로 둔다 (예: `gak_name: '야장각'`).
|
||||
- 개인정보(아이디, 닉네임 등)는 값에 넣지 않는다.
|
||||
- 페이지 이동은 코드로 보내지 않는다. GTM의 "기록 변경(History Change)" 트리거로 잡는다. 모든 이벤트에는 GA4가 `page_location`을 자동으로 붙이므로 어느 탭에서 일어났는지는 따로 보내지 않는다.
|
||||
- 페이지 이동은 코드로 보내지 않는다. GA4 향상된 측정의 "브라우저 기록 이벤트 기반 페이지 변경"이 잡는다(기본 켜짐). 모든 이벤트에 GA4가 `page_location`을 붙이므로 어느 탭에서 일어났는지는 따로 보내지 않는다.
|
||||
|
||||
## 이벤트 목록
|
||||
|
||||
@@ -33,13 +33,7 @@ GTM 컨테이너 `GTM-PKQMKPFC`를 `index.html`에 심고, 화면에서는 `trac
|
||||
- `region_change`의 `location`은 처음 온 사람의 자동 위치 맞춤도 포함한다.
|
||||
- 새 이벤트는 `analytics.ts`의 `Events` 타입에 먼저 더한다. 타입에 없는 이름은 빌드에서 걸린다.
|
||||
|
||||
## GTM 설정
|
||||
## GA4 설정
|
||||
|
||||
이벤트마다 아래 두 개를 만든다.
|
||||
|
||||
1. **트리거**: 유형 "맞춤 이벤트", 이벤트 이름은 위 표의 이름 (예: `view_gak`).
|
||||
2. **태그**: 유형 "Google 애널리틱스: GA4 이벤트", 이벤트 이름은 같은 이름. 이벤트 매개변수에 위 표의 값을 하나씩 더하고, 값은 "데이터 영역 변수"(이름은 값 키 그대로, 예: `gak_name`)로 넣는다.
|
||||
|
||||
GA4 보고서에서 맞춤 값(`gak_name`, `ratio`, `region_name` 등)으로 나눠 보려면 GA4 관리 → 맞춤 정의에서 이벤트 범위 측정기준으로 등록한다.
|
||||
|
||||
확인은 GTM 미리보기 모드에서 운영 빌드(`docker compose up --build frontend`, http://localhost:8080)를 열어 한다.
|
||||
- 맞춤 값(`gak_name`, `ratio`, `region_name` 등)으로 보고서를 나눠 보려면 GA4 관리 → 맞춤 정의에서 이벤트 범위 측정기준으로 등록한다. 등록 전 값은 보고서에 소급되지 않는다.
|
||||
- 확인은 GA4 보고서 → 실시간, 또는 관리 → DebugView에서 한다. 운영 빌드(`docker compose up --build frontend`, http://localhost:8080)나 운영 사이트에서 눌러 본다.
|
||||
+145
@@ -0,0 +1,145 @@
|
||||
# 점수 계산식
|
||||
|
||||
화면에 나오는 점수·판정의 계산식을 한곳에 모은 문서입니다. 각별 비중·시간대는 [각_계산기준.md](각_계산기준.md)에 있습니다.
|
||||
|
||||
| 점수 | 화면 | 코드 |
|
||||
|---|---|---|
|
||||
| 오늘 날씨 점수 | 오늘 탭 히어로 큰 숫자 | `backend/services/index_service.py` (`WEATHER_SCORE_DEF`) |
|
||||
| 각 점수 | 각 탭, 피드 각 카드 | `backend/services/calc/index_calc.py` (`evaluate`) |
|
||||
| 나들이 점수 | 주말 탭 전국 순위, 당일치기 카드 | `backend/services/calc/index_calc.py` (`outing`) |
|
||||
| 노을 점수·판정 | 노을 탭, 피드 노을 카드, 노을 순위 | `backend/services/calc/sky_score.py`, `backend/services/sky_service.py` |
|
||||
| 노을 시각 | 노을 탭 시간표 | `backend/services/calc/sun.py`, `sky_score.py` (`best_times`) |
|
||||
| 달 밝기 | 밤 히어로 | `backend/services/calc/moon.py` |
|
||||
| 불쾌지수 | 히어로 칸 | `backend/services/calc/weather_calc.py` |
|
||||
|
||||
## 1. 공통 — 요소 점수와 섞는 법
|
||||
|
||||
오늘 날씨·각·나들이 점수는 모두 같은 방식입니다.
|
||||
|
||||
1. 요소(기온·비·바람·습도·미세먼지·햇빛 등)마다 0~100점을 매깁니다.
|
||||
2. 비중(합 100%)대로 섞습니다.
|
||||
3. 가장 낮은 요소로 깎습니다: **최종 = 섞은 점수 × (0.75 + 0.25 × 가장 낮은 요소 ÷ 100)**. 비중 0%인 요소는 빼고 봅니다. 한 요소가 0점이면 최대 25% 깎입니다.
|
||||
4. 0점 조건·최대 N점 조건이 있으면 적용합니다.
|
||||
|
||||
그래서 100점은 **비중이 있는 요소가 모두 100점**일 때만 나옵니다.
|
||||
|
||||
### 내려가는 곡선
|
||||
|
||||
만점 구간을 벗어나면 정규분포 곡선 모양으로 내려갑니다. 만점 근처는 천천히, 멀어질수록 빨리 떨어집니다.
|
||||
|
||||
`곡선(t) = (e^(−t²/2) − e^(−0.5)) ÷ (1 − e^(−0.5))` — t=0이면 1, t=1이면 0.
|
||||
|
||||
### 요소별 점수
|
||||
|
||||
| 요소 | 규칙 | 계산 |
|
||||
|---|---|---|
|
||||
| 기온(체감) | 편한 범위 lo~hi, 최적 best | 최적 ± 만점폭(기본 2°, 범위 끝까지 거리의 1/3 넘지 않음)은 100 → 범위 끝에서 85 → 범위 밖은 1°마다 8점 꼴로 곡선을 따라 0 (약 10.6° 벗어나면 0) |
|
||||
| 기온 | 높을수록·낮을수록 | zero에서 0, full에서 100, 사이는 곡선 |
|
||||
| 비 (마른 날이 좋음) | | 비 소식이 있으면 0. 아니면 비 확률 0%=100 → 100%=0, 곡선 |
|
||||
| 비 (비 오면 좋음) | 막걸리·배달폭주각 등 | 비 소식이 있으면 100. 아니면 비 확률 0%=0 → 100%=100 |
|
||||
| 바람 (잔잔할수록) | ok, limit | ok/2 이하 100 → ok에서 85 (직선) → limit에서 0 (곡선). 시간대 중 가장 센 바람 기준 |
|
||||
| 습도 | 편한 범위 | 기온과 같은 모양, 만점폭 5%, 범위 밖은 1%마다 2점 꼴 |
|
||||
| 미세먼지 | | 초미세먼지 15㎍/㎥ 이하 100 → 75 이상 0, 곡선. 집콕각은 거꾸로 |
|
||||
| 자외선·햇빛·가시거리 | zero, full | 직선 대신 곡선으로 zero→full |
|
||||
| 정보 없음 | | 바람·미세먼지·자외선·햇빛·가시거리 정보가 없으면 70점 |
|
||||
|
||||
## 2. 오늘 날씨 점수
|
||||
|
||||
오늘 낮 **9~21시**가 밖에 나가기 좋은 정도. 1의 방식으로 계산합니다.
|
||||
|
||||
| 요소 | 비중 | 100점 조건 |
|
||||
|---|---:|---|
|
||||
| 체감온도 (시간 평균) | 30% | 20.5~21.5° (편한 범위 18~24°, 최적 21°, 만점폭 0.5°) |
|
||||
| 비 | 25% | 비 소식 없음, 비 확률 0%대 |
|
||||
| 바람 (가장 센 값) | 10% | 초속 1m 이하 (2m에서 85점, 10m에서 0점) |
|
||||
| 습도 (시간 평균) | 10% | 45~55% (편한 범위 40~60%) |
|
||||
| 초미세먼지 | 10% | 10㎍/㎥ 이하 (75에서 0점) |
|
||||
| 해 난 비율 (Open-Meteo) | 15% | 90% 이상 (20%에서 0점), 정보 없으면 70점 |
|
||||
|
||||
여섯 가지가 동시에 맞아야 100점입니다. 기준값은 눈대중으로 잡은 것이며, 실제로 1년에 며칠 나오는지는 확인하지 않았습니다.
|
||||
|
||||
예: 체감 22.5°, 비 10%, 바람 2.5m, 습도 62%, 초미세먼지 15, 해 70% → 95점 미만.
|
||||
|
||||
## 3. 각 점수
|
||||
|
||||
- 1의 방식. 요소·비중·시간대·0점 조건은 각마다 다르며 [각_계산기준.md](각_계산기준.md)에 있습니다.
|
||||
- **시간대가 여러 개면 그중 가장 좋은 시간대 점수**를 그날 점수로 씁니다. 그래서 하루 동안 바뀌지 않습니다.
|
||||
- 순위는 점수 × 중요도(상 1.0 · 중 0.85 · 하 0.7). 화면 숫자는 점수 그대로입니다.
|
||||
- 단기예보가 닿지 않는 날(토·일 등)은 중기예보의 최저·최고 기온으로 시각별 기온을 어림하고(새벽 6시 최저, 오후 3시 최고, 코사인 곡선), 바람·습도·미세먼지는 정보 없음으로 둔 '예상 점수'입니다.
|
||||
|
||||
## 4. 나들이 점수 (주말 순위·당일치기)
|
||||
|
||||
토·일 **10~17시** 기준.
|
||||
|
||||
| 요소 | 비중 | 계산 |
|
||||
|---|---:|---|
|
||||
| 비 | 40% | 마른 날 규칙 (1 참고) |
|
||||
| 체감온도 | 35% | 편한 범위 17~24°, 최적 21° |
|
||||
| 하늘 | 15% | 시간마다 맑음 100 · 구름많음 80 · 흐림 50의 평균 |
|
||||
| 바람 | 10% | 4m/s 이하 100 → 12m/s 0 |
|
||||
|
||||
- 1처럼 가장 낮은 요소로 깎습니다.
|
||||
- 비 소식이 있거나 비 확률 60% 이상이면 **최대 30점**.
|
||||
- 중기예보뿐인 날은 기온을 어림하고 바람은 70점입니다.
|
||||
- 전국 순위: 노을 순위 대표 30곳을 점수순으로 정렬합니다.
|
||||
- 당일치기: 내 지역에서 직선 20~200km 안 후보 도시 중 토·일 중 더 좋은 날 점수가 가장 높은 곳입니다. 동점이면 비 확률이 낮은 곳 → 이른 날 → 가까운 곳 순입니다. 1위가 50점 미만이면 카드를 보이지 않습니다.
|
||||
|
||||
## 5. 노을 점수
|
||||
|
||||
해 지는(뜨는) 시각에 가장 가까운 정시의 구름을, 해 지는 방향 **20km(머리 위)**와 **100km(먼 쪽)** 두 지점에서 봅니다. 예보 모델마다 계산해 평균합니다.
|
||||
|
||||
### 구름 점수
|
||||
|
||||
- 물들 구름 = 20km 지점의 중층·상층 구름 중 큰 값(%)
|
||||
- **물들 정도** = 물들 구름 0%면 0.2 → 50%에서 1.0까지 직선 → 100%에서 0까지 직선
|
||||
- **머리 위 막힘** = 1 − 0.8 × 20km 낮은 구름 ÷ 100
|
||||
- **빛 들어옴** = 1 − min(100km 낮은 구름 + 0.5 × 100km 중층 구름, 100) ÷ 100
|
||||
- **구름 점수 = 100 × (0.75 × 물들 정도 + 0.25 × 머리 위 막힘) × (0.25 + 0.75 × 빛 들어옴)**
|
||||
|
||||
### 공기 보정 (곱함)
|
||||
|
||||
| 조건 | 배수 |
|
||||
|---|---|
|
||||
| 가시거리 (Open-Meteo) | 40km 이상 1.0 → 5km 이하 0.6, 사이 직선 |
|
||||
| 습도 | 50% 이하 1.0 → 90% 이상 0.75, 사이 직선 |
|
||||
| 비 갠 뒤 | 해 지기 2~6시간 전 비 확률 60% 이상이고 그 시각 40% 미만이면 × 1.15 |
|
||||
|
||||
**노을 점수 = min(100, 모델 평균 구름 점수 × 공기 보정)**. 값이 없는 보정은 건너뜁니다.
|
||||
|
||||
### 등급·판정
|
||||
|
||||
- 등급: 80↑ 붉음 · 60↑ 고움 · 40↑ 은은함 · 그 아래 잿빛
|
||||
- 하늘 상황 (모델 평균 구름으로, 위에서부터 먼저 걸리는 것):
|
||||
|
||||
| 상황 | 조건 | 판정 |
|
||||
|---|---|---|
|
||||
| 구름에 가려요 | 100km 낮은 구름 + 0.5 × 중층 ≥ 60 | 쉬어요 |
|
||||
| 낮은 구름이 덮어요 | 20km 낮은 구름 ≥ 60 | 쉬어요 |
|
||||
| 구름이 적어 짧게 끝나요 | 물들 구름 < 25 | 애매해요 |
|
||||
| 구름이 두꺼워 색이 약해요 | 물들 구름 > 75 | 애매해요 |
|
||||
| 하늘이 넓게 물들 수 있어요 | 그 밖 (25~75) | 나가 볼 만해요 |
|
||||
|
||||
- 화면 결론(나가 볼 만해요·애매해요·쉬어요)은 **하늘 상황 기준**입니다. 상황이 없을 때만 점수로 정합니다(60↑ 나가 볼 만해요, 40↑ 애매해요).
|
||||
- 확신도: 모델별 점수의 표준편차가 8 미만이면 높음, 15 미만이면 보통, 그 이상이거나 모델이 1개면 낮음.
|
||||
- 노을 순위: 대표 30곳을 노을 점수순으로 정렬합니다. 70% 이상이 같은 상황이면 한 줄 요약을 붙입니다.
|
||||
|
||||
## 6. 노을 시각
|
||||
|
||||
| 시각 | 정의 |
|
||||
|---|---|
|
||||
| 골든아워 | 해 고도가 **6°**로 내려온 때부터 해 질 때까지. 햇빛이 낮게 비쳐 금빛으로 보이는 시간 |
|
||||
| 해 져요 | 일몰 |
|
||||
| 가장 붉을 때 | 일몰 + 10분 + (20km 상층 구름 % ÷ 10)분. 상층 구름이 많을수록 늦게까지 물듦 |
|
||||
| 블루아워 | 해가 진 뒤 해 고도 **−6°**(시민박명 끝)가 되는 때. 해는 졌지만 하늘이 푸르게 남는 시간 |
|
||||
|
||||
일출은 순서가 거꾸로입니다(블루아워 → 가장 붉을 때 → 해 떠요).
|
||||
|
||||
## 7. 달 밝기
|
||||
|
||||
- **밝기 = (1 − cos(2π × 삭에서 지난 비율)) ÷ 2**. 0이면 그믐(안 보임), 1이면 보름입니다. 삭 시각은 Meeus 계산(오차 2분 안)입니다.
|
||||
- 달 모양에서 **빛나는 면의 비율**일 뿐, 구름·달 고도·월출 시각은 반영하지 않습니다.
|
||||
|
||||
## 8. 불쾌지수
|
||||
|
||||
- **불쾌지수 = 0.81 × 기온 + 0.01 × 습도 × (0.99 × 기온 − 14.3) + 46.3**
|
||||
- 68 미만 쾌적 · 75 미만 보통 · 80 미만 불쾌 · 그 이상 매우 불쾌
|
||||
+1
-1
@@ -210,7 +210,7 @@ td .note{display:block;color:var(--muted);font-size:12px;margin-top:3px;line-hei
|
||||
<div><span class="n">1</span><p>히어로는 맨 위 고정. 히어로에는 날씨와 오늘 1위 각만 작게 두고, 1~3위 상세는 카드에서 보여 줍니다(확정).</p></div>
|
||||
<div><span class="n">2</span><p>같은 종류 카드는 붙이지 않습니다(확정). 각 3장 사이에는 다른 카드가 하나씩 끼어듭니다.</p></div>
|
||||
<div><span class="n">3</span><p>조건이 안 맞는 카드는 아예 빼고, 빈 카드나 "오늘은 없어요" 카드는 만들지 않습니다.<small>예외: 노을은 흐린 날에도 한 줄로 남깁니다(확정).</small></p></div>
|
||||
<div><span class="n">4</span><p>좋아요·댓글은 카드에 붙고, 전국 사용자가 같이 봅니다. 순서가 바뀌어도 같은 카드면 좋아요가 이어집니다.</p></div>
|
||||
<div><span class="n">4</span><p>좋아요·댓글은 카드에 붙습니다. 지역 데이터 카드는 같은 시도 사용자끼리, 계절 소식·날씨 상식·한 문장·달은 전국 사용자가 같이 봅니다. 순서가 바뀌어도 같은 카드면 좋아요가 이어집니다.</p></div>
|
||||
<div><span class="n">5</span><p>시간대가 바뀌는 순간(05·11시, 일몰 2시간 전·일몰 1시간 뒤)과 일몰 시각, 예보 갱신 때 피드가 새로 짜입니다.<small>앞에서 문제가 됐던 "새 칸이 늦게 보이는 문제"가 생기지 않습니다.</small></p></div>
|
||||
<div><span class="n">6</span><p>카드마다 보낼 문구가 있고, 보내면 카드 그대로 이미지+링크로 갑니다(확정).</p></div>
|
||||
<div><span class="n">7</span><p>UI는 따로 고민하지 않고 인스타그램·페이스북 방식을 그대로 따릅니다(확정, 10/2).</p></div>
|
||||
|
||||
+9
-6
@@ -1,13 +1,13 @@
|
||||
# 피드 동작 방식: 만들기 · 순서 · 갱신
|
||||
|
||||
기준: `backend/services/feed_service.py`, `backend/services/index_service.py`, `backend/scheduler/jobs.py`, `backend/router/v1/feed/feed.py` (2026-10-07)
|
||||
기준: `backend/services/feed_service.py`, `backend/services/index_service.py`, `backend/scheduler/jobs.py`, `backend/router/v1/feed/feed.py` (2026-10-08)
|
||||
|
||||
## 한 줄 요약
|
||||
|
||||
새벽 3시에 **전국 공통 틀(칸 19개)**을 DB에 만들고, 누가 피드를 열 때 **그 구의 데이터로 칸을 채워** Redis에 잠깐 둔다. 좋아요·댓글 수는 매번 DB에서 새로 읽어 덮어쓴다.
|
||||
새벽 3시에 **틀(칸 19개)**을 DB에 만들고(계절 소식·날씨 상식·한 문장·달은 전국 한 벌, 나머지는 시도마다 한 벌), 누가 피드를 열 때 **그 구의 데이터로 칸을 채워** Redis에 잠깐 둔다. 좋아요·댓글 수는 매번 DB에서 새로 읽어 덮어쓴다.
|
||||
|
||||
```
|
||||
[03:00 worker] ── 틀 19칸 → PostgreSQL post
|
||||
[03:00 worker] ── 틀 19칸(전국 칸 + 시도별 칸) → PostgreSQL post
|
||||
└─ Redis feed:* 전부 삭제
|
||||
|
||||
[사용자가 /v1/feed?region=구]
|
||||
@@ -18,11 +18,14 @@
|
||||
⑤ 좋아요·댓글 수, 내가 누른 표시를 DB에서 읽어 덮어쓴다 → 응답
|
||||
```
|
||||
|
||||
## 1. 틀 만들기 (하루 한 번, 전국 공통)
|
||||
## 1. 틀 만들기 (하루 한 번)
|
||||
|
||||
- **언제**: 매일 03:00 worker가 `build_feed_day`를 돌린다. 하루는 03:00에 시작해 다음 날 03:00에 끝난다.
|
||||
피드 요청이 올 때마다 같은 함수가 한 번 더 돈다. 이미 있는 칸은 그대로 두고, 빠진 칸(03:00 작업을 놓쳤거나 배포로 새 종류가 생긴 경우)만 더한다.
|
||||
- **어디에**: PostgreSQL `post` 테이블에 하루 19줄.
|
||||
- **어디에**: PostgreSQL `post` 테이블. 줄마다 `scope`가 있다 — `'00'`은 전국, 그 밖은 시도 코드(`region.code` 앞 2자리).
|
||||
계절 소식·날씨 상식·한 문장·달 칸은 전국 한 줄, 나머지 칸은 시도마다 한 줄(시도 16곳, 광주·전남이 같은 `12`). 하루 약 260줄.
|
||||
같은 날짜·칸·`scope`는 한 줄만(`uq_post_feed_scope`).
|
||||
- **피드에서 읽을 때**: 그 구의 시도 줄과 전국 줄을 같이 읽는다. 같은 칸에 둘 다 있으면 전국 줄을 쓴다(시도 나누기 전에 만든 날을 위해).
|
||||
- **한 줄에 들어가는 것**: 글 번호, 날짜, 칸 번호, 종류, 같은 종류 중 몇 번째인지, 유효 시간, 좋아요·댓글 수.
|
||||
계절 소식·날씨 상식 칸만 그날 보여줄 글 번호를 미리 정해 둔다(날짜마다 돌아가며).
|
||||
- **들어가지 않는 것**: 점수, 문장, 숫자 같은 내용. 내용은 구마다 다르므로 열 때 채운다.
|
||||
@@ -136,6 +139,6 @@
|
||||
|
||||
## 4. 알아 둘 점
|
||||
|
||||
- **좋아요·댓글은 전국이 같은 글에 쌓인다.** 글 번호가 전국 공통이라, 분당구의 "각 1위(환기각)"와 마포구의 "각 1위(야장각)"가 같은 글 번호를 쓴다.
|
||||
- **좋아요·댓글은 같은 시도끼리 같은 글에 쌓인다.** 지역 카드는 시도마다 글 번호가 따로라, 강남구와 마포구의 "각 1위"는 같은 글 번호(서울)를, 부산 구는 다른 글 번호를 쓴다. 계절 소식·날씨 상식·한 문장·달은 전국이 같은 글 번호.
|
||||
- **공유 링크(`/v1/feed/post/{id}`)는 지금 그 구의 피드에서 글을 찾는다.** 어제 글이나 지금 꺼진 글은 "없는 글"이 된다. 공유한 글을 다시 보여줄 계획이 생기면 그때 공유한 글만 따로 저장한다.
|
||||
- **아무도 안 여는 구는 만들지 않는다.** 외부 API 호출도 그 구를 누가 열 때만 일어난다.
|
||||
+26
-15
@@ -1,28 +1,43 @@
|
||||
<!doctype html>
|
||||
<html lang="ko">
|
||||
<head>
|
||||
<!-- Google Tag Manager -->
|
||||
<script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
|
||||
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
|
||||
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
|
||||
'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
|
||||
})(window,document,'script','dataLayer','GTM-PKQMKPFC');</script>
|
||||
<!-- End Google Tag Manager -->
|
||||
<!-- Google tag (gtag.js) -->
|
||||
<script async src="https://www.googletagmanager.com/gtag/js?id=G-D378J4X373"></script>
|
||||
<script>
|
||||
window.dataLayer = window.dataLayer || [];
|
||||
function gtag(){dataLayer.push(arguments);}
|
||||
gtag('js', new Date());
|
||||
|
||||
gtag('config', 'G-D378J4X373');
|
||||
</script>
|
||||
<meta charset="UTF-8" />
|
||||
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
|
||||
<link rel="apple-touch-icon" href="/apple-touch-icon.png" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1, user-scalable=no, viewport-fit=cover" />
|
||||
<meta name="description" content="오늘 날씨를 지수로. 노을, 야장각, 주말 계획까지 날씨각에서 확인하세요." />
|
||||
<title>날씨각</title>
|
||||
<meta name="theme-color" content="#d6ebff" />
|
||||
<meta name="description" content="세차각·빨래각·러닝각처럼 오늘 날씨에 맞는 일을 점수로. 노을이 예쁜 시간과 명소, 이번 주말 가까운 축제까지 날씨각에서 확인하세요." />
|
||||
<title>날씨각 · 오늘 날씨 지수, 노을, 주말 행사</title>
|
||||
<meta property="og:type" content="website" />
|
||||
<meta property="og:site_name" content="날씨각" />
|
||||
<meta property="og:title" content="날씨각" />
|
||||
<meta property="og:description" content="오늘 날씨를 지수로. 노을, 야장각, 주말 계획까지 날씨각에서 확인하세요." />
|
||||
<meta property="og:title" content="날씨각 · 오늘 날씨 지수, 노을, 주말 행사" />
|
||||
<meta property="og:description" content="세차각·빨래각·러닝각처럼 오늘 날씨에 맞는 일을 점수로. 노을이 예쁜 시간과 명소, 이번 주말 가까운 축제까지 날씨각에서 확인하세요." />
|
||||
<meta property="og:url" content="%VITE_SITE_URL%/" />
|
||||
<link rel="canonical" href="%VITE_SITE_URL%/" />
|
||||
<meta property="og:image" content="%VITE_SITE_URL%/og.png" />
|
||||
<meta property="og:image:width" content="1200" />
|
||||
<meta property="og:image:height" content="630" />
|
||||
<meta name="twitter:card" content="summary_large_image" />
|
||||
<meta property="og:locale" content="ko_KR" />
|
||||
<meta name="google-site-verification" content="ageFc5cYyqCTlRxsQTu4d3uetA4WG7y7yUPR1f7muVk" />
|
||||
<script type="application/ld+json">
|
||||
{
|
||||
"@context": "https://schema.org",
|
||||
"@type": "WebSite",
|
||||
"name": "날씨각",
|
||||
"url": "%VITE_SITE_URL%/",
|
||||
"inLanguage": "ko-KR"
|
||||
}
|
||||
</script>
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com" />
|
||||
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
|
||||
<link
|
||||
@@ -37,10 +52,6 @@
|
||||
/>
|
||||
</head>
|
||||
<body>
|
||||
<!-- Google Tag Manager (noscript) -->
|
||||
<noscript><iframe src="https://www.googletagmanager.com/ns.html?id=GTM-PKQMKPFC"
|
||||
height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
|
||||
<!-- End Google Tag Manager (noscript) -->
|
||||
<div id="root"></div>
|
||||
<script type="module" src="/src/main.tsx"></script>
|
||||
</body>
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 33 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 28 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 28 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 25 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 29 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 37 KiB |
@@ -0,0 +1,4 @@
|
||||
User-agent: *
|
||||
Allow: /
|
||||
|
||||
Sitemap: https://weather.o2o.kr/sitemap.xml
|
||||
@@ -0,0 +1,4 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
|
||||
<url><loc>https://weather.o2o.kr/</loc></url>
|
||||
</urlset>
|
||||
@@ -222,7 +222,7 @@ export const getWeekRankingOptions = (options?: Options<GetWeekRankingData>) =>
|
||||
export const listPlacesQueryKey = (options: Options<ListPlacesData>) => createQueryKey('listPlaces', options);
|
||||
|
||||
/**
|
||||
* 날씨 맞춤 데이트 명소
|
||||
* 날씨 맞춤 데이트 명소 (구 중심 30km 안, 없으면 가장 가까운 곳)
|
||||
*/
|
||||
export const listPlacesOptions = (options: Options<ListPlacesData>) => queryOptions<ListPlacesResponse, ListPlacesError, ListPlacesResponse, ReturnType<typeof listPlacesQueryKey>>({
|
||||
queryFn: async ({ queryKey, signal }) => {
|
||||
|
||||
@@ -69,7 +69,7 @@ export const getWeek = <ThrowOnError extends boolean = true>(options: Options<Ge
|
||||
export const getWeekRanking = <ThrowOnError extends boolean = true>(options?: Options<GetWeekRankingData, ThrowOnError>): RequestResult<GetWeekRankingResponses, unknown, ThrowOnError> => (options?.client ?? client).get<GetWeekRankingResponses, unknown, ThrowOnError>({ url: '/v1/week/ranking', ...options });
|
||||
|
||||
/**
|
||||
* 날씨 맞춤 데이트 명소
|
||||
* 날씨 맞춤 데이트 명소 (구 중심 30km 안, 없으면 가장 가까운 곳)
|
||||
*/
|
||||
export const listPlaces = <ThrowOnError extends boolean = true>(options: Options<ListPlacesData, ThrowOnError>): RequestResult<ListPlacesResponses, ListPlacesErrors, ThrowOnError> => (options.client ?? client).get<ListPlacesResponses, ListPlacesErrors, ThrowOnError>({ url: '/v1/week/place/list', ...options });
|
||||
|
||||
|
||||
@@ -110,6 +110,14 @@ export type ArticleSummary = {
|
||||
* Icon
|
||||
*/
|
||||
icon: string;
|
||||
/**
|
||||
* Image
|
||||
*/
|
||||
image?: string | null;
|
||||
/**
|
||||
* Image Credit
|
||||
*/
|
||||
image_credit?: string | null;
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -148,6 +156,14 @@ export type BandArticle = {
|
||||
* Icon
|
||||
*/
|
||||
icon: string;
|
||||
/**
|
||||
* Image
|
||||
*/
|
||||
image?: string | null;
|
||||
/**
|
||||
* Image Credit
|
||||
*/
|
||||
image_credit?: string | null;
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -792,6 +808,18 @@ export type PlaceData = {
|
||||
* Is Good
|
||||
*/
|
||||
is_good: boolean;
|
||||
/**
|
||||
* Distance Km
|
||||
*/
|
||||
distance_km: number;
|
||||
/**
|
||||
* Image
|
||||
*/
|
||||
image?: string | null;
|
||||
/**
|
||||
* Image Credit
|
||||
*/
|
||||
image_credit?: string | null;
|
||||
};
|
||||
|
||||
/**
|
||||
|
||||
@@ -30,7 +30,7 @@ function TopBar() {
|
||||
const tab = TABS.find((t) => t.to !== '/' && pathname.startsWith(t.to))
|
||||
|
||||
return (
|
||||
<header className="sticky top-0 z-20 flex h-[54px] items-center justify-between gap-2.5 px-4">
|
||||
<header className="sticky top-0 z-20 flex h-[calc(54px+env(safe-area-inset-top,0px))] items-center justify-between gap-2.5 px-4 pt-[env(safe-area-inset-top,0px)]">
|
||||
{tab?.title ? <h1 className="font-jua text-[22px] font-normal">{tab.title}</h1> : <h1 className="font-jua text-[25px] font-normal text-(--orange)">날씨각</h1>}
|
||||
<button
|
||||
type="button"
|
||||
@@ -143,17 +143,30 @@ function SkyProvider({ children }: { children: ReactNode }) {
|
||||
)
|
||||
}
|
||||
|
||||
// 노치 띠·상태바 색: 하늘 맨 위 색에 .b-topbg 를 겹친 색
|
||||
const NOTCH_BG: Record<TimeKind, string> = {
|
||||
morning: '#ffe6cf',
|
||||
day: '#d6ebff',
|
||||
sunset: '#ffd8c2',
|
||||
night: '#0e1433',
|
||||
}
|
||||
|
||||
function Shell() {
|
||||
const { pathname } = useLocation()
|
||||
const { kind } = useSky()
|
||||
useEffect(() => {
|
||||
window.scrollTo({ top: 0 })
|
||||
}, [pathname])
|
||||
useEffect(() => {
|
||||
document.querySelector('meta[name="theme-color"]')?.setAttribute('content', NOTCH_BG[kind])
|
||||
}, [kind])
|
||||
|
||||
return (
|
||||
<div className="min-h-dvh text-(--ink)">
|
||||
<SkyBg />
|
||||
{/* 위·아래 바: 띠는 화면 끝까지, 내용은 가운데 440px 안 */}
|
||||
<div className="b-topbg fixed inset-x-0 top-0 z-[19] h-[54px] backdrop-blur-md" aria-hidden="true" />
|
||||
<div className="b-topbg fixed inset-x-0 top-0 z-[19] h-[calc(54px+env(safe-area-inset-top,0px))] backdrop-blur-md" aria-hidden="true" />
|
||||
<div className="fixed inset-x-0 top-0 z-[19] h-[env(safe-area-inset-top,0px)] transition-colors duration-1400" style={{ backgroundColor: NOTCH_BG[kind] }} aria-hidden="true" />
|
||||
<div className="relative mx-auto min-h-dvh max-w-[440px] overflow-x-clip pb-[calc(70px+env(safe-area-inset-bottom,0px))]">
|
||||
<TopBar />
|
||||
<main className="relative z-[1]">
|
||||
|
||||
@@ -11,7 +11,7 @@ import { useAuth } from './authContext'
|
||||
import { useSheet } from './sheetContext'
|
||||
import { CommentIcon, HeartIcon, SendIcon } from './svg'
|
||||
import { useCarousel } from './carousel'
|
||||
import { Arrows, Credit, Ic, Rows, Skel, Thumb } from './ui'
|
||||
import { Arrows, Credit, Ic, Rows, Skel, TAP44, Thumb } from './ui'
|
||||
|
||||
const ACCOUNTS: Record<PostType, readonly [string, string]> = {
|
||||
[PostType.WEATHER]: ['오늘 날씨', 'sun'],
|
||||
@@ -423,13 +423,13 @@ function FullCard({ post }: PostProps) {
|
||||
)}
|
||||
</div>
|
||||
<div className="flex items-center gap-3.5 px-3 pt-2.5 pb-1 [&_svg]:size-[26px] [&_svg]:stroke-[1.9]">
|
||||
<button type="button" onClick={() => setLike(!liked)} aria-pressed={liked} aria-label="좋아요" className="grid size-7 cursor-pointer place-items-center">
|
||||
<button type="button" onClick={() => setLike(!liked)} aria-pressed={liked} aria-label="좋아요" className={cx('relative grid size-7 cursor-pointer place-items-center', TAP44)}>
|
||||
<HeartIcon className={liked ? 'fill-(--heart) stroke-(--heart)' : 'fill-none stroke-(--ink)'} />
|
||||
</button>
|
||||
<button type="button" onClick={comments} aria-label="댓글 보기" className="grid size-7 cursor-pointer place-items-center">
|
||||
<button type="button" onClick={comments} aria-label="댓글 보기" className={cx('relative grid size-7 cursor-pointer place-items-center', TAP44)}>
|
||||
<CommentIcon className="fill-none stroke-(--ink) [stroke-linejoin:round]" />
|
||||
</button>
|
||||
<button type="button" onClick={share} aria-label="보내기" className="grid size-7 cursor-pointer place-items-center">
|
||||
<button type="button" onClick={share} aria-label="보내기" className={cx('relative grid size-7 cursor-pointer place-items-center', TAP44)}>
|
||||
<SendIcon className="fill-none stroke-(--ink) [stroke-linecap:round] [stroke-linejoin:round]" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
@@ -5,7 +5,7 @@ import { ArticleCategory } from '../api/client/types.gen'
|
||||
import { cx } from '../lib/utils'
|
||||
import { ARTICLE_CAT, cardBg, dateRange, fall, loadOf, shortDay } from './lib'
|
||||
import { useSheet } from './sheetContext'
|
||||
import { Chips, Ic, Skel, StateBox } from './ui'
|
||||
import { Chips, Ic, Skel, StateBox, Thumb } from './ui'
|
||||
|
||||
const CATS = [
|
||||
['all', '전체'],
|
||||
@@ -126,9 +126,7 @@ export function SeasonPage() {
|
||||
<b className="mt-0.5 block font-jua text-[17.5px] leading-snug font-normal">{a.title}</b>
|
||||
<small className="mt-1 block text-xs font-semibold text-(--ink3)">{a.read_minutes}분 읽기</small>
|
||||
</span>
|
||||
<span className={cx('grid h-[84px] place-items-center rounded-[18px]', `b-bg-${cardBg(a.icon, a.article_id)}`)}>
|
||||
<Ic name={a.icon} className="w-[54px]" />
|
||||
</span>
|
||||
<Thumb image={a.image} icon={a.icon} credit={a.image_credit} className={cx('h-[84px] rounded-[18px]', `b-bg-${cardBg(a.icon, a.article_id)}`)} iconClassName="w-[54px]" creditClassName="right-1 bottom-1 max-w-[calc(100%-8px)] whitespace-normal!" />
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
+49
-19
@@ -29,16 +29,39 @@ import { useSky } from './skyContext'
|
||||
import { SHARE_SIZES, shareImage, type ShareSize } from './storyImage'
|
||||
import { SheetContext, useSheet, type SharePayload, type SheetState } from './sheetContext'
|
||||
import { HeartIcon } from './svg'
|
||||
import { Avatar, Ic, Skel, StateBox } from './ui'
|
||||
import { Avatar, Ic, Skel, StateBox, TAP44, Thumb } from './ui'
|
||||
|
||||
export function SheetProvider({ children }: { children: ReactNode }) {
|
||||
const [state, setState] = useState<SheetState>(null)
|
||||
const open = useCallback((s: Exclude<SheetState, null>) => setState(s), [])
|
||||
const close = useCallback(() => setState(null), [])
|
||||
// 창이 열려 있는 동안 방문 기록을 하나 쌓아 두어 뒤로 가기가 창만 닫게 한다
|
||||
const pushed = useRef(false)
|
||||
const open = useCallback((s: Exclude<SheetState, null>) => {
|
||||
if (!pushed.current) {
|
||||
window.history.pushState({ ...window.history.state, sheet: true }, '')
|
||||
pushed.current = true
|
||||
}
|
||||
setState(s)
|
||||
}, [])
|
||||
const close = useCallback(() => {
|
||||
setState(null)
|
||||
if (!pushed.current) return
|
||||
pushed.current = false
|
||||
window.history.back()
|
||||
}, [])
|
||||
const api = useMemo(() => ({ open, close }), [open, close])
|
||||
|
||||
useEffect(() => {
|
||||
const onPop = () => {
|
||||
if (!pushed.current) return
|
||||
pushed.current = false
|
||||
setState(null)
|
||||
}
|
||||
window.addEventListener('popstate', onPop)
|
||||
return () => window.removeEventListener('popstate', onPop)
|
||||
}, [])
|
||||
|
||||
// 로그인이 필요한 요청이 401을 받으면 로그인 창을 띄운다
|
||||
useEffect(() => subscribeAuth((reason) => reason === 'required' && setState({ type: 'login' })), [])
|
||||
useEffect(() => subscribeAuth((reason) => reason === 'required' && open({ type: 'login' })), [open])
|
||||
|
||||
return (
|
||||
<SheetContext value={api}>
|
||||
@@ -54,6 +77,7 @@ const TITLES = { article: '읽을거리', seasonWeek: '이번 주 특집', share
|
||||
function SheetHost({ state, onClose }: { state: SheetState; onClose: () => void }) {
|
||||
const ref = useRef<HTMLDialogElement>(null)
|
||||
const { kind } = useSky()
|
||||
const { open } = useSheet()
|
||||
const [gakTitle, setGakTitle] = useState('')
|
||||
const [articleTitle, setArticleTitle] = useState('')
|
||||
|
||||
@@ -76,6 +100,7 @@ function SheetHost({ state, onClose }: { state: SheetState; onClose: () => void
|
||||
}
|
||||
}, [isOpen])
|
||||
|
||||
const then = state?.type === 'login' ? state.then : undefined
|
||||
const title = !state ? '' : state.type === 'gak' ? gakTitle : state.type === 'article' ? articleTitle || TITLES.article : TITLES[state.type]
|
||||
|
||||
return (
|
||||
@@ -90,11 +115,11 @@ function SheetHost({ state, onClose }: { state: SheetState; onClose: () => void
|
||||
className="b-sheet-dialog b-app fixed inset-x-0 top-auto bottom-0 m-0 mx-auto max-h-[86dvh] w-full max-w-[440px] overflow-visible bg-transparent p-0 text-(--ink)"
|
||||
>
|
||||
{state && (
|
||||
<div className="b-sheet flex max-h-[86dvh] flex-col rounded-t-[22px] bg-white">
|
||||
<div className="b-sheet flex max-h-[86dvh] flex-col rounded-t-[22px] bg-white pb-[env(safe-area-inset-bottom,0px)]">
|
||||
<div className="relative border-b border-(--line) px-4 pt-2 pb-2.5 text-center">
|
||||
<div className="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)">
|
||||
<button type="button" onClick={onClose} aria-label="닫기" className={cx('absolute right-3 bottom-2 grid size-[30px] cursor-pointer place-items-center text-xl text-(--ink2)', TAP44)}>
|
||||
×
|
||||
</button>
|
||||
</div>
|
||||
@@ -102,8 +127,8 @@ function SheetHost({ state, onClose }: { state: SheetState; onClose: () => void
|
||||
{state.type === 'article' && <ArticleSheet articleId={state.articleId} onTitle={setArticleTitle} />}
|
||||
{state.type === 'seasonWeek' && <SeasonWeekSheet />}
|
||||
{state.type === 'share' && <ShareSheet share={state.share} />}
|
||||
{state.type === 'comments' && <CommentsSheet postId={state.postId} />}
|
||||
{state.type === 'login' && <LoginSheet onDone={onClose} />}
|
||||
{state.type === 'comments' && <CommentsSheet postId={state.postId} draft={state.draft} />}
|
||||
{state.type === 'login' && <LoginSheet onDone={onClose} onLoggedIn={then ? () => open(then) : onClose} />}
|
||||
{state.type === 'me' && <MeSheet onDone={onClose} />}
|
||||
{state.type === 'region' && <RegionSheet onDone={onClose} />}
|
||||
</div>
|
||||
@@ -413,9 +438,7 @@ function ArticleSheet({ articleId, onTitle }: { articleId: number; onTitle: (t:
|
||||
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)}`)}>
|
||||
<Ic name={a.icon} className="w-24" />
|
||||
</div>
|
||||
<Thumb image={a.image} icon={a.icon} credit={a.image_credit} className={cx('mb-3.5 h-[150px] rounded-[20px]', `b-bg-${cardBg(a.icon, a.article_id)}`)} iconClassName="w-24" />
|
||||
<p className="text-[13px] font-extrabold text-(--ink2)">{articleMeta(a)}</p>
|
||||
<h4 className="mt-1.5 mb-2.5 font-jua text-2xl leading-tight font-normal">{a.title}</h4>
|
||||
{(q.data?.body ?? []).map((t) => (
|
||||
@@ -654,14 +677,14 @@ function CommentRow({ c, postId }: { c: CommentData; postId: number }) {
|
||||
)}
|
||||
</small>
|
||||
</div>
|
||||
<button type="button" onClick={toggle} aria-pressed={liked} aria-label="댓글 좋아요" className="cursor-pointer pt-1">
|
||||
<button type="button" onClick={toggle} aria-pressed={liked} aria-label="댓글 좋아요" className={cx('relative cursor-pointer pt-1', TAP44)}>
|
||||
<HeartIcon className={cx('size-4 stroke-2', liked ? 'fill-(--heart) stroke-(--heart)' : 'fill-none stroke-(--ink3)')} />
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function CommentsSheet({ postId }: { postId: number }) {
|
||||
function CommentsSheet({ postId, draft }: { postId: number; draft?: string }) {
|
||||
const { region } = useRegion()
|
||||
const { open } = useSheet()
|
||||
const { loggedIn, me } = useAuth()
|
||||
@@ -673,13 +696,13 @@ function CommentsSheet({ postId }: { postId: number }) {
|
||||
})
|
||||
const add = useMutation(addCommentMutation())
|
||||
const [addFailed, setAddFailed] = useState(false)
|
||||
const [text, setText] = useState('')
|
||||
const [text, setText] = useState(draft ?? '')
|
||||
const inputRef = useRef<HTMLInputElement>(null)
|
||||
const comments = list.data?.pages.flatMap((p) => p.comments ?? []) ?? []
|
||||
|
||||
const submit = (e: FormEvent) => {
|
||||
e.preventDefault()
|
||||
if (!loggedIn) return open({ type: 'login' })
|
||||
if (!loggedIn) return open({ type: 'login', then: { type: 'comments', postId, draft: text } })
|
||||
const body = text.trim()
|
||||
if (!body || add.isPending) return
|
||||
setAddFailed(false)
|
||||
@@ -736,7 +759,7 @@ function CommentsSheet({ postId }: { postId: number }) {
|
||||
<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))]">
|
||||
<form onSubmit={submit} className="flex items-center gap-2.5 border-t border-(--line) px-3 pt-2.5 pb-2.5">
|
||||
<input ref={inputRef} value={text} onChange={(e) => setText(e.target.value)} readOnly={add.isPending} maxLength={60} placeholder={me ? `${me.nickname}(으)로 댓글 달기…` : '댓글 달기…'} aria-label="댓글" className="min-w-0 flex-1 rounded-full border border-[#dfe5ee] bg-[#f7f9fc] px-3.5 py-2.5" />
|
||||
<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} />
|
||||
@@ -753,7 +776,7 @@ const AUTH_ERRORS: Record<string, string> = {
|
||||
INVALID_INPUT: '아이디는 영어 소문자·숫자·_ 4~20자, 비밀번호는 8~64자, 닉네임은 2~12자로 써 주세요.',
|
||||
}
|
||||
|
||||
function LoginSheet({ onDone }: { onDone: () => void }) {
|
||||
function LoginSheet({ onDone, onLoggedIn }: { onDone: () => void; onLoggedIn: () => void }) {
|
||||
const { me } = useAuth()
|
||||
const [mode, setMode] = useState<'login' | 'signup'>('login')
|
||||
const [loginId, setLoginId] = useState('')
|
||||
@@ -771,7 +794,7 @@ function LoginSheet({ onDone }: { onDone: () => void }) {
|
||||
}
|
||||
setTokens(res.access_token, res.refresh_token ?? null)
|
||||
track(mode === 'login' ? 'login' : 'sign_up', { method: 'id' })
|
||||
onDone()
|
||||
onLoggedIn()
|
||||
}
|
||||
const fail = () => setError('서버에 닿지 못했어요. 잠시 뒤에 다시 해 주세요.')
|
||||
|
||||
@@ -948,6 +971,13 @@ function RegionSheet({ onDone }: { onDone: () => void }) {
|
||||
const { region, setRegion, locate, locateStatus } = useRegion()
|
||||
const { me, logout } = useAuth()
|
||||
const { open } = useSheet()
|
||||
const alive = useRef(true)
|
||||
useEffect(() => {
|
||||
alive.current = true
|
||||
return () => {
|
||||
alive.current = false
|
||||
}
|
||||
}, [])
|
||||
const [q, setQ] = useState('')
|
||||
const deferred = useDeferredValue(q.trim())
|
||||
const list = useQuery(listRegionsOptions(deferred ? { query: { q: deferred } } : undefined))
|
||||
@@ -956,7 +986,7 @@ function RegionSheet({ onDone }: { onDone: () => void }) {
|
||||
|
||||
return (
|
||||
<Body>
|
||||
<button type="button" onClick={locate} disabled={locateStatus === 'locating'} className="w-full cursor-pointer rounded-full bg-(--orange) p-3 font-jua text-[17px] text-white shadow-[inset_0_-5px_0_var(--orange-deep)] disabled:opacity-60">
|
||||
<button type="button" onClick={() => locate(() => alive.current && onDone())} disabled={locateStatus === 'locating'} className="w-full cursor-pointer rounded-full bg-(--orange) p-3 font-jua text-[17px] text-white shadow-[inset_0_-5px_0_var(--orange-deep)] disabled:opacity-60">
|
||||
지금 위치로 찾기
|
||||
</button>
|
||||
<p className="mt-2 min-h-5 text-center text-[13px] font-bold text-(--ink2)" aria-live="polite">
|
||||
|
||||
@@ -73,6 +73,22 @@ function Timeline({ rows }: { rows?: BestTime[] }) {
|
||||
</li>
|
||||
))}
|
||||
</ol>
|
||||
{rows && (
|
||||
<dl className="mx-2 mt-3 flex flex-col gap-1 border-t-[1.5px] border-(--line) pt-2.5 text-[12px] leading-snug text-(--ink2)">
|
||||
{rows.some((t) => t.kind === 'golden') && (
|
||||
<div>
|
||||
<dt className="inline font-extrabold text-(--ink)">골든아워</dt>
|
||||
<dd className="ml-1.5 inline">해가 낮게 떠 햇빛이 금빛으로 물드는 시간, 해 지기 전 약 30분~1시간</dd>
|
||||
</div>
|
||||
)}
|
||||
{rows.some((t) => t.kind === 'blue') && (
|
||||
<div>
|
||||
<dt className="inline font-extrabold text-(--ink)">블루아워</dt>
|
||||
<dd className="ml-1.5 inline">해가 진 뒤 하늘이 짙은 푸른빛으로 남는 시간, 적힌 시각쯤 어두워져요</dd>
|
||||
</div>
|
||||
)}
|
||||
</dl>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -284,9 +284,7 @@ function SeasonBand({ news }: { news: BandArticle[] }) {
|
||||
<Rail>
|
||||
{news.map((a) => (
|
||||
<button key={a.article_id} type="button" onClick={() => open({ type: 'article', articleId: a.article_id })} className="w-[200px] cursor-pointer overflow-hidden rounded-[22px] bg-white text-left shadow-[inset_0_-5px_0_var(--shade),0_8px_16px_rgb(40_48_74/0.06)]">
|
||||
<span className={cx('grid h-[116px] place-items-center', `b-bg-${cardBg(a.icon, a.article_id)}`)}>
|
||||
<Ic name={a.icon} className="w-[76px]" />
|
||||
</span>
|
||||
<Thumb image={a.image} icon={a.icon} credit={a.image_credit} className={cx('h-[116px]', `b-bg-${cardBg(a.icon, a.article_id)}`)} iconClassName="w-[76px]" />
|
||||
<span className="block px-3 pt-2.5 pb-3">
|
||||
<b className="block font-jua text-[16.5px] leading-snug font-normal">{a.title}</b>
|
||||
<small className="text-[12.5px] font-semibold text-(--ink2)">{a.meta}</small>
|
||||
|
||||
@@ -2,7 +2,7 @@ import { useRef, useState, type ReactNode } from 'react'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { getWeekOptions, getWeekRankingOptions, listEventsOptions, listPlacesOptions } from '../api/client/@tanstack/react-query.gen'
|
||||
import { cx } from '../lib/utils'
|
||||
import { cardBg, dateRange, loadOf, shortDay, sidoOf } from './lib'
|
||||
import { cardBg, dateRange, loadOf, shortDay } from './lib'
|
||||
import { useRegion } from './regionContext'
|
||||
import { useSheet } from './sheetContext'
|
||||
import { Arrows, Chips, Ic, MapLink, Rail, Sec, Skel, SkelRail, StateBox, Thumb } from './ui'
|
||||
@@ -155,7 +155,6 @@ export function WeekPage() {
|
||||
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 ?? []
|
||||
@@ -227,7 +226,7 @@ export function WeekPage() {
|
||||
{(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} · 데이트 명소
|
||||
30km 안 · 데이트 명소
|
||||
</label>
|
||||
<select id="b-area" value={area} onChange={(e) => setAreaPick({ region: region.code, area: e.target.value })} disabled={!areas.length} className="rounded-full bg-white px-3 py-[7px] font-bold text-(--ink) shadow-[inset_0_-3px_0_var(--shade)] disabled:opacity-60">
|
||||
{['전체', ...areas].map((a) => (
|
||||
@@ -236,7 +235,7 @@ export function WeekPage() {
|
||||
</select>
|
||||
</div>
|
||||
)}
|
||||
{/* 명소 데이터가 없는 지역은 칸 전체를 숨긴다 (지금은 서울만 있음) */}
|
||||
{/* 명소 데이터가 없으면 칸 전체를 숨긴다 */}
|
||||
{!(placeLoad === 'ready' && !placeList.length) && (
|
||||
<>
|
||||
<Sec title="날씨 맞춤 데이트 명소" sub={sel ? `${sel.weekday}요일은 ${rainy ? '비가 와서 실내 명소를 먼저' : sel.icon === 'sun' ? '맑아서 야외 명소를 먼저' : '비 소식이 없어 야외 명소를 먼저'} 보여 줘요` : weekLoad === 'loading' ? <Skel className="w-56" /> : '날씨에 맞춰 골라 보여 줘요'} className="pt-3" />
|
||||
@@ -244,13 +243,12 @@ export function WeekPage() {
|
||||
<Rail className={cx('transition-opacity', places.isPlaceholderData && 'opacity-60')}>
|
||||
{placeList.map((p, i) => (
|
||||
<div key={p.place_id} className={PLACE_CARD}>
|
||||
<span className={cx('relative grid h-[104px] place-items-center', `b-bg-${PLACE_BG[p.icon] ?? (p.is_outdoor ? 'mint' : cardBg(p.icon, i))}`)}>
|
||||
<Thumb image={p.image} icon={p.icon} credit={p.image_credit} className={cx('h-[104px]', `b-bg-${PLACE_BG[p.icon] ?? (p.is_outdoor ? 'mint' : cardBg(p.icon, i))}`)} iconClassName="w-[62px]">
|
||||
{p.is_good && <span className={cx('absolute top-2.5 left-2.5 rounded-full px-2 py-[3px] text-[11.5px] font-extrabold text-white', p.is_outdoor ? 'bg-[#1f9d62]' : 'bg-(--rain)')}>{p.is_outdoor ? '오늘 딱' : '비 와도 OK'}</span>}
|
||||
<Ic name={p.icon} className="w-[62px]" />
|
||||
</span>
|
||||
</Thumb>
|
||||
<span className="block px-3 pt-2.5 pb-3">
|
||||
<span className="text-[11.5px] font-extrabold text-(--ink3)">
|
||||
{p.area} · {p.is_outdoor ? '야외' : '실내'}
|
||||
{p.area} · {p.distance_km}km · {p.is_outdoor ? '야외' : '실내'}
|
||||
</span>
|
||||
<b className="block font-jua text-[16.5px] font-normal">
|
||||
<MapLink place={p.name}>{p.name}</MapLink>
|
||||
@@ -267,7 +265,7 @@ export function WeekPage() {
|
||||
) : placeLoad === 'loading' ? (
|
||||
<PlacesSkel />
|
||||
) : (
|
||||
<StateBox load={placeLoad} onRetry={() => places.refetch()} empty={sel ? `${sido} 데이트 명소는 아직 준비 중이에요.` : '날씨를 불러오면 명소를 골라 드려요.'} hold={<PlacesSkel />} className="inset-x-3 top-3 bottom-1" />
|
||||
<StateBox load={placeLoad} onRetry={() => places.refetch()} empty={sel ? '30km 안에 데이트 명소가 아직 없어요.' : '날씨를 불러오면 명소를 골라 드려요.'} hold={<PlacesSkel />} className="inset-x-3 top-3 bottom-1" />
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
@@ -275,7 +273,7 @@ export function WeekPage() {
|
||||
{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={() => {}} />
|
||||
<Chips label="순위 볼 날" items={RANK_TABS_HOLD} value="토" onChange={() => {}} disabled />
|
||||
)}
|
||||
{rankItems.length ? (
|
||||
<ul className={cx('mx-3 mt-1.5 flex flex-col transition-opacity', ranking.isPlaceholderData && 'opacity-60')}>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import type { CSSProperties } from 'react'
|
||||
|
||||
const SHARED = new Set(['bear', 'bike', 'bronze', 'camping', 'carwash', 'chimaek', 'cloud', 'coldwind', 'delivery', 'dog', 'garden', 'glasses', 'gold', 'hiking', 'iced_hot', 'jjamppong', 'laundry', 'letter', 'makeup', 'makgeolli', 'maple', 'moon', 'muggy', 'naengmyeon', 'photo', 'picnic', 'rabbit', 'rain', 'running', 'silver', 'snow', 'stars', 'sun_cloud', 'sun', 'sunset', 'taxi', 'umbrella', 'vent', 'walk', 'yajang', 'baseball', 'study', 'netflix', 'chestnut', 'peanut', 'tangerine', 'sweet_potato', 'fallen_leaf', 'kimchi', 'apple', 'mask'])
|
||||
const SHARED = new Set(['bear', 'bike', 'bronze', 'camping', 'carwash', 'chimaek', 'cloud', 'coldwind', 'delivery', 'dog', 'garden', 'glasses', 'gold', 'hiking', 'iced_hot', 'jjamppong', 'laundry', 'letter', 'makeup', 'makgeolli', 'maple', 'moon', 'muggy', 'naengmyeon', 'photo', 'picnic', 'rabbit', 'rain', 'running', 'silver', 'snow', 'stars', 'sun_cloud', 'sun', 'sunset', 'taxi', 'umbrella', 'vent', 'walk', 'yajang', 'baseball', 'study', 'netflix', 'chestnut', 'peanut', 'tangerine', 'sweet_potato', 'fallen_leaf', 'kimchi', 'apple', 'mask', 'golf', 'jipkok', 'fishing', 'drive', 'kite', 'waterplay'])
|
||||
const OWN = new Set(['fireworks', 'bulb', 'calendar', 'thermo', 'sheaf', 'popup', 'exhibition', 'concert'])
|
||||
|
||||
/** 아이콘 이름 → 파일 경로 (공용 public/icons, B 전용 public/b/icons). 'none'(데이터 없는 칸)은 그림 없음 */
|
||||
|
||||
@@ -36,7 +36,7 @@ export function RegionProvider({ children }: { children: ReactNode }) {
|
||||
writeStored(r)
|
||||
}, [])
|
||||
|
||||
const findNearest = useCallback(() => {
|
||||
const findNearest = useCallback((onFound?: () => void) => {
|
||||
navigator.geolocation.getCurrentPosition(
|
||||
(pos) => {
|
||||
nearestRegion({ query: { lat: pos.coords.latitude, lon: pos.coords.longitude } })
|
||||
@@ -45,6 +45,7 @@ export function RegionProvider({ children }: { children: ReactNode }) {
|
||||
setRegion(res.region)
|
||||
setLocateStatus('idle')
|
||||
track('region_change', { region_name: res.region.name, method: 'location' })
|
||||
onFound?.()
|
||||
})
|
||||
.catch(() => setLocateStatus('error'))
|
||||
},
|
||||
@@ -53,13 +54,13 @@ export function RegionProvider({ children }: { children: ReactNode }) {
|
||||
)
|
||||
}, [setRegion])
|
||||
|
||||
const locate = useCallback(() => {
|
||||
const locate = useCallback((onFound?: () => void) => {
|
||||
if (!canLocate) {
|
||||
setLocateStatus('error')
|
||||
return
|
||||
}
|
||||
setLocateStatus('locating')
|
||||
findNearest()
|
||||
findNearest(onFound)
|
||||
}, [canLocate, findNearest])
|
||||
|
||||
// 처음 온 사람만 위치 권한을 물어 가장 가까운 구로 맞춘다
|
||||
|
||||
@@ -3,7 +3,7 @@ import type { RegionData } from '../api/client/types.gen'
|
||||
|
||||
export type LocateStatus = 'idle' | 'locating' | 'denied' | 'error'
|
||||
|
||||
export type RegionApi = { region: RegionData; setRegion: (r: RegionData) => void; locate: () => void; locateStatus: LocateStatus }
|
||||
export type RegionApi = { region: RegionData; setRegion: (r: RegionData) => void; locate: (onFound?: () => void) => void; locateStatus: LocateStatus }
|
||||
|
||||
export const DEFAULT_REGION: RegionData = { code: '1144000000', name: '서울 마포구', short_name: '마포구', lat: 37.56071, lon: 126.91053 }
|
||||
|
||||
|
||||
@@ -1,13 +1,15 @@
|
||||
import { createContext, use } from 'react'
|
||||
export type SharePayload = { title: string; slides: HTMLElement[] }
|
||||
|
||||
type CommentsState = { type: 'comments'; postId: number; draft?: string }
|
||||
|
||||
export type SheetState =
|
||||
| { type: 'gak'; indexId: number }
|
||||
| { type: 'article'; articleId: number }
|
||||
| { type: 'share'; share: SharePayload }
|
||||
| { type: 'comments'; postId: number }
|
||||
| CommentsState
|
||||
| { type: 'seasonWeek' }
|
||||
| { type: 'login' }
|
||||
| { type: 'login'; then?: CommentsState }
|
||||
| { type: 'me' }
|
||||
| { type: 'region' }
|
||||
| null
|
||||
|
||||
+11
-7
@@ -17,16 +17,16 @@ export function Credit({ text, className = 'right-1 bottom-1' }: { text: string;
|
||||
return <small className={cx('pointer-events-none absolute z-[1] rounded-[5px] bg-[rgb(16_20_34/0.5)] px-1 py-px text-[9px] leading-tight font-semibold whitespace-nowrap text-white', className)}>{text}</small>
|
||||
}
|
||||
|
||||
type ThumbProps = { image?: string | null; icon: string; credit?: string | null; className?: string; iconClassName?: string; children?: ReactNode }
|
||||
type ThumbProps = { image?: string | null; icon: string; credit?: string | null; className?: string; iconClassName?: string; creditClassName?: string; children?: ReactNode }
|
||||
|
||||
/** 사진이 있으면 사진(+출처), 없거나 못 불러오면 아이콘 */
|
||||
export function Thumb({ image, icon, credit, className, iconClassName, children }: ThumbProps) {
|
||||
export function Thumb({ image, icon, credit, className, iconClassName, creditClassName, children }: ThumbProps) {
|
||||
const [failed, setFailed] = useState<string | null>(null)
|
||||
const photo = image && image !== failed ? image : null
|
||||
return (
|
||||
<span className={cx('relative grid place-items-center overflow-hidden', className)}>
|
||||
{photo ? <img src={photo} alt="" loading="lazy" decoding="async" onError={() => setFailed(photo)} className="absolute inset-0 size-full object-cover" /> : <Ic name={icon} className={iconClassName} />}
|
||||
{photo && credit && <Credit text={credit} />}
|
||||
{photo && credit && <Credit text={credit} className={creditClassName} />}
|
||||
{children}
|
||||
</span>
|
||||
)
|
||||
@@ -69,7 +69,7 @@ export function Sec({ title, sub, more, className }: SecProps) {
|
||||
|
||||
/** PC(마우스)에서만 보이는 좌우 화살표 */
|
||||
export function Arrows({ api, prev, next, className }: { api: Carousel; prev: boolean; next: boolean; className?: string }) {
|
||||
const btn = 'absolute top-1/2 z-[3] hidden size-8 -translate-y-1/2 cursor-pointer place-items-center rounded-full bg-white/90 text-lg font-extrabold text-[#28304a] shadow-[0_4px_10px_rgb(40_48_74/0.18)] pointer-fine:grid'
|
||||
const btn = 'absolute top-1/2 z-[3] grid size-8 -translate-y-1/2 cursor-pointer place-items-center rounded-full bg-white/90 text-lg font-extrabold text-[#28304a] shadow-[0_4px_10px_rgb(40_48_74/0.18)]'
|
||||
return (
|
||||
<>
|
||||
{prev && (
|
||||
@@ -109,9 +109,12 @@ export function Rail({ children, className, label }: { children: ReactNode; clas
|
||||
)
|
||||
}
|
||||
|
||||
type ChipsProps<K extends string> = { items: readonly (readonly [K, string])[]; value: K; onChange: (k: K) => void; label: string }
|
||||
// 보이는 크기는 두고 누르는 영역만 가운데 44×44로 넓힌다 (위치 지정된 요소에 붙인다)
|
||||
export const TAP44 = 'after:absolute after:top-1/2 after:left-1/2 after:size-11 after:-translate-1/2'
|
||||
|
||||
export function Chips<K extends string>({ items, value, onChange, label }: ChipsProps<K>) {
|
||||
type ChipsProps<K extends string> = { items: readonly (readonly [K, string])[]; value: K; onChange: (k: K) => void; label: string; disabled?: boolean }
|
||||
|
||||
export function Chips<K extends string>({ items, value, onChange, label, disabled }: ChipsProps<K>) {
|
||||
return (
|
||||
<ChipStrip label={label}>
|
||||
{items.map(([k, l]) => (
|
||||
@@ -119,8 +122,9 @@ export function Chips<K extends string>({ items, value, onChange, label }: Chips
|
||||
key={k}
|
||||
type="button"
|
||||
aria-pressed={value === k}
|
||||
disabled={disabled}
|
||||
onClick={() => onChange(k)}
|
||||
className={cx('shrink-0 cursor-pointer rounded-full px-3.5 py-[7px] text-[13.5px] font-bold', value === k ? 'bg-(--ink) text-white' : 'bg-white text-(--ink2) shadow-[inset_0_-3px_0_var(--shade)]')}
|
||||
className={cx('shrink-0 cursor-pointer rounded-full disabled:cursor-default px-3.5 py-[7px] text-[13.5px] font-bold', value === k ? 'bg-(--ink) text-white' : 'bg-white text-(--ink2) shadow-[inset_0_-3px_0_var(--shade)]')}
|
||||
>
|
||||
{l}
|
||||
</button>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
/** GTM으로 보내는 이벤트와 값. 목록과 GTM 설정은 docs/이벤트_추적.md */
|
||||
/** GA4로 보내는 이벤트와 값. 목록은 docs/이벤트_추적.md */
|
||||
type Events = {
|
||||
view_gak: { index_id: number; gak_name: string; score: number; rank: number }
|
||||
select_content: { content_type: 'article'; item_id: number; category: string }
|
||||
@@ -10,12 +10,11 @@ type Events = {
|
||||
|
||||
declare global {
|
||||
interface Window {
|
||||
dataLayer?: Record<string, unknown>[]
|
||||
gtag?: (command: 'event', name: string, params: Record<string, unknown>) => void
|
||||
}
|
||||
}
|
||||
|
||||
export function track<E extends keyof Events>(event: E, params: Events[E]) {
|
||||
if (import.meta.env.DEV) return
|
||||
window.dataLayer ??= []
|
||||
window.dataLayer.push({ event, ...params })
|
||||
window.gtag?.('event', event, params)
|
||||
}
|
||||
Reference in new issue
Block a user