chore: feat/date-place-nationwide 병합
This commit is contained in:
commit
64bdbcae39
16 files changed
+2659
-47
No files matched your search
@@ -74,7 +74,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`) |
|
||||
|
||||
@@ -227,6 +227,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):
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -303,18 +303,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 (
|
||||
|
||||
@@ -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
|
||||
])
|
||||
|
||||
@@ -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()))
|
||||
@@ -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 = [
|
||||
|
||||
+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
@@ -1,4 +1,5 @@
|
||||
import asyncio
|
||||
import math
|
||||
from dataclasses import dataclass
|
||||
from datetime import date, timedelta
|
||||
from typing import Optional
|
||||
@@ -36,6 +37,10 @@ MAX_EVENT_DAYS = 60
|
||||
EVENT_RADIUS_KM = 30
|
||||
# 행사는 시도 단위로 받는다. 구 중심이 이 거리 안에 있는 시도는 경계가 반경에 걸칠 수 있어 같이 받는다.
|
||||
_SIDO_REACH_KM = EVENT_RADIUS_KM + 20
|
||||
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 +67,7 @@ class DayPlan:
|
||||
class PlaceItem:
|
||||
place: Place
|
||||
is_good: bool
|
||||
distance_km: float
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -137,6 +143,22 @@ def is_nearby(region: Region, e: Event, distance_km: Optional[float]) -> bool:
|
||||
return e.sido_code == region.code[:2]
|
||||
|
||||
|
||||
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]:
|
||||
if e.start_date <= today <= e.end_date:
|
||||
return "live", "진행 중"
|
||||
@@ -229,19 +251,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)
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -179,6 +179,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
|
||||
|
||||
@@ -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 });
|
||||
|
||||
|
||||
@@ -808,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;
|
||||
};
|
||||
|
||||
/**
|
||||
|
||||
@@ -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" />
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
|
||||
Reference in new issue
Block a user