Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3b43446fe6 | ||
|
|
01824a7a91 |
No files matched your search
+8
-29
@@ -1,20 +1,10 @@
|
||||
# cp .env.example .env 후 값을 채운다. .env 는 커밋되지 않는다.
|
||||
# 우선순위: 실제 환경변수(compose) > .env > 코드 기본값(config_models.py)
|
||||
#
|
||||
# ★ 값 뒤에 주석을 붙이지 않는다. compose 의 `env_file` 은 줄 끝 주석을 **값으로 읽는다** —
|
||||
# `AZURE_STORAGE_CONNECTION_STRING= # 비우면...` 은 "빈 값"이 아니라 "# 비우면..." 이라는 값이다.
|
||||
# 실측(2026-09-07): 그래서 Azure 를 끈 로컬에서 발행 잡이 업로드를 시도하고
|
||||
# "Connection string is either blank or malformed" 로 죽었다. 게이트는 통과했는데 발행만 실패한다.
|
||||
# 주석은 반드시 **윗줄**에 둔다.
|
||||
|
||||
# ── 공통 solution/backend · admin/backend (server_configs 가 읽는다)
|
||||
APP_ENV=local
|
||||
|
||||
# ★ compose 로 띄우면 `host.docker.internal` 이다 — 컨테이너 안의 127.0.0.1 은 그 컨테이너다.
|
||||
# 127.0.0.1 은 백엔드를 **네이티브로**(.venv/bin/python) 돌릴 때만 맞다.
|
||||
# 이 값을 그대로 두고 `docker compose up` 하면 API 는 healthz 200 으로 멀쩡해 보이는데
|
||||
# 워커만 조용히 재시작을 반복한다(ConnectionRefusedError 5432) — 발행 잡이 영원히 안 돈다.
|
||||
DB_HOST=host.docker.internal
|
||||
DB_HOST=127.0.0.1
|
||||
DB_PORT=5432
|
||||
DB_USER=postgres
|
||||
DB_PASSWORD=
|
||||
@@ -27,15 +17,12 @@ JWT_REFRESH_SECRET=
|
||||
|
||||
# 키가 비면 그 어댑터만 꺼진다. 서버는 뜬다.
|
||||
PERPLEXITY_API_KEY=
|
||||
# Perplexity 채널 발견. 0=끔(기본)
|
||||
COLLECT_USE_PERPLEXITY=0
|
||||
COLLECT_USE_PERPLEXITY=0 # Perplexity 채널 발견. 0=끔(기본)
|
||||
NAVER_CLIENT_ID=
|
||||
NAVER_CLIENT_SECRET=
|
||||
# 미발급. 없으면 네이버 지역검색을 쓴다
|
||||
KAKAO_REST_API_KEY=
|
||||
KAKAO_REST_API_KEY= # 미발급. 없으면 네이버 지역검색을 쓴다
|
||||
GEMINI_API_KEY=
|
||||
# 디코딩된 키(인코딩 키는 이중 인코딩된다)
|
||||
TOUR_API_KEY=
|
||||
TOUR_API_KEY= # 디코딩된 키(인코딩 키는 이중 인코딩된다)
|
||||
|
||||
# 구글 로그인. 비우면 구글 로그인만 꺼진다(서버는 뜨고, 화면에 버튼도 안 뜬다).
|
||||
# Google Cloud Console > API 및 서비스 > 사용자 인증 정보 > OAuth 2.0 클라이언트 ID(웹 애플리케이션)
|
||||
@@ -52,23 +39,15 @@ GOOGLE_CLIENT_ID=
|
||||
|
||||
# ── solution/frontend 브라우저가 부르는 주소 (compose 가 VITE_* 로 주입)
|
||||
# ★ 브라우저가 부르는 주소다. 서버에 올리면 localhost 는 즉시 틀린다.
|
||||
# ★ **앱과 같은 오리진을 적는다.** nginx(:80)가 /v1 을 같은 오리진으로 프록시하므로
|
||||
# (nginx/site.conf) 앱이 부를 주소는 `:9800` 이 아니라 앱 주소 그 자체다. `:9800` 을 적으면
|
||||
# 스스로 크로스 오리진을 만들어 CORS 가 붙고, 화면은 뜨는데 **로그인만 계속 실패한다** —
|
||||
# 서버는 200 에 토큰까지 내려보내고 브라우저가 allow-origin 이 없어 그 응답을 버린다.
|
||||
# 실측(2026-09-07): 이 기본값 그대로 띄우면 :80 으로 연 앱에서 로그인이 안 된다.
|
||||
# ★ 값을 바꾸면 번들을 다시 구워야 한다: ./deploy.sh solution-site
|
||||
PUBLIC_API_BASE_URL=http://localhost
|
||||
PUBLIC_WEB_BASE_URL=http://localhost
|
||||
# PUBLIC_API_BASE_URL=http://localhost:9800
|
||||
# PUBLIC_WEB_BASE_URL=http://localhost:3000
|
||||
|
||||
# ── solution/site 발행물 — solution/backend 도 같이 본다
|
||||
# canonical·og:url·sitemap·IndexNow 가 전부 SITE_PUBLIC_HOST 를 쓴다.
|
||||
# 로컬은 비워 둔다(기본값 localhost). 서버에 올릴 때만 실제 도메인을 적는다.
|
||||
# SITE_PUBLIC_HOST=web4ai.o2osolution.ai
|
||||
# 비우면 색인 통보를 건너뛴다(발행은 정상)
|
||||
INDEXNOW_KEY=
|
||||
# 비우면 로컬 발행만 한다
|
||||
AZURE_STORAGE_CONNECTION_STRING=
|
||||
INDEXNOW_KEY= # 비우면 색인 통보를 건너뛴다(발행은 정상)
|
||||
AZURE_STORAGE_CONNECTION_STRING= # 비우면 로컬 발행만 한다
|
||||
AZURE_STORAGE_CONTAINER=
|
||||
AZURE_STORAGE_PREFIX=
|
||||
|
||||
|
||||
@@ -9,9 +9,13 @@ import {customFetch} from '@/api/mutator/custom-fetch';
|
||||
import {toast} from 'sonner';
|
||||
|
||||
type Status = 1 | 2 | 3;
|
||||
// LocalContentType — common/enums.py 와 값을 맞춘다. WEATHER(1) 은 사업장 발행본에 실시간으로
|
||||
// 붙는 별도 흐름이라 이 화면에서는 다루지 않는다(services/local_content_service.get_weather).
|
||||
type ContentType = 2 | 3 | 4;
|
||||
|
||||
type LocalContent = {
|
||||
id: string;
|
||||
contentType: ContentType;
|
||||
title: string;
|
||||
region: string;
|
||||
period: string;
|
||||
@@ -24,10 +28,15 @@ type LocalContent = {
|
||||
};
|
||||
|
||||
const STATUS_LABEL: Record<Status, string> = {1: '검수 대기', 2: '발행됨', 3: '종료됨'};
|
||||
const TYPE_LABEL: Record<ContentType, string> = {2: '축제', 3: '관광지', 4: '맛집'};
|
||||
const TYPE_BADGE_VARIANT: Record<ContentType, 'accent' | 'default' | 'outline'> = {
|
||||
2: 'accent', 3: 'default', 4: 'outline',
|
||||
};
|
||||
|
||||
type ApiContent = {
|
||||
local_content_id: string;
|
||||
region_code: string;
|
||||
content_type: ContentType;
|
||||
external_id?: string;
|
||||
title?: string;
|
||||
body: Record<string, unknown>;
|
||||
@@ -43,14 +52,17 @@ function formatDate(value: unknown) {
|
||||
}
|
||||
|
||||
function toContent(item: ApiContent): LocalContent {
|
||||
// 기간은 축제만 있다(eventstartdate/eventenddate) — 관광지·맛집은 상시 정보라 비어 있는 게 정상이다.
|
||||
const start = formatDate(item.body.eventstartdate);
|
||||
const end = formatDate(item.body.eventenddate);
|
||||
const period = [start, end].filter(Boolean).join(' ~ ') || (item.content_type === 2 ? '기간 미정' : '상시');
|
||||
return {
|
||||
id: item.local_content_id,
|
||||
contentType: item.content_type,
|
||||
title: item.title || '제목 없음',
|
||||
region: String(item.body.addr1 || item.region_code),
|
||||
period: [start, end].filter(Boolean).join(' ~ ') || '기간 미정',
|
||||
source: `공공데이터포털 전국문화축제표준데이터 · ${item.external_id ?? '-'}`,
|
||||
period,
|
||||
source: `한국관광공사 TourAPI · ${item.external_id ?? '-'}`,
|
||||
status: item.status,
|
||||
selected: false,
|
||||
displayStart: item.display_start_at,
|
||||
@@ -95,15 +107,24 @@ export function LocalContentPage() {
|
||||
} catch { toast.error('발행하지 못했습니다.'); }
|
||||
};
|
||||
const sync = async () => {
|
||||
const regionCode = window.prompt('내부 지역 코드(예: gunsan)를 입력하세요.', 'gunsan')?.trim();
|
||||
if (!regionCode) return;
|
||||
// ★ 주변정보는 업장 단위(place_contents)다 — 지역 코드가 아니라 사업장 id 로 받는다.
|
||||
// 이 화면의 목록은 아직 지역 캐시(local_contents)를 보여준다. 업장별 목록 화면은 다음 작업이다.
|
||||
const placeId = window.prompt('사업장 ID(place_id)를 입력하세요. 사업장 목록 주소의 /places/ 뒤 값입니다.')?.trim();
|
||||
if (!placeId) return;
|
||||
setSyncing(true);
|
||||
try {
|
||||
const res = await customFetch<{result?: {success?: boolean}; msg?: string; collected?: number; skipped?: number}>({
|
||||
url: '/v1/admin/local-content/sync-festivals', method: 'POST', data: {region_code: regionCode},
|
||||
});
|
||||
const res = await customFetch<{
|
||||
result?: {success?: boolean}; msg?: string;
|
||||
festivals?: number; attractions?: number; restaurants?: number; changed?: boolean;
|
||||
}>({url: `/v1/admin/local-content/place/${placeId}/sync`, method: 'POST'});
|
||||
if (res.result?.success === false) throw new Error(res.msg);
|
||||
toast.success(`${res.collected ?? 0}건 수집 · ${res.skipped ?? 0}건 중복 제외`);
|
||||
// ★ 여행코스(코스)는 2026-09-08부터 수집하지 않는다(반경을 넓혀도 데이터가 거의 없었다) — 표기에서 뺀다.
|
||||
const summary = `축제 ${res.festivals ?? 0} · 관광지 ${res.attractions ?? 0} · 맛집 ${res.restaurants ?? 0}건`;
|
||||
if (!res.changed) {
|
||||
toast.info(`바뀐 내용이 없습니다 (${summary}, TourAPI 원문 그대로).`);
|
||||
} else {
|
||||
toast.success(`${summary} 반영 — 다음 빌드부터 발행본에 실립니다.`);
|
||||
}
|
||||
await load();
|
||||
} catch (error) {
|
||||
toast.error(error instanceof Error ? error.message : '공공데이터 수집에 실패했습니다.');
|
||||
@@ -138,7 +159,7 @@ export function LocalContentPage() {
|
||||
return (
|
||||
<PageContainer
|
||||
title="지역 콘텐츠"
|
||||
description="공공데이터에서 지역 축제를 가져와 검수한 뒤 사장님에게 발행합니다."
|
||||
description="한국관광공사 TourAPI 에서 지역 축제·관광지·맛집을 가져와 자동 발행합니다. 필요하면 여기서 수정하거나 발행을 종료할 수 있습니다."
|
||||
actions={<Button onClick={sync} disabled={syncing}><Download className="size-4" />{syncing ? '수집 중…' : '공공데이터 수집'}</Button>}
|
||||
>
|
||||
<div className="mb-4 grid gap-3 sm:grid-cols-3">
|
||||
@@ -174,6 +195,7 @@ export function LocalContentPage() {
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="mb-1 flex flex-wrap items-center gap-2">
|
||||
<h2 className="text-sm font-semibold">{item.title}</h2>
|
||||
<Badge variant={TYPE_BADGE_VARIANT[item.contentType]}>{TYPE_LABEL[item.contentType]}</Badge>
|
||||
<Badge variant={item.status === 2 ? 'success' : 'warning'}>{STATUS_LABEL[item.status]}</Badge>
|
||||
</div>
|
||||
<div className="flex flex-wrap gap-x-4 gap-y-1 text-xs text-muted-foreground">
|
||||
|
||||
+1
-3
@@ -260,9 +260,7 @@ services:
|
||||
args:
|
||||
# ★ VITE_* 는 **번들에 구워진다.** .env 를 고쳐도 재빌드 전엔 안 바뀐다
|
||||
# → 주소를 바꿨으면 `./deploy.sh solution-site`.
|
||||
# ★ 기본값이 앱과 **같은 오리진**이다. nginx 가 /v1 을 프록시하므로 :9800 을 박으면
|
||||
# 스스로 크로스 오리진을 만들어 로그인만 조용히 실패한다(위 주석 · .env.example).
|
||||
VITE_API_BASE_URL: ${PUBLIC_API_BASE_URL:-http://localhost}
|
||||
VITE_API_BASE_URL: ${PUBLIC_API_BASE_URL:-http://localhost:9800}
|
||||
VITE_PUBLISH_HOST: ${SITE_PUBLIC_HOST:-localhost}
|
||||
VITE_SITE_PREVIEW_URL: ${PUBLIC_WEB_BASE_URL:-http://localhost}
|
||||
# ⚠️ 비어 있으면 자동 로그인은 아예 꺼진다(기본값 없음). 채우면 번들에 구워진다.
|
||||
|
||||
-183
@@ -5,55 +5,6 @@
|
||||
|
||||
---
|
||||
|
||||
## 2026-09-09 — 예약 안내 안에 날짜·시간 목업을 넣는다 (연동 없음)
|
||||
|
||||
**무슨 일** — 예약 흐름을 화면으로 보기 위해 `StayBookingDemo` 를 예약 안내 섹션 안에 넣었다.
|
||||
날짜(2주) · 도착 시간 · 객실 · 인원을 고르면 확인 화면이 나오고, 거기서 전화로 잇는다.
|
||||
**어디에도 연동하지 않는다** — 재고 조회도 접수도 결제도 없다(PRODUCT.md 6절은 그대로다).
|
||||
|
||||
**목업이라도 지킨 선**
|
||||
- **"마감/잔여" 를 만들지 않는다.** 우리는 그 값을 모른다. 그럴듯하게 지어내면 목업이 아니라
|
||||
거짓말이고, 손님은 그 표시를 보고 다른 날을 고른다
|
||||
- **시간 후보를 임의로 늘어놓지 않는다.** 체크인 fact(16:00)에서 시작해 5칸을 만든다 —
|
||||
fact 가 없으면 시간 선택을 아예 내지 않는다. 확인된 값과 어긋나는 선택지는 만들지 않는다
|
||||
- **요금은 요금표·JSON-LD 와 같은 출처**(`unitBaseRate`)를 쓴다. 데모라고 다른 숫자를 보이면
|
||||
같은 페이지가 두 값을 말하게 된다
|
||||
- 확인 화면은 "접수됐다" 고 쓰지 않는다 — 어디에도 보내지 않으므로 사실이 아니다.
|
||||
반대로 "접수되지 않았다" 는 경고도 두지 않는다(2026-09-09 결정: 흐름을 보는 화면이라
|
||||
경고문이 흐름을 가린다). **선택 내용 확인**까지만 말하고 전화로 잇는다
|
||||
|
||||
**★ 날짜는 브라우저에서 만든다 (mounted 게이트)**
|
||||
프리렌더가 서버에서 날짜를 구우면 **발행 시각의 날짜가 정적 HTML 에 박힌다.** 한 달 뒤
|
||||
크롤러가 그 페이지를 읽으면 지난 날짜가 예약 가능일로 적혀 있다 — 화면은 멀쩡한데 기계가
|
||||
읽는 값만 틀리는, 이 레포가 가장 자주 밟은 종류다. 그래서 서버 렌더에서는 달력을 그리지 않고
|
||||
안내 한 줄만 내보내고, 달력은 하이드레이션 후에 그린다. 자바스크립트가 꺼진 크롤러가 보는
|
||||
것은 "실제 예약 가능 여부와 결제는 아래 예약 창구에서" 뿐이다.
|
||||
|
||||
**구조화 데이터는 건드리지 않았다.** 데모는 JSON-LD 에도 llms.txt 에도 나가지 않는다 —
|
||||
`makesOffer.availability` 는 여전히 없고(빈 방을 모른다), llms.txt 는 "이 홈페이지는 빈 방
|
||||
재고와 결제를 처리하지 않습니다" 를 그대로 말한다. 목업을 AI 에게 예약 창구로 소개하면
|
||||
그때부터는 목업이 아니다.
|
||||
|
||||
**연동을 붙일 자리** — `ConfirmPanel` 한 곳이다. 실시간 재고·접수가 생기면 그 함수만 바뀐다.
|
||||
|
||||
**빌더 캔버스도 같이 맞췄다** — 사장님 편집 화면은 여전히 "네이버 실시간 온라인 예약 /
|
||||
캘린더에서 바로 확정 예약" 을 그리고 있었다. 우리는 실시간 예약을 하지 않는데다,
|
||||
**에디터에서 본 것과 발행된 사이트가 서로 다른 물건**이었다.
|
||||
- `booking/BookingCard`: 발행본 구성(날짜 칩 · 도착 시간 · 인원 · 예약 요청 · 전화 창구)의
|
||||
미리보기로 갈아엎었다. 캔버스의 클릭은 "이 섹션을 고른다" 는 뜻이라 상태를 두지 않고
|
||||
첫 칸이 골라진 모습으로 고정한다. 시간 칸은 발행본과 같은 규칙으로 **체크인 fact 가 있을
|
||||
때만** 그린다
|
||||
- `booking/BookingBanner` "실시간 캘린더" → "날짜와 시간을 고르고 예약 창구로 이어집니다",
|
||||
`rooms/RoomCard` "실시간 예약 신청" → "예약 안내 보기", `hero/HeroEditorial` "실시간 예약"
|
||||
→ "예약 안내"
|
||||
- `LinkChannel.NAVER_BOOKING` 을 orval 생성물에 반영. ★ `npm run orval` 을 그대로 돌리면
|
||||
**141파일 6,400줄**이 바뀐다 — 전부 따옴표·줄바꿈 포매팅 드리프트고 스펙 변경은 enum
|
||||
한 줄뿐이다. 그래서 생성물을 되돌리고 그 한 줄만 남겼다(실측 2026-09-09)
|
||||
|
||||
**검증** — `tsc·eslint` 통과, `vitest` 51 passed(신규 4건: 날짜가 HTML 에 안 박히는지 ·
|
||||
JSON-LD 무영향 · llms.txt 무영향 · 객실 0개면 안 그림). 실제 발행본 재굽기 후
|
||||
`/s/<slug>` 에서 데모 껍데기와 안내 문구 확인.
|
||||
|
||||
## 2026-09-08 — 발행본 목록의 정본 주소를 `/s` 로 — `/s` 가 앱 셸을 200 으로 주고 있었다
|
||||
|
||||
**무슨 일**
|
||||
@@ -160,140 +111,6 @@ False 라서다(썸네일은 Blob 에만 올라간다). 키를 채우면 다음
|
||||
건드려야 해서 이번 변경에 섞지 않았다.
|
||||
|
||||
---
|
||||
## 2026-09-08 — "예약" 을 누르면 검색 화면이 떴다 — 네이버 예약 주소를 수집해서 쓴다
|
||||
|
||||
**무슨 일**
|
||||
발행본의 예약 버튼이 네이버 **플레이스** 링크를 그대로 열었다. 잘해야 가게 홈이라 예약을 한 번
|
||||
더 눌러야 하고, 자동 발견이 물어온 URL 이 `map.naver.com/p/search/…`(검색 결과 주소)인 사장님은
|
||||
**예약하려고 눌렀는데 검색 화면**을 봤다. 예약하러 온 손님은 거기서 끝난다.
|
||||
|
||||
**근거 — 주소를 지어내지 않아도 된다**
|
||||
플레이스 모바일 응답(`__APOLLO_STATE__`)의 `ROOT_QUERY.placeDetail(...).naverBooking` 에
|
||||
네이버가 예약 주소를 직접 준다(실측 2026-09-08, place 1273971279):
|
||||
|
||||
naverBookingUrl : "https://m.booking.naver.com/booking/6/bizes/1067685"
|
||||
tabs : [home, feed, menu, booking(예약), review, …]
|
||||
|
||||
★ `bookingBusinessId`(1067685)와 `businessTypeId`(6)로 주소를 **조립하지 않는다.** 조립하면
|
||||
예약을 받지 않는 업소에도 그럴듯한 주소가 생기고, 눌러서 빈 화면을 본 손님은 그 가게가 예약을
|
||||
안 받는 줄로 읽는다. 응답이 `naverBookingUrl` 을 줄 때만 준 그대로 쓴다(미사용 업소는 null).
|
||||
|
||||
**바꾼 것**
|
||||
- `LinkChannel.NAVER_BOOKING = 7` (백엔드 enum · shared enum · init.sql 주석). 플레이스와 가른
|
||||
이유는 성격이 다르기 때문이다 — 이건 **예약 화면 그 자체**다
|
||||
- `collector/base.py`: `RawSource.booking_url` — 채널이 스스로 알려준 예약 주소를 싣는 자리
|
||||
- `naver_place_adapter._booking_url()`: 위 노드에서 읽는다. 키에 질의 인자가 통째로 박혀 있어
|
||||
(`placeDetail({"input":…})`) 이름으로 못 찾으므로 접두사로 찾는다
|
||||
- `collect_service._store_booking_link()`: 예약 채널 링크로 등록하고 **자동 확정**한다.
|
||||
근거는 `discover_naver_place` 와 같다 — 이미 확정된 플레이스가 자기 예약 주소로 내놓은
|
||||
값이라 남의 가게가 섞일 경로가 없다. 여기서 클릭을 한 번 더 받으면 그 사이 예약 버튼은
|
||||
계속 검색 화면으로 간다
|
||||
- `site/seo/jsonld.ts` `BOOKING_CHANNELS`: **순서가 우선순위**가 됐다(네이버 예약 → 야놀자 →
|
||||
여기어때 → 플레이스). `bookingChannelUrl` 이 이 순서로 고르므로 화면 버튼과
|
||||
`makesOffer.url`·`potentialAction` 이 같은 곳을 가리킨다
|
||||
- `site/lib/derive.ts`: 예약 버튼을 같은 순서로 정렬하고, **검색 결과 주소는 뺀다** —
|
||||
예약하러 온 사람에게 검색 화면을 주는 건 링크가 없는 것보다 나쁘다. 링크가 하나도 없으면
|
||||
"온라인 예약 채널은 등록되지 않았습니다" 로 전화만 남는다는 것을 말해 준다
|
||||
- `bookingCtaLabel()`: `${채널}에서 예약` 을 일괄로 쓰면 "네이버 예약에서 예약" 이 된다.
|
||||
그리고 이 채널만 누르는 즉시 예약 화면이므로 버튼이 그 차이를 말해야 한다 —
|
||||
"네이버 예약으로 바로 예약하기"
|
||||
- 빌더도 이 채널을 안다(`useCollectFlow` 라벨, `ChannelUrlInput` 의 호스트 판정)
|
||||
|
||||
**검증** — 실제 네이버 응답으로 어댑터 확인: `RawSource.booking_url =
|
||||
https://m.booking.naver.com/booking/6/bizes/1067685` · 예약 노드가 없는 응답에서는 None.
|
||||
`tsc·eslint` 통과, `vitest` 47 passed(신규 4건: 채널 우선순위 · 버튼 문구 · JSON-LD 대상 ·
|
||||
검색 URL 배제).
|
||||
|
||||
## 2026-09-07 — `.env.example` 그대로 쓰면 로컬 발행이 안 됐다 — 함정 둘
|
||||
|
||||
클론 직후 문서대로 `cp .env.example .env` 하고 `docker compose up -d` 한 다음 발행을 걸어 봤다.
|
||||
**게이트는 통과하는데 발행만 실패한다.** 두 가지가 겹쳐 있었다.
|
||||
|
||||
**1) `DB_HOST=127.0.0.1`** — 컨테이너 안의 127.0.0.1 은 그 컨테이너다. compose 기본값은
|
||||
`host.docker.internal` 인데 `.env` 가 그걸 덮어쓴다. 증상이 고약하다: API 는 `/healthz` 가
|
||||
DB 를 안 보므로 **200 healthy** 로 뜨고, **워커만 조용히 재시작을 반복한다** — 화면은 멀쩡하고
|
||||
발행 잡만 영원히 안 돈다.
|
||||
|
||||
**2) 줄 끝 주석이 값이 된다.** compose 의 `env_file` 은 `KEY= # 설명` 을 "빈 값"으로 읽지
|
||||
않는다 — 값이 `"# 설명"` 이다. 그래서 Azure 를 끈 로컬에서 `is_configured()` 가 참이 되고
|
||||
발행 잡이 업로드를 시도해 `Connection string is either blank or malformed` 로 죽었다.
|
||||
같은 모양이 5개였다: `COLLECT_USE_PERPLEXITY`(값 `0` 이 `"0 # ..."` 가 된다) ·
|
||||
`KAKAO_REST_API_KEY` · `TOUR_API_KEY` · `INDEXNOW_KEY` · `AZURE_STORAGE_CONNECTION_STRING`.
|
||||
|
||||
**3) 앱이 스스로 크로스 오리진을 만든다.** `nginx/site.conf` 는 `/v1` 을 같은 오리진으로
|
||||
프록시하고 주석에도 "앱과 같은 오리진이라 프리플라이트가 아예 발생하지 않는다" 고 적혀
|
||||
있는데, compose 의 빌드 인자 기본값이 `VITE_API_BASE_URL=http://localhost:9800` 이었다.
|
||||
`:80` 으로 앱을 열면 번들이 `:9800` 을 부르므로 크로스 오리진이 되고, `CLIENT_URL` 기본값
|
||||
(3000~3005)에 `http://localhost` 가 없어 **로그인만 계속 실패한다.** 증상이 사람을 속인다 —
|
||||
서버는 200 에 토큰까지 내려보내고, 브라우저가 `allow-origin` 이 없어 그 응답을 버리므로
|
||||
화면에는 "로그인에 실패했습니다" 만 뜬다. 비밀번호를 의심하게 된다.
|
||||
|
||||
**고친 것**
|
||||
- `.env.example`: `DB_HOST` 기본값을 `host.docker.internal` 로. 값 뒤 주석은 전부 **윗줄로**
|
||||
올리고, 파일 머리에 "값 뒤에 주석을 붙이지 않는다" 를 근거와 함께 박았다
|
||||
- `.env.example` · `docker-compose.yml`: 앱이 부르는 API 주소 기본값을 **앱과 같은 오리진**
|
||||
(`http://localhost`)으로. CORS 를 허용해서 뚫는 게 아니라 **크로스 오리진을 만들지 않는다** —
|
||||
nginx 가 이미 같은 오리진으로 프록시하고 있었다. `PUBLIC_API_BASE_URL` 을 주석이 아니라
|
||||
값으로 내놨다(주석으로 두면 compose 기본값이 이기고, 그 기본값이 문제였다)
|
||||
|
||||
**검증** — 새 DB(`web4ai_db`)에 `init.sql` 적용 → `docker compose down -v` 후 `up -d --build` →
|
||||
번들에 `localhost:9800` 참조 0건 · `POST http://localhost/v1/auth/login` 200(프리플라이트 없음) ·
|
||||
프리렌더가 기동하며 payload 2건 재굽기 → `/` `/s/` `/s/<slug>` 전부 200. 그리고 →
|
||||
`scripts/demo_build.py` 로 발행: 게이트 통과 · `published: true` · 프리렌더가 굽고
|
||||
`http://localhost/s/<slug>` 200. ★ 참고로 `demo_build.py` 는 자기 안에서 워커를 한 번 돌리는데,
|
||||
compose 워커가 잡을 먼저 집어가므로 **스크립트 출력은 "게이트 거부"로 보인다** — 실제 결과는
|
||||
`job.jobs.result` 와 워커 로그에 있다.
|
||||
|
||||
## 2026-09-07 — 숙박 예약 구성 — "실시간 예약" 섹션이 전화번호 한 줄이었다
|
||||
|
||||
**왜**
|
||||
숙박으로 발행하면 서버 기본표(`site_payload._DEFAULT_THEME`)가 `booking` 섹션을 켠다. 그런데
|
||||
발행본의 `BookingSection` 이 읽는 fact 는 `reservation_required`·`reservation_channel` 두 개이고,
|
||||
**둘 다 숙박 스키마(`lodging.json`)에 없다.** 그래서 펜션·민박 페이지의 "실시간 예약" 섹션에는
|
||||
전화번호 한 줄만 남았다 — 요금도, 인원도, 취소 규정도, 예약 창구도 없었다. 숙박은 예약이 곧
|
||||
매출이고 "얼마예요 / 몇 명까지 / 어떻게 예약해요" 가 이 업종 질의의 대부분인데, 그 답의 근거가
|
||||
페이지에 없으면 AI 는 OTA 후기에서 추측한다.
|
||||
|
||||
★ **예약을 처리하게 만든 게 아니다.** 빈 방 재고도 결제도 갖지 않는다([PRODUCT.md 6절](PRODUCT.md)
|
||||
— "사이트는 예약 채널로 보낸다"). 날짜 선택기·예약 폼을 그리지 않았다 — 없는 기능을 화면으로
|
||||
흉내내면 손님은 예약한 줄 알고 안 오고, 그 전화는 사장님이 받는다. 대신 **예약에 필요한 사실 +
|
||||
실제로 예약이 되는 창구**를 한자리에 모았고, "여기서 결제되지 않는다"를 화면 맨 앞과 llms.txt 에
|
||||
명시했다.
|
||||
|
||||
**바꾼 것**
|
||||
- `site/src/sections/StayBookingSection.tsx` (신규) — 객실별 요금·인원 / 예약 창구(전화 + 확정
|
||||
채널) / 예약 전 확인(체크인·체크아웃·취소환불·추가인원·프런트 시간·취사·반려동물·흡연).
|
||||
근거가 하나도 없으면 섹션째 안 나간다
|
||||
- `site/src/lib/derive.ts` — `stayBookingView()` 가 **그릴지 말지까지** 판단한다. 상단 내비·하단
|
||||
탭이 같은 함수를 본다 — 세 곳이 각자 판단하면 눌러도 아무 일 없는 "예약" 탭이 생긴다.
|
||||
예약 창구로 나가는 채널은 문의 목록에서 뺀다(네이버 플레이스가 두 번 보였다)
|
||||
- `site/src/seo/jsonld.ts` — `unitBaseRate()` 를 **요금 숫자의 단일 출처**로 만들고 화면과
|
||||
`makesOffer.price` 가 같이 쓴다(각자 계산하면 절대규칙 3 위반으로 발행이 멈춘다).
|
||||
`makesOffer`(객실별 1박 요금) · `potentialAction: ReserveAction`(확정 채널만) 추가.
|
||||
**`availability` 는 넣지 않았다** — 빈 방을 모르는데 InStock 을 주장하면 그게 거짓이다
|
||||
- `site/src/seo/llms.ts` — 숙박 `## 예약` 블록. LLM 은 위에서부터 읽는다. 예약 경로가 "공식 채널"
|
||||
절 맨 아래에만 있으면 답에 안 실린다
|
||||
- `frontend/src/data/industryData.ts` · `backend/services/site_payload.py` — 숙박 기본 섹션 이름을
|
||||
**"실시간 예약" → "예약 안내"**. 실시간 예약을 하지 않는데 제목이 그렇게 말하고 있었다.
|
||||
두 파일은 `tests/test_site_theme.py` 가 1:1 로 묶어 두므로 같이 고쳤다
|
||||
- 데모 fixture 의 theme 에 `rules`·`booking` 을 넣었다 — 서버 기본표에는 있는데 fixture 에만
|
||||
없어서, 개발 서버로는 이 두 섹션을 아예 볼 수 없었다
|
||||
|
||||
**곁에서 나온 것 — 데모 payload 는 원래 굽히지 않았다**
|
||||
`npm run prerender`(payload 미지정 = 데모)가 **절대규칙 3 대조 9건으로 실패**하고 있었다.
|
||||
내 변경 전에도 같은 건수로 실패했다(main 에서 재현 확인).
|
||||
1. `verify.ts` 가 URL 을 **원본 HTML 문자열**에서 찾았다. 속성으로 나갈 때 `&` 가 `&` 로
|
||||
이스케이프되므로 쿼리스트링 있는 이미지 URL 은 **화면에 있는데도** 절대 안 찾아진다.
|
||||
→ 엔티티를 되돌린 사본에서도 찾아본다. 표기 차이는 거짓이 아니다(숫자 `asShown()` 과 같은 이유).
|
||||
되돌린 사본에서도 못 찾으면 그대로 실패다 — 느슨해지지 않았다.
|
||||
2. `unitCode: 'MTK'`(㎡ 의 UN/CEFACT 코드)를 본문에서 찾고 있었다. 한국어 페이지에 'MTK' 가
|
||||
찍힐 일은 없다 — `priceCurrency`('KRW')와 같은 종류의 메타값이라 `STRUCTURAL` 로 옮겼다.
|
||||
★ 사람이 읽는 `unitText` 는 옮기지 않았다 — 그건 화면에 있어야 하는 말이다.
|
||||
|
||||
**검증** — `tsc·eslint` 통과, `vitest` 43 passed(신규 21건: 예약 뷰·발행 HTML·JSON-LD 대조·llms.txt).
|
||||
데모 payload 재굽기 성공(1개 중 1개) → `npm run serve` 로 `/s/moonlight-stay-jeju` 200 확인.
|
||||
백엔드 pytest 는 이 환경에 venv 가 없어 못 돌렸다 — 에디터↔서버 섹션표 parity 는 그 테스트와
|
||||
같은 방식으로 손으로 대조했다(stay: `예약 안내` 양쪽 일치).
|
||||
|
||||
## 2026-09-07 — (사고 2) 목업 사이트가 죽었다 — 참조된 자산은 기간과 무관하게 남긴다
|
||||
|
||||
|
||||
@@ -84,6 +84,7 @@ CREATE TABLE IF NOT EXISTS place.places (
|
||||
latitude NUMERIC(10,7) NULL, -- 위도
|
||||
longitude NUMERIC(10,7) NULL, -- 경도
|
||||
region_code VARCHAR(10) NULL, -- 카카오 행정구역 코드 — ★ 지역정보 캐시 키
|
||||
external_category VARCHAR(200) NULL, -- 외부 장소 DB 분류 원문("음식점 > 한식 > 육류" / "펜션") — 주변 맛집 경쟁업소 제외 기준(폴백)
|
||||
verified_at TIMESTAMPTZ NULL, -- ★ 동일 업소 검증 통과 시각. NULL = 수집·발행 금지
|
||||
verified_by uuid NULL, -- 검증자(company.users.user_id)
|
||||
content_updated_at TIMESTAMPTZ NULL, -- ★ 노출값이 마지막으로 바뀐 시각 — 개별 재빌드 대상 판별용
|
||||
@@ -105,7 +106,7 @@ CREATE TABLE IF NOT EXISTS place.place_aliases (
|
||||
CREATE TABLE IF NOT EXISTS place.place_links (
|
||||
link_id uuid PRIMARY KEY DEFAULT gen_random_uuid(), -- 링크 식별자(PK)
|
||||
place_id uuid NOT NULL, -- 사업장(place.places.place_id)
|
||||
channel SMALLINT NOT NULL, -- 채널(LinkChannel): 1=야놀자 2=여기어때 3=네이버플레이스 4=인스타 5=공식홈 6=블로그 7=네이버예약 99=기타
|
||||
channel SMALLINT NOT NULL, -- 채널(LinkChannel): 1=야놀자 2=여기어때 3=네이버플레이스 4=인스타 5=공식홈 6=블로그 99=기타
|
||||
url VARCHAR(1000) NOT NULL, -- 발견된 URL
|
||||
title VARCHAR(300) NULL, -- 제목/스니펫
|
||||
discovered_by SMALLINT NOT NULL, -- 발견 주체(SourceType): 2=api(Perplexity) 1=owner(직접)
|
||||
@@ -211,6 +212,25 @@ CREATE TABLE IF NOT EXISTS local.local_contents (
|
||||
deleted BOOLEAN NOT NULL DEFAULT FALSE
|
||||
);
|
||||
|
||||
-- 업장 반경의 주변 정보(맛집·관광지·축제·여행코스). ★ 키는 place_id — local_contents(행정구역 캐시)와 다르다.
|
||||
-- 빌드 때마다 TourAPI locationBasedList2 로 갱신. 응답에서 사라진 행은 소프트 삭제, hidden 은 유지.
|
||||
CREATE TABLE IF NOT EXISTS local.place_contents (
|
||||
place_content_id uuid PRIMARY KEY DEFAULT gen_random_uuid(), -- 주변 정보 식별자(PK)
|
||||
place_id uuid NOT NULL, -- 사업장(place.places.place_id)
|
||||
content_type SMALLINT NOT NULL, -- 종류(LocalContentType): 2=축제 3=관광지 4=맛집 5=여행코스
|
||||
external_id VARCHAR(100) NOT NULL, -- TourAPI contentid
|
||||
title VARCHAR(300) NOT NULL,
|
||||
body JSONB NOT NULL, -- 정규화한 TourAPI 항목(좌표·주소·사진·기간)
|
||||
distance_m INTEGER NOT NULL, -- 업장 좌표에서의 거리(m). 정렬 기준
|
||||
has_image BOOLEAN NOT NULL DEFAULT FALSE, -- 상업 이용 가능한 대표사진 유무
|
||||
display_end_at TIMESTAMPTZ NULL, -- 축제 종료. 지나면 스냅샷이 거른다
|
||||
hidden BOOLEAN NOT NULL DEFAULT FALSE, -- 운영자 숨김(재수집이 덮어쓰지 않음)
|
||||
collected_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
deleted BOOLEAN NOT NULL DEFAULT FALSE
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS local.routes (
|
||||
route_id uuid PRIMARY KEY DEFAULT gen_random_uuid(), -- 경로 식별자(PK)
|
||||
place_id uuid NOT NULL, -- 사업장(place.places.place_id)
|
||||
@@ -379,6 +399,8 @@ CREATE INDEX IF NOT EXISTS idx_facts_publishable ON fact.facts (place_id, status
|
||||
-- local
|
||||
CREATE INDEX IF NOT EXISTS idx_local_contents_region ON local.local_contents (region_code);
|
||||
CREATE INDEX IF NOT EXISTS idx_routes_place ON local.routes (place_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_place_contents_place ON local.place_contents (place_id);
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS uq_place_contents_keyed ON local.place_contents (place_id, content_type, external_id) WHERE deleted = false;
|
||||
CREATE INDEX IF NOT EXISTS idx_nearby_links_place ON local.nearby_links (place_id);
|
||||
|
||||
-- 지역 캐시 중복 방지. external_id 가 있는 항목(축제·관광지·맛집)과 없는 항목(날씨)을 나눠 건다.
|
||||
|
||||
@@ -19,6 +19,10 @@
|
||||
{ "key": "breakfast", "label": "조식 제공", "type": "bool", "scope": "place", "required": false, "critical": false, "allow_llm": false },
|
||||
{ "key": "baby_amenities", "label": "유아용품 비치", "type": "bool", "scope": "place", "required": false, "critical": false, "allow_llm": false },
|
||||
{ "key": "pickup_service", "label": "픽업 서비스", "type": "bool", "scope": "place", "required": false, "critical": false, "allow_llm": false },
|
||||
{ "key": "facilities", "label": "부대시설", "type": "text", "scope": "place", "required": false, "critical": false, "allow_llm": false },
|
||||
{ "key": "total_rooms", "label": "객실 수", "type": "number", "scope": "place", "required": false, "critical": false, "allow_llm": false, "unit": "실" },
|
||||
{ "key": "accommodation_capacity", "label": "수용 인원", "type": "number", "scope": "place", "required": false, "critical": false, "allow_llm": false, "unit": "명" },
|
||||
{ "key": "building_scale", "label": "규모", "type": "text", "scope": "place", "required": false, "critical": false, "allow_llm": false },
|
||||
{ "key": "intro", "label": "숙소 소개", "type": "text", "scope": "place", "required": false, "critical": false, "allow_llm": true },
|
||||
|
||||
{ "key": "room_type", "label": "객실 타입", "type": "text", "scope": "unit", "required": true, "critical": false, "allow_llm": false },
|
||||
@@ -29,6 +33,15 @@
|
||||
{ "key": "bathroom_count", "label": "욕실 수", "type": "number", "scope": "unit", "required": false, "critical": false, "allow_llm": false, "unit": "개" },
|
||||
{ "key": "has_kitchen", "label": "주방 여부", "type": "bool", "scope": "unit", "required": false, "critical": true, "allow_llm": false },
|
||||
{ "key": "has_aircon", "label": "에어컨", "type": "bool", "scope": "unit", "required": false, "critical": false, "allow_llm": false },
|
||||
{ "key": "has_bathroom", "label": "욕실", "type": "bool", "scope": "unit", "required": false, "critical": false, "allow_llm": false },
|
||||
{ "key": "has_tv", "label": "TV", "type": "bool", "scope": "unit", "required": false, "critical": false, "allow_llm": false },
|
||||
{ "key": "has_internet", "label": "인터넷", "type": "bool", "scope": "unit", "required": false, "critical": false, "allow_llm": false },
|
||||
{ "key": "has_refrigerator", "label": "냉장고", "type": "bool", "scope": "unit", "required": false, "critical": false, "allow_llm": false },
|
||||
{ "key": "has_hairdryer", "label": "드라이기", "type": "bool", "scope": "unit", "required": false, "critical": false, "allow_llm": false },
|
||||
{ "key": "has_toiletries", "label": "세면도구", "type": "bool", "scope": "unit", "required": false, "critical": false, "allow_llm": false },
|
||||
{ "key": "has_table", "label": "테이블", "type": "bool", "scope": "unit", "required": false, "critical": false, "allow_llm": false },
|
||||
{ "key": "has_sofa", "label": "소파", "type": "bool", "scope": "unit", "required": false, "critical": false, "allow_llm": false },
|
||||
{ "key": "has_home_theater", "label": "홈시어터", "type": "bool", "scope": "unit", "required": false, "critical": false, "allow_llm": false },
|
||||
{ "key": "view", "label": "전망", "type": "text", "scope": "unit", "required": false, "critical": false, "allow_llm": false },
|
||||
{ "key": "weekday_price", "label": "주중 요금", "type": "number", "scope": "unit", "required": false, "critical": true, "allow_llm": false, "unit": "원" },
|
||||
{ "key": "weekend_price", "label": "주말 요금", "type": "number", "scope": "unit", "required": false, "critical": true, "allow_llm": false, "unit": "원" },
|
||||
|
||||
@@ -99,6 +99,10 @@ class places(MainTableMixin, MAIN_BASE):
|
||||
latitude = Column(Numeric(10, 7), nullable=True)
|
||||
longitude = Column(Numeric(10, 7), nullable=True)
|
||||
region_code = Column(String(10), nullable=True) # 행정구역 코드 — ★ 지역정보 캐시 키(사이트 50개여도 조회 1회)
|
||||
# 외부 장소 DB 가 준 분류 문자열 원문(카카오 "음식점 > 한식 > 육류" · 네이버 "펜션"). 검증 때 박제한다.
|
||||
# ★ 쓰임: 주변 맛집에서 **같은 중분류(경쟁 업소)를 빼는** 기준. TourAPI 에 등록된 업장이면 그쪽 분류가 우선이고,
|
||||
# 이 값은 그 폴백이다(services/local_content_service._own_food_class).
|
||||
external_category = Column(String(200), nullable=True)
|
||||
verified_at = Column(DateTime(timezone=True), nullable=True) # ★ NULL = 미검증 → 수집·발행 금지
|
||||
verified_by = Column(UUID(as_uuid=True), nullable=True)
|
||||
# ★ 노출값(VERIFIED/CORRECTED fact)이 마지막으로 바뀐 시각. 개별 재빌드 대상 판별용 —
|
||||
@@ -315,6 +319,42 @@ class local_contents(MainTableMixin, MAIN_BASE):
|
||||
expires_at = Column(DateTime(timezone=True), nullable=True) # TTL — 지나면 갱신 대상(값은 유지)
|
||||
|
||||
|
||||
class place_contents(MainTableMixin, MAIN_BASE):
|
||||
"""업장 반경의 주변 정보(맛집·관광지·축제·여행코스). ★ 키는 place_id 다.
|
||||
|
||||
local_contents 는 행정구역(region_code) 단위 캐시라 '그 시군구에 있는 것'을 줄 뿐
|
||||
'이 업장에서 가까운 것'을 못 준다(2026-09-04 결정, specs/2026-09-04-tourapi-radius-spike.md).
|
||||
그래서 업장 좌표로 TourAPI locationBasedList2 를 직접 물어 여기 담는다.
|
||||
|
||||
★ 빌드 때마다 갱신된다(services/local_content_service.sync_place). 응답에서 사라진 행은
|
||||
소프트 삭제한다 — 업장 전용 데이터라 반경 밖으로 밀린 것을 남길 이유가 없다.
|
||||
단 hidden(운영자 숨김)은 재수집이 덮어쓰지 않는다.
|
||||
★ 외부 API 실패 시 행을 지우거나 비우지 않는다 — 직전 값을 그대로 쓴다."""
|
||||
|
||||
__tablename__ = "place_contents"
|
||||
__table_args__ = (
|
||||
Index(
|
||||
"uq_place_contents_keyed",
|
||||
"place_id", "content_type", "external_id",
|
||||
unique=True,
|
||||
postgresql_where=text("deleted = false"),
|
||||
),
|
||||
{"schema": "local"},
|
||||
)
|
||||
|
||||
place_content_id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
||||
place_id = Column(UUID(as_uuid=True), nullable=False, index=True)
|
||||
content_type = Column(SmallInteger, nullable=False) # LocalContentType 2~5
|
||||
external_id = Column(String(100), nullable=False) # TourAPI contentid
|
||||
title = Column(String(300), nullable=False)
|
||||
body = Column(JSONB, nullable=False) # 정규화한 TourAPI 항목(좌표·주소·사진·기간)
|
||||
distance_m = Column(Integer, nullable=False) # 업장 좌표에서의 거리(m). 정렬 기준
|
||||
has_image = Column(Boolean, nullable=False, server_default=text("false"), default=False) # 상업 이용 가능한 대표사진이 있는가
|
||||
display_end_at = Column(DateTime(timezone=True), nullable=True) # 축제 종료(KST 자정). 지나면 스냅샷이 거른다
|
||||
hidden = Column(Boolean, nullable=False, server_default=text("false"), default=False) # 운영자 숨김
|
||||
collected_at = Column(DateTime(timezone=True), nullable=False, server_default=_utc_now_sql())
|
||||
|
||||
|
||||
class routes(MainTableMixin, MAIN_BASE):
|
||||
"""가는 길. 검증 상태(FactStatus)를 그대로 쓴다 — 틀린 경로 안내도 헛걸음을 만든다."""
|
||||
|
||||
|
||||
@@ -267,11 +267,6 @@ class LinkChannel(CodeEnum):
|
||||
INSTAGRAM = 4
|
||||
OFFICIAL_SITE = 5 # 사장님 자체 홈페이지
|
||||
BLOG = 6
|
||||
# ★ 플레이스와 가른 이유: 이건 **예약 화면 그 자체**다.
|
||||
# 플레이스 홈은 예약 버튼을 한 번 더 눌러야 하고, 자동 발견이 검색 URL 을 물어온
|
||||
# 경우에는 아예 검색 결과가 뜬다 — 발행본의 "예약" 버튼이 그리로 가면 손님은
|
||||
# 예약을 포기한다. 주소는 지어내지 않는다: 플레이스 응답의 naverBookingUrl 그대로다.
|
||||
NAVER_BOOKING = 7 # 네이버 예약(m.booking.naver.com)
|
||||
ETC = 99
|
||||
|
||||
|
||||
@@ -291,10 +286,12 @@ VISION_AUTO_APPROVE_CONFIDENCE = 0.7
|
||||
class LocalContentType(CodeEnum):
|
||||
"""local_contents.content_type 코드값. 행정구역 코드 단위로 캐싱되는 지역 정보 종류."""
|
||||
|
||||
WEATHER = 1 # 날씨 (Open-Meteo)
|
||||
FESTIVAL = 2 # 축제 (TourAPI 행사정보, 주 1회)
|
||||
ATTRACTION = 3 # 관광지 (TourAPI 지역기반, 월 1회)
|
||||
RESTAURANT = 4 # 주변 맛집 (카카오 카테고리 검색)
|
||||
WEATHER = 1 # 날씨 (Open-Meteo) — local_contents(지역 캐시)
|
||||
# ↓ 2~5 는 place_contents(업장 반경 캐시). TourAPI locationBasedList2 contentTypeId 와 짝: 15·12·39·25
|
||||
FESTIVAL = 2 # 축제/공연/행사 (15)
|
||||
ATTRACTION = 3 # 관광지 (12)
|
||||
RESTAURANT = 4 # 음식점 (39)
|
||||
COURSE = 5 # 여행코스 (25) — 백엔드만. 렌더러 자리는 아직 없다
|
||||
|
||||
|
||||
class LocalSource(CodeEnum):
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
"""좌표 거리 — 공용 한 벌.
|
||||
|
||||
★ 같은 하버사인 공식이 tour_lookup(500m 동일업소 판정)·itinerary(일정 반경)·tour_api(축제 20km 필터)
|
||||
세 곳에 각각 복사돼 있었다(2026-09-08 정리). 지구 반지름·단위가 파일마다 달라지면 같은 두 점의
|
||||
거리가 모듈마다 다르게 나온다 — 거리로 무엇을 넣고 뺄지 정하는 코드가 셋이라 한 벌이어야 한다.
|
||||
|
||||
국내 범위라 하버사인(구면 근사)이면 충분하다. 오차는 수 m 수준으로, 우리가 쓰는 판정
|
||||
(500m 이내·5~20km 반경)에서 결과를 바꾸지 않는다.
|
||||
"""
|
||||
import math
|
||||
|
||||
EARTH_RADIUS_M = 6_371_000.0
|
||||
|
||||
|
||||
def haversine_m(lat1: float, lng1: float, lat2: float, lng2: float) -> float:
|
||||
"""두 좌표(위도, 경도) 사이의 거리(m). ★ 인자 순서는 (위도, 경도) — mapx/mapy 는 (경도, 위도)라 뒤집어 넣는다."""
|
||||
p1, p2 = math.radians(lat1), math.radians(lat2)
|
||||
dp, dl = math.radians(lat2 - lat1), math.radians(lng2 - lng1)
|
||||
a = math.sin(dp / 2) ** 2 + math.cos(p1) * math.cos(p2) * math.sin(dl / 2) ** 2
|
||||
return 2 * EARTH_RADIUS_M * math.asin(math.sqrt(a))
|
||||
|
||||
|
||||
def haversine_km(lat1: float, lng1: float, lat2: float, lng2: float) -> float:
|
||||
return haversine_m(lat1, lng1, lat2, lng2) / 1000.0
|
||||
@@ -9,7 +9,9 @@ from common.utils.gtime import GTime
|
||||
|
||||
class LocalContentCRUD:
|
||||
async def list(self, db, status: int | None = None, region_code: str | None = None):
|
||||
conds = [local_contents.deleted == False, local_contents.content_type == LocalContentType.FESTIVAL.value] # noqa: E712
|
||||
"""축제·관광지·맛집·날씨 전 종류. ★ 예전엔 FESTIVAL 로 고정돼 있어 sync_region 이 받은
|
||||
관광지·맛집이 이 목록에 영영 안 보였다(admin 화면이 축제만 검수/발행하는 줄 알게 됨)."""
|
||||
conds = [local_contents.deleted == False] # noqa: E712
|
||||
if status is not None:
|
||||
conds.append(local_contents.status == status)
|
||||
if region_code:
|
||||
@@ -21,18 +23,6 @@ class LocalContentCRUD:
|
||||
async def insert(self, db, row):
|
||||
return await DB_SESSION_MNG.insert(db, row)
|
||||
|
||||
async def get_by_external_id(self, db, region_code: str, external_id: str):
|
||||
err, rows = await DB_SESSION_MNG.execute(
|
||||
db,
|
||||
select(local_contents).where(
|
||||
local_contents.region_code == region_code,
|
||||
local_contents.content_type == LocalContentType.FESTIVAL.value,
|
||||
local_contents.external_id == external_id,
|
||||
local_contents.deleted == False, # noqa: E712
|
||||
).limit(1),
|
||||
)
|
||||
return err, rows[0] if rows else None
|
||||
|
||||
async def publish(self, db, ids: list, user_id):
|
||||
return await DB_SESSION_MNG.add_with_rowcount(
|
||||
db,
|
||||
@@ -52,6 +42,40 @@ class LocalContentCRUD:
|
||||
async def end(self, db, content_id):
|
||||
return await self.update(db, content_id, {"status": 3})
|
||||
|
||||
async def list_keyed(self, db, region_code: str, content_type: int):
|
||||
"""지역 × 종류의 외부 ID 있는 행 전부(축제·관광지·맛집). 동기화가 기존값과 비교할 때 쓴다."""
|
||||
return await DB_SESSION_MNG.execute(
|
||||
db,
|
||||
select(local_contents).where(
|
||||
local_contents.region_code == region_code,
|
||||
local_contents.content_type == content_type,
|
||||
local_contents.external_id.isnot(None),
|
||||
local_contents.deleted == False, # noqa: E712
|
||||
),
|
||||
)
|
||||
|
||||
async def upsert_keyed(self, db, values: dict):
|
||||
"""외부 ID 로 식별되는 행(축제·관광지·맛집)의 삽입/갱신.
|
||||
|
||||
★ uq_local_contents_keyed 부분 유니크 인덱스에 태운다 — 같은 지역을 두 번 동기화해도
|
||||
중복 행이 생기지 않고 기존 값만 갱신된다."""
|
||||
stmt = pg_insert(local_contents).values(**values)
|
||||
stmt = stmt.on_conflict_do_update(
|
||||
index_elements=[local_contents.region_code, local_contents.content_type, local_contents.external_id],
|
||||
index_where=and_(local_contents.deleted == False, local_contents.external_id.isnot(None)), # noqa: E712
|
||||
set_={
|
||||
"title": stmt.excluded.title,
|
||||
"body": stmt.excluded.body,
|
||||
"source": stmt.excluded.source,
|
||||
"status": stmt.excluded.status,
|
||||
"collected_at": stmt.excluded.collected_at,
|
||||
"display_end_at": stmt.excluded.display_end_at,
|
||||
"published_at": stmt.excluded.published_at,
|
||||
"updated_at": GTime.UTC(),
|
||||
},
|
||||
)
|
||||
return await DB_SESSION_MNG.add(db, stmt)
|
||||
|
||||
async def get_weather(self, db, region_code: str):
|
||||
err, rows = await DB_SESSION_MNG.execute(
|
||||
db,
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
from sqlalchemy import and_, select, update
|
||||
from sqlalchemy.dialects.postgresql import insert as pg_insert
|
||||
|
||||
from common.database.db_session_manager import DB_SESSION_MNG
|
||||
from common.database.model.models import place_contents
|
||||
from common.utils.gtime import GTime
|
||||
|
||||
|
||||
class PlaceContentCRUD:
|
||||
"""업장 반경 주변정보(place_contents). 키는 place_id 다."""
|
||||
|
||||
async def list_by_place(self, db, place_id, *, include_hidden: bool = True):
|
||||
conds = [place_contents.place_id == place_id, place_contents.deleted == False] # noqa: E712
|
||||
if not include_hidden:
|
||||
conds.append(place_contents.hidden == False) # noqa: E712
|
||||
return await DB_SESSION_MNG.execute(
|
||||
db,
|
||||
select(place_contents).where(and_(*conds))
|
||||
.order_by(place_contents.content_type.asc(), place_contents.has_image.desc(), place_contents.distance_m.asc()),
|
||||
)
|
||||
|
||||
async def upsert(self, db, values: dict):
|
||||
"""(place_id, content_type, external_id) 로 삽입/갱신. ★ hidden 은 건드리지 않는다 —
|
||||
운영자가 숨긴 것을 재수집이 되살리면 안 된다."""
|
||||
stmt = pg_insert(place_contents).values(**values)
|
||||
stmt = stmt.on_conflict_do_update(
|
||||
index_elements=[place_contents.place_id, place_contents.content_type, place_contents.external_id],
|
||||
index_where=(place_contents.deleted == False), # noqa: E712
|
||||
set_={
|
||||
"title": stmt.excluded.title,
|
||||
"body": stmt.excluded.body,
|
||||
"distance_m": stmt.excluded.distance_m,
|
||||
"has_image": stmt.excluded.has_image,
|
||||
"display_end_at": stmt.excluded.display_end_at,
|
||||
"collected_at": stmt.excluded.collected_at,
|
||||
"updated_at": GTime.UTC(),
|
||||
},
|
||||
)
|
||||
return await DB_SESSION_MNG.add(db, stmt)
|
||||
|
||||
async def soft_delete_missing(self, db, place_id, keep: set[tuple[int, str]]):
|
||||
"""이번 응답에 없는 행을 소프트 삭제. keep = {(content_type, external_id)}."""
|
||||
err, rows = await DB_SESSION_MNG.execute(
|
||||
db,
|
||||
select(place_contents.place_content_id, place_contents.content_type, place_contents.external_id)
|
||||
.where(place_contents.place_id == place_id, place_contents.deleted == False), # noqa: E712
|
||||
)
|
||||
gone = [r.place_content_id for r in (rows or []) if (int(r.content_type), r.external_id) not in keep]
|
||||
if not gone:
|
||||
return err, 0
|
||||
return await DB_SESSION_MNG.add_with_rowcount(
|
||||
db,
|
||||
update(place_contents).where(place_contents.place_content_id.in_(gone))
|
||||
.values(deleted=True, updated_at=GTime.UTC()),
|
||||
)
|
||||
|
||||
async def set_hidden(self, db, place_content_id, hidden: bool):
|
||||
return await DB_SESSION_MNG.add_with_rowcount(
|
||||
db,
|
||||
update(place_contents).where(
|
||||
place_contents.place_content_id == place_content_id, place_contents.deleted == False # noqa: E712
|
||||
).values(hidden=hidden, updated_at=GTime.UTC()),
|
||||
)
|
||||
@@ -1,10 +1,15 @@
|
||||
import uuid
|
||||
|
||||
from fastapi import APIRouter, Depends, Query
|
||||
|
||||
from common.enums import LocalContentStatus
|
||||
from common.models.gmodel import UserInfo
|
||||
from router.v1.validator.dependencies import RequireOwner, RemoveNoneResponse
|
||||
from services.local_content_service import LocalContentService
|
||||
from .protocol import ReqPublishLocalContent, ReqSyncFestivals, ReqUpdateLocalContent, ResLocalContentList, ResSyncFestivals, ResWeather
|
||||
from .protocol import (
|
||||
ReqHidePlaceContent, ReqPublishLocalContent, ReqUpdateLocalContent,
|
||||
ResLocalContentList, ResLocalGuide, ResPlaceContentList, ResSyncPlace, ResWeather,
|
||||
)
|
||||
|
||||
router = APIRouter(prefix="/v1/admin/local-content", tags=["LocalContent"])
|
||||
weather_router = APIRouter(prefix="/v1/local", tags=["LocalContent"])
|
||||
@@ -20,6 +25,35 @@ async def get_weather(
|
||||
return RemoveNoneResponse(await service.get_weather(region_code, latitude, longitude))
|
||||
|
||||
|
||||
@weather_router.get("/guide", response_model=ResLocalGuide, summary="업장 주변 가이드(맛집·명소·축제·코스) — 에디터 캔버스용")
|
||||
async def get_guide(
|
||||
place_id: uuid.UUID = Query(),
|
||||
service: LocalContentService = Depends(),
|
||||
):
|
||||
"""날씨와 같은 공개 조회다 — 운영자가 숨기지 않은 공공데이터만 나가므로 인증을 요구하지 않는다."""
|
||||
return RemoveNoneResponse(await service.get_guide(place_id))
|
||||
|
||||
|
||||
@router.get("/place/{place_id}", response_model=ResPlaceContentList, summary="업장 주변정보 목록 (숨김 포함)")
|
||||
async def list_place_contents(place_id: uuid.UUID, service: LocalContentService = Depends(), _user=Depends(RequireOwner)):
|
||||
return RemoveNoneResponse(await service.list_place_contents(place_id))
|
||||
|
||||
|
||||
@router.post("/place/{place_id}/sync", response_model=ResSyncPlace, summary="업장 주변정보 재수집 (TourAPI 반경)")
|
||||
async def sync_place(place_id: uuid.UUID, service: LocalContentService = Depends(), _user=Depends(RequireOwner)):
|
||||
"""빌드가 매번 하는 것과 같은 수집을 운영자가 직접 누른다. 무인 갱신(스케줄러)은 아직 없다."""
|
||||
return RemoveNoneResponse(await service.sync_place_by_id(place_id))
|
||||
|
||||
|
||||
@router.post("/place-content/{place_content_id}/hide", response_model=ResPlaceContentList, summary="주변정보 숨김/해제")
|
||||
async def hide_place_content(
|
||||
place_content_id: uuid.UUID, req: ReqHidePlaceContent,
|
||||
service: LocalContentService = Depends(), _user=Depends(RequireOwner),
|
||||
):
|
||||
"""숨긴 항목은 재수집이 되살리지 않는다. 다음 빌드부터 발행본에서 빠진다."""
|
||||
return RemoveNoneResponse(await service.set_hidden(place_content_id, req.hidden))
|
||||
|
||||
|
||||
@router.get("", response_model=ResLocalContentList)
|
||||
async def list_contents(
|
||||
status: LocalContentStatus | None = Query(None), region_code: str | None = Query(None),
|
||||
@@ -28,11 +62,6 @@ async def list_contents(
|
||||
return RemoveNoneResponse(await service.list(status.value if status else None, region_code))
|
||||
|
||||
|
||||
@router.post("/sync-festivals", response_model=ResSyncFestivals)
|
||||
async def sync_festivals(req: ReqSyncFestivals, service: LocalContentService = Depends(), _user=Depends(RequireOwner)):
|
||||
return RemoveNoneResponse(await service.sync_festivals(req))
|
||||
|
||||
|
||||
@router.post("/publish", response_model=ResLocalContentList)
|
||||
async def publish(req: ReqPublishLocalContent, service: LocalContentService = Depends(), user=Depends(RequireOwner)):
|
||||
return RemoveNoneResponse(await service.publish(req.content_ids, user.user_id))
|
||||
|
||||
@@ -25,10 +25,29 @@ class LocalContentData(WebPacketProtocol):
|
||||
display_end_at: datetime | None = None
|
||||
|
||||
|
||||
class ReqSyncFestivals(WebPacketProtocol):
|
||||
region_code: str = Field(min_length=1, max_length=10)
|
||||
area_code: str | None = None
|
||||
start_date: str | None = Field(default=None, pattern=r"^\d{8}$")
|
||||
class PlaceContentData(WebPacketProtocol):
|
||||
"""업장 반경 주변정보 1건(admin 목록용)."""
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
|
||||
place_content_id: uuid.UUID
|
||||
place_id: uuid.UUID
|
||||
content_type: LocalContentType
|
||||
external_id: str
|
||||
title: str
|
||||
body: dict[str, Any]
|
||||
distance_m: int
|
||||
has_image: bool
|
||||
hidden: bool
|
||||
display_end_at: datetime | None = None
|
||||
collected_at: datetime | None = None
|
||||
|
||||
|
||||
class ResPlaceContentList(Res_WebPacketProtocol):
|
||||
contents: list[PlaceContentData] = []
|
||||
|
||||
|
||||
class ReqHidePlaceContent(WebPacketProtocol):
|
||||
hidden: bool
|
||||
|
||||
|
||||
class ReqPublishLocalContent(WebPacketProtocol):
|
||||
@@ -46,9 +65,25 @@ class ResLocalContentList(Res_WebPacketProtocol):
|
||||
contents: list[LocalContentData] = []
|
||||
|
||||
|
||||
class ResSyncFestivals(Res_WebPacketProtocol):
|
||||
collected: int = 0
|
||||
skipped: int = 0
|
||||
class ResSyncPlace(Res_WebPacketProtocol):
|
||||
"""업장 반경 동기화 결과 — 종류별로 **남긴** 건수(반경·기간 필터 뒤). changed 는 값이 바뀌었는지."""
|
||||
|
||||
festivals: int = 0
|
||||
attractions: int = 0
|
||||
restaurants: int = 0
|
||||
courses: int = 0
|
||||
changed: bool = False
|
||||
|
||||
|
||||
class ResLocalGuide(Res_WebPacketProtocol):
|
||||
"""에디터 캔버스가 그리는 지역 가이드. ★ 항목 모양은 발행 payload 의 LocalContents 와 **동일**하다
|
||||
(services/site_payload._local 을 그대로 거친다) — 캔버스와 발행본이 다른 목록을 보이면 안 된다."""
|
||||
|
||||
attractions: list[dict[str, Any]] = []
|
||||
restaurants: list[dict[str, Any]] = []
|
||||
festivals: list[dict[str, Any]] = []
|
||||
courses: list[dict[str, Any]] = []
|
||||
synced_at: str | None = None
|
||||
|
||||
|
||||
class WeatherData(WebPacketProtocol):
|
||||
|
||||
@@ -40,6 +40,8 @@ class Req_VerifyPlace(PlaceProtocol):
|
||||
latitude: Optional[Decimal] = None
|
||||
longitude: Optional[Decimal] = None
|
||||
region_code: Optional[str] = None
|
||||
# 외부 장소 DB 의 분류 문자열(후보의 category_name). 주변 맛집에서 같은 업태(경쟁 업소)를 빼는 기준으로 박제한다.
|
||||
category_name: Optional[str] = None
|
||||
|
||||
|
||||
class Req_VerifyPlaceByUrl(PlaceProtocol):
|
||||
|
||||
@@ -30,6 +30,7 @@ from common.utils.gtime import GTime
|
||||
from crud.site_crud import SiteCRUD
|
||||
from crud.place_crud import PlaceCRUD
|
||||
from services import azure_static, indexnow, publish_gate, render_report, site_payload, site_thumbnail
|
||||
from services.local_content_service import LocalContentService
|
||||
from services.site_payload import emit_payload
|
||||
from services.snapshot import build_snapshot
|
||||
|
||||
@@ -114,6 +115,17 @@ async def run_build(job: dict) -> dict:
|
||||
raise BuildAborted(f"사업장을 찾을 수 없다: {place_id}")
|
||||
|
||||
site = await ensure_site(place_id)
|
||||
|
||||
# ★ 주변 정보(맛집·관광지·축제·코스)는 빌드 시점에 업장 좌표로 새로 받는다 — 발행본은 정적이라
|
||||
# 이때 받은 값이 실린다. 실패해도 빌드는 계속한다: 곁들이 정보가 사장님 사이트 발행을 막을 이유가 없고,
|
||||
# place_contents 는 직전 값을 그대로 갖고 있다.
|
||||
try:
|
||||
synced = await LocalContentService().sync_place(place)
|
||||
if not synced.result.success:
|
||||
LOG.w(f"[build] place={place_id} 주변정보 갱신 건너뜀(직전 값 사용): {synced.msg}")
|
||||
except Exception as ex: # noqa: BLE001 — 곁들이 정보 실패가 빌드를 죽이면 안 된다
|
||||
LOG.w(f"[build] place={place_id} 주변정보 갱신 실패(직전 값 사용): {type(ex).__name__}: {ex}")
|
||||
|
||||
snapshot = await build_snapshot(place)
|
||||
|
||||
v_err, version_no = await DB_SESSION_MNG.execute_lambda(
|
||||
|
||||
@@ -521,8 +521,6 @@ async def run_collect(job: dict) -> dict:
|
||||
),
|
||||
)
|
||||
|
||||
await _store_booking_link(place, place_id, source)
|
||||
|
||||
unit_map = await ensure_units(place_id, [source])
|
||||
unit_total = max(unit_total, len(unit_map))
|
||||
f = await store_facts(actor, place_id, [source], unit_map)
|
||||
@@ -550,40 +548,6 @@ async def run_collect(job: dict) -> dict:
|
||||
return result
|
||||
|
||||
|
||||
async def _store_booking_link(place, place_id: str, source) -> bool:
|
||||
"""수집 중 채널이 알려준 예약 주소를 **예약 채널 링크**로 남긴다.
|
||||
|
||||
★ 왜 필요한가 (실측 2026-09-08)
|
||||
발행본의 "예약" 버튼이 네이버 플레이스 링크를 그대로 열었다. 그 링크는 잘해야 플레이스
|
||||
홈이라 예약까지 한 번 더 눌러야 하고, 자동 발견이 검색 URL(`map.naver.com/p/search/…`)을
|
||||
물어온 경우에는 **검색 결과 화면**이 뜬다. 예약하려고 누른 손님이 검색 결과를 만나면
|
||||
거기서 끝난다.
|
||||
|
||||
★ 주소를 만들지 않는다. 플레이스 응답의 `naverBookingUrl` 을 그대로 쓴다
|
||||
(naver_place_adapter._booking_url 머리주석). 예약을 받지 않는 업소에는 이 값이 없고,
|
||||
없으면 링크도 없다 — 없는 예약 창구를 만들어내지 않는다.
|
||||
|
||||
★ 자동 확정한다. 근거는 `discover_naver_place` 와 같다 — 이 URL 은 **이미 확정된**
|
||||
플레이스 페이지가 자기 예약 주소로 내놓은 값이라, 남의 가게가 섞일 경로가 없다.
|
||||
여기서 클릭을 한 번 더 받으면 사장님이 확정을 안 한 사이트는 예약 버튼이 계속
|
||||
검색 화면으로 간다.
|
||||
"""
|
||||
url = (getattr(source, "booking_url", None) or "").strip()
|
||||
if not url:
|
||||
return False
|
||||
|
||||
added = await _add_link(
|
||||
place_id, LinkChannel.NAVER_BOOKING, url,
|
||||
f"{place.name} 네이버 예약", SourceType.CRAWL,
|
||||
)
|
||||
await DB_SESSION_MNG.execute_lambda_claim(
|
||||
place_links.DBType(),
|
||||
lambda s: _place_crud.confirm_link_by_url(s, uuid.UUID(place_id), url, place.verified_by, GTime.UTC()),
|
||||
)
|
||||
LOG.i(f"[collect] 네이버 예약 링크 {'등록·확정' if added else '확정'} — {url}")
|
||||
return added
|
||||
|
||||
|
||||
async def _finish(place_id: str, owner_user_id: str, status: PlaceStatus):
|
||||
"""수집이 끝나면 사업장을 검수 대기로 돌린다 — 수집값은 전부 후보라 사람이 봐야 한다."""
|
||||
await DB_SESSION_MNG.execute_lambda_claim(
|
||||
|
||||
@@ -99,10 +99,6 @@ class RawSource:
|
||||
text: Optional[str] = None # 태그 걷어낸 본문
|
||||
facts: list[CollectedFact] = field(default_factory=list)
|
||||
media: list[CollectedMedia] = field(default_factory=list)
|
||||
# ★ 수집 중 **그 채널이 스스로 알려준** 예약 주소. 우리가 만든 주소가 아니다.
|
||||
# 네이버 플레이스 응답의 naverBookingUrl 이 여기 실린다 — 발행본의 "예약" 버튼이
|
||||
# 플레이스 홈(한 번 더 눌러야 한다)이나 검색 결과가 아니라 예약 화면으로 바로 가게 하는 값.
|
||||
booking_url: Optional[str] = None
|
||||
|
||||
def __post_init__(self):
|
||||
if not (self.url or "").strip():
|
||||
|
||||
@@ -145,12 +145,8 @@ class NaverPlaceAdapter:
|
||||
|
||||
facts = self._to_facts(base, state)
|
||||
media = self._to_media(state)
|
||||
booking_url = self._booking_url(state)
|
||||
|
||||
LOG.i(
|
||||
f"[naver_place] {base.get('name')} — fact {len(facts)}건 · 사진 {len(media)}장"
|
||||
f"{' · 예약 주소 있음' if booking_url else ''} (id={place_id})"
|
||||
)
|
||||
LOG.i(f"[naver_place] {base.get('name')} — fact {len(facts)}건 · 사진 {len(media)}장 (id={place_id})")
|
||||
return RawSource(
|
||||
url=url,
|
||||
adapter_id=self.id,
|
||||
@@ -165,36 +161,9 @@ class NaverPlaceAdapter:
|
||||
),
|
||||
facts=facts,
|
||||
media=media,
|
||||
booking_url=booking_url,
|
||||
)
|
||||
|
||||
# ---- 내부 ----------------------------------------------------------
|
||||
|
||||
@staticmethod
|
||||
def _booking_url(state: dict) -> Optional[str]:
|
||||
"""네이버 예약 화면 주소. **네이버가 준 값 그대로**다 — 조립하지 않는다.
|
||||
|
||||
★ 왜 조립하지 않나
|
||||
응답에는 `bookingBusinessId`(1067685)와 `businessTypeId`(6)가 같이 있어서
|
||||
`m.booking.naver.com/booking/{type}/bizes/{id}` 를 만들 수 있을 것처럼 보인다.
|
||||
그러면 예약을 받지 않는 업소에도 그럴듯한 주소가 생기고, 눌렀는데 빈 화면이
|
||||
나오면 손님은 그 가게가 예약을 안 받는 줄로 읽는다. 응답이 `naverBookingUrl` 을
|
||||
줄 때만, 준 그대로 쓴다. 없으면 없는 것이다(실측: 예약 미사용 업소는 null).
|
||||
|
||||
★ 값은 ROOT_QUERY 의 placeDetail 응답 안에 있다. 키에 질의 인자가 통째로 박혀 있어
|
||||
(`placeDetail({"input":{...}})`) 이름으로 못 찾는다 — 접두사로 찾는다.
|
||||
"""
|
||||
root = state.get("ROOT_QUERY")
|
||||
if not isinstance(root, dict):
|
||||
return None
|
||||
detail = next(
|
||||
(v for k, v in root.items() if k.startswith("placeDetail") and isinstance(v, dict)), None
|
||||
)
|
||||
booking = (detail or {}).get("naverBooking")
|
||||
if not isinstance(booking, dict):
|
||||
return None
|
||||
url = str(booking.get("naverBookingUrl") or "").strip()
|
||||
return url or None
|
||||
async def _resolve_place_id(self, url: str) -> str:
|
||||
"""URL 에서 place id 를 뽑는다.
|
||||
|
||||
|
||||
@@ -284,9 +284,11 @@ class TourApiAdapter:
|
||||
def _lodging_facts(self, intro: dict) -> list[CollectedFact]:
|
||||
"""숙박 detailIntro2 → 사업장 단위 fact.
|
||||
|
||||
★ 스키마에 없는 값은 만들지 않는다. roomcount·scalelodging·foodplace 는
|
||||
lodging 스키마에 자리가 없어서 **일부러 버린다** — 억지로 다른 key 에 넣으면
|
||||
'식음료장 있음' 이 '조식 제공' 으로 둔갑한다.
|
||||
★ 스키마에 없는 값은 만들지 않는다. foodplace('식음료장 있음')는 lodging 스키마에
|
||||
자리가 없어서 **일부러 버린다** — 억지로 breakfast 에 넣으면 '조식 제공' 으로 둔갑한다.
|
||||
★ roomcount·scalelodging·accomcountlodging·subfacility 는 2026-09-07 에 자리를 만들었다
|
||||
(total_rooms·building_scale·accommodation_capacity·facilities). 실측(오블로모프 3103191)에서
|
||||
TourAPI 가 준 값의 절반이 자리가 없어 버려지고 있었다.
|
||||
"""
|
||||
return self._collect([
|
||||
("check_in_time", self._plain(intro.get("checkintime"))[:40]),
|
||||
@@ -296,6 +298,11 @@ class TourApiAdapter:
|
||||
("parking", self._bool_str(self._head_bool(intro.get("parkinglodging")))),
|
||||
("pickup_service", self._bool_str(self._head_bool(intro.get("pickup")))),
|
||||
("bbq_available", self._bool_str(self._yn(intro.get("barbecue")))),
|
||||
("facilities", self._plain(intro.get("subfacility"))[:500]),
|
||||
("total_rooms", self._number(intro.get("roomcount"))),
|
||||
("accommodation_capacity", self._number(intro.get("accomcountlodging"))),
|
||||
# "약 23평" · "대지 면적 11,570㎡" 처럼 단위가 제각각이라 숫자로 뽑지 않고 원문을 싣는다.
|
||||
("building_scale", self._plain(intro.get("scalelodging"))[:200]),
|
||||
])
|
||||
|
||||
def _restaurant_facts(self, intro: dict) -> list[CollectedFact]:
|
||||
@@ -362,6 +369,16 @@ class TourApiAdapter:
|
||||
("peak_price", self._number(row.get("roompeakseasonminfee1")), name),
|
||||
("has_kitchen", self._bool_str(self._yn(row.get("roomcook"))), name),
|
||||
("has_aircon", self._bool_str(self._yn(row.get("roomaircondition"))), name),
|
||||
# 객실 편의시설 Y/N. ★ 빈 값은 '없음'이 아니라 '모름'이다 — _yn 이 None 을 주면 fact 를 만들지 않는다.
|
||||
("has_bathroom", self._bool_str(self._yn(row.get("roombathfacility"))), name),
|
||||
("has_tv", self._bool_str(self._yn(row.get("roomtv"))), name),
|
||||
("has_internet", self._bool_str(self._yn(row.get("roominternet"))), name),
|
||||
("has_refrigerator", self._bool_str(self._yn(row.get("roomrefrigerator"))), name),
|
||||
("has_hairdryer", self._bool_str(self._yn(row.get("roomhairdryer"))), name),
|
||||
("has_toiletries", self._bool_str(self._yn(row.get("roomtoiletries"))), name),
|
||||
("has_table", self._bool_str(self._yn(row.get("roomtable"))), name),
|
||||
("has_sofa", self._bool_str(self._yn(row.get("roomsofa"))), name),
|
||||
("has_home_theater", self._bool_str(self._yn(row.get("roomhometheater"))), name),
|
||||
])
|
||||
return facts
|
||||
|
||||
|
||||
+24
-1
@@ -43,9 +43,10 @@ _BASE_URL = "https://dapi.kakao.com"
|
||||
_KEYWORD_URL = f"{_BASE_URL}/v2/local/search/keyword.json"
|
||||
_COORD2REGION_URL = f"{_BASE_URL}/v2/local/geo/coord2regioncode.json"
|
||||
_CATEGORY_URL = f"{_BASE_URL}/v2/local/search/category.json"
|
||||
_ADDRESS_URL = f"{_BASE_URL}/v2/local/search/address.json"
|
||||
|
||||
# 초과 단가(원). 로그에 함께 남겨 어떤 호출이 비싼지 바로 보이게 한다.
|
||||
_UNIT_COST_KRW = {"keyword": 2.0, "category": 2.0, "coord2region": 0.5}
|
||||
_UNIT_COST_KRW = {"keyword": 2.0, "category": 2.0, "coord2region": 0.5, "address": 0.5}
|
||||
|
||||
# 프로세스 누적 호출 수 — 생성 1건당 검색 횟수를 세는 근거.
|
||||
_CALL_COUNTS: Counter = Counter()
|
||||
@@ -362,6 +363,28 @@ class KakaoLocalClient:
|
||||
picked = next((d for d in docs if d.get("region_type") == "H"), docs[0])
|
||||
return RegionCode.from_document(picked)
|
||||
|
||||
# ---- 2-1) 주소 → 좌표 ----
|
||||
async def geocode_address(self, address: str) -> Optional[tuple[float, float]]:
|
||||
"""도로명·지번 주소 → (위도, 경도). 결과가 없으면 None — 좌표를 지어내지 않는다.
|
||||
|
||||
★ 쓰는 곳: 좌표 없이 검증된 사업장의 주변 정보 수집(local_content_service.sync_place).
|
||||
동일 업소 검증(카카오 후보·네이버 상세)은 좌표를 같이 주므로 보통은 비어 있지 않다 —
|
||||
비는 건 옛 데이터나 좌표 없는 후보를 고른 경우다. 그때 주소로 한 번 더 찾는다.
|
||||
싸다(초과 시 건당 0.5원). 결과는 places 에 박제하므로 사업장당 1회다.
|
||||
"""
|
||||
query = (address or "").strip()
|
||||
if not query:
|
||||
return None
|
||||
data = await self._get(_ADDRESS_URL, {"query": query, "size": "1"}, "address")
|
||||
docs = data.get("documents") or []
|
||||
if not docs:
|
||||
LOG.i(f"[kakao] 주소 → 좌표 결과 없음: {query[:60]}")
|
||||
return None
|
||||
lat, lon = _to_float(docs[0].get("y")), _to_float(docs[0].get("x")) # ★ y=위도 · x=경도
|
||||
if lat is None or lon is None:
|
||||
return None
|
||||
return lat, lon
|
||||
|
||||
# ---- 3) 주변 맛집·시설 ----
|
||||
async def search_category(
|
||||
self,
|
||||
|
||||
+263
-49
@@ -1,17 +1,58 @@
|
||||
"""공공데이터포털 전국문화축제표준데이터 클라이언트.
|
||||
"""한국관광공사 TourAPI(KorService2) — **업장 반경** 주변정보 수집 클라이언트.
|
||||
|
||||
설정 키 이름은 기존 배포 계약을 유지하기 위해 TOUR_API_KEY를 그대로 사용한다.
|
||||
collector/tour_api_adapter.py 가 '사업장 1곳'의 fact 를 캐는 쪽이라면, 여기는
|
||||
업장 좌표 반경 안의 곁들이 정보(맛집·관광지·축제·여행코스)를 긁는 쪽이다.
|
||||
결과는 place_contents(업장 단위 캐시)에 들어가 발행본·캔버스의 지역 정보 섹션이 된다.
|
||||
|
||||
★ 왜 행정구역이 아니라 좌표인가 (2026-09-04, specs/2026-09-04-tourapi-radius-spike.md)
|
||||
처음엔 법정동 코드로 areaBasedList2 를 불렀다. 그건 '그 시군구에 있는 것'이지
|
||||
'이 업장에서 가까운 것'이 아니다 — 양양군 업장 옆 5km 속초 관광지가 빠지고,
|
||||
같은 시군구 반대편 30km 맛집이 붙는다. locationBasedList2 는 좌표+반경으로 묻고
|
||||
거리(dist)까지 준다. 실측(군산 절골길 18): 10km 안 133건, 5km 안 100건.
|
||||
|
||||
★ 호출 수 — 업장당 종류별 1회 (맛집·관광지·축제)
|
||||
2026-09-08 부터 종류마다 **따로** 부른다(맛집 5km · 관광지 10km · 축제는 시도 전체, 반경 없음) —
|
||||
한 걸음에 갈 맛집과 차 타고 갈 축제를 같은 반경으로 재는 게 맞지 않았다.
|
||||
여행코스(25)는 실측 결과 반경을 넓혀도 데이터가 거의 없어(전북 전체 3건) 뺐다.
|
||||
|
||||
★ 축제는 locationBasedList2 가 아니라 searchFestival2 를 쓴다 (2026-09-08 교체)
|
||||
locationBasedList2(contentTypeId=15) 의 위치 색인은 못 믿는다 — 실측(군산 절골길 18):
|
||||
반경 20km 를 아무리 넓혀도 2023년에 끝난 서천 전시 1건만 나오고, 코앞 500m 의
|
||||
진행 예정 축제(군산시간여행축제 등)는 끝내 안 잡혔다. searchFestival2 는 법정동(시도)
|
||||
단위로 묻지만 정확하고 기간까지 함께 준다 — 그래서 시도 전체를 받아 우리가 거리로 거른다.
|
||||
eventStartDate 는 파라미터로 준 날짜 **이후 시작하는** 행사만 거른다(이전에 시작해 아직
|
||||
진행 중인 행사는 잡히지 않는다 — 실측). 그래서 항상 **그 해 1월 1일**로 고정해 부르고,
|
||||
이미 끝난 행사(eventenddate < 오늘)만 우리가 한 번 더 거른다.
|
||||
|
||||
★ 이미지 저작권 — 수집 단계에서 끝낸다 (collector/tour_api_adapter.py 와 같은 규칙)
|
||||
firstimage 는 공공누리 Type1(출처표시)·Type3(출처표시+변경금지)만 남긴다.
|
||||
발행본은 상업적 이용이라 Type2·Type4 는 싣지 못한다. 유형을 모르면 버린다.
|
||||
"""
|
||||
|
||||
import hashlib
|
||||
from datetime import date
|
||||
from urllib.parse import unquote
|
||||
from typing import Optional
|
||||
from urllib.parse import unquote, urlencode
|
||||
|
||||
import httpx
|
||||
|
||||
from common.enums import LocalContentType
|
||||
from common.utils.geo import haversine_m
|
||||
from config.server_configs import external_api_config
|
||||
|
||||
_URL = "https://api.data.go.kr/openapi/tn_pubr_public_cltur_fstvl_api"
|
||||
BASE_URL = "https://apis.data.go.kr/B551011/KorService2"
|
||||
REQUEST_TIMEOUT = 25
|
||||
PAGE_SIZE = 100
|
||||
# 반경 10km 도심은 300건을 넘지 않는다(실측 133건). 그 이상은 어차피 종류별 20건 상한에 안 든다.
|
||||
MAX_PAGES = 4
|
||||
|
||||
# TourAPI contentTypeId ↔ 우리 종류 코드(locationBasedList2 용). 축제(15)는 여기 없다 —
|
||||
# searchFestival2 로 따로 받는다(위 모듈 docstring 참고). 여행코스(25)도 뺐다(데이터 부족).
|
||||
CONTENT_TYPE_MAP = {
|
||||
"39": LocalContentType.RESTAURANT.value,
|
||||
"12": LocalContentType.ATTRACTION.value,
|
||||
}
|
||||
|
||||
# 상업적 이용이 허용된 공공누리 유형(tour_api_adapter 와 동일 규칙·동일 이유).
|
||||
_COMMERCIAL_OK_LICENSES = frozenset({"type1", "type3"})
|
||||
|
||||
|
||||
class TourApiNotConfigured(RuntimeError):
|
||||
@@ -22,52 +63,225 @@ class TourApiRequestFailed(RuntimeError):
|
||||
pass
|
||||
|
||||
|
||||
def _normalize(item: dict) -> dict:
|
||||
"""표준데이터 필드명을 화면/저장소의 공통 축제 필드로 변환한다."""
|
||||
identity = "|".join(str(item.get(key) or "") for key in ("fstvlNm", "fstvlStartDate", "fstvlEndDate", "insttCode"))
|
||||
return {
|
||||
"contentid": hashlib.sha256(identity.encode("utf-8")).hexdigest()[:32],
|
||||
"title": item.get("fstvlNm"),
|
||||
"eventstartdate": str(item.get("fstvlStartDate") or "").replace("-", ""),
|
||||
"eventenddate": str(item.get("fstvlEndDate") or "").replace("-", ""),
|
||||
"addr1": item.get("rdnmadr") or item.get("lnmadr") or item.get("eventPlace"),
|
||||
"mapx": item.get("longitude"),
|
||||
"mapy": item.get("latitude"),
|
||||
"tel": item.get("phoneNumber"),
|
||||
"homepage": item.get("homepageUrl"),
|
||||
"organizer": item.get("suprtInsttNm"),
|
||||
"overview": item.get("relateInfo") or item.get("opar"),
|
||||
"raw": item,
|
||||
}
|
||||
# ── HTTP ───────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
async def search_festivals(*, start_date: date, area_code: str | None = None, rows: int = 100) -> list[dict]:
|
||||
def _service_key() -> str:
|
||||
key = (external_api_config.tour_api_key or "").strip()
|
||||
if not key:
|
||||
raise TourApiNotConfigured("TOUR_API_KEY is not configured")
|
||||
params = {
|
||||
# 포털의 "Encoding" 키를 넣어도 httpx가 이중 인코딩하지 않도록 원문으로 되돌린다.
|
||||
"serviceKey": unquote(key),
|
||||
"type": "json",
|
||||
"numOfRows": max(1, min(rows, 1000)),
|
||||
"pageNo": 1,
|
||||
}
|
||||
return key
|
||||
|
||||
|
||||
async def _call(client: httpx.AsyncClient, op: str, **params) -> tuple[list[dict], int]:
|
||||
"""오퍼레이션 1회 → (항목, totalCount). 결과 없음은 빈 목록 — 없는 것과 실패를 구분한다.
|
||||
|
||||
★ 포털의 'Encoding' 키를 그대로 넣어도 이중 인코딩되지 않도록 원문으로 되돌린다
|
||||
(collector/tour_api_adapter._call 과 같은 처리).
|
||||
"""
|
||||
query = urlencode(
|
||||
{"serviceKey": unquote(_service_key()), "MobileOS": "ETC", "MobileApp": "o2o-web4ai",
|
||||
"_type": "json", "numOfRows": str(PAGE_SIZE), "pageNo": "1", **params},
|
||||
safe="",
|
||||
)
|
||||
res = await client.get(f"{BASE_URL}/{op}?{query}")
|
||||
if res.status_code != 200:
|
||||
raise TourApiRequestFailed(f"{op} HTTP {res.status_code}")
|
||||
try:
|
||||
async with httpx.AsyncClient(timeout=httpx.Timeout(20.0, connect=5.0)) as client:
|
||||
response = await client.get(_URL, params=params)
|
||||
response.raise_for_status()
|
||||
payload = response.json()
|
||||
response_data = payload.get("response", payload)
|
||||
header = response_data.get("header", {})
|
||||
if header.get("resultCode") not in (None, "00", "0000"):
|
||||
raise TourApiRequestFailed(header.get("resultMsg") or "TourAPI returned an error")
|
||||
items_node = response_data.get("body", {}).get("items", [])
|
||||
items = items_node.get("item", []) if isinstance(items_node, dict) else items_node
|
||||
if isinstance(items, dict):
|
||||
items = [items]
|
||||
normalized = [_normalize(item) for item in (items or [])]
|
||||
# API가 날짜 필터를 제공하지 않으므로 종료된 축제는 애플리케이션에서 제외한다.
|
||||
cutoff = start_date.strftime("%Y%m%d")
|
||||
return [item for item in normalized if not item["eventenddate"] or item["eventenddate"] >= cutoff]
|
||||
except (httpx.HTTPError, ValueError, TypeError) as ex:
|
||||
raise TourApiRequestFailed(str(ex)) from ex
|
||||
payload = res.json()
|
||||
except ValueError:
|
||||
# 인증 실패·쿼터 초과는 XML 로 온다. 본문 앞부분을 그대로 올려 원인을 감추지 않는다.
|
||||
raise TourApiRequestFailed(f"{op} 응답이 JSON 이 아니다: {res.text[:160]}")
|
||||
|
||||
# 게이트웨이 오류(미등록 키 등)는 200 + JSON 이지만 response 가 없다. 그것도 원인을 드러낸다.
|
||||
if "response" not in payload:
|
||||
raise TourApiRequestFailed(f"{op} 게이트웨이 오류: {str(payload)[:160]}")
|
||||
header = payload["response"].get("header", {})
|
||||
code = str(header.get("resultCode") or "")
|
||||
if code not in ("0000", "00"):
|
||||
raise TourApiRequestFailed(f"{op} 실패 [{code}] {header.get('resultMsg')}")
|
||||
|
||||
body = payload["response"].get("body", {}) or {}
|
||||
items = (body.get("items") or {}).get("item") if isinstance(body.get("items"), dict) else None
|
||||
if isinstance(items, dict):
|
||||
items = [items]
|
||||
total = int(body.get("totalCount") or 0)
|
||||
return items or [], total
|
||||
|
||||
|
||||
# ── 정규화 ──────────────────────────────────────────────────────────────
|
||||
|
||||
def _int(value) -> Optional[int]:
|
||||
try:
|
||||
return int(float(str(value).strip()))
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
|
||||
|
||||
def _normalize(item: dict) -> Optional[dict]:
|
||||
"""locationBasedList2 항목 1건 → place_contents.body. contentid·title·거리·종류 없으면 버린다."""
|
||||
content_id = str(item.get("contentid") or "").strip()
|
||||
title = str(item.get("title") or "").strip()
|
||||
kind = CONTENT_TYPE_MAP.get(str(item.get("contenttypeid") or "").strip())
|
||||
distance = _int(item.get("dist"))
|
||||
if not content_id or not title or kind is None or distance is None:
|
||||
return None
|
||||
|
||||
body = {"contentid": content_id, "title": title, "content_type": kind, "distance_m": distance}
|
||||
# lclsSystm1~3 = 분류체계 대/중/소. ★ 중분류(lclsSystm2)가 주변 맛집에서 같은 업태(경쟁 업소)를 빼는 기준이다.
|
||||
for key in ("addr1", "addr2", "tel", "mapx", "mapy", "lDongRegnCd", "lDongSignguCd",
|
||||
"lclsSystm1", "lclsSystm2", "lclsSystm3"):
|
||||
value = str(item.get(key) or "").strip()
|
||||
if value:
|
||||
body[key] = value
|
||||
|
||||
# 사진은 상업적 이용이 허용된 공공누리 유형일 때만 싣는다. 유형을 모르면 버린다.
|
||||
image = str(item.get("firstimage") or "").strip()
|
||||
license_code = str(item.get("cpyrhtDivCd") or "").strip().lower()
|
||||
if image and license_code in _COMMERCIAL_OK_LICENSES:
|
||||
body["firstimage"] = image
|
||||
body["license"] = license_code
|
||||
thumb = str(item.get("firstimage2") or "").strip()
|
||||
if thumb:
|
||||
body["firstimage2"] = thumb
|
||||
return body
|
||||
|
||||
|
||||
# ── 공개 API ────────────────────────────────────────────────────────────
|
||||
|
||||
def make_client() -> httpx.AsyncClient:
|
||||
return httpx.AsyncClient(timeout=REQUEST_TIMEOUT)
|
||||
|
||||
|
||||
async def fetch_nearby(client: httpx.AsyncClient, latitude: float, longitude: float,
|
||||
*, radius_m: int, content_type_id: str) -> list[dict]:
|
||||
"""업장 좌표 반경 안의 한 종류(정규화, 거리순). 종류마다 반경이 달라 호출도 따로 한다.
|
||||
|
||||
★ mapX=경도 · mapY=위도. 뒤집으면 엉뚱한 지역이 붙는다(카카오와 같은 함정).
|
||||
"""
|
||||
out: list[dict] = []
|
||||
seen: set[str] = set()
|
||||
for page in range(1, MAX_PAGES + 1):
|
||||
items, total = await _call(
|
||||
client, "locationBasedList2",
|
||||
mapX=str(longitude), mapY=str(latitude), radius=str(radius_m),
|
||||
contentTypeId=content_type_id, arrange="E", pageNo=str(page),
|
||||
)
|
||||
for item in items:
|
||||
body = _normalize(item)
|
||||
if body and body["contentid"] not in seen:
|
||||
seen.add(body["contentid"])
|
||||
out.append(body)
|
||||
if not items or page * PAGE_SIZE >= total:
|
||||
break
|
||||
out.sort(key=lambda b: b["distance_m"])
|
||||
return out
|
||||
|
||||
|
||||
def _normalize_festival(item: dict, distance_m: int) -> Optional[dict]:
|
||||
"""searchFestival2 항목 1건 → place_contents.body. locationBasedList2 와 달리 `dist` 를
|
||||
안 주므로(호출측이 haversine 으로 잰 값을) 그대로 받는다. 기간은 여기 이미 있다."""
|
||||
content_id = str(item.get("contentid") or "").strip()
|
||||
title = str(item.get("title") or "").strip()
|
||||
if not content_id or not title:
|
||||
return None
|
||||
|
||||
body = {"contentid": content_id, "title": title,
|
||||
"content_type": LocalContentType.FESTIVAL.value, "distance_m": distance_m}
|
||||
for key in ("addr1", "addr2", "tel", "mapx", "mapy", "lDongRegnCd", "lDongSignguCd",
|
||||
"lclsSystm1", "lclsSystm2", "lclsSystm3", "eventstartdate", "eventenddate"):
|
||||
value = str(item.get(key) or "").strip()
|
||||
if value:
|
||||
body[key] = value
|
||||
|
||||
image = str(item.get("firstimage") or "").strip()
|
||||
license_code = str(item.get("cpyrhtDivCd") or "").strip().lower()
|
||||
if image and license_code in _COMMERCIAL_OK_LICENSES:
|
||||
body["firstimage"] = image
|
||||
body["license"] = license_code
|
||||
thumb = str(item.get("firstimage2") or "").strip()
|
||||
if thumb:
|
||||
body["firstimage2"] = thumb
|
||||
return body
|
||||
|
||||
|
||||
def _festival_not_ended(body: dict, today: date) -> bool:
|
||||
"""종료일이 지났으면 끝난 축제 — 신지 않는다. 기간을 아예 모르면 못 믿으니 역시 뺀다.
|
||||
종료일 없이 시작일만 있으면(무기한 진행) 유지한다 — 끝났다는 증거가 없다."""
|
||||
end, start = body.get("eventenddate"), body.get("eventstartdate")
|
||||
ymd = today.strftime("%Y%m%d")
|
||||
if end:
|
||||
return len(end) == 8 and end.isdigit() and end >= ymd
|
||||
return bool(start)
|
||||
|
||||
|
||||
async def fetch_festivals_in_sido(client: httpx.AsyncClient, latitude: float, longitude: float,
|
||||
*, sido_code: str, today: date) -> list[dict]:
|
||||
"""업장이 속한 시도의 축제 **전부**(정규화, 거리순, 이미 끝난 것 제외). 반경으로 자르지 않는다.
|
||||
|
||||
★ 반경을 안 두는 이유(2026-09-08 결정): 축제는 차로 가는 행사라 20km 로 자르면 시도 안의
|
||||
큰 축제가 빠진다. 시도 전체를 그대로 싣고, 거리는 정렬·표시용으로만 잰다.
|
||||
(종류별 노출 상한은 스냅샷이 20건으로 자른다 — 사진 있는 것 우선 → 가까운 순.)
|
||||
★ locationBasedList2 의 위치 색인은 못 믿어서 searchFestival2 를 쓴다(위 모듈 docstring).
|
||||
eventStartDate 는 그 해 1월 1일로 **고정** — "오늘" 을 넣으면 그 이전에 시작해 아직 진행 중인
|
||||
축제가 파라미터 자체에서 빠진다(실측). 연초부터 전부 받고, 끝난 것만 여기서 거른다.
|
||||
★ 좌표 없는 항목은 뺀다 — distance_m 이 NOT NULL 이고, 거리 없는 카드는 도보 필터에 못 얹는다.
|
||||
"""
|
||||
start_date = date(today.year, 1, 1).strftime("%Y%m%d")
|
||||
out: list[dict] = []
|
||||
seen: set[str] = set()
|
||||
for page in range(1, MAX_PAGES + 1):
|
||||
items, total = await _call(
|
||||
client, "searchFestival2",
|
||||
eventStartDate=start_date, lDongRegnCd=sido_code, pageNo=str(page),
|
||||
)
|
||||
for item in items:
|
||||
lnglat = _mapxy(item) # (경도, 위도) — 좌표가 없으면 거리를 잴 수 없다
|
||||
if lnglat is None:
|
||||
continue
|
||||
lng, lat = lnglat
|
||||
distance = haversine_m(latitude, longitude, lat, lng) # 자르지 않는다 — 정렬·표시용
|
||||
body = _normalize_festival(item, round(distance))
|
||||
if not body or body["contentid"] in seen:
|
||||
continue
|
||||
if not _festival_not_ended(body, today):
|
||||
continue
|
||||
seen.add(body["contentid"])
|
||||
out.append(body)
|
||||
if not items or page * PAGE_SIZE >= total:
|
||||
break
|
||||
out.sort(key=lambda b: b["distance_m"])
|
||||
return out
|
||||
|
||||
|
||||
def _mapxy(item: dict) -> Optional[tuple[float, float]]:
|
||||
"""(경도, 위도). 좌표가 없거나 숫자가 아니면 None — 거리를 잴 수 없는 항목은 반경으로 못 거른다."""
|
||||
try:
|
||||
return float(item.get("mapx")), float(item.get("mapy"))
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
|
||||
|
||||
async def fetch_content_class(client: httpx.AsyncClient, content_id: str) -> Optional[str]:
|
||||
"""콘텐츠 1건의 중분류 코드(lclsSystm2). 못 구하면 None.
|
||||
|
||||
업장 자신이 TourAPI 에 등록돼 있을 때(place_links 의 tour:// 링크) 그 업장의 업태를 여기서 읽는다 —
|
||||
주변 맛집에서 같은 중분류를 빼기 위해서다. 외부 분류 문자열 매핑보다 이 값이 우선이다(같은 체계라 오차가 없다).
|
||||
"""
|
||||
items, _ = await _call(client, "detailCommon2", contentId=content_id)
|
||||
if not items:
|
||||
return None
|
||||
code = str(items[0].get("lclsSystm2") or "").strip()
|
||||
return code or None
|
||||
|
||||
|
||||
def festival_is_current(period: Optional[tuple[str, str]], today: date) -> bool:
|
||||
"""종료일이 지났으면 끝난 축제 — 싣지 않는다. 기간을 아예 모르면(None) 못 믿으니 역시 뺀다.
|
||||
종료일 없이 시작일만 있으면(무기한 진행) 시작일이 지났어도 유지한다 — 끝났다는 증거가 없다."""
|
||||
if not period:
|
||||
return False
|
||||
start, end = period
|
||||
ymd = today.strftime("%Y%m%d")
|
||||
if end:
|
||||
return len(end) == 8 and end.isdigit() and end >= ymd
|
||||
return bool(start)
|
||||
@@ -0,0 +1,120 @@
|
||||
"""여행 일정(1박2일·2박3일) 생성 — 순수 함수 모듈. DB·HTTP 없음.
|
||||
|
||||
빌드(payload) 시점에 그 지역의 발행된 지역정보(관광지·맛집·축제)와 업체 좌표로
|
||||
일정을 **즉석 계산**한다. 저장하지 않는 이유: 재료(local_contents)가 갱신되면
|
||||
다음 빌드에서 일정도 저절로 최신이 된다 — 따로 저장하면 그 동기화를 또 만들어야 한다.
|
||||
(docs/superpowers/specs/2026-09-03-local-tourapi-sync-design.md)
|
||||
|
||||
★ 지어내지 않는 규칙은 여기도 적용된다.
|
||||
재료가 부족하면 채울 수 있는 만큼만 담고, 하루도 못 채우면 일정 자체를 내지 않는다.
|
||||
좌표 없는 항목은 거리를 잴 수 없으므로 후보에서 뺀다 — 동선을 보장 못 하는 추천은 틀린 추천이다.
|
||||
|
||||
하루의 뼈대: 관광지 2 + 맛집 2(점심·저녁). 진행 중 축제가 있으면 그날 관광지 한 자리를 대신한다.
|
||||
일자 배분은 업체에서 가까운 순으로 후보를 끊고, 일자 안에서는 최근접 이웃 순서로 동선을 만든다.
|
||||
"""
|
||||
from typing import Optional
|
||||
|
||||
from common.utils.geo import haversine_km
|
||||
|
||||
# 하루 구성 정원. 관광지 자리는 축제가 하나 대신할 수 있다.
|
||||
_SPOTS_PER_DAY = 2
|
||||
_MEALS_PER_DAY = 2
|
||||
# 후보 반경(km). 업체에서 이보다 먼 곳은 '근처'가 아니다 — 1박2일 생활권을 넘는다.
|
||||
_MAX_RADIUS_KM = 30.0
|
||||
|
||||
_STOP_ATTRACTION = "attraction"
|
||||
_STOP_RESTAURANT = "restaurant"
|
||||
_STOP_FESTIVAL = "festival"
|
||||
|
||||
|
||||
def _as_float(value) -> Optional[float]:
|
||||
try:
|
||||
return float(value)
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
|
||||
|
||||
def _candidates(rows: list[dict], stop_type: str,
|
||||
base_lat: float, base_lng: float) -> list[dict]:
|
||||
"""payload 지역정보 행 → 거리 오름차순 후보. 좌표가 없거나 반경 밖이면 뺀다.
|
||||
|
||||
행 모양은 스냅샷 local.contents 의 body(services/external/tour_api._normalize)다 —
|
||||
mapx=경도, mapy=위도 (WGS84 문자열).
|
||||
"""
|
||||
out = []
|
||||
for row in rows:
|
||||
body = row.get("body") or {}
|
||||
name = str(row.get("title") or body.get("title") or "").strip()
|
||||
lat, lng = _as_float(body.get("mapy")), _as_float(body.get("mapx"))
|
||||
if not name or lat is None or lng is None:
|
||||
continue
|
||||
dist = haversine_km(base_lat, base_lng, lat, lng)
|
||||
if dist > _MAX_RADIUS_KM:
|
||||
continue
|
||||
out.append({"type": stop_type, "name": name, "lat": lat, "lng": lng,
|
||||
"distanceKm": round(dist, 1)})
|
||||
out.sort(key=lambda c: c["distanceKm"])
|
||||
return out
|
||||
|
||||
|
||||
def _order_by_route(stops: list[dict], base_lat: float, base_lng: float) -> list[dict]:
|
||||
"""일자 안 동선: 업체에서 출발해 최근접 이웃 순으로 잇는다."""
|
||||
remaining = list(stops)
|
||||
ordered: list[dict] = []
|
||||
lat, lng = base_lat, base_lng
|
||||
while remaining:
|
||||
nxt = min(remaining, key=lambda s: haversine_km(lat, lng, s["lat"], s["lng"]))
|
||||
remaining.remove(nxt)
|
||||
ordered.append(nxt)
|
||||
lat, lng = nxt["lat"], nxt["lng"]
|
||||
return ordered
|
||||
|
||||
|
||||
def _take(pool: list[dict], count: int) -> list[dict]:
|
||||
taken, pool[:] = pool[:count], pool[count:]
|
||||
return taken
|
||||
|
||||
|
||||
def _plan_days(days: int, attractions: list[dict], restaurants: list[dict],
|
||||
festivals: list[dict], base_lat: float, base_lng: float) -> Optional[dict]:
|
||||
"""일자별 계획. 첫날 하루도 못 채우면 None — 반쪽짜리 일정은 내지 않는다."""
|
||||
spots = list(attractions)
|
||||
meals = list(restaurants)
|
||||
fests = list(festivals)
|
||||
plan = []
|
||||
for day in range(1, days + 1):
|
||||
day_stops = []
|
||||
# 축제는 하루 하나까지, 관광지 한 자리를 대신한다.
|
||||
fest = _take(fests, 1)
|
||||
day_stops += fest
|
||||
day_stops += _take(spots, _SPOTS_PER_DAY - len(fest))
|
||||
day_stops += _take(meals, _MEALS_PER_DAY)
|
||||
if not day_stops:
|
||||
break
|
||||
plan.append({"day": day, "stops": _order_by_route(day_stops, base_lat, base_lng)})
|
||||
if not plan:
|
||||
return None
|
||||
return {"days": days, "plan": plan}
|
||||
|
||||
|
||||
def build_itineraries(base_lat: Optional[float], base_lng: Optional[float],
|
||||
attractions: list[dict], restaurants: list[dict],
|
||||
festivals: list[dict]) -> list[dict]:
|
||||
"""업체 좌표 기준 1박2일(2일)·2박3일(3일) 일정. 좌표가 없으면 빈 배열.
|
||||
|
||||
입력 행 모양은 스냅샷 local.contents 항목({title, body:{mapx, mapy, …}})이다.
|
||||
"""
|
||||
if base_lat is None or base_lng is None:
|
||||
return []
|
||||
spot_pool = _candidates(attractions, _STOP_ATTRACTION, base_lat, base_lng)
|
||||
meal_pool = _candidates(restaurants, _STOP_RESTAURANT, base_lat, base_lng)
|
||||
fest_pool = _candidates(festivals, _STOP_FESTIVAL, base_lat, base_lng)
|
||||
|
||||
out = []
|
||||
for days in (2, 3):
|
||||
# 세트마다 독립된 풀 복사 — 1박2일이 소비한 후보가 2박3일에서 빠지면 안 된다.
|
||||
built = _plan_days(days, list(spot_pool), list(meal_pool), list(fest_pool),
|
||||
base_lat, base_lng)
|
||||
if built:
|
||||
out.append(built)
|
||||
return out
|
||||
@@ -1,17 +1,71 @@
|
||||
from datetime import date, datetime, timedelta, timezone
|
||||
import re
|
||||
import uuid
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from decimal import Decimal
|
||||
|
||||
from sqlalchemy import select
|
||||
|
||||
from common.database.db_session_manager import DB_SESSION_MNG
|
||||
from common.database.model.models import local_contents
|
||||
from common.enums import DBWRType, ErrorType, LocalContentStatus, LocalContentType, LocalSource
|
||||
from common.database.model.models import local_contents, place_contents, place_links, places
|
||||
from common.enums import DBWRType, ErrorType, LocalContentStatus, LocalContentType, LocalSource, PlaceCategory
|
||||
from common.logger import LOG
|
||||
from crud.local_content_crud import LocalContentCRUD
|
||||
from router.v1.local.protocol import ResLocalContentList, ResSyncFestivals, ResWeather, WeatherData
|
||||
from crud.place_content_crud import PlaceContentCRUD
|
||||
from crud.place_crud import PlaceCRUD
|
||||
from services.external.kakao import KakaoLocalClient, KakaoNotConfigured, KakaoRequestFailed
|
||||
from services.external.naver import region_key
|
||||
from router.v1.local.protocol import (
|
||||
ResLocalContentList, ResLocalGuide, ResPlaceContentList, ResSyncPlace, ResWeather, WeatherData,
|
||||
)
|
||||
from services.external import tour_api
|
||||
from services.external.open_meteo import OpenMeteoRequestFailed, fetch_current_weather
|
||||
from services.external.tour_api import TourApiNotConfigured, TourApiRequestFailed, search_festivals
|
||||
from services.external.tour_api import TourApiNotConfigured, TourApiRequestFailed
|
||||
from services.place_category import guess_food_class
|
||||
|
||||
# collect_service.discover_tour_api 가 등록하는 업장 자신의 TourAPI 링크. (contentTypeId, contentId)
|
||||
_TOUR_LINK = re.compile(r"^tour://(\d+)/(\d+)$", re.I)
|
||||
# 업종별 기본 중분류 — 외부 분류도 TourAPI 링크도 없을 때의 마지막 폴백. 카페는 카페(FD05)를 뺀다.
|
||||
# 음식점은 어떤 음식인지 모르면 아무것도 빼지 않는다(한식당에서 양식집을 빼면 안 된다).
|
||||
_DEFAULT_FOOD_CLASS = {PlaceCategory.CAFE.value: "FD05"}
|
||||
|
||||
# 축제 노출 종료를 KST 그 날 자정으로 잡기 위한 시간대. 행사 날짜는 한국 날짜다.
|
||||
_KST = timezone(timedelta(hours=9))
|
||||
|
||||
# 업장 반경(m). 2026-09-04 실측(군산 절골길 18)으로 정했다 — specs/2026-09-04-tourapi-radius-spike.md
|
||||
# 관광지·축제·여행코스 10km: 5km 는 관광지 16건, 10km 는 38건. 원도심 밖 명소가 10km 에서 잡힌다.
|
||||
# 맛집 5km: 10km 에서도 66건 중 59건이 5km 안이다. 밥은 동네에서 먹는다.
|
||||
# 종류마다 반경이 다르다(2026-09-08) — 걸어갈 맛집과 차로 갈 관광지를 같은 반경으로 재지 않는다.
|
||||
# 축제는 반경이 없다 — 업장이 속한 시도 전체를 그대로 싣는다(tour_api.fetch_festivals_in_sido).
|
||||
RESTAURANT_RADIUS_M = 5_000
|
||||
ATTRACTION_RADIUS_M = 10_000
|
||||
|
||||
|
||||
def _festival_display_end(body: dict) -> datetime | None:
|
||||
"""eventenddate(YYYYMMDD) → 그 날 KST 자정(다음날 00:00) UTC.
|
||||
|
||||
★ 이 값이 있어야 끝난 축제가 발행본에서 저절로 빠진다 —
|
||||
스냅샷의 노출창 필터(snapshot._local_contents)가 display_end_at 을 본다."""
|
||||
raw = str(body.get("eventenddate") or "").strip()
|
||||
if len(raw) != 8 or not raw.isdigit():
|
||||
return None
|
||||
try:
|
||||
end_day = datetime(int(raw[:4]), int(raw[4:6]), int(raw[6:]), tzinfo=_KST)
|
||||
except ValueError:
|
||||
return None
|
||||
return (end_day + timedelta(days=1)).astimezone(timezone.utc)
|
||||
|
||||
|
||||
def _as_float(value) -> float | None:
|
||||
try:
|
||||
return float(value) if value is not None else None
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
|
||||
|
||||
class LocalContentService:
|
||||
def __init__(self):
|
||||
self.crud = LocalContentCRUD()
|
||||
self.place_crud = PlaceContentCRUD()
|
||||
|
||||
async def list(self, status=None, region_code=None):
|
||||
res = ResLocalContentList()
|
||||
@@ -22,11 +76,67 @@ class LocalContentService:
|
||||
res.contents = list(rows) if err == ErrorType.SUCCESS else []
|
||||
return res
|
||||
|
||||
async def sync_festivals(self, req):
|
||||
res = ResSyncFestivals()
|
||||
# ── 업장 반경 주변정보 ───────────────────────────────────────────────
|
||||
|
||||
async def sync_place(self, place) -> ResSyncPlace:
|
||||
"""업장 좌표 반경의 맛집·관광지·축제를 TourAPI 에서 받아 place_contents 를 맞춘다.
|
||||
종류마다 따로 부른다(맛집 5km · 관광지 10km · 축제는 시도 전체, 2026-09-08).
|
||||
여행코스(25)는 뺐다 — 반경을 넓혀도 데이터가 거의 없다(전북 전체 3건 실측).
|
||||
|
||||
빌드가 매번 부른다(services/build_service.run_build) — 발행본은 정적이라 이때 채운 값이 실린다.
|
||||
★ 실패해도 기존 행을 지우지 않는다 — 직전 값 유지가 이 캐시의 규약이다(모델 주석).
|
||||
★ 응답에 없는 행은 소프트 삭제한다 — 반경 밖으로 밀렸거나 TourAPI 가 내린 것이다.
|
||||
hidden(운영자 숨김)은 재수집이 덮어쓰지 않는다(crud.upsert). 이 변경으로 기존에 저장된
|
||||
여행코스 행도 다음 재수집 때 자연스레 소프트 삭제된다(더는 keep 목록에 없으므로).
|
||||
★ 공공데이터는 검수 없이 그대로 싣는다(2026-09-03 결정). 틀린 항목은 운영자가 숨긴다.
|
||||
"""
|
||||
res = ResSyncPlace()
|
||||
place_id = getattr(place, "place_id", None)
|
||||
if place_id is None:
|
||||
res.result.SetResult(ErrorType.INVALID_REQUEST_DATA)
|
||||
return res
|
||||
lat, lng = _as_float(getattr(place, "latitude", None)), _as_float(getattr(place, "longitude", None))
|
||||
if lat is None or lng is None:
|
||||
# ★ 좌표가 비면 주소로 한 번 더 찾는다(카카오 주소검색). 주변 정보는 TourAPI 에 이 업소가
|
||||
# 등록돼 있느냐와 무관하다 — 필요한 건 좌표뿐이다. 찾으면 places 에 박제해 다음부터는 안 부른다.
|
||||
found = await self._geocode_and_store(place)
|
||||
if found is None:
|
||||
res.result.SetResult(ErrorType.INVALID_REQUEST_DATA)
|
||||
res.msg = "사업장 좌표가 없어 주변 정보를 받을 수 없습니다(주소로도 찾지 못함)."
|
||||
return res
|
||||
lat, lng = found
|
||||
|
||||
try:
|
||||
start = datetime.strptime(req.start_date, "%Y%m%d").date() if req.start_date else date.today()
|
||||
items = await search_festivals(start_date=start, area_code=req.area_code)
|
||||
async with tour_api.make_client() as client:
|
||||
# 종류마다 반경이 달라 따로 부른다 — 맛집은 걸어갈 거리, 축제는 차로 갈 거리다.
|
||||
restaurants = await tour_api.fetch_nearby(
|
||||
client, lat, lng, radius_m=RESTAURANT_RADIUS_M, content_type_id="39")
|
||||
# ★ 업종별 제외(2026-09-08 결정): 음식점·카페 업장은 **같은 중분류(경쟁 업소)** 를 뺀다 —
|
||||
# 카페 사이트에 옆 카페를, 한식당 사이트에 옆 한식당을 추천할 이유가 없다.
|
||||
# 숙박 업장은 숙박(32)을 빼야 하는데 애초에 요청하지 않으므로 여기서 할 일이 없다.
|
||||
own_class = await self._own_food_class(client, place)
|
||||
if own_class:
|
||||
before = len(restaurants)
|
||||
restaurants = [r for r in restaurants if r.get("lclsSystm2") != own_class]
|
||||
LOG.i(f"[local] place={place_id} 같은 업태({own_class}) 맛집 {before - len(restaurants)}건 제외")
|
||||
attractions = await tour_api.fetch_nearby(
|
||||
client, lat, lng, radius_m=ATTRACTION_RADIUS_M, content_type_id="12")
|
||||
|
||||
# ★ 축제는 locationBasedList2 가 아니라 searchFestival2 를 쓴다(2026-09-08 교체) —
|
||||
# 위치 색인을 못 믿는다(실측: 반경 20km 를 넓혀도 몇 년 전에 끝난 전시만 잡히고,
|
||||
# 500m 옆 진행 예정 축제는 안 잡혔다). 시도 코드가 있어야 부를 수 있다.
|
||||
sido_code = str(getattr(place, "region_code", None) or "")[:2] or None
|
||||
if not sido_code:
|
||||
address = str(getattr(place, "road_address", None) or getattr(place, "address", None) or "")
|
||||
derived = region_key(address)
|
||||
sido_code = derived[:2] if derived else None
|
||||
today = datetime.now(_KST).date()
|
||||
if sido_code:
|
||||
festivals = await tour_api.fetch_festivals_in_sido(
|
||||
client, lat, lng, sido_code=sido_code, today=today)
|
||||
else:
|
||||
LOG.w(f"[local] place={place_id} 시도 코드를 못 구해 축제는 건너뜀")
|
||||
festivals = []
|
||||
except TourApiNotConfigured:
|
||||
res.result.SetResult(ErrorType.LOCAL_NOT_CONFIGURED)
|
||||
res.msg = "TOUR_API_KEY를 먼저 설정해주세요."
|
||||
@@ -36,35 +146,208 @@ class LocalContentService:
|
||||
res.msg = str(ex)
|
||||
return res
|
||||
|
||||
collected = skipped = 0
|
||||
for item in items:
|
||||
external_id = str(item.get("contentid") or "")
|
||||
if not external_id:
|
||||
skipped += 1
|
||||
kept: list[dict] = restaurants + attractions + festivals
|
||||
|
||||
err, rows = await DB_SESSION_MNG.execute_lambda(
|
||||
place_contents.DBType(), DBWRType.DB_READ.value,
|
||||
lambda s: self.place_crud.list_by_place(s, place_id),
|
||||
)
|
||||
if err != ErrorType.SUCCESS:
|
||||
res.result.SetResult(err)
|
||||
return res
|
||||
existing = {(int(r.content_type), r.external_id): r for r in (rows or [])}
|
||||
|
||||
now = datetime.now(timezone.utc)
|
||||
changed = 0
|
||||
for body in kept:
|
||||
key = (body["content_type"], body["contentid"])
|
||||
prev = existing.get(key)
|
||||
# 원문이 그대로면 쓰지 않는다 — collected_at 만 밀리면 '갱신된 척'이 된다.
|
||||
if prev is not None and prev.body == body:
|
||||
continue
|
||||
_, existing = await DB_SESSION_MNG.execute_lambda(
|
||||
local_contents.DBType(), DBWRType.DB_READ.value,
|
||||
lambda s, eid=external_id: self.crud.get_by_external_id(s, req.region_code, eid),
|
||||
values = {
|
||||
"place_id": place_id,
|
||||
"content_type": body["content_type"],
|
||||
"external_id": body["contentid"],
|
||||
"title": body["title"],
|
||||
"body": body,
|
||||
"distance_m": body["distance_m"],
|
||||
"has_image": bool(body.get("firstimage")),
|
||||
"display_end_at": (
|
||||
_festival_display_end(body) if body["content_type"] == LocalContentType.FESTIVAL.value else None
|
||||
),
|
||||
"collected_at": now,
|
||||
}
|
||||
write_err = await DB_SESSION_MNG.execute_lambda_run(
|
||||
[place_contents.DBType()], [lambda s, v=values: self.place_crud.upsert(s, v)]
|
||||
)
|
||||
if existing:
|
||||
skipped += 1
|
||||
continue
|
||||
row = local_contents(
|
||||
region_code=req.region_code,
|
||||
content_type=LocalContentType.FESTIVAL.value,
|
||||
source=LocalSource.TOUR_API.value,
|
||||
external_id=external_id,
|
||||
title=item.get("title"),
|
||||
body=item,
|
||||
status=LocalContentStatus.REVIEW.value,
|
||||
collected_at=datetime.now(timezone.utc),
|
||||
)
|
||||
err = await DB_SESSION_MNG.execute_lambda_run([row.DBType()], [lambda s, r=row: self.crud.insert(s, r)])
|
||||
collected += int(err == ErrorType.SUCCESS)
|
||||
skipped += int(err != ErrorType.SUCCESS)
|
||||
res.collected, res.skipped = collected, skipped
|
||||
if write_err == ErrorType.SUCCESS:
|
||||
changed += 1
|
||||
|
||||
keep_keys = {(b["content_type"], b["contentid"]) for b in kept}
|
||||
_, removed = await DB_SESSION_MNG.execute_lambda_claim(
|
||||
place_contents.DBType(), lambda s: self.place_crud.soft_delete_missing(s, place_id, keep_keys)
|
||||
)
|
||||
|
||||
counts = {k: 0 for k in (LocalContentType.FESTIVAL.value, LocalContentType.ATTRACTION.value,
|
||||
LocalContentType.RESTAURANT.value, LocalContentType.COURSE.value)}
|
||||
for b in kept:
|
||||
counts[b["content_type"]] += 1
|
||||
res.festivals = counts[LocalContentType.FESTIVAL.value]
|
||||
res.attractions = counts[LocalContentType.ATTRACTION.value]
|
||||
res.restaurants = counts[LocalContentType.RESTAURANT.value]
|
||||
res.courses = counts[LocalContentType.COURSE.value]
|
||||
res.changed = changed > 0 or bool(removed)
|
||||
LOG.i(f"[local] place={place_id} 주변정보 {len(kept)}건(갱신 {changed} · 제거 {removed or 0})")
|
||||
return res
|
||||
|
||||
async def _own_food_class(self, client, place) -> str | None:
|
||||
"""음식점·카페 업장 자신의 TourAPI 중분류(FD01~FD05). 숙박·병원은 None(제외할 게 없다).
|
||||
|
||||
우선순위 — 정확한 쪽부터:
|
||||
1. 업장이 TourAPI 에 등록돼 있으면(place_links 의 tour:// 링크) 그 콘텐츠의 lclsSystm2.
|
||||
주변 항목과 **같은 체계**라 오차가 없다. 링크는 수집(COLLECT)이 상호+좌표 검증을 거쳐 붙인다.
|
||||
2. 검증 때 박제한 외부 분류 문자열(places.external_category)을 키워드로 매핑.
|
||||
3. 그래도 모르면 업종 기본값 — 카페는 FD05. 음식점은 None(무엇을 빼야 할지 모른다).
|
||||
실패는 전부 '제외 없음'으로 떨어진다 — 경쟁 업소가 섞이는 것이 맛집 섹션이 통째로 비는 것보다 낫다.
|
||||
"""
|
||||
category = getattr(place, "category", None)
|
||||
if category not in (PlaceCategory.CAFE.value, PlaceCategory.RESTAURANT.value):
|
||||
return None
|
||||
|
||||
err, links = await DB_SESSION_MNG.execute_lambda(
|
||||
place_links.DBType(), DBWRType.DB_READ.value,
|
||||
lambda s: PlaceCRUD().list_links(s, place.place_id, confirmed_only=True),
|
||||
)
|
||||
for link in (links or []) if err == ErrorType.SUCCESS else []:
|
||||
m = _TOUR_LINK.match(str(getattr(link, "url", "") or ""))
|
||||
if not m:
|
||||
continue
|
||||
try:
|
||||
code = await tour_api.fetch_content_class(client, m.group(2))
|
||||
except TourApiRequestFailed as ex:
|
||||
LOG.w(f"[local] 업장 TourAPI 분류 조회 실패(외부 분류로 폴백): {ex}")
|
||||
code = None
|
||||
if code:
|
||||
return code
|
||||
break
|
||||
|
||||
guessed = guess_food_class(getattr(place, "external_category", None))
|
||||
if guessed:
|
||||
return guessed
|
||||
return _DEFAULT_FOOD_CLASS.get(category)
|
||||
|
||||
async def _geocode_and_store(self, place) -> tuple[float, float] | None:
|
||||
"""주소 → 좌표(카카오). 찾으면 places.latitude/longitude 에 박제한다. 키가 없거나 실패하면 None."""
|
||||
address = str(getattr(place, "road_address", None) or getattr(place, "address", None) or "").strip()
|
||||
if not address:
|
||||
return None
|
||||
client = KakaoLocalClient()
|
||||
if not client.enabled:
|
||||
LOG.w("[local] 좌표 없는 사업장인데 KAKAO_REST_API_KEY 가 없어 주소로 찾지 못한다")
|
||||
return None
|
||||
try:
|
||||
found = await client.geocode_address(address)
|
||||
except (KakaoNotConfigured, KakaoRequestFailed) as ex:
|
||||
LOG.w(f"[local] 주소 → 좌표 실패(계속): {ex}")
|
||||
return None
|
||||
finally:
|
||||
await client.aclose()
|
||||
if found is None:
|
||||
return None
|
||||
|
||||
lat, lng = found
|
||||
company_id = getattr(place, "company_id", None)
|
||||
if company_id is not None:
|
||||
data = {"latitude": Decimal(str(lat)), "longitude": Decimal(str(lng))}
|
||||
err, _ = await DB_SESSION_MNG.execute_lambda_claim(
|
||||
places.DBType(),
|
||||
lambda s: PlaceCRUD().update_place(s, company_id, place.place_id, data),
|
||||
)
|
||||
if err != ErrorType.SUCCESS:
|
||||
LOG.w(f"[local] 좌표 박제 실패(이번 수집엔 그대로 씀): {err.name}")
|
||||
else:
|
||||
place.latitude, place.longitude = data["latitude"], data["longitude"]
|
||||
LOG.i(f"[local] place={place.place_id} 주소로 좌표 확보 ({lat:.5f}, {lng:.5f}) — {address[:40]}")
|
||||
return lat, lng
|
||||
|
||||
async def _load_place(self, place_id):
|
||||
"""회사 스코프 없이 사업장 1건. ★ 공개 조회(guide)와 운영자 화면이 쓴다 — 사장님 API 는 place_service 를 탄다."""
|
||||
err, rows = await DB_SESSION_MNG.execute_lambda(
|
||||
places.DBType(), DBWRType.DB_READ.value,
|
||||
lambda s: DB_SESSION_MNG.execute(
|
||||
s, select(places).where(places.place_id == place_id, places.deleted == False).limit(1) # noqa: E712
|
||||
),
|
||||
)
|
||||
return (rows[0] if rows else None) if err == ErrorType.SUCCESS else None
|
||||
|
||||
async def sync_place_by_id(self, place_id: uuid.UUID) -> ResSyncPlace:
|
||||
place = await self._load_place(place_id)
|
||||
if place is None:
|
||||
res = ResSyncPlace()
|
||||
res.result.SetResult(ErrorType.DB_EMPTY_DATA)
|
||||
return res
|
||||
return await self.sync_place(place)
|
||||
|
||||
async def list_place_contents(self, place_id: uuid.UUID) -> ResPlaceContentList:
|
||||
res = ResPlaceContentList()
|
||||
err, rows = await DB_SESSION_MNG.execute_lambda(
|
||||
place_contents.DBType(), DBWRType.DB_READ.value,
|
||||
lambda s: self.place_crud.list_by_place(s, place_id, include_hidden=True),
|
||||
)
|
||||
res.result.SetResult(err)
|
||||
res.contents = list(rows) if err == ErrorType.SUCCESS else []
|
||||
return res
|
||||
|
||||
async def set_hidden(self, place_content_id: uuid.UUID, hidden: bool) -> ResPlaceContentList:
|
||||
res = ResPlaceContentList()
|
||||
err, count = await DB_SESSION_MNG.execute_lambda_claim(
|
||||
place_contents.DBType(), lambda s: self.place_crud.set_hidden(s, place_content_id, hidden)
|
||||
)
|
||||
res.result.SetResult(err if count else ErrorType.DB_EMPTY_DATA)
|
||||
return res
|
||||
|
||||
async def get_guide(self, place_id: uuid.UUID) -> ResLocalGuide:
|
||||
"""에디터 캔버스용 주변 가이드(맛집·명소·축제·코스).
|
||||
|
||||
★ 스냅샷 필터(숨김·노출창)와 payload 변환을 **그대로 재사용**한다 —
|
||||
캔버스가 발행본과 다른 목록을 보이면 사장님이 "미리보기와 다르다"고 읽는다.
|
||||
그래서 여기서 DB 를 따로 읽지 않고 발행 파이프라인의 두 함수를 잇기만 한다.
|
||||
★ 일정(itineraries)은 payload 가 만들어도 여기선 내려보내지 않는다 — 캔버스에 그릴 자리가 아직 없다.
|
||||
"""
|
||||
# 순환 import 회피 — snapshot·site_payload 는 발행 파이프라인 모듈이라 서비스 최상단에서 끌어오지 않는다.
|
||||
from services.site_payload import _local
|
||||
from services.snapshot import _local_contents
|
||||
|
||||
res = ResLocalGuide()
|
||||
place = await self._load_place(place_id)
|
||||
if place is None:
|
||||
res.result.SetResult(ErrorType.DB_EMPTY_DATA)
|
||||
return res
|
||||
|
||||
# ★ 아직 한 번도 수집하지 않은 사업장은 **지금** 채운다(cache-aside — 날씨와 같은 규약).
|
||||
# 빌드 때만 채우면 방금 만든 사업장은 첫 빌드 전까지 캔버스가 계속 "준비 중"이다(2026-09-07 실측).
|
||||
# 행이 하나라도 있으면 부르지 않는다 — 갱신은 빌드·운영자 재수집이 맡는다.
|
||||
err, rows = await DB_SESSION_MNG.execute_lambda(
|
||||
place_contents.DBType(), DBWRType.DB_READ.value,
|
||||
lambda s: self.place_crud.list_by_place(s, place_id),
|
||||
)
|
||||
if err == ErrorType.SUCCESS and not rows:
|
||||
synced = await self.sync_place(place)
|
||||
if not synced.result.success:
|
||||
LOG.w(f"[local] place={place_id} 첫 조회 수집 실패(빈 채로 응답): {synced.msg}")
|
||||
|
||||
snapshot_local = await _local_contents(place)
|
||||
local, synced_at = _local(snapshot_local, _as_float(place.latitude), _as_float(place.longitude))
|
||||
res.attractions = local.get("attractions") or []
|
||||
res.restaurants = local.get("restaurants") or []
|
||||
res.festivals = local.get("festivals") or []
|
||||
res.courses = local.get("courses") or []
|
||||
res.synced_at = synced_at
|
||||
return res
|
||||
|
||||
# ── 지역 캐시(local_contents) — 운영자 수기 항목·날씨 ────────────────
|
||||
|
||||
async def publish(self, ids, user_id):
|
||||
res = ResLocalContentList()
|
||||
err, _ = await DB_SESSION_MNG.execute_lambda_claim(
|
||||
|
||||
@@ -68,3 +68,39 @@ def _match(text: str) -> Optional[PlaceCategory]:
|
||||
if any(word in text for word in words):
|
||||
return category
|
||||
return None
|
||||
|
||||
|
||||
# ── 음식 중분류(TourAPI lclsSystm2) 추정 ─────────────────────────────────
|
||||
# 주변 맛집에서 **같은 중분류(경쟁 업소)를 빼는** 기준이다(2026-09-08 결정).
|
||||
# TourAPI 분류체계(lclsSystmCode2 실측) — FD01 한식 · FD02 외국식(중·일·서양·기타외국·퓨전)
|
||||
# · FD03 간이음식(제과·피자/햄버거/샌드위치·치킨·김밥분식·이동음식) · FD04 주점 · FD05 카페/찻집.
|
||||
#
|
||||
# ★ 순서가 결과를 바꾼다. 카카오는 카페를 "음식점 > 카페 > …" 아래 두므로 "음식점"이 항상 붙어 있다 —
|
||||
# 그래서 "음식점" 은 판정어로 쓰지 않고, 구체적인 업태(카페·주점·간이·외국식)를 한식보다 먼저 본다.
|
||||
# ★ 한식은 마지막이고 판정어가 좁다("한식"·"한정식"·"백반"·"국밥"…). 고기·회 같은 재료명은 넣지 않는다 —
|
||||
# "양식 > 스테이크" 를 고기라고 한식으로 넣으면 서양식 스테이크집이 한식이 된다.
|
||||
_FOOD_CLASS_KEYWORDS: list[tuple[str, tuple[str, ...]]] = [
|
||||
("FD05", ("카페", "커피", "찻집", "디저트", "음료", "주스", "빙수", "케이크", "브런치")),
|
||||
("FD04", ("주점", "술집", "호프", "맥주", "이자카야", "포차", "와인바", "칵테일", "펍")),
|
||||
("FD03", ("제과", "베이커리", "빵", "도넛", "피자", "햄버거", "샌드위치", "치킨", "분식", "김밥",
|
||||
"떡볶이", "간식", "토스트", "패스트푸드")),
|
||||
("FD02", ("중식", "중국", "일식", "일본", "초밥", "라멘", "양식", "서양", "이탈리", "파스타", "스테이크",
|
||||
"프렌치", "프랑스", "멕시", "아시아", "베트남", "태국", "인도", "퓨전")),
|
||||
("FD01", ("한식", "한정식", "백반", "국밥", "찌개", "국수", "냉면", "삼겹", "갈비", "곱창", "족발", "보쌈",
|
||||
"해장국", "설렁탕", "감자탕", "칼국수", "횟집", "회")),
|
||||
]
|
||||
|
||||
|
||||
def guess_food_class(category_name: Optional[str]) -> Optional[str]:
|
||||
"""외부 분류 문자열 → TourAPI 음식 중분류 코드(FD01~FD05). 모르면 None(제외 없음).
|
||||
|
||||
예 — 카카오 "음식점 > 카페 > 커피전문점" → FD05 · 네이버 "카페,디저트" → FD05 ·
|
||||
카카오 "음식점 > 한식 > 육류,고기" → FD01 · "음식점 > 양식 > 스테이크,립" → FD02
|
||||
"""
|
||||
text = (category_name or "").replace(" ", "")
|
||||
if not text:
|
||||
return None
|
||||
for code, words in _FOOD_CLASS_KEYWORDS:
|
||||
if any(word in text for word in words):
|
||||
return code
|
||||
return None
|
||||
@@ -243,6 +243,8 @@ class PlaceService:
|
||||
phone=base.get("phone") or base.get("virtualPhone") or None,
|
||||
latitude=Decimal(str(coord.get("y"))) if coord.get("y") else None,
|
||||
longitude=Decimal(str(coord.get("x"))) if coord.get("x") else None,
|
||||
# 네이버 상세의 분류("펜션"·"카페,디저트"). 주변 맛집 경쟁업소 제외의 폴백 근거(실측 2026-09-08: 있음).
|
||||
category_name=str(base.get("category") or "").strip() or None,
|
||||
)
|
||||
verified = await self.verify_place(user_info, place_id, verify_req)
|
||||
if not verified.result.success:
|
||||
@@ -321,6 +323,9 @@ class PlaceService:
|
||||
"verified_at": now,
|
||||
"verified_by": uuid.UUID(user_info.user_id),
|
||||
}
|
||||
# ★ 값이 왔을 때만 덮는다 — 네이버 URL 재검증이 분류를 못 읽었다고 카카오가 준 값을 지우면 안 된다.
|
||||
if (req.category_name or "").strip():
|
||||
data["external_category"] = req.category_name.strip()[:200]
|
||||
err_type, rowcount = await DB_SESSION_MNG.execute_lambda_claim(
|
||||
places.DBType(),
|
||||
lambda s: self.crud.update_place(s, uid, uuid.UUID(place_id), data),
|
||||
|
||||
@@ -31,6 +31,7 @@ from common.enums import (
|
||||
SourceType,
|
||||
)
|
||||
from common.logger import LOG
|
||||
from services.itinerary import build_itineraries
|
||||
|
||||
# 렌더러가 확인하는 스키마 버전. 모양이 바뀌면 여기와 site-payload.ts 를 같이 올린다.
|
||||
SCHEMA_VERSION = 1
|
||||
@@ -86,7 +87,7 @@ _DEFAULT_THEME = {
|
||||
"card": "#fafafa", "text": "#09090b", "accent": "#2563eb"},
|
||||
"sections": [
|
||||
("hero", "히어로", True), ("intro", "소개", False), ("rooms", "객실 안내", False),
|
||||
("info", "기본 정보", True), ("rules", "이용 규정", False), ("booking", "예약 안내", False),
|
||||
("info", "기본 정보", True), ("rules", "이용 규정", False), ("booking", "실시간 예약", False),
|
||||
("photos", "사진 갤러리", False), ("map", "오시는 길", True), ("weather", "날씨", False),
|
||||
("local", "지역 정보", False), ("faq", "자주 묻는 질문", False),
|
||||
],
|
||||
@@ -477,32 +478,77 @@ def _festival(row: dict):
|
||||
# 공식 홈페이지는 출처가 준 값일 때만 싣는다. 형식이 URL 이 아니면 링크로 걸지 않는다.
|
||||
if homepage.startswith("http://") or homepage.startswith("https://"):
|
||||
entry["officialUrl"] = homepage
|
||||
# 업장 반경 캐시(place_contents)에서 온 축제는 거리·사진도 있다 — 카드 캐러셀이 맛집·명소와
|
||||
# 같은 모양으로 그리려면 필요하다(2026-09-07, 도보 시간 필터 형식 결정).
|
||||
_put_distance(entry, body)
|
||||
image = _text(body.get("firstimage"))
|
||||
if image:
|
||||
entry["imageUrl"] = image
|
||||
return entry
|
||||
|
||||
|
||||
def _local_place(row: dict, category: str):
|
||||
"""LocalPlace(주변 명소·맛집).
|
||||
|
||||
★ title 컬럼만 믿는다. 이 두 종류(ATTRACTION·RESTAURANT)를 채우는 수집기가 아직 없어서
|
||||
body 의 모양이 정해지지 않았다 — 있지도 않은 키를 가정해 파싱하면 수집기가 붙는 날
|
||||
조용히 빈 값이 나간다. 지금은 테이블 스키마가 보장하는 것(title)만 쓰고,
|
||||
설명·거리는 실제 수집기가 붙을 때 그 모양을 보고 채운다."""
|
||||
body 는 TourAPI 수집기가 채운다(services/external/tour_api._normalize) —
|
||||
주소(addr1)가 있으면 위치로 싣는다. 없는 값은 만들지 않는다."""
|
||||
name = _text(row.get("title"))
|
||||
if not name:
|
||||
return None
|
||||
return {"name": name, "category": category, "searchQuery": name}
|
||||
body = row.get("body") or {}
|
||||
entry = {"name": name, "category": category, "searchQuery": name}
|
||||
location = _text(body.get("addr1"))
|
||||
if location:
|
||||
entry["location"] = location
|
||||
# 거리는 수집 시점에 업장 좌표로 잰 값(place_contents.distance_m). 지역 캐시 항목엔 없다.
|
||||
# ★ 숫자(distanceMeters)도 함께 싣는다 — 화면이 도보 시간 필터(분속 80m 환산)를 계산하려면
|
||||
# "1.2km" 같은 문자열을 다시 파싱하는 것보다 원값이 안전하다.
|
||||
_put_distance(entry, body)
|
||||
image = _text(body.get("firstimage"))
|
||||
if image:
|
||||
entry["imageUrl"] = image
|
||||
return entry
|
||||
|
||||
|
||||
def _local(snapshot_local: dict) -> tuple[dict, str | None]:
|
||||
def _put_distance(entry: dict, body: dict) -> None:
|
||||
"""distance_m → distanceText("850m") + distanceMeters(850). 값이 없거나 음수면 둘 다 넣지 않는다."""
|
||||
distance = _distance_text(body.get("distance_m"))
|
||||
if not distance:
|
||||
return
|
||||
entry["distanceText"] = distance
|
||||
entry["distanceMeters"] = int(body.get("distance_m"))
|
||||
|
||||
|
||||
def _distance_text(meters) -> str:
|
||||
"""850 → "850m", 1234 → "1.2km". 없으면 빈 문자열."""
|
||||
try:
|
||||
m = int(meters)
|
||||
except (TypeError, ValueError):
|
||||
return ""
|
||||
if m < 0:
|
||||
return ""
|
||||
if m < 1000:
|
||||
return f"{m}m"
|
||||
# 반올림은 '5 는 올림'으로 — f"{1.45:.1f}" 는 부동소수 탓에 1.4 가 나온다.
|
||||
return f"{(m + 50) // 100 / 10:.1f}km"
|
||||
|
||||
|
||||
def _local(snapshot_local: dict, base_lat: float | None, base_lng: float | None) -> tuple[dict, str | None]:
|
||||
"""스냅샷의 지역 정보 → LocalContents.
|
||||
|
||||
★ 스냅샷이 이미 걸렀다(PUBLISHED + 노출 기간 안). 여기서 더 거르지 않고 모양만 바꾼다 —
|
||||
fact·사진과 같은 분업이다.
|
||||
★ 예전에는 이 자리가 무조건 빈 배열이었다. local_contents 에 검수·발행된 지역 정보가 있어도
|
||||
payload 경계에서 통째로 버려져, 모든 발행 사이트의 지역 정보 섹션이 영구히 안 나왔다."""
|
||||
payload 경계에서 통째로 버려져, 모든 발행 사이트의 지역 정보 섹션이 영구히 안 나왔다.
|
||||
★ itineraries(1박2일·2박3일 일정)는 저장하지 않고 여기서 즉석 계산한다 —
|
||||
재료가 갱신되면 다음 빌드에서 일정도 저절로 최신이 된다(services/itinerary.py).
|
||||
렌더러에 아직 이 필드의 자리가 없다 — 모르는 필드는 무시되므로 화면은 변하지 않는다."""
|
||||
contents = (snapshot_local or {}).get("contents") or []
|
||||
local = {"attractions": [], "restaurants": [], "festivals": []}
|
||||
# courses(여행코스)는 백엔드만 채운다 — 렌더러 타입에 아직 자리가 없어 화면은 무시한다(2026-09-07).
|
||||
local = {"attractions": [], "restaurants": [], "festivals": [], "courses": []}
|
||||
synced_at = None
|
||||
# 일정 계산용 원본 행(좌표가 body 에 있다). payload 항목은 좌표를 싣지 않으므로 따로 모은다.
|
||||
raw = {"attractions": [], "restaurants": [], "festivals": []}
|
||||
|
||||
for row in contents:
|
||||
if not isinstance(row, dict):
|
||||
@@ -523,16 +569,29 @@ def _local(snapshot_local: dict) -> tuple[dict, str | None]:
|
||||
entry = _festival(row)
|
||||
if entry:
|
||||
local["festivals"].append(entry)
|
||||
raw["festivals"].append(row)
|
||||
elif content_type == LocalContentType.ATTRACTION.value:
|
||||
entry = _local_place(row, "관광지")
|
||||
if entry:
|
||||
local["attractions"].append(entry)
|
||||
raw["attractions"].append(row)
|
||||
elif content_type == LocalContentType.RESTAURANT.value:
|
||||
entry = _local_place(row, "맛집")
|
||||
if entry:
|
||||
local["restaurants"].append(entry)
|
||||
raw["restaurants"].append(row)
|
||||
elif content_type == LocalContentType.COURSE.value:
|
||||
entry = _local_place(row, "여행코스")
|
||||
if entry:
|
||||
local["courses"].append(entry)
|
||||
# 그 밖의 content_type 은 버린다 — 렌더러 타입에 담을 자리가 없다.
|
||||
|
||||
itineraries = build_itineraries(
|
||||
base_lat, base_lng, raw["attractions"], raw["restaurants"], raw["festivals"]
|
||||
)
|
||||
if itineraries:
|
||||
local["itineraries"] = itineraries
|
||||
|
||||
return local, synced_at
|
||||
|
||||
|
||||
@@ -708,7 +767,10 @@ def to_site_payload(place, snapshot: dict, site, version, links) -> dict:
|
||||
# ★ 스냅샷에서 읽는다 — 여기서 DB 를 다시 읽으면 '스냅샷과 다른 페이지'가 나온다(파일 상단 원칙).
|
||||
# 지역 정보를 스냅샷에 담는 필터링은 services/snapshot._local_contents 가 한다.
|
||||
# 옛 스냅샷에는 "local" 키가 없다. 그때는 빈 채로 나가고, 다음 빌드에서 채워진다.
|
||||
local, local_synced_at = _local(snapshot.get("local") or {})
|
||||
local, local_synced_at = _local(
|
||||
snapshot.get("local") or {},
|
||||
_as_float(snap_place.get("latitude")), _as_float(snap_place.get("longitude")),
|
||||
)
|
||||
if local_synced_at:
|
||||
local["syncedAt"] = local_synced_at
|
||||
|
||||
|
||||
@@ -22,13 +22,14 @@ from sqlalchemy import or_, select
|
||||
|
||||
from common.category_schema import get_schema
|
||||
from common.database.db_session_manager import DB_SESSION_MNG
|
||||
from common.database.model.models import facts, faqs, local_contents, media, units
|
||||
from common.database.model.models import facts, faqs, local_contents, media, place_contents, units
|
||||
from common.enums import (
|
||||
PUBLISHABLE_FACT_STATUSES,
|
||||
DBWRType,
|
||||
ErrorType,
|
||||
FactStatus,
|
||||
LocalContentStatus,
|
||||
LocalSource,
|
||||
MediaStatus,
|
||||
PlaceCategory,
|
||||
)
|
||||
@@ -38,9 +39,9 @@ from services.external.naver import region_key
|
||||
_PUBLISHABLE = tuple(s.value for s in PUBLISHABLE_FACT_STATUSES)
|
||||
|
||||
# 지역 정보를 종류별로 몇 건까지 박제할지.
|
||||
# ★ 스냅샷은 site_versions.snapshot 에 통째로 들어간다. 지역 캐시는 region_code 단위 공용이라
|
||||
# 한 지역에 수백 건이 쌓일 수 있고, 그걸 다 박제하면 버전 행마다 그만큼이 복사된다.
|
||||
# 화면(LocalGuideSection)도 그만큼 보여주지 않는다 — 최근 수집분 위주로 자른다.
|
||||
# ★ 종류별(맛집·관광지·축제·코스) 노출 상한 — 화면·캔버스·발행본 모두 이 수까지만 보여준다(2026-09-07 결정).
|
||||
# 스냅샷은 site_versions.snapshot 에 통째로 들어가므로 반경 안 수백 건을 다 박제하면 버전 행마다 복사된다.
|
||||
# 두 캐시(지역 수기 항목 + 업장 반경)를 **합쳐서** 센다 — 따로 세면 최대 40건이 나간다.
|
||||
_LOCAL_MAX_PER_TYPE = 20
|
||||
|
||||
# 지역 원문(body)에서 스냅샷으로 옮기지 않는 키.
|
||||
@@ -164,7 +165,11 @@ async def build_snapshot(place) -> dict:
|
||||
|
||||
|
||||
async def _local_contents(place) -> dict:
|
||||
"""사업장 지역의 노출 가능한 지역 정보. {"region_code", "contents":[...]}
|
||||
"""사업장의 노출 가능한 지역·주변 정보. {"region_code", "contents":[...]}
|
||||
|
||||
두 캐시를 합친다 —
|
||||
local_contents (region_code) 날씨 + 운영자가 수기로 발행한 항목
|
||||
place_contents (place_id) TourAPI 반경 수집분(맛집·관광지·축제·여행코스). 숨김·종료된 것 제외
|
||||
|
||||
★ 노출 가능 = PUBLISHED + 노출 기간 안.
|
||||
local_contents.status 는 운영 관리자의 검수 결과다(REVIEW=1 · PUBLISHED=2 · ENDED=3).
|
||||
@@ -192,48 +197,77 @@ async def _local_contents(place) -> dict:
|
||||
region_code = region_key(
|
||||
str(getattr(place, "road_address", None) or getattr(place, "address", None) or "")
|
||||
) or ""
|
||||
if not region_code:
|
||||
return {"region_code": None, "contents": []}
|
||||
|
||||
now = datetime.now(timezone.utc)
|
||||
query = (
|
||||
select(local_contents)
|
||||
.where(
|
||||
local_contents.region_code == region_code,
|
||||
local_contents.deleted == False, # noqa: E712
|
||||
local_contents.status == LocalContentStatus.PUBLISHED.value,
|
||||
or_(local_contents.display_start_at.is_(None), local_contents.display_start_at <= now),
|
||||
or_(local_contents.display_end_at.is_(None), local_contents.display_end_at > now),
|
||||
)
|
||||
.order_by(local_contents.content_type.asc(), local_contents.collected_at.desc())
|
||||
)
|
||||
err, rows = await DB_SESSION_MNG.execute_lambda(
|
||||
local_contents.DBType(), DBWRType.DB_READ.value, lambda s: DB_SESSION_MNG.execute(s, query)
|
||||
)
|
||||
if err != ErrorType.SUCCESS:
|
||||
# ★ 지역 정보가 없다고 발행을 막지 않는다 — 사업장의 사실이 아니라 곁들이는 정보다.
|
||||
# 빈 채로 나가면 렌더러가 그 섹션을 아예 그리지 않는다.
|
||||
LOG.w(f"[snapshot] 지역 정보 조회 실패 region={region_code}: {err.name}")
|
||||
return {"region_code": region_code, "contents": []}
|
||||
contents: list[dict] = []
|
||||
seen: dict[int, int] = {} # 종류별 누적 건수 — 두 캐시를 합쳐 상한을 센다
|
||||
|
||||
seen: dict[int, int] = {}
|
||||
contents = []
|
||||
for row in rows or []:
|
||||
# ── 지역 캐시(local_contents): 날씨 + 운영자가 수기로 발행한 항목 ──
|
||||
if region_code:
|
||||
query = (
|
||||
select(local_contents)
|
||||
.where(
|
||||
local_contents.region_code == region_code,
|
||||
local_contents.deleted == False, # noqa: E712
|
||||
local_contents.status == LocalContentStatus.PUBLISHED.value,
|
||||
or_(local_contents.display_start_at.is_(None), local_contents.display_start_at <= now),
|
||||
or_(local_contents.display_end_at.is_(None), local_contents.display_end_at > now),
|
||||
)
|
||||
.order_by(local_contents.content_type.asc(), local_contents.collected_at.desc())
|
||||
)
|
||||
err, rows = await DB_SESSION_MNG.execute_lambda(
|
||||
local_contents.DBType(), DBWRType.DB_READ.value, lambda s: DB_SESSION_MNG.execute(s, query)
|
||||
)
|
||||
if err != ErrorType.SUCCESS:
|
||||
# ★ 지역 정보가 없다고 발행을 막지 않는다 — 사업장의 사실이 아니라 곁들이는 정보다.
|
||||
LOG.w(f"[snapshot] 지역 정보 조회 실패 region={region_code}: {err.name}")
|
||||
rows = []
|
||||
contents += _local_rows(rows or [], seen)
|
||||
|
||||
# ── 업장 반경 캐시(place_contents): 맛집·관광지·축제·여행코스 ──
|
||||
# ★ 정렬은 **사진 있는 것 우선 → 가까운 순**(2026-09-07 결정). 종류별 상한 안에 들려면
|
||||
# 사진 없는 가까운 곳보다 사진 있는 조금 먼 곳이 이긴다 — 화면이 카드라 사진이 없으면 자리가 빈다.
|
||||
place_id = getattr(place, "place_id", None)
|
||||
if place_id is not None:
|
||||
nearby_q = (
|
||||
select(place_contents)
|
||||
.where(
|
||||
place_contents.place_id == place_id,
|
||||
place_contents.deleted == False, # noqa: E712
|
||||
place_contents.hidden == False, # noqa: E712
|
||||
or_(place_contents.display_end_at.is_(None), place_contents.display_end_at > now),
|
||||
)
|
||||
.order_by(place_contents.content_type.asc(), place_contents.has_image.desc(), place_contents.distance_m.asc())
|
||||
)
|
||||
err, rows = await DB_SESSION_MNG.execute_lambda(
|
||||
place_contents.DBType(), DBWRType.DB_READ.value, lambda s: DB_SESSION_MNG.execute(s, nearby_q)
|
||||
)
|
||||
if err != ErrorType.SUCCESS:
|
||||
LOG.w(f"[snapshot] 주변 정보 조회 실패 place={place_id}: {err.name}")
|
||||
rows = []
|
||||
contents += _local_rows(rows or [], seen, source=LocalSource.TOUR_API.value)
|
||||
|
||||
return {"region_code": region_code or None, "contents": contents}
|
||||
|
||||
|
||||
def _local_rows(rows, seen: dict[int, int], source: int | None = None) -> list[dict]:
|
||||
"""행 → 스냅샷 항목. 종류별 상한(_LOCAL_MAX_PER_TYPE)은 들어온 순서(정렬)대로 자른다.
|
||||
seen 은 호출측이 넘겨 두 캐시에 걸쳐 누적한다."""
|
||||
out = []
|
||||
for row in rows:
|
||||
content_type = int(row.content_type)
|
||||
# 종류별 상한. 위 order_by 가 collected_at 내림차순이라 최근 수집분이 남는다.
|
||||
taken = seen.get(content_type, 0)
|
||||
if taken >= _LOCAL_MAX_PER_TYPE:
|
||||
continue
|
||||
seen[content_type] = taken + 1
|
||||
body = row.body if isinstance(row.body, dict) else {}
|
||||
contents.append({
|
||||
out.append({
|
||||
"content_type": content_type,
|
||||
"source": row.source,
|
||||
"source": source if source is not None else row.source,
|
||||
"title": row.title,
|
||||
"body": {k: v for k, v in body.items() if k not in _LOCAL_BODY_DROP},
|
||||
"collected_at": _iso(row.collected_at),
|
||||
})
|
||||
return {"region_code": region_code, "contents": contents}
|
||||
return out
|
||||
|
||||
|
||||
def _iso(value) -> str | None:
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
User-agent: *
|
||||
Disallow: /admin/
|
||||
@@ -0,0 +1,10 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
|
||||
|
||||
<url>
|
||||
<loc>https://web4ai.o2osolution.ai/</loc>
|
||||
<lastmod>2026-08-12T00:00:00+09:00</lastmod>
|
||||
<priority>1.0</priority>
|
||||
</url>
|
||||
|
||||
</urlset>
|
||||
@@ -19,6 +19,5 @@ export const LinkChannel = {
|
||||
INSTAGRAM: 4,
|
||||
OFFICIAL_SITE: 5,
|
||||
BLOG: 6,
|
||||
NAVER_BOOKING: 7,
|
||||
ETC: 99,
|
||||
} as const;
|
||||
@@ -1,8 +0,0 @@
|
||||
/**
|
||||
* Generated by orval v7.21.0 🍺
|
||||
* Do not edit manually.
|
||||
* Web4Ai API
|
||||
* OpenAPI spec version: 0.1.0
|
||||
*/
|
||||
|
||||
export type PlaceSearchItemNaverPlaceUrl = string | null;
|
||||
@@ -126,7 +126,7 @@ export const INDUSTRY_CONFIGS: Record<IndustryType, IndustryData> = {
|
||||
{ id: 'rooms', type: 'rooms', name: '객실 안내', isLocked: false, isEnabled: true, description: '객실 타입, 구조, 비치 물품' },
|
||||
{ id: 'info', type: 'info', name: '기본 정보', isLocked: true, isEnabled: true, description: '체크인, 주차, 시설 핵심 정보' },
|
||||
{ id: 'rules', type: 'rules', name: '이용 규정', isLocked: false, isEnabled: true, description: '환불 규정, 입실 수칙 및 에티켓' },
|
||||
{ id: 'booking', type: 'booking', name: '예약 안내', isLocked: false, isEnabled: true, description: '요금 · 예약 창구 안내' },
|
||||
{ id: 'booking', type: 'booking', name: '실시간 예약', isLocked: false, isEnabled: true, description: '예약 현황 및 예약 신청' },
|
||||
{ id: 'photos', type: 'photos', name: '사진 갤러리', isLocked: false, isEnabled: true, description: '감성 인테리어와 외부 풍경' },
|
||||
{ id: 'map', type: 'map', name: '오시는 길', isLocked: true, isEnabled: true, description: '위치 안내 및 대중교통 경로' },
|
||||
{ id: 'weather', type: 'weather', name: '날씨', isLocked: false, isEnabled: true, description: '현재 기온과 사업장 주변 날씨' },
|
||||
|
||||
@@ -0,0 +1,205 @@
|
||||
import {useCallback, useEffect, useRef, useState, type ReactNode} from 'react';
|
||||
import {ArrowUpRight, ChevronLeft, ChevronRight} from 'lucide-react';
|
||||
import type {TemplateItem} from '@o2o/shared';
|
||||
import {cn} from '@/lib/utils';
|
||||
import type {GuideCard} from '../variants/local/types';
|
||||
import {walkMinutes} from '../variants/local/walking';
|
||||
|
||||
const naverSearch = (q: string) =>
|
||||
`https://search.naver.com/search.naver?query=${encodeURIComponent(q)}`;
|
||||
|
||||
/**
|
||||
* 가이드 카드 한 장 — 사진(좌하단 "도보 약 N분 850m" 배지) · 이름 · 설명 2줄 · "검색으로 열기".
|
||||
*
|
||||
* ★ 사진이 없으면 회색 판에 이름을 크게 쓴다(스크린샷의 '군산복집' 카드). 자리를 비우거나
|
||||
* 남의 사진을 채우지 않는다 — 카드 폭이 들쭉날쭉해지면 캐러셀이 흔들린다.
|
||||
* ★ 거리를 모르면 배지를 생략한다. "도보 N분"은 업장 기준 직선거리에서만 계산한다.
|
||||
*/
|
||||
function GuideCardView({card, colors, leading}: {card: GuideCard; colors: TemplateItem['colors']; leading?: ReactNode}) {
|
||||
const minutes = card.distanceMeters !== undefined ? walkMinutes(card.distanceMeters) : undefined;
|
||||
return (
|
||||
<a
|
||||
href={naverSearch(card.searchQuery)}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
className="group flex w-[240px] shrink-0 snap-start flex-col overflow-hidden rounded-lg border border-stone-200/80 bg-white shadow-2xs transition-shadow hover:shadow-md sm:w-[260px]"
|
||||
>
|
||||
<div className="relative aspect-[4/3] w-full overflow-hidden bg-stone-200/70">
|
||||
{card.imageUrl ? (
|
||||
<img
|
||||
src={card.imageUrl}
|
||||
alt={card.name}
|
||||
loading="lazy"
|
||||
className="size-full object-cover transition-transform duration-300 group-hover:scale-[1.03]"
|
||||
/>
|
||||
) : (
|
||||
<div className="flex size-full items-center justify-center px-4 text-center">
|
||||
<span className="serif-title text-base font-bold text-stone-700">{card.name}</span>
|
||||
</div>
|
||||
)}
|
||||
{minutes !== undefined && (
|
||||
<span className="absolute bottom-2.5 left-2.5 inline-flex items-center gap-1.5 rounded bg-stone-900/80 px-2 py-1 text-[11px] font-semibold text-white backdrop-blur-sm">
|
||||
<span>도보 약 {minutes}분</span>
|
||||
{card.distanceText && <span className="font-mono font-normal text-white/75">{card.distanceText}</span>}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex flex-1 flex-col gap-1.5 p-3.5">
|
||||
{leading}
|
||||
<h4 className="text-sm font-bold text-stone-900" style={{color: colors.text}}>
|
||||
{card.name}
|
||||
</h4>
|
||||
{card.description && (
|
||||
<p className="line-clamp-2 text-xs leading-relaxed text-stone-500">{card.description}</p>
|
||||
)}
|
||||
<span className="mt-auto flex items-center gap-0.5 pt-1 text-[11px] font-medium text-stone-400 group-hover:text-stone-900">
|
||||
검색으로 열기
|
||||
<ArrowUpRight className="size-3" />
|
||||
</span>
|
||||
</div>
|
||||
</a>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 카드 캐러셀 — 가로 스크롤(스냅) + 좌우 화살표 + 점 페이지네이션 + "1 / N".
|
||||
*
|
||||
* ★ 페이지 = 한 화면에 온전히 들어가는 카드 수. 미리보기 해상도(PC/태블릿/모바일)가 바뀌면
|
||||
* ResizeObserver 가 다시 센다 — 고정 4장으로 두면 모바일에서 점이 카드 수와 어긋난다.
|
||||
* ★ 화살표는 컨테이너 폭만큼 넘긴다(한 페이지). 한 장씩 넘기면 24장에 화살표 23번이다.
|
||||
*/
|
||||
export function PlaceCarousel({
|
||||
cards,
|
||||
colors,
|
||||
renderLeading,
|
||||
}: {
|
||||
cards: GuideCard[];
|
||||
colors: TemplateItem['colors'];
|
||||
/** 카드 이름 위에 얹을 배지(축제의 "10월" 등). */
|
||||
renderLeading?: (card: GuideCard) => ReactNode;
|
||||
}) {
|
||||
const trackRef = useRef<HTMLDivElement>(null);
|
||||
const [perPage, setPerPage] = useState(1);
|
||||
const [page, setPage] = useState(0);
|
||||
|
||||
const pages = Math.max(1, Math.ceil(cards.length / perPage));
|
||||
|
||||
// 카드 한 장 폭(gap 포함)으로 한 화면에 몇 장 들어가는지 잰다.
|
||||
const measure = useCallback(() => {
|
||||
const track = trackRef.current;
|
||||
const first = track?.firstElementChild as HTMLElement | null;
|
||||
if (!track || !first) return;
|
||||
const gap = parseFloat(getComputedStyle(track).columnGap || '0') || 0;
|
||||
const step = first.offsetWidth + gap;
|
||||
const fit = Math.max(1, Math.floor((track.clientWidth + gap) / step));
|
||||
setPerPage(fit);
|
||||
setPage(Math.min(Math.round(track.scrollLeft / (step * fit)), Math.max(0, Math.ceil(cards.length / fit) - 1)));
|
||||
}, [cards.length]);
|
||||
|
||||
useEffect(() => {
|
||||
measure();
|
||||
const track = trackRef.current;
|
||||
if (!track) return;
|
||||
const ro = new ResizeObserver(measure);
|
||||
ro.observe(track);
|
||||
return () => ro.disconnect();
|
||||
}, [measure]);
|
||||
|
||||
// 필터가 바뀌어 카드가 줄면 첫 페이지로.
|
||||
useEffect(() => {
|
||||
trackRef.current?.scrollTo({left: 0});
|
||||
setPage(0);
|
||||
}, [cards]);
|
||||
|
||||
const scrollToPage = (next: number) => {
|
||||
const track = trackRef.current;
|
||||
if (!track) return;
|
||||
const clamped = Math.max(0, Math.min(pages - 1, next));
|
||||
track.scrollTo({left: clamped * track.clientWidth, behavior: 'smooth'});
|
||||
setPage(clamped);
|
||||
};
|
||||
|
||||
const onScroll = () => {
|
||||
const track = trackRef.current;
|
||||
if (!track || track.clientWidth === 0) return;
|
||||
setPage(Math.max(0, Math.min(pages - 1, Math.round(track.scrollLeft / track.clientWidth))));
|
||||
};
|
||||
|
||||
const arrow =
|
||||
'flex size-9 cursor-pointer items-center justify-center rounded-full border transition-colors disabled:cursor-default disabled:opacity-30';
|
||||
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
<div className="flex items-center justify-end gap-2">
|
||||
<button
|
||||
type="button"
|
||||
aria-label="이전"
|
||||
disabled={page === 0}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
scrollToPage(page - 1);
|
||||
}}
|
||||
className={cn(arrow, 'border-stone-300/70 bg-white/70 text-stone-500 hover:bg-white')}
|
||||
>
|
||||
<ChevronLeft className="size-4" />
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
aria-label="다음"
|
||||
disabled={page >= pages - 1}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
scrollToPage(page + 1);
|
||||
}}
|
||||
style={{borderColor: colors.text, color: colors.text}}
|
||||
className={cn(arrow, 'bg-white hover:bg-stone-50')}
|
||||
>
|
||||
<ChevronRight className="size-4" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div
|
||||
ref={trackRef}
|
||||
onScroll={onScroll}
|
||||
className="scrollbar-none flex snap-x snap-mandatory gap-4 overflow-x-auto pb-1"
|
||||
>
|
||||
{cards.map((card) => (
|
||||
<GuideCardView
|
||||
key={`${card.name}-${card.distanceMeters ?? ''}`}
|
||||
card={card}
|
||||
colors={colors}
|
||||
leading={renderLeading?.(card)}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{pages > 1 && (
|
||||
<div className="flex items-center justify-center gap-3">
|
||||
<div className="flex items-center gap-1.5">
|
||||
{Array.from({length: pages}, (_, i) => (
|
||||
<button
|
||||
key={i}
|
||||
type="button"
|
||||
aria-label={`${i + 1}페이지`}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
scrollToPage(i);
|
||||
}}
|
||||
className={cn(
|
||||
'h-1.5 cursor-pointer rounded-full transition-all',
|
||||
i === page ? 'w-5' : 'w-1.5 bg-stone-300 hover:bg-stone-400',
|
||||
)}
|
||||
style={i === page ? {backgroundColor: colors.text} : undefined}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
<span className="font-mono text-[11px] text-stone-400">
|
||||
{page + 1} / {pages}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
import type {TemplateItem} from '@o2o/shared';
|
||||
import {cn} from '@/lib/utils';
|
||||
import {
|
||||
WALK_FILTERS,
|
||||
matchesWalkFilter,
|
||||
type WalkFilterKey,
|
||||
} from '../variants/local/walking';
|
||||
|
||||
/**
|
||||
* 도보 시간 필터 탭 — "전체 24 · 걸어서 5분 이내 8 · 10분 이내 19 · 10분 이상 5".
|
||||
*
|
||||
* ★ 구간은 누적이다(walking.ts 주석). 그래서 숫자가 서로 더해져 전체가 되지 않는다 —
|
||||
* "5분 이내" ⊂ "10분 이내". 배타 구간으로 바꾸면 라벨("이내")과 숫자가 어긋난다.
|
||||
* ★ 상태는 부르는 쪽(카테고리 섹션)이 든다. 섹션마다 필터가 따로 움직여야 한다.
|
||||
*/
|
||||
export function WalkFilterTabs({
|
||||
distances,
|
||||
value,
|
||||
onChange,
|
||||
colors,
|
||||
}: {
|
||||
/** 항목별 거리(m). 모르는 항목은 undefined — '전체'에만 센다. */
|
||||
distances: (number | undefined)[];
|
||||
value: WalkFilterKey;
|
||||
onChange: (key: WalkFilterKey) => void;
|
||||
colors: TemplateItem['colors'];
|
||||
}) {
|
||||
return (
|
||||
<div className="flex flex-wrap items-center gap-2" role="tablist" aria-label="도보 시간 필터">
|
||||
{WALK_FILTERS.map(({key, label}) => {
|
||||
const count = distances.filter((m) => matchesWalkFilter(key, m)).length;
|
||||
const active = key === value;
|
||||
return (
|
||||
<button
|
||||
key={key}
|
||||
type="button"
|
||||
role="tab"
|
||||
aria-selected={active}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
onChange(key);
|
||||
}}
|
||||
style={active ? {backgroundColor: colors.text, borderColor: colors.text} : undefined}
|
||||
className={cn(
|
||||
'flex cursor-pointer items-center gap-1.5 rounded-full border px-3.5 py-1.5 text-xs font-semibold transition-colors',
|
||||
active
|
||||
? 'text-white'
|
||||
: 'border-stone-300/80 bg-white/70 text-stone-700 hover:bg-white',
|
||||
)}
|
||||
>
|
||||
<span>{label}</span>
|
||||
<span className={cn('font-mono text-[11px]', active ? 'text-white/80' : 'text-stone-400')}>{count}</span>
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -12,6 +12,8 @@ export {EmptyStateNotice} from './EmptyStateNotice';
|
||||
export {PhotoTile, type TilePhoto} from './PhotoTile';
|
||||
export {Lightbox} from './Lightbox';
|
||||
export {PlaceRow, ListCard} from './PlaceRow';
|
||||
export {PlaceCarousel} from './PlaceCarousel';
|
||||
export {WalkFilterTabs} from './WalkFilterTabs';
|
||||
export {PriceRow, type PricedItem} from './PriceRow';
|
||||
export {AddressCard} from './AddressCard';
|
||||
export {FeatureCard} from './FeatureCard';
|
||||
|
||||
@@ -28,9 +28,7 @@ import {PhotosWithVideos} from './variants/photos/PhotosWithVideos';
|
||||
import {MapDetailed} from './variants/map/MapDetailed';
|
||||
import {MapCompact} from './variants/map/MapCompact';
|
||||
|
||||
import {LocalFull} from './variants/local/LocalFull';
|
||||
import {LocalTabs} from './variants/local/LocalTabs';
|
||||
import {LocalCompact} from './variants/local/LocalCompact';
|
||||
import {LocalGuide} from './variants/local/LocalGuide';
|
||||
import {WeatherSection} from './variants/weather/WeatherSection';
|
||||
|
||||
import {FaqAccordion} from './variants/faq/FaqAccordion';
|
||||
@@ -208,29 +206,17 @@ export const SECTION_VARIANTS: Record<string, SectionVariant[]> = {
|
||||
},
|
||||
],
|
||||
|
||||
// ★ 전체/탭/요약 세 개를 하나로 통일했다(2026-09-07). 저장된 옛 id(local.tabs·local.compact)는
|
||||
// resolveVariant 가 기본값으로 떨어뜨리므로 기존 사이트가 깨지지 않는다.
|
||||
local: [
|
||||
{
|
||||
id: 'local.full',
|
||||
name: '전체',
|
||||
description: '날씨 + 맛집 + 명소 + 축제를 전부 세로로.',
|
||||
id: 'local.guide',
|
||||
name: '가이드',
|
||||
description: '맛집 · 명소 · 축제를 도보 시간으로 걸러 카드로 넘겨 본다.',
|
||||
thumb: 'stack',
|
||||
Component: LocalFull,
|
||||
Component: LocalGuide,
|
||||
isDefault: true,
|
||||
},
|
||||
{
|
||||
id: 'local.tabs',
|
||||
name: '탭 전환',
|
||||
description: '맛집/명소/축제를 탭으로. 화면 길이를 1/3 로 줄인다.',
|
||||
thumb: 'accordion',
|
||||
Component: LocalTabs,
|
||||
},
|
||||
{
|
||||
id: 'local.compact',
|
||||
name: '요약',
|
||||
description: '날씨 한 줄과 추천 6곳만. 주인공이 아닐 때.',
|
||||
thumb: 'compact',
|
||||
Component: LocalCompact,
|
||||
},
|
||||
],
|
||||
|
||||
weather: [
|
||||
|
||||
@@ -1,10 +1,6 @@
|
||||
/**
|
||||
* 예약 · 띠배너 — 브랜드 색으로 화면을 가로지르는 강한 전환 유도.
|
||||
* 예약이 유일한 목표인 사이트에 맞는다(대신 자주 쓰면 광고처럼 보인다).
|
||||
*
|
||||
* ★ 문구에서 "실시간 캘린더" 를 걷어냈다(2026-09-09). 우리는 실시간 재고를 갖지 않는다
|
||||
* (PRODUCT.md 6절). 발행본이 하는 일 그대로 — 날짜·시간을 고르고 예약 창구로 잇는다 —
|
||||
* 을 말한다. 에디터가 보여주는 것이 곧 발행될 것이어야 한다.
|
||||
*/
|
||||
import {Calendar} from 'lucide-react';
|
||||
import {CtaLink, SectionFrame} from '../../primitives';
|
||||
@@ -23,14 +19,14 @@ export function BookingBanner(props: SectionRenderProps) {
|
||||
{section.name}
|
||||
</h3>
|
||||
<p className="text-xs opacity-90 sm:text-sm">
|
||||
{section.body || section.description || `${storeName} · 날짜와 시간을 고르고 예약 창구로 이어집니다`}
|
||||
{section.body || section.description || `${storeName} · 실시간 캘린더에서 남은 날짜를 확인할 수 있습니다`}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="flex shrink-0 items-center gap-2">
|
||||
<CtaLink href={bookingHref(industryId, storeName)} variant="pill">
|
||||
<Calendar className="size-3.5" />
|
||||
<span>날짜 · 시간 고르기</span>
|
||||
<span>예약 캘린더</span>
|
||||
</CtaLink>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -1,146 +1,34 @@
|
||||
/**
|
||||
* 예약 · 카드 — **발행본의 예약 안내를 그대로 미리 보여준다.**
|
||||
*
|
||||
* ★ 왜 갈아엎었나 (2026-09-09)
|
||||
* 이 카드는 "네이버 실시간 온라인 예약 / 캘린더에서 바로 확정 예약" 을 그리고 있었다.
|
||||
* 우리는 실시간 예약을 하지 않는다(PRODUCT.md 6절 — 재고도 결제도 갖지 않는다).
|
||||
* 게다가 발행본은 날짜·시간을 고르는 화면인데 캔버스만 다른 문구를 보여줘서,
|
||||
* 사장님이 편집 화면에서 본 것과 발행된 사이트가 서로 다른 물건이었다.
|
||||
* **에디터가 보여주는 것이 곧 발행될 것**이어야 한다.
|
||||
*
|
||||
* ★ 여기서는 **누르지 않는다.** 캔버스의 클릭은 "이 섹션을 고른다" 는 뜻이라
|
||||
* 상태를 가진 위젯을 넣으면 선택과 싸운다. 첫 칸이 골라진 모습으로 고정해 두고,
|
||||
* 실제 동작은 발행본(`solution/site` StayBookingDemo)이 한다.
|
||||
*
|
||||
* ★ 시간 칸은 **체크인 fact 가 있을 때만** 그린다. 발행본과 같은 규칙이다 —
|
||||
* 체크인이 16:00 인데 미리보기가 14:00 을 보여주면 사장님은 그 선택지가 생긴 줄 안다.
|
||||
* 예약 · 카드 — 가운데 놓인 조용한 안내 카드. 다른 섹션의 흐름을 끊지 않는다.
|
||||
*/
|
||||
import {CalendarDays, Clock, Minus, Phone, Plus} from 'lucide-react';
|
||||
import type {InfoField} from '@o2o/shared';
|
||||
import {SectionBody, SectionFrame, SectionHeading} from '../../primitives';
|
||||
import {Calendar} from 'lucide-react';
|
||||
import {CtaLink, SectionBody, SectionFrame, SectionHeading} from '../../primitives';
|
||||
import type {SectionRenderProps} from '../../types';
|
||||
|
||||
const WEEKDAY_LABEL = ['일', '월', '화', '수', '목', '금', '토'] as const;
|
||||
|
||||
/** 오늘부터 7칸. 캔버스는 브라우저에서만 도므로 날짜를 그대로 그려도 된다
|
||||
* (발행본은 정적 HTML 이라 날짜를 굽지 않는다 — StayBookingDemo 머리주석). */
|
||||
function nextDays(count: number) {
|
||||
const today = new Date();
|
||||
return Array.from({length: count}, (_, index) => {
|
||||
const date = new Date(today.getFullYear(), today.getMonth(), today.getDate() + index);
|
||||
return {day: date.getDate(), weekday: WEEKDAY_LABEL[date.getDay()]};
|
||||
});
|
||||
}
|
||||
|
||||
/** 확인된 값만 읽는다 — 캔버스도 발행본과 같은 규칙이다. */
|
||||
function verified(fields: InfoField[], id: string): string | undefined {
|
||||
const field = fields.find((f) => f.id === id);
|
||||
if (!field || field.requiresVerification || !field.value?.trim()) return undefined;
|
||||
return field.value.trim();
|
||||
}
|
||||
|
||||
function arrivalSlots(checkIn?: string): string[] {
|
||||
const match = /(\d{1,2})\s*:\s*(\d{2})/.exec(checkIn ?? '');
|
||||
if (!match) return [];
|
||||
const start = Number(match[1]);
|
||||
if (!Number.isFinite(start)) return [];
|
||||
return Array.from({length: 4}, (_, i) => start + i)
|
||||
.filter((hour) => hour <= 23)
|
||||
.map((hour) => `${String(hour).padStart(2, '0')}:${match[2]}`);
|
||||
}
|
||||
import {bookingHref} from '../common';
|
||||
|
||||
export function BookingCard(props: SectionRenderProps) {
|
||||
const {section, isSelected, onSelect, template, infoFields} = props;
|
||||
const days = nextDays(7);
|
||||
const checkIn = verified(infoFields, 'check_in_time');
|
||||
const slots = arrivalSlots(checkIn);
|
||||
const phone = verified(infoFields, 'phone');
|
||||
const accent = template.colors.primary;
|
||||
const {section, isSelected, onSelect, industryId, storeName, template} = props;
|
||||
|
||||
return (
|
||||
<SectionFrame section={section} isSelected={isSelected} onSelect={onSelect} tone="white">
|
||||
<SectionBody>
|
||||
<SectionHeading title={section.name} subtitle={section.description} colors={template.colors} />
|
||||
|
||||
<div className="mx-auto max-w-lg overflow-hidden rounded-xl border border-stone-200/80 bg-white shadow-2xs">
|
||||
<p className="flex items-center gap-2 border-b border-stone-200/80 px-4 py-3 text-xs font-bold text-stone-900">
|
||||
<CalendarDays className="size-3.5 text-stone-400" />
|
||||
<span>날짜 · 시간 선택</span>
|
||||
<div className="mx-auto max-w-lg space-y-3 rounded-xl border border-stone-200/80 bg-white p-6 text-center shadow-2xs">
|
||||
<h4 className="text-sm font-bold text-stone-900" style={{color: template.colors.text}}>
|
||||
네이버 실시간 온라인 예약
|
||||
</h4>
|
||||
<p className="text-xs text-stone-500">
|
||||
{section.body || '원하시는 날짜와 객실을 선택하여 캘린더에서 바로 확정 예약하실 수 있습니다.'}
|
||||
</p>
|
||||
|
||||
<div className="space-y-4 p-4">
|
||||
<div>
|
||||
<p className="mb-1.5 text-[11px] font-semibold text-stone-400">날짜</p>
|
||||
<ul className="flex gap-1.5 overflow-hidden">
|
||||
{days.map((day, index) => (
|
||||
<li
|
||||
key={day.day}
|
||||
className="flex w-11 shrink-0 flex-col items-center gap-0.5 rounded-lg border px-2 py-1.5 text-xs"
|
||||
style={
|
||||
index === 0
|
||||
? {borderColor: accent, backgroundColor: accent, color: '#fff'}
|
||||
: {borderColor: 'rgb(231 229 228)', backgroundColor: 'rgb(250 250 249)'}
|
||||
}
|
||||
>
|
||||
<span className="text-[10px] opacity-70">{day.weekday}</span>
|
||||
<span className="font-bold">{day.day}</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
{slots.length > 0 && (
|
||||
<div>
|
||||
<p className="mb-1.5 flex items-center gap-1 text-[11px] font-semibold text-stone-400">
|
||||
<Clock className="size-3" />
|
||||
<span>도착 예정 시간 (체크인 {checkIn} 이후)</span>
|
||||
</p>
|
||||
<ul className="flex flex-wrap gap-1.5">
|
||||
{slots.map((time, index) => (
|
||||
<li
|
||||
key={time}
|
||||
className="rounded-md border px-2.5 py-1 text-xs"
|
||||
style={
|
||||
index === 0
|
||||
? {borderColor: accent, backgroundColor: accent, color: '#fff'}
|
||||
: {borderColor: 'rgb(231 229 228)', backgroundColor: 'rgb(250 250 249)'}
|
||||
}
|
||||
>
|
||||
{time}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex items-center justify-between">
|
||||
<p className="text-[11px] font-semibold text-stone-400">인원</p>
|
||||
<div className="flex items-center gap-2 text-stone-500">
|
||||
<span className="flex size-6 items-center justify-center rounded-md border border-stone-200">
|
||||
<Minus className="size-3" />
|
||||
</span>
|
||||
<span className="w-9 text-center text-sm font-bold text-stone-900">2명</span>
|
||||
<span className="flex size-6 items-center justify-center rounded-md border border-stone-200">
|
||||
<Plus className="size-3" />
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div
|
||||
className="rounded-lg px-4 py-2.5 text-center text-xs font-bold text-white"
|
||||
style={{backgroundColor: accent}}
|
||||
>
|
||||
예약 요청 확인하기
|
||||
</div>
|
||||
|
||||
{/* ★ 실제 예약이 되는 창구. 발행본과 같은 순서다 — 데모 다음에 진짜 창구가 온다. */}
|
||||
{phone && (
|
||||
<p className="flex items-center justify-center gap-1.5 text-[11px] text-stone-500">
|
||||
<Phone className="size-3" />
|
||||
<span>전화 예약 {phone}</span>
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
<CtaLink
|
||||
href={bookingHref(industryId, storeName)}
|
||||
variant="solid"
|
||||
colors={template.colors}
|
||||
>
|
||||
<Calendar className="size-3.5" />
|
||||
<span>네이버 예약 캘린더 열기</span>
|
||||
</CtaLink>
|
||||
</div>
|
||||
</SectionBody>
|
||||
</SectionFrame>
|
||||
|
||||
@@ -55,7 +55,7 @@ export function HeroEditorial(props: SectionRenderProps) {
|
||||
colors={template.colors}
|
||||
>
|
||||
<Calendar className="size-3.5" />
|
||||
<span>예약 안내</span>
|
||||
<span>실시간 예약</span>
|
||||
</CtaLink>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -1,27 +0,0 @@
|
||||
import {useEffect, useState} from 'react';
|
||||
|
||||
/** "실시간 업데이트: 오후 4:41:56" 표시. 1초마다 갱신된다. */
|
||||
export function LiveClock() {
|
||||
const [clock, setClock] = useState('');
|
||||
|
||||
useEffect(() => {
|
||||
const update = () => {
|
||||
const now = new Date();
|
||||
const period = now.getHours() >= 12 ? '오후' : '오전';
|
||||
const hours = now.getHours() % 12 || 12;
|
||||
const minutes = String(now.getMinutes()).padStart(2, '0');
|
||||
const seconds = String(now.getSeconds()).padStart(2, '0');
|
||||
setClock(`${period} ${hours}:${minutes}:${seconds}`);
|
||||
};
|
||||
update();
|
||||
const timer = setInterval(update, 1000);
|
||||
return () => clearInterval(timer);
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<span className="flex items-center gap-1.5 rounded-full border border-stone-200/80 bg-white px-2.5 py-1 text-[11px] text-stone-500 shadow-2xs">
|
||||
<span className="size-1.5 animate-pulse rounded-full bg-emerald-500" />
|
||||
<span>실시간 업데이트: {clock}</span>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
/**
|
||||
* 지역 가이드 · 카테고리 한 묶음 — 제목(아이콘) → 도보 시간 필터 → 카드 캐러셀.
|
||||
*
|
||||
* 맛집·명소·축제가 전부 이 모양이다. 필터 상태는 묶음마다 따로 든다 —
|
||||
* 맛집을 "5분 이내"로 걸렀는데 명소까지 줄어들면 사장님이 명소가 사라진 줄 안다.
|
||||
*/
|
||||
import {useState, type ReactNode} from 'react';
|
||||
import type {LucideIcon} from 'lucide-react';
|
||||
import type {TemplateItem} from '@o2o/shared';
|
||||
import {EmptyStateNotice, PlaceCarousel, WalkFilterTabs} from '../../primitives';
|
||||
import type {GuideCard} from './types';
|
||||
import {matchesWalkFilter, type WalkFilterKey} from './walking';
|
||||
|
||||
export function LocalCategorySection({
|
||||
icon: Icon,
|
||||
title,
|
||||
cards,
|
||||
emptyText,
|
||||
colors,
|
||||
renderLeading,
|
||||
}: {
|
||||
icon: LucideIcon;
|
||||
title: string;
|
||||
cards: GuideCard[];
|
||||
emptyText: string;
|
||||
colors: TemplateItem['colors'];
|
||||
renderLeading?: (card: GuideCard) => ReactNode;
|
||||
}) {
|
||||
const [filter, setFilter] = useState<WalkFilterKey>('all');
|
||||
const visible = cards.filter((c) => matchesWalkFilter(filter, c.distanceMeters));
|
||||
|
||||
return (
|
||||
<section className="space-y-4">
|
||||
<h3
|
||||
className="flex items-center gap-2 text-sm font-bold text-stone-900"
|
||||
style={{color: colors.text}}
|
||||
>
|
||||
<Icon className="size-4" style={{color: colors.primary}} />
|
||||
<span>{title}</span>
|
||||
</h3>
|
||||
|
||||
{cards.length === 0 ? (
|
||||
<EmptyStateNotice>{emptyText}</EmptyStateNotice>
|
||||
) : (
|
||||
<>
|
||||
<WalkFilterTabs
|
||||
distances={cards.map((c) => c.distanceMeters)}
|
||||
value={filter}
|
||||
onChange={setFilter}
|
||||
colors={colors}
|
||||
/>
|
||||
{visible.length === 0 ? (
|
||||
<EmptyStateNotice>이 거리 안에는 아직 없습니다. 다른 구간을 눌러 보세요.</EmptyStateNotice>
|
||||
) : (
|
||||
<PlaceCarousel cards={visible} colors={colors} renderLeading={renderLeading} />
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -1,50 +0,0 @@
|
||||
/**
|
||||
* 지역 가이드 · 요약 — 날씨 한 줄과 추천 6곳만.
|
||||
* 지역 정보가 주인공이 아닌 사이트에서 "있긴 하다" 정도로 둘 때.
|
||||
*/
|
||||
import {
|
||||
EmptyStateNotice,
|
||||
ListCard,
|
||||
PlaceRow,
|
||||
SectionBody,
|
||||
SectionFrame,
|
||||
SectionHeading,
|
||||
} from '../../primitives';
|
||||
import type {SectionRenderProps} from '../../types';
|
||||
|
||||
const naverSearch = (q: string) =>
|
||||
`https://search.naver.com/search.naver?query=${encodeURIComponent(q)}`;
|
||||
|
||||
export function LocalCompact(props: SectionRenderProps) {
|
||||
const {section, isSelected, onSelect, location, template} = props;
|
||||
|
||||
// 맛집·명소를 섞어 딱 6개만. 목록이 길어지면 요약이 아니게 된다.
|
||||
// ★ 지역 정보는 서버(local.local_contents)가 소유하고 캔버스 계약(SectionRenderProps)에 없다.
|
||||
// 시연용 목록(제주 애월)으로 자리를 메우지 않는다 — 남의 동네 맛집이 사장님 사이트에 붙는다.
|
||||
const picks: {name: string; meta: string; description: string; q: string}[] = [];
|
||||
|
||||
return (
|
||||
<SectionFrame section={section} isSelected={isSelected} onSelect={onSelect} tone="paper">
|
||||
<SectionBody width="narrow">
|
||||
<SectionHeading variant="minimal" title="주변 안내" colors={template.colors} />
|
||||
{picks.length === 0 ? (
|
||||
<EmptyStateNotice>주변 추천은 아직 준비 중입니다.</EmptyStateNotice>
|
||||
) : (
|
||||
<ListCard>
|
||||
{picks.map((p) => (
|
||||
<PlaceRow
|
||||
key={p.name}
|
||||
name={p.name}
|
||||
meta={p.meta}
|
||||
description={p.description}
|
||||
href={naverSearch(p.q)}
|
||||
actionLabel="보기"
|
||||
colors={template.colors}
|
||||
/>
|
||||
))}
|
||||
</ListCard>
|
||||
)}
|
||||
</SectionBody>
|
||||
</SectionFrame>
|
||||
);
|
||||
}
|
||||
@@ -1,163 +0,0 @@
|
||||
/**
|
||||
* 지역 가이드 · 전체 — 날씨 카드 + 맛집 + 명소 + 월별 축제를 세로로 전부.
|
||||
* "여기 오면 근처에 뭐가 있나"를 한 화면에서 다 보여주고 싶을 때.
|
||||
*/
|
||||
import {Calendar, MapPin, Sparkles, Utensils} from 'lucide-react';
|
||||
import type {TemplateItem} from '@o2o/shared';
|
||||
import {
|
||||
EmptyStateNotice,
|
||||
ListCard,
|
||||
PlaceRow,
|
||||
Pill,
|
||||
SectionBody,
|
||||
SectionFrame,
|
||||
SectionHeading,
|
||||
} from '../../primitives';
|
||||
import type {SectionRenderProps} from '../../types';
|
||||
import {LiveClock} from './LiveClock';
|
||||
import type {FestivalItem, NearbyPlace} from './types';
|
||||
|
||||
const naverSearch = (q: string) =>
|
||||
`https://search.naver.com/search.naver?query=${encodeURIComponent(q)}`;
|
||||
|
||||
function GroupHeading({
|
||||
icon: Icon,
|
||||
title,
|
||||
note,
|
||||
colors,
|
||||
}: {
|
||||
icon: typeof Utensils;
|
||||
title: string;
|
||||
note: string;
|
||||
colors: TemplateItem['colors'];
|
||||
}) {
|
||||
return (
|
||||
<div className="flex items-center justify-between">
|
||||
<h3
|
||||
className="serif-title flex items-center gap-2 text-base font-bold text-stone-900 sm:text-lg"
|
||||
style={{color: colors.text}}
|
||||
>
|
||||
<Icon className="size-4 text-stone-600" style={{color: colors.primary}} />
|
||||
<span>{title}</span>
|
||||
</h3>
|
||||
{/* 오른쪽 출처 문구는 부가 정보라 중립 회색 그대로 둔다. */}
|
||||
<span className="text-[11px] text-stone-400">{note}</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function LocalFull(props: SectionRenderProps) {
|
||||
const {section, isSelected, onSelect, industryId, location, template} = props;
|
||||
const isStay = industryId === 'stay';
|
||||
const locName = location.split(' ')[0] || '주변';
|
||||
// ★ 맛집·명소·축제는 전부 제주 애월 시연용 목록이다 — 실사업장은 빈 목록으로 떨어진다.
|
||||
// (지역 큐레이션을 읽어올 백엔드 창구가 아직 없어 당분간 계속 빈다.)
|
||||
// 지역 정보는 서버(local.local_contents)가 소유하고 캔버스 계약에 없다 — 시연용 목록을 깔지 않는다.
|
||||
const foods: NearbyPlace[] = [];
|
||||
const spots: NearbyPlace[] = [];
|
||||
const festivals: FestivalItem[] = [];
|
||||
|
||||
return (
|
||||
<SectionFrame section={section} isSelected={isSelected} onSelect={onSelect} tone="paper">
|
||||
<SectionBody className="space-y-8">
|
||||
<SectionHeading
|
||||
variant="eyebrow"
|
||||
eyebrow="AI Local Guide"
|
||||
title={`AI ${locName} 실시간 가이드`}
|
||||
subtitle="실시간 날씨와 인근 미식·명소·축제를 AI가 큐레이션합니다"
|
||||
trailing={<LiveClock />}
|
||||
colors={template.colors}
|
||||
/>
|
||||
|
||||
<div className="space-y-3.5">
|
||||
<GroupHeading
|
||||
icon={Utensils}
|
||||
title="숙소 인근 엄선 맛집 & 카페"
|
||||
note="호스트 & 네이버 플레이스 연동"
|
||||
colors={template.colors}
|
||||
/>
|
||||
{foods.length === 0 ? (
|
||||
<EmptyStateNotice>주변 맛집·카페 추천은 아직 준비 중입니다.</EmptyStateNotice>
|
||||
) : (
|
||||
<ListCard>
|
||||
{foods.map((place) => (
|
||||
<PlaceRow
|
||||
key={place.name}
|
||||
name={place.name}
|
||||
meta={place.distance}
|
||||
description={place.description}
|
||||
href={naverSearch(place.searchQuery)}
|
||||
colors={template.colors}
|
||||
/>
|
||||
))}
|
||||
</ListCard>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="space-y-3.5">
|
||||
<GroupHeading
|
||||
icon={MapPin}
|
||||
title="주변 힐링 명소 & 해변"
|
||||
note="차량 5~20분 거리"
|
||||
colors={template.colors}
|
||||
/>
|
||||
{spots.length === 0 ? (
|
||||
<EmptyStateNotice>주변 명소 추천은 아직 준비 중입니다.</EmptyStateNotice>
|
||||
) : (
|
||||
<ListCard>
|
||||
{spots.map((spot) => (
|
||||
<PlaceRow
|
||||
key={spot.name}
|
||||
name={spot.name}
|
||||
meta={spot.duration}
|
||||
description={spot.description}
|
||||
href={naverSearch(spot.searchQuery)}
|
||||
actionLabel="상세정보"
|
||||
colors={template.colors}
|
||||
/>
|
||||
))}
|
||||
</ListCard>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{isStay && (
|
||||
<div className="space-y-3.5">
|
||||
<GroupHeading
|
||||
icon={Calendar}
|
||||
title="월별 축제 & 문화 행사"
|
||||
note="사계절 캘린더"
|
||||
colors={template.colors}
|
||||
/>
|
||||
{festivals.length === 0 ? (
|
||||
<EmptyStateNotice>월별 축제 안내는 아직 준비 중입니다.</EmptyStateNotice>
|
||||
) : (
|
||||
<ListCard>
|
||||
{festivals.map((fest) => (
|
||||
<PlaceRow
|
||||
key={fest.name}
|
||||
name={fest.name}
|
||||
description={fest.description || fest.period}
|
||||
href={naverSearch(fest.searchQuery)}
|
||||
actionLabel="검색"
|
||||
leading={
|
||||
<>
|
||||
<Pill tone="accent">{fest.month}</Pill>
|
||||
{fest.isFeatured && (
|
||||
<Pill tone="good">
|
||||
<Sparkles className="size-2.5" />
|
||||
대표축제
|
||||
</Pill>
|
||||
)}
|
||||
</>
|
||||
}
|
||||
colors={template.colors}
|
||||
/>
|
||||
))}
|
||||
</ListCard>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</SectionBody>
|
||||
</SectionFrame>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
/**
|
||||
* 지역 가이드 — 맛집 · 명소 · 축제를 카테고리별 "도보 시간 필터 + 카드 캐러셀"로 세로 나열.
|
||||
*
|
||||
* ★ 2026-09-07 결정으로 전체/탭/요약 세 배리에이션을 이 하나로 통일했다.
|
||||
* 데이터가 이미 카테고리별로 나뉘어 있어 "탭으로 갈아끼우기"라는 구분이 캐러셀 구조에서는
|
||||
* 의미가 없어졌고, 요약(6곳)은 필터가 그 역할을 대신한다.
|
||||
* ★ 값은 서버(local.place_contents)가 소유한다 — 업장 좌표 반경으로 받은 것만 그린다.
|
||||
* 시연용 목록으로 자리를 메우지 않는다(남의 동네 맛집이 사장님 사이트에 붙는다).
|
||||
*/
|
||||
import {Calendar, MapPin, Utensils} from 'lucide-react';
|
||||
import {useLocalGuide} from '@/hooks/useLocalGuide';
|
||||
import {Pill, SectionBody, SectionFrame, SectionHeading} from '../../primitives';
|
||||
import type {SectionRenderProps} from '../../types';
|
||||
import type {FestivalCard, GuideCard} from './types';
|
||||
import {LocalCategorySection} from './LocalCategorySection';
|
||||
import {WALK_DISCLAIMER} from './walking';
|
||||
|
||||
/** "2026년 9월 3일 갱신" — 서버 수집 시각(ISO)에서. 없으면 비운다(지어내지 않는다). */
|
||||
function syncedLabel(iso?: string): string | undefined {
|
||||
if (!iso) return undefined;
|
||||
const d = new Date(iso);
|
||||
if (Number.isNaN(d.getTime())) return undefined;
|
||||
return `${d.getFullYear()}년 ${d.getMonth() + 1}월 ${d.getDate()}일 갱신`;
|
||||
}
|
||||
|
||||
/** "전북특별자치도 군산시 …" → "군산시". 시군구 토큰이 없으면 첫 토큰. */
|
||||
function regionLabel(location: string): string {
|
||||
const tokens = location.split(' ').filter(Boolean);
|
||||
return tokens[1] ?? tokens[0] ?? '주변';
|
||||
}
|
||||
|
||||
export function LocalGuide(props: SectionRenderProps) {
|
||||
const {section, isSelected, onSelect, industryId, location, template} = props;
|
||||
const {foods, spots, festivals, syncedAt} = useLocalGuide();
|
||||
const colors = template.colors;
|
||||
const isStay = industryId === 'stay';
|
||||
const synced = syncedLabel(syncedAt);
|
||||
|
||||
return (
|
||||
<SectionFrame section={section} isSelected={isSelected} onSelect={onSelect} tone="paper">
|
||||
<SectionBody width="wide" className="space-y-10">
|
||||
<SectionHeading
|
||||
title={section.name || '주변 안내'}
|
||||
subtitle={`${regionLabel(location)} 지역의 맛집 · 명소 안내입니다.`}
|
||||
trailing={synced && <span className="text-xs text-stone-400">{synced}</span>}
|
||||
colors={colors}
|
||||
/>
|
||||
|
||||
<LocalCategorySection
|
||||
icon={Utensils}
|
||||
title="주변 맛집"
|
||||
cards={foods}
|
||||
emptyText="주변 맛집·카페 추천은 아직 준비 중입니다."
|
||||
colors={colors}
|
||||
/>
|
||||
|
||||
<LocalCategorySection
|
||||
icon={MapPin}
|
||||
title="주변 명소"
|
||||
cards={spots}
|
||||
emptyText="주변 명소 추천은 아직 준비 중입니다."
|
||||
colors={colors}
|
||||
/>
|
||||
|
||||
{isStay && (
|
||||
<LocalCategorySection
|
||||
icon={Calendar}
|
||||
title="주변 축제 & 문화 행사"
|
||||
cards={festivals}
|
||||
emptyText="주변 축제 안내는 아직 준비 중입니다."
|
||||
colors={colors}
|
||||
renderLeading={(card: GuideCard) => {
|
||||
const fest = card as FestivalCard;
|
||||
return (
|
||||
<div className="flex flex-wrap items-center gap-1.5">
|
||||
{fest.month && <Pill tone="accent">{fest.month}</Pill>}
|
||||
{fest.period && <Pill mono>{fest.period}</Pill>}
|
||||
</div>
|
||||
);
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
|
||||
<p className="text-[11px] leading-relaxed text-stone-400">{WALK_DISCLAIMER}</p>
|
||||
</SectionBody>
|
||||
</SectionFrame>
|
||||
);
|
||||
}
|
||||
@@ -1,124 +0,0 @@
|
||||
/**
|
||||
* 지역 가이드 · 탭 — 맛집/명소/축제를 탭으로 갈아 끼운다.
|
||||
* 목록이 길어 스크롤이 부담스러울 때 화면 길이를 1/3 로 줄인다.
|
||||
*/
|
||||
import {useState} from 'react';
|
||||
import {Calendar, MapPin, Utensils} from 'lucide-react';
|
||||
import {cn} from '@/lib/utils';
|
||||
import {
|
||||
EmptyStateNotice,
|
||||
ListCard,
|
||||
Pill,
|
||||
PlaceRow,
|
||||
SectionBody,
|
||||
SectionFrame,
|
||||
SectionHeading,
|
||||
} from '../../primitives';
|
||||
import type {SectionRenderProps} from '../../types';
|
||||
import type {FestivalItem, NearbyPlace} from './types';
|
||||
|
||||
const naverSearch = (q: string) =>
|
||||
`https://search.naver.com/search.naver?query=${encodeURIComponent(q)}`;
|
||||
|
||||
type TabKey = 'food' | 'spots' | 'festivals';
|
||||
|
||||
const TABS: {key: TabKey; label: string; icon: typeof Utensils}[] = [
|
||||
{key: 'food', label: '맛집 · 카페', icon: Utensils},
|
||||
{key: 'spots', label: '명소', icon: MapPin},
|
||||
{key: 'festivals', label: '축제', icon: Calendar},
|
||||
];
|
||||
|
||||
export function LocalTabs(props: SectionRenderProps) {
|
||||
const {section, isSelected, onSelect, industryId, location, template} = props;
|
||||
const [tab, setTab] = useState<TabKey>('food');
|
||||
const isStay = industryId === 'stay';
|
||||
const tabs = isStay ? TABS : TABS.filter((t) => t.key !== 'festivals');
|
||||
const locName = location.split(' ')[0] || '주변';
|
||||
// ★ 세 탭 모두 제주 애월 시연용 목록이다 — 실사업장은 빈 목록으로 떨어진다.
|
||||
// 지역 정보는 서버(local.local_contents)가 소유하고 캔버스 계약에 없다 — 시연용 목록을 깔지 않는다.
|
||||
const foods: NearbyPlace[] = [];
|
||||
const spots: NearbyPlace[] = [];
|
||||
const festivals: FestivalItem[] = [];
|
||||
// 탭을 눌렀는데 아무것도 없으면 섹션이 사라진 것처럼 보인다 — 자리는 지키고 상태만 알린다.
|
||||
const isEmpty = (tab === 'food' ? foods : tab === 'spots' ? spots : festivals).length === 0;
|
||||
|
||||
return (
|
||||
<SectionFrame section={section} isSelected={isSelected} onSelect={onSelect} tone="paper">
|
||||
<SectionBody>
|
||||
<SectionHeading
|
||||
variant="eyebrow"
|
||||
eyebrow="AI Local Guide"
|
||||
title={`AI ${locName} 실시간 가이드`}
|
||||
subtitle="탭을 눌러 원하는 정보만 보세요"
|
||||
colors={template.colors}
|
||||
/>
|
||||
|
||||
<div className="flex items-center gap-1 rounded-xl border border-stone-200/80 bg-white p-1">
|
||||
{tabs.map(({key, label, icon: Icon}) => (
|
||||
<button
|
||||
key={key}
|
||||
type="button"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
setTab(key);
|
||||
}}
|
||||
aria-pressed={tab === key}
|
||||
style={tab === key ? {backgroundColor: template.colors.primary} : undefined}
|
||||
className={cn(
|
||||
'flex flex-1 cursor-pointer items-center justify-center gap-1.5 rounded-lg py-2 text-xs font-semibold transition-colors',
|
||||
tab === key ? 'text-white' : 'text-stone-500 hover:bg-stone-100',
|
||||
)}
|
||||
>
|
||||
<Icon className="size-3.5" />
|
||||
<span>{label}</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{isEmpty ? (
|
||||
<EmptyStateNotice>주변 정보는 아직 준비 중입니다.</EmptyStateNotice>
|
||||
) : (
|
||||
<ListCard>
|
||||
{tab === 'food' &&
|
||||
foods.map((place) => (
|
||||
<PlaceRow
|
||||
key={place.name}
|
||||
name={place.name}
|
||||
meta={place.distance}
|
||||
description={place.description}
|
||||
href={naverSearch(place.searchQuery)}
|
||||
colors={template.colors}
|
||||
/>
|
||||
))}
|
||||
|
||||
{tab === 'spots' &&
|
||||
spots.map((spot) => (
|
||||
<PlaceRow
|
||||
key={spot.name}
|
||||
name={spot.name}
|
||||
meta={spot.duration}
|
||||
description={spot.description}
|
||||
href={naverSearch(spot.searchQuery)}
|
||||
actionLabel="상세정보"
|
||||
colors={template.colors}
|
||||
/>
|
||||
))}
|
||||
|
||||
{tab === 'festivals' &&
|
||||
festivals.map((fest) => (
|
||||
<PlaceRow
|
||||
key={fest.name}
|
||||
name={fest.name}
|
||||
description={fest.description || fest.period}
|
||||
href={naverSearch(fest.searchQuery)}
|
||||
actionLabel="검색"
|
||||
leading={<Pill tone="accent">{fest.month}</Pill>}
|
||||
colors={template.colors}
|
||||
/>
|
||||
))}
|
||||
</ListCard>
|
||||
)}
|
||||
</SectionBody>
|
||||
</SectionFrame>
|
||||
);
|
||||
}
|
||||
@@ -1,32 +1,26 @@
|
||||
/**
|
||||
* 지역 정보 항목의 모양.
|
||||
* 지역 가이드 카드 한 장의 모양(맛집·명소·축제 공통).
|
||||
*
|
||||
* ★ 원래 이 타입들은 시연용 데이터 파일(data/stayData.ts)이 소유했다. 그 파일을 지우면서
|
||||
* 실제로 쓰는 쪽인 여기로 옮겼다 — 타입이 데이터 시드에 매여 있을 이유가 없다.
|
||||
*
|
||||
* ★ 값은 서버(local.local_contents)가 소유한다. 지금은 캔버스 계약(SectionRenderProps)에
|
||||
* 지역 정보가 없어서 배리에이션들이 빈 목록을 그린다. 흘려보낼 창구가 생기면
|
||||
* 이 모양에 맞춰 매핑하면 된다.
|
||||
* ★ 값은 서버(local.place_contents)가 소유한다. hooks/useLocalGuide 가 GET /v1/local/guide
|
||||
* 응답(발행 payload 와 같은 모양)을 이 타입으로 매핑한다.
|
||||
* ★ 도보 시간 배지·필터는 distanceMeters 로 계산한다(walking.ts::walkMinutes, 분속 80m).
|
||||
* distanceMeters 가 없으면(지역 캐시에서 온 수기 항목 등) 배지·필터 대상에서 빠진다 —
|
||||
* 업장 기준 거리를 모르는 값으로 "도보 N분"을 지어내지 않는다.
|
||||
*/
|
||||
export interface NearbyPlace {
|
||||
export interface GuideCard {
|
||||
name: string;
|
||||
category: string;
|
||||
/** 거리 표기("차로 5분", "1.2km") — 원문 그대로 옮긴다. */
|
||||
distance: string;
|
||||
duration: string;
|
||||
description: string;
|
||||
/** 상세 페이지 대신 검색으로 보낸다 — 없는 주소를 지어내지 않기 위해서다. */
|
||||
searchQuery: string;
|
||||
tag: string;
|
||||
imageUrl?: string;
|
||||
distanceMeters?: number;
|
||||
/** 화면 배지에 그대로 쓰는 거리 문자열("850m"/"1.2km"). */
|
||||
distanceText?: string;
|
||||
}
|
||||
|
||||
export interface FestivalItem {
|
||||
/** 축제는 기간·월 배지가 더 붙는다. */
|
||||
export interface FestivalCard extends GuideCard {
|
||||
month: string;
|
||||
name: string;
|
||||
period: string;
|
||||
location: string;
|
||||
description: string;
|
||||
isFeatured?: boolean;
|
||||
officialUrl?: string;
|
||||
searchQuery: string;
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
/**
|
||||
* 도보 시간 환산 — 직선거리(m) → 분.
|
||||
*
|
||||
* ★ 분속 80m 로 나눈다(보통 걸음 4.8km/h). 스크린샷 문구와 같은 기준이며 화면 하단에도 그대로 적는다:
|
||||
* "도보 시간은 숙소에서 잰 직선거리를 분속 80m 로 환산한 값입니다. 실제로 걷는 길은 이보다 길 수 있습니다."
|
||||
* ★ 실측 검증(2026-09-07): 135m→2분 · 297m→4분 · 305m→4분 · 566m→7분 · 13m→1분 — 반올림 + 최소 1분.
|
||||
*/
|
||||
export const WALK_METERS_PER_MINUTE = 80;
|
||||
|
||||
export const WALK_DISCLAIMER =
|
||||
`도보 시간은 숙소에서 잰 직선거리를 분속 ${WALK_METERS_PER_MINUTE}m 로 환산한 값입니다. 실제로 걷는 길은 이보다 길 수 있습니다.`;
|
||||
|
||||
export function walkMinutes(meters: number): number {
|
||||
return Math.max(1, Math.round(meters / WALK_METERS_PER_MINUTE));
|
||||
}
|
||||
|
||||
/**
|
||||
* 도보 시간 필터. ★ 구간은 배타적이 아니라 **누적**이다 — "10분 이내"는 "5분 이내"를 포함한다.
|
||||
* (스크린샷 수치 8·19·5 → 19+5=24=전체 로 확인. "5분 이내"는 "10분 이내"의 부분집합.)
|
||||
*/
|
||||
export type WalkFilterKey = 'all' | 'within5' | 'within10' | 'over10';
|
||||
|
||||
export const WALK_FILTERS: {key: WalkFilterKey; label: string; test: (minutes: number) => boolean}[] = [
|
||||
{key: 'all', label: '전체', test: () => true},
|
||||
{key: 'within5', label: '걸어서 5분 이내', test: (m) => m <= 5},
|
||||
{key: 'within10', label: '걸어서 10분 이내', test: (m) => m <= 10},
|
||||
{key: 'over10', label: '걸어서 10분 이상', test: (m) => m > 10},
|
||||
];
|
||||
|
||||
/** 거리를 모르는 항목은 '전체'에만 들어간다 — 모르는 값으로 구간을 정하지 않는다. */
|
||||
export function matchesWalkFilter(key: WalkFilterKey, meters: number | undefined): boolean {
|
||||
if (key === 'all') return true;
|
||||
if (meters === undefined) return false;
|
||||
const filter = WALK_FILTERS.find((f) => f.key === key);
|
||||
return filter ? filter.test(walkMinutes(meters)) : true;
|
||||
}
|
||||
@@ -129,9 +129,7 @@ export function RoomCard({
|
||||
const action = (
|
||||
<div className="p-4 pt-0 sm:p-5 sm:pt-0">
|
||||
<CtaLink href={bookingUrl} variant="solid" size="sm" colors={colors} block>
|
||||
{/* ★ "실시간 예약 신청" 이었다(2026-09-09 수정). 실시간 재고를 갖지 않으므로
|
||||
누르면 예약이 확정되는 것처럼 읽히면 안 된다 — 발행본과 같은 말로 맞춘다. */}
|
||||
<span>예약 안내 보기</span>
|
||||
<span>실시간 예약 신청</span>
|
||||
<ExternalLink className="size-3.5" />
|
||||
</CtaLink>
|
||||
</div>
|
||||
|
||||
@@ -315,9 +315,7 @@ export const TOKEN_AWARE_VARIANT_IDS = new Set([
|
||||
'photos.with-videos',
|
||||
'map.detailed',
|
||||
'map.compact',
|
||||
'local.full',
|
||||
'local.tabs',
|
||||
'local.compact',
|
||||
'local.guide',
|
||||
'faq.accordion',
|
||||
'faq.open-list',
|
||||
'faq.two-column',
|
||||
|
||||
@@ -32,9 +32,6 @@ function guessChannel(url: string): {channel: LinkChannelCode; label: string} |
|
||||
if (u.includes('blog.naver') || u.includes('cafe.naver')) return null;
|
||||
return {channel: LinkChannel.NAVER_PLACE, label: '네이버 플레이스'};
|
||||
}
|
||||
// 네이버 예약은 플레이스보다 먼저 본다 — 호스트가 booking.naver.com 이라 플레이스 판정에 안 걸리지만,
|
||||
// 순서를 명시해 두지 않으면 나중에 판정 조건이 넓어질 때 조용히 플레이스로 흡수된다.
|
||||
if (u.includes('booking.naver.com')) return {channel: LinkChannel.NAVER_BOOKING, label: '네이버 예약'};
|
||||
if (u.includes('yanolja.com')) return {channel: LinkChannel.YANOLJA, label: '야놀자'};
|
||||
if (u.includes('goodchoice.kr') || u.includes('yeogi.com')) {
|
||||
return {channel: LinkChannel.GOODCHOICE, label: '여기어때'};
|
||||
|
||||
@@ -26,7 +26,6 @@ export const CHANNEL_LABEL: Record<number, string> = {
|
||||
[LinkChannel.YANOLJA]: '야놀자',
|
||||
[LinkChannel.GOODCHOICE]: '여기어때',
|
||||
[LinkChannel.NAVER_PLACE]: '네이버 플레이스',
|
||||
[LinkChannel.NAVER_BOOKING]: '네이버 예약',
|
||||
[LinkChannel.INSTAGRAM]: '인스타그램',
|
||||
[LinkChannel.OFFICIAL_SITE]: '공식 홈페이지',
|
||||
[LinkChannel.BLOG]: '블로그',
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
import {useEffect, useState} from 'react';
|
||||
import type {FestivalCard, GuideCard} from '@/features/builder/canvas/variants/local/types';
|
||||
import {useBuilderStore} from '@/stores/builder';
|
||||
|
||||
export interface LocalGuideData {
|
||||
foods: GuideCard[];
|
||||
spots: GuideCard[];
|
||||
festivals: FestivalCard[];
|
||||
/** 서버가 가장 최근에 수집한 시각(ISO). 아직 아무것도 없으면 undefined. */
|
||||
syncedAt?: string;
|
||||
}
|
||||
|
||||
const EMPTY: LocalGuideData = {foods: [], spots: [], festivals: []};
|
||||
// 종류별 노출 상한. 서버(snapshot._LOCAL_MAX_PER_TYPE)가 같은 수로 자르지만, 화면이 먼저 넘치지 않게 여기서도 막는다.
|
||||
const MAX_PER_TYPE = 20;
|
||||
|
||||
/** 서버 응답 항목 — 발행 payload 의 LocalPlace / FestivalEntry 와 같은 모양(백엔드 ResLocalGuide 주석). */
|
||||
interface GuidePlace {
|
||||
name: string;
|
||||
category: string;
|
||||
searchQuery: string;
|
||||
distanceText?: string;
|
||||
distanceMeters?: number;
|
||||
imageUrl?: string;
|
||||
location?: string;
|
||||
description?: string;
|
||||
}
|
||||
interface GuideFestival extends GuidePlace {
|
||||
month: string;
|
||||
period?: string;
|
||||
officialUrl?: string;
|
||||
}
|
||||
|
||||
function toCard(p: GuidePlace): GuideCard {
|
||||
return {
|
||||
name: p.name,
|
||||
// 설명이 없으면 주소로 대신한다 — 카드에 이름만 덜렁 있는 것보다 어디인지가 낫다.
|
||||
description: p.description ?? p.location ?? '',
|
||||
searchQuery: p.searchQuery,
|
||||
imageUrl: p.imageUrl,
|
||||
distanceMeters: typeof p.distanceMeters === 'number' ? p.distanceMeters : undefined,
|
||||
distanceText: p.distanceText,
|
||||
};
|
||||
}
|
||||
|
||||
function toFestival(f: GuideFestival): FestivalCard {
|
||||
return {
|
||||
...toCard(f),
|
||||
month: f.month,
|
||||
period: f.period ?? '',
|
||||
officialUrl: f.officialUrl,
|
||||
};
|
||||
}
|
||||
|
||||
// 사업장 하나당 한 번만 받는다 — 필터·캐러셀 조작마다 API 를 다시 때리지 않는다.
|
||||
const cache = new Map<string, LocalGuideData>();
|
||||
|
||||
/**
|
||||
* 업장 주변 가이드(맛집·명소·축제). 날씨(useWeather)와 같은 규약이다 —
|
||||
* 실패해도 에러를 띄우지 않고 빈 목록을 유지한다. 부가 정보라 사장님 작업을 막을 이유가 없다.
|
||||
*
|
||||
* ★ 값은 서버(local.place_contents)가 소유하고, 발행본과 같은 필터·모양으로 온다.
|
||||
* 캔버스가 보여주는 목록 = 발행 사이트에 나갈 목록. 첫 조회 때 서버가 채우므로 비어 있는 건 잠깐이다.
|
||||
*/
|
||||
export function useLocalGuide(): LocalGuideData {
|
||||
const placeId = useBuilderStore((s) => s.placeId);
|
||||
const [guide, setGuide] = useState<LocalGuideData>(() => (placeId && cache.get(placeId)) || EMPTY);
|
||||
|
||||
useEffect(() => {
|
||||
if (!placeId) {
|
||||
setGuide(EMPTY);
|
||||
return;
|
||||
}
|
||||
const cached = cache.get(placeId);
|
||||
if (cached) {
|
||||
setGuide(cached);
|
||||
return;
|
||||
}
|
||||
let alive = true;
|
||||
const controller = new AbortController();
|
||||
|
||||
async function fetchGuide() {
|
||||
try {
|
||||
const baseUrl = import.meta.env.VITE_API_BASE_URL ?? 'http://localhost:9800';
|
||||
const query = new URLSearchParams({place_id: placeId!});
|
||||
const res = await fetch(`${baseUrl}/v1/local/guide?${query}`, {signal: controller.signal});
|
||||
if (!res.ok) return;
|
||||
const data = await res.json();
|
||||
if (!data?.result?.success || !alive) return;
|
||||
const next: LocalGuideData = {
|
||||
foods: ((data.restaurants ?? []) as GuidePlace[]).slice(0, MAX_PER_TYPE).map(toCard),
|
||||
spots: ((data.attractions ?? []) as GuidePlace[]).slice(0, MAX_PER_TYPE).map(toCard),
|
||||
festivals: ((data.festivals ?? []) as GuideFestival[]).slice(0, MAX_PER_TYPE).map(toFestival),
|
||||
syncedAt: data.synced_at ?? undefined,
|
||||
};
|
||||
// ★ 빈 응답은 캐시하지 않는다 — 수집 전에 열어둔 화면이 빈 결과를 물고 있으면
|
||||
// 수집이 끝나도 새로고침 전까지 계속 "준비 중"으로 보인다.
|
||||
if (next.foods.length || next.spots.length || next.festivals.length) cache.set(placeId!, next);
|
||||
setGuide(next);
|
||||
} catch {
|
||||
// 빈 목록 유지 — 화면에 에러를 띄우지 않는다.
|
||||
}
|
||||
}
|
||||
|
||||
void fetchGuide();
|
||||
return () => {
|
||||
alive = false;
|
||||
controller.abort();
|
||||
};
|
||||
}, [placeId]);
|
||||
|
||||
return guide;
|
||||
}
|
||||
@@ -77,8 +77,6 @@ export const LinkChannel = {
|
||||
INSTAGRAM: 4,
|
||||
OFFICIAL_SITE: 5,
|
||||
BLOG: 6,
|
||||
/** 네이버 예약 화면 그 자체(m.booking.naver.com). 플레이스 홈과 가른다 — 발행본의 예약 버튼이 쓴다. */
|
||||
NAVER_BOOKING: 7,
|
||||
ETC: 99,
|
||||
} as const;
|
||||
export type LinkChannel = (typeof LinkChannel)[keyof typeof LinkChannel];
|
||||
|
||||
@@ -207,7 +207,9 @@ export interface FestivalEntry {
|
||||
description?: string;
|
||||
officialUrl?: string;
|
||||
searchQuery: string;
|
||||
/** 대표 사진. 권리가 확실한 출처만 — 없으면 카드가 글자만 남는다. */
|
||||
/** 업장 좌표 기준 거리("850m"/"1.2km"). 지역 캐시에서 온 항목엔 없을 수 있다. */
|
||||
distanceText?: string;
|
||||
distanceMeters?: number;
|
||||
imageUrl?: string;
|
||||
}
|
||||
|
||||
|
||||
@@ -534,11 +534,6 @@ export const MOONLIGHT_STAY_PAYLOAD: SitePayload = {
|
||||
{id: 'intro', name: '소개', enabled: true, locked: false},
|
||||
{id: 'rooms', name: '객실 안내', enabled: true, locked: false},
|
||||
{id: 'info', name: '기본 정보', enabled: true, locked: true},
|
||||
// ★ 서버 기본표(`site_payload._DEFAULT_THEME`)의 숙박 목록에 있는 두 섹션이
|
||||
// fixture 에는 빠져 있었다. 그래서 개발 서버로는 이용 규정·예약 안내가 보이지 않아
|
||||
// "발행하면 나오는데 여기서는 안 나온다" 를 확인할 수 없었다.
|
||||
{id: 'rules', name: '이용 규정', enabled: true, locked: false},
|
||||
{id: 'booking', name: '예약 안내', enabled: true, locked: false},
|
||||
{id: 'photos', name: '사진 갤러리', enabled: true, locked: false},
|
||||
{id: 'weather', name: '날씨', enabled: true, locked: false},
|
||||
{id: 'local', name: '지역 정보', enabled: true, locked: false},
|
||||
|
||||
+16
-185
@@ -12,7 +12,7 @@ import {
|
||||
type SitePayload,
|
||||
type UnitInfo,
|
||||
} from '@o2o/shared';
|
||||
import {BOOKING_CHANNELS, UNIT_SPEC, unitBaseRate} from '@/seo/jsonld';
|
||||
import {UNIT_SPEC} from '@/seo/jsonld';
|
||||
|
||||
/**
|
||||
* payload → 화면이 바로 쓰는 모양.
|
||||
@@ -96,15 +96,12 @@ export function unitViews(payload: SitePayload): UnitView[] {
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 카드에 얹는 "얼마부터".
|
||||
*
|
||||
* ★ 숫자를 여기서 고르지 않는다 — `unitBaseRate`(seo/jsonld.ts) 하나가 고른 값을 표기만 한다.
|
||||
* 화면과 JSON-LD 가 각자 계산하면 어긋날 수 있고, 어긋나면 절대규칙 3 위반으로 발행이 막힌다.
|
||||
*/
|
||||
function unitPriceText(unit: UnitInfo): string | undefined {
|
||||
const rate = unitBaseRate(unit);
|
||||
return rate ? `${rate.price.toLocaleString('ko-KR')}원부터` : undefined;
|
||||
const weekday = Number(factText(unit.facts, 'weekday_price')?.replace(/[^0-9]/g, ''));
|
||||
const price = Number(factText(unit.facts, 'price')?.replace(/[^0-9]/g, ''));
|
||||
const base = Number.isFinite(weekday) && weekday > 0 ? weekday : price;
|
||||
if (!Number.isFinite(base) || base <= 0) return undefined;
|
||||
return `${base.toLocaleString('ko-KR')}원부터`;
|
||||
}
|
||||
|
||||
/** 갤러리에 낼 이미지 — 대체 텍스트 없는 것은 뺀다(검색·낭독기 모두 못 읽는다). */
|
||||
@@ -272,7 +269,6 @@ export function exhibitionRows(payload: SitePayload): InfoRow[] {
|
||||
|
||||
/** 채널 코드 → 사람이 읽는 이름. link.title 이 있으면 그쪽이 우선이다. */
|
||||
export const CHANNEL_LABEL: Record<number, string> = {
|
||||
[LinkChannel.NAVER_BOOKING]: '네이버 예약',
|
||||
[LinkChannel.YANOLJA]: '야놀자',
|
||||
[LinkChannel.GOODCHOICE]: '여기어때',
|
||||
[LinkChannel.NAVER_PLACE]: '네이버 플레이스',
|
||||
@@ -287,26 +283,17 @@ export function channelLabel(link: ChannelLink): string {
|
||||
}
|
||||
|
||||
/**
|
||||
* 예약 버튼에 찍을 말.
|
||||
* 예약을 실제로 받는 채널.
|
||||
*
|
||||
* ★ `${channelLabel}에서 예약` 로 일괄 처리하면 네이버 예약이 "네이버 예약에서 예약" 이 된다.
|
||||
* 그리고 이 채널은 다른 채널과 성격이 다르다 — 누르면 **예약 화면 그 자체**가 뜬다.
|
||||
* 그 차이를 버튼이 말해 줘야 손님이 한 번 더 눌러야 하는지 아닌지를 안다.
|
||||
*/
|
||||
export function bookingCtaLabel(link: ChannelLink): string {
|
||||
if (link.channel === LinkChannel.NAVER_BOOKING) return '네이버 예약으로 바로 예약하기';
|
||||
return `${channelLabel(link)}에서 예약`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 예약을 실제로 받는 채널 목록은 `seo/jsonld.ts` 의 `BOOKING_CHANNELS` 한 벌이다.
|
||||
*
|
||||
* ★ 블로그·인스타그램은 그 목록에 없다. 눌러도 예약 화면이 안 나오는 링크를 "예약하기"
|
||||
* 자리에 두면 손님이 예약한 줄 알고 안 온다. 공식 사이트도 없다 — 지금 보고 있는 이
|
||||
* 사이트가 그 자리라, 자기 자신으로 돌려보내는 버튼이 된다.
|
||||
* ★ 화면의 예약 버튼과 JSON-LD 의 `makesOffer.url`·`potentialAction` 이 **같은 링크**를
|
||||
* 가리켜야 한다. 목록을 두 곳에 적으면 그게 조용히 갈라진다.
|
||||
* ★ 블로그·인스타그램은 뺀다. 눌러도 예약 화면이 안 나오는 링크를 "예약하기" 자리에
|
||||
* 두면 손님이 예약한 줄 알고 안 온다. 공식 사이트도 뺀다 — 지금 보고 있는 이 사이트가
|
||||
* 그 자리라, 자기 자신으로 돌려보내는 버튼이 된다.
|
||||
*/
|
||||
const BOOKING_CHANNELS: readonly number[] = [
|
||||
LinkChannel.YANOLJA,
|
||||
LinkChannel.GOODCHOICE,
|
||||
LinkChannel.NAVER_PLACE,
|
||||
];
|
||||
|
||||
/**
|
||||
* 문의를 실제로 받을 수 있는 채널 — 네이버 톡톡·인스타 DM 처럼 말을 걸 수 있는 곳만.
|
||||
@@ -321,164 +308,8 @@ function confirmedLinks(payload: SitePayload, channels: readonly number[]): Chan
|
||||
return payload.links.filter((link) => link.confirmed && channels.includes(link.channel));
|
||||
}
|
||||
|
||||
/**
|
||||
* 예약 버튼에 낼 채널. **BOOKING_CHANNELS 순서대로** 정렬한다 — 예약 화면으로 바로 가는
|
||||
* 채널이 맨 위 버튼이어야 한다.
|
||||
*
|
||||
* ★ 검색 결과 주소는 뺀다. 자동 발견이 `map.naver.com/p/search/…` 를 물어오는 경우가 있고
|
||||
* (실측 2026-09-08), 그걸 "예약" 버튼에 걸면 손님이 검색 화면을 만난다 — 예약하러 온
|
||||
* 사람에게 검색 결과를 주는 건 링크가 없는 것보다 나쁘다. 가게를 특정하지 못하는 주소라
|
||||
* 애초에 예약 창구가 아니다.
|
||||
*/
|
||||
export function bookingLinks(payload: SitePayload): ChannelLink[] {
|
||||
const order = new Map(BOOKING_CHANNELS.map((channel, index) => [channel, index]));
|
||||
return confirmedLinks(payload, BOOKING_CHANNELS)
|
||||
.filter((link) => !isSearchUrl(link.url))
|
||||
.sort((a, b) => (order.get(a.channel) ?? 99) - (order.get(b.channel) ?? 99));
|
||||
}
|
||||
|
||||
/** 가게가 아니라 **검색 결과**를 가리키는 주소인지. */
|
||||
function isSearchUrl(url: string): boolean {
|
||||
return /\/p\/search\/|[?&]query=/.test(url);
|
||||
}
|
||||
|
||||
/**
|
||||
* ─────────────────────────────────────────────────────────────────────────
|
||||
* 숙박 예약 — 손님이 "이 방을 이 값에 이 창구로" 예약할 수 있게 하는 데이터.
|
||||
* ─────────────────────────────────────────────────────────────────────────
|
||||
*
|
||||
* ★ 왜 숙박만 따로 만드나
|
||||
* `bookingRows()` 가 읽는 `reservation_required`·`reservation_channel` 은 **숙박 스키마에
|
||||
* 없는 key** 다(lodging.json 확인). 그래서 숙박으로 발행하면 서버 기본표가 "실시간 예약"
|
||||
* 섹션을 켜 두는데도(`site_payload._DEFAULT_THEME`) 화면에는 전화번호 한 줄만 남았다 —
|
||||
* 요금도, 인원도, 취소 규정도, 예약 창구도 없는 "예약" 섹션이었다.
|
||||
* 펜션·민박은 예약이 곧 매출이고, AI 가 "얼마예요 / 몇 명까지 / 어떻게 예약해요" 에
|
||||
* 답할 근거가 이 자리에 있어야 한다.
|
||||
*
|
||||
* ★ 우리는 예약을 **처리하지 않는다.** 빈 방 재고도 결제도 갖지 않고(PRODUCT.md 6절),
|
||||
* 확정된 예약 채널과 전화로 **보낸다.** 그래서 이 구성은 "예약 폼" 이 아니라
|
||||
* **"예약에 필요한 사실 + 실제로 예약이 되는 창구"** 다. 없는 기능을 화면으로 흉내내면
|
||||
* 손님은 예약한 줄 알고 안 온다.
|
||||
*/
|
||||
|
||||
/**
|
||||
* 예약 전에 반드시 확인해야 하는 fact.
|
||||
*
|
||||
* ★ 이용 규정(`RULE_FACT_KEYS`)과 목록이 겹친다 — 일부러다. 같은 사실이라도 손님이 그것을
|
||||
* 찾는 순간이 다르다(규정은 "어떤 곳인가", 여기는 "예약을 눌러도 되는가"). 두 섹션이
|
||||
* 같이 켜져 있으면 값이 두 번 보이는데, 값이 같으므로 거짓이 되지 않는다.
|
||||
* ★ 프런트 운영시간을 넣는다 — 전화 예약이 1순위인 업소에서 "언제 전화하면 받나" 는
|
||||
* 예약 성공 여부를 가르는 값이다.
|
||||
*/
|
||||
const STAY_BOOKING_NOTICE_KEYS = [
|
||||
'check_in_time',
|
||||
'check_out_time',
|
||||
'cancel_policy',
|
||||
'extra_person_fee',
|
||||
'reception_hours',
|
||||
'cooking_allowed',
|
||||
'pet_allowed',
|
||||
'smoking',
|
||||
] as const;
|
||||
|
||||
/** 예약 창구 한 줄에 필요한 객실 정보. */
|
||||
export interface StayOffer {
|
||||
unitId: string;
|
||||
name: string;
|
||||
/** "기준 2명 · 최대 4명". 확인된 값만으로 만들고, 둘 다 없으면 undefined. */
|
||||
capacityText?: string;
|
||||
/** 주중·주말·성수기 요금. 확인된 것만. */
|
||||
rateRows: InfoRow[];
|
||||
/**
|
||||
* 기준 요금 표기("주중 1박 280,000원").
|
||||
*
|
||||
* ★ 숫자는 `unitBaseRate`(seo/jsonld.ts)가 고른 그 값이다 — JSON-LD 의
|
||||
* `makesOffer.price` 와 **같은 숫자**여야 화면 ↔ 구조화 데이터 대조를 통과한다.
|
||||
*/
|
||||
baseRateText?: string;
|
||||
/** 객실 상세(사진·전체 스펙)는 객실 섹션이 갖고 있다. 한 장 사이트라 앵커다. */
|
||||
href: string;
|
||||
}
|
||||
|
||||
function stayOffers(payload: SitePayload): StayOffer[] {
|
||||
return sanitizeUnits(payload.units).map((unit) => {
|
||||
const standard = factText(unit.facts, 'standard_capacity');
|
||||
const max = factText(unit.facts, 'max_capacity');
|
||||
const rate = unitBaseRate(unit);
|
||||
|
||||
return {
|
||||
unitId: unit.unitId,
|
||||
name: unit.name,
|
||||
capacityText: [standard && `기준 ${standard}`, max && `최대 ${max}`]
|
||||
.filter(Boolean)
|
||||
.join(' · ') || undefined,
|
||||
rateRows: (['weekday_price', 'weekend_price', 'peak_price'] as const)
|
||||
.map((key) => {
|
||||
const value = factText(unit.facts, key);
|
||||
const label = unit.facts.find((f) => f.key === key)?.label ?? key;
|
||||
return value ? {label, value} : null;
|
||||
})
|
||||
.filter((row): row is InfoRow => row !== null),
|
||||
baseRateText: rate ? `${rate.label} ${rate.price.toLocaleString('ko-KR')}원` : undefined,
|
||||
href: '#units',
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
export interface StayBookingView {
|
||||
offers: StayOffer[];
|
||||
notices: InfoRow[];
|
||||
/** 실제로 예약이 되는 채널. 확정된 것만. */
|
||||
links: ChannelLink[];
|
||||
/** 말을 걸 수 있는 채널(네이버 톡톡·인스타 DM). */
|
||||
contacts: ChannelLink[];
|
||||
phone?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* 숙박 예약 구성에 필요한 것 전부. **근거가 하나도 없으면 null** 이다.
|
||||
*
|
||||
* ★ null 을 돌려주는 이유: 섹션을 그릴지 말지를 컴포넌트·상단 내비·하단 탭이 각자
|
||||
* 판단하면 세 곳이 갈라진다. 눌러도 아무 일 없는 "예약" 탭은 고장으로 읽힌다.
|
||||
* 판단은 이 함수 하나가 한다.
|
||||
*/
|
||||
export function stayBookingView(payload: SitePayload): StayBookingView | null {
|
||||
if (payload.place.category !== PlaceCategory.LODGING) return null;
|
||||
|
||||
const view: StayBookingView = {
|
||||
offers: stayOffers(payload).filter(
|
||||
(offer) => offer.rateRows.length > 0 || offer.capacityText !== undefined,
|
||||
),
|
||||
notices: placeRowsByKeys(payload, STAY_BOOKING_NOTICE_KEYS),
|
||||
links: bookingLinks(payload),
|
||||
// ★ 예약 창구로 이미 나가는 채널은 문의에 다시 넣지 않는다. 네이버 플레이스는 두
|
||||
// 목록에 모두 들어 있어서, 그대로 두면 같은 링크가 "예약" 과 "문의" 로 두 번 보인다 —
|
||||
// 손님은 둘이 다른 곳인 줄 알고 어느 쪽을 눌러야 하는지 망설인다.
|
||||
contacts: contactLinks(payload).filter(
|
||||
(contact) => !bookingLinks(payload).some((link) => link.url === contact.url),
|
||||
),
|
||||
phone: payload.place.phone,
|
||||
};
|
||||
|
||||
const empty =
|
||||
view.offers.length === 0 &&
|
||||
view.notices.length === 0 &&
|
||||
view.links.length === 0 &&
|
||||
view.contacts.length === 0 &&
|
||||
!view.phone;
|
||||
|
||||
return empty ? null : view;
|
||||
}
|
||||
|
||||
/**
|
||||
* 섹션 설정에 그 섹션 자체가 있는지.
|
||||
*
|
||||
* ★ `isSectionEnabled()` 와 다르다 — "사장님이 껐다" 와 "payload 에 항목이 아예 없다" 는
|
||||
* 다른 상태다. 항목이 없는 payload(옛 버전·손으로 만든 fixture)에서는 기본으로 내보내고,
|
||||
* **명시적으로 끈 것은 존중한다.** 둘을 같이 묶으면 사장님이 끈 섹션이 되살아난다.
|
||||
*/
|
||||
export function hasSection(payload: SitePayload, id: string): boolean {
|
||||
return payload.theme.sections.some((section) => section.id === id);
|
||||
return confirmedLinks(payload, BOOKING_CHANNELS);
|
||||
}
|
||||
|
||||
export function contactLinks(payload: SitePayload): ChannelLink[] {
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import {PlaceCategory} from '@o2o/shared';
|
||||
import {
|
||||
AboutSection,
|
||||
AnswerBlock,
|
||||
@@ -16,12 +15,11 @@ import {
|
||||
LocationSection,
|
||||
RulesSection,
|
||||
SpaceSection,
|
||||
StayBookingSection,
|
||||
StorySection,
|
||||
UnitsSection,
|
||||
} from '@/sections';
|
||||
import {useSite} from '@/lib/site-context';
|
||||
import {hasSection, isSectionEnabled} from '@/lib/derive';
|
||||
import {isSectionEnabled} from '@/lib/derive';
|
||||
|
||||
/**
|
||||
* StorySection 이 탭으로 묶어 그리는 아이템.
|
||||
@@ -48,7 +46,6 @@ const STORY_KINDS = ['songs', 'people', 'chronicle', 'literature', 'postcard', '
|
||||
*/
|
||||
export function HomePage() {
|
||||
const payload = useSite();
|
||||
const isLodging = payload.place.category === PlaceCategory.LODGING;
|
||||
|
||||
/**
|
||||
* 섹션 id → 발행본 컴포넌트.
|
||||
@@ -66,9 +63,7 @@ export function HomePage() {
|
||||
menu: UnitsSection,
|
||||
programs: UnitsSection,
|
||||
rules: RulesSection,
|
||||
// ★ 숙박은 예약 섹션이 다른 컴포넌트다. 같은 이름의 섹션이 업종에 따라 다른 것을
|
||||
// 그리는 자리는 여기가 유일하다 — 이유는 StayBookingSection 머리주석.
|
||||
booking: isLodging ? StayBookingSection : BookingSection,
|
||||
booking: BookingSection,
|
||||
space: SpaceSection,
|
||||
inquiry: InquirySection,
|
||||
exhibition: ExhibitionSection,
|
||||
@@ -107,13 +102,6 @@ export function HomePage() {
|
||||
|
||||
{/* 섹션 설정에 없더라도 오시는 길은 항상 나간다 — 위치 질의의 근거다. */}
|
||||
{!isSectionEnabled(payload, 'map') && <LocationSection />}
|
||||
|
||||
{/* ★ 숙박에서 예약 안내는 **항목이 없을 때만** 기본으로 낸다.
|
||||
"사장님이 껐다" 와 "payload 에 항목이 아예 없다" 는 다른 상태다(`hasSection`) —
|
||||
옛 payload·손으로 만든 fixture 에는 booking 항목이 없는데, 숙박에서 예약 창구가
|
||||
없는 페이지는 이 업종 질의의 대부분("어떻게 예약해요")에 답을 못 한다.
|
||||
끈 것을 되살리지는 않는다 — 그건 사장님 결정이다. */}
|
||||
{isLodging && !hasSection(payload, 'booking') && <StayBookingSection />}
|
||||
</main>
|
||||
);
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
import {ArrowUpRight, CalendarCheck, Phone} from 'lucide-react';
|
||||
import {useSite} from '@/lib/site-context';
|
||||
import {bookingCtaLabel, bookingLinks, bookingRows, sectionName} from '@/lib/derive';
|
||||
import {bookingLinks, bookingRows, channelLabel, sectionName} from '@/lib/derive';
|
||||
|
||||
/**
|
||||
* 예약 안내.
|
||||
@@ -85,7 +85,7 @@ export function BookingSection() {
|
||||
className="inline-flex items-center gap-1.5 rounded-xl border border-black/10 px-4 py-2.5 text-xs font-semibold transition-colors hover:bg-black/5"
|
||||
style={{backgroundColor: 'var(--color-surface-alt)'}}
|
||||
>
|
||||
<span>{bookingCtaLabel(link)}</span>
|
||||
<span>{channelLabel(link)}</span>
|
||||
<ArrowUpRight className="size-3.5" />
|
||||
</a>
|
||||
))}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import {CalendarCheck, Home, Image as ImageIcon, MapPin, Sparkles} from 'lucide-react';
|
||||
import {Home, Image as ImageIcon, MapPin, Sparkles} from 'lucide-react';
|
||||
import {useSite} from '@/lib/site-context';
|
||||
import {isSectionEnabled, stayBookingView, unitSpec} from '@/lib/derive';
|
||||
import {isSectionEnabled, unitSpec} from '@/lib/derive';
|
||||
import {useActiveSection} from '@/lib/use-active-section';
|
||||
|
||||
/**
|
||||
@@ -20,9 +20,6 @@ export function MobileTabBar() {
|
||||
const tabs = [
|
||||
{id: 'top', label: '홈', icon: Home},
|
||||
...(payload.units.length > 0 ? [{id: 'units', label: spec.label, icon: ImageIcon}] : []),
|
||||
...(stayBookingView(payload) !== null
|
||||
? [{id: 'booking', label: '예약', icon: CalendarCheck}]
|
||||
: []),
|
||||
...(isSectionEnabled(payload, 'local') ? [{id: 'guide', label: '주변', icon: Sparkles}] : []),
|
||||
{id: 'location', label: '위치', icon: MapPin},
|
||||
];
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import {Phone} from 'lucide-react';
|
||||
import {useSite} from '@/lib/site-context';
|
||||
import {isSectionEnabled, stayBookingView, unitSpec} from '@/lib/derive';
|
||||
import {isSectionEnabled, unitSpec} from '@/lib/derive';
|
||||
|
||||
/**
|
||||
* 상단 내비.
|
||||
@@ -19,9 +19,6 @@ export function SiteHeader() {
|
||||
const items = [
|
||||
{label: '소개', href: '#about', show: isSectionEnabled(payload, 'intro')},
|
||||
{label: spec.label, href: '#units', show: payload.units.length > 0},
|
||||
// ★ 숙박에서 예약은 이 사이트의 목적지다. 근거(요금·창구)가 하나도 없으면 링크도 없다 —
|
||||
// 눌러도 아무 일 없는 메뉴는 고장으로 읽힌다. 판단은 stayBookingView() 한 곳이 한다.
|
||||
{label: '예약', href: '#booking', show: stayBookingView(payload) !== null},
|
||||
{label: '주변 정보', href: '#guide', show: isSectionEnabled(payload, 'local')},
|
||||
{label: '오시는 길', href: '#location', show: true},
|
||||
{label: 'FAQ', href: '#faq', show: payload.faqs.length > 0},
|
||||
|
||||
@@ -1,378 +0,0 @@
|
||||
import {useEffect, useMemo, useState} from 'react';
|
||||
import {CalendarDays, Check, Clock, Minus, Phone, Plus, RotateCcw} from 'lucide-react';
|
||||
import {factText, sanitizeUnits, selectPublishable, type SitePayload} from '@o2o/shared';
|
||||
import {useSite} from '@/lib/site-context';
|
||||
import {unitBaseRate} from '@/seo/jsonld';
|
||||
|
||||
/**
|
||||
* 예약 데모 — **화면 안에서만 도는 목업이다.**
|
||||
*
|
||||
* ★ 무엇이 아닌가
|
||||
* 빈 방 재고를 조회하지 않고, 어디에도 접수하지 않으며, 결제도 없다. 네이버 예약·OTA 와
|
||||
* 연동되어 있지 않다(PRODUCT.md 6절 — "사이트는 예약 채널로 보낸다. 거래를 품지 않는다").
|
||||
* 흐름을 눈으로 보기 위한 구성이다.
|
||||
*
|
||||
* ★ 마지막 화면은 고른 내용을 확인해 주고 **진짜 창구(전화)로 잇는다.**
|
||||
* "접수됐다" 고 쓰지 않는다 — 어디에도 보내지 않으므로 사실이 아니다. 반대로 "접수되지
|
||||
* 않았다" 는 경고도 두지 않는다(2026-09-09 결정): 흐름을 보여주는 화면이라 경고문이
|
||||
* 흐름을 가린다. 연동을 붙일 자리는 ConfirmPanel 한 곳이다.
|
||||
*
|
||||
* ★ 날짜는 **브라우저에서** 만든다(mounted 게이트).
|
||||
* 프리렌더가 서버에서 날짜를 구우면 발행 시각의 날짜가 정적 HTML 에 박힌다 — 한 달 뒤
|
||||
* 크롤러가 그 페이지를 읽으면 지난 날짜가 예약 가능일로 적혀 있다. 그건 조용히 거짓이
|
||||
* 되는 종류라, 서버 렌더에서는 안내만 내보내고 달력은 하이드레이션 후에 그린다.
|
||||
*
|
||||
* ★ "마감/잔여" 같은 표시를 만들지 않는다. 우리는 그 값을 모른다 — 그럴듯하게 지어내면
|
||||
* 목업이 아니라 거짓말이 된다. 고를 수 없는 날은 **지난 날짜**뿐이고, 그건 사실이다.
|
||||
*/
|
||||
|
||||
/** 달력에 낼 날짜 수. 두 주면 흐름을 보기에 충분하고, 화면도 한 줄에 들어온다. */
|
||||
const DAY_COUNT = 14;
|
||||
const WEEKDAY_LABEL = ['일', '월', '화', '수', '목', '금', '토'] as const;
|
||||
|
||||
interface DayCell {
|
||||
iso: string;
|
||||
month: number;
|
||||
day: number;
|
||||
weekday: number;
|
||||
/** 토·일은 주말 요금이 붙는 날이다. 요금 계산의 근거가 화면에도 보여야 한다. */
|
||||
isWeekend: boolean;
|
||||
}
|
||||
|
||||
function buildDays(from: Date): DayCell[] {
|
||||
return Array.from({length: DAY_COUNT}, (_, index) => {
|
||||
const date = new Date(from.getFullYear(), from.getMonth(), from.getDate() + index);
|
||||
const weekday = date.getDay();
|
||||
return {
|
||||
iso: `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`,
|
||||
month: date.getMonth() + 1,
|
||||
day: date.getDate(),
|
||||
weekday,
|
||||
isWeekend: weekday === 0 || weekday === 6,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 도착 시간 후보. **체크인 시간 fact 에서 시작한다.**
|
||||
*
|
||||
* ★ 왜 임의의 시간대를 늘어놓지 않나
|
||||
* 이 숙소의 체크인이 16:00 인데 데모가 14:00 을 고르게 두면, 손님은 그 시간에 갈 수 있다고
|
||||
* 읽는다. 확인된 fact 와 어긋나는 선택지는 목업이라도 만들지 않는다.
|
||||
* fact 가 없으면 시간 선택 자체를 내지 않는다(추측한 시간표를 그리는 것보다 낫다).
|
||||
*/
|
||||
function buildArrivalSlots(checkIn?: string): string[] {
|
||||
const match = /(\d{1,2})\s*:\s*(\d{2})/.exec(checkIn ?? '');
|
||||
if (!match) return [];
|
||||
const startHour = Number(match[1]);
|
||||
const minute = match[2];
|
||||
if (!Number.isFinite(startHour)) return [];
|
||||
return Array.from({length: 5}, (_, index) => startHour + index)
|
||||
.filter((hour) => hour <= 23)
|
||||
.map((hour) => `${String(hour).padStart(2, '0')}:${minute}`);
|
||||
}
|
||||
|
||||
interface DemoUnit {
|
||||
unitId: string;
|
||||
name: string;
|
||||
weekdayPrice?: number;
|
||||
weekendPrice?: number;
|
||||
maxCapacity?: number;
|
||||
}
|
||||
|
||||
function demoUnits(payload: SitePayload): DemoUnit[] {
|
||||
return sanitizeUnits(payload.units).map((unit) => {
|
||||
const num = (key: string) => {
|
||||
const value = Number(factText(unit.facts, key)?.replace(/[^0-9]/g, ''));
|
||||
return Number.isFinite(value) && value > 0 ? value : undefined;
|
||||
};
|
||||
return {
|
||||
unitId: unit.unitId,
|
||||
name: unit.name,
|
||||
// 주중 요금은 JSON-LD·요금표와 같은 출처를 쓴다 — 데모라고 다른 숫자를 보이면 안 된다.
|
||||
weekdayPrice: unitBaseRate(unit)?.price,
|
||||
weekendPrice: num('weekend_price'),
|
||||
maxCapacity: num('max_capacity'),
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
export function StayBookingDemo() {
|
||||
const payload = useSite();
|
||||
const units = useMemo(() => demoUnits(payload), [payload]);
|
||||
const checkIn = useMemo(
|
||||
() => selectPublishable(payload.facts).find((fact) => fact.key === 'check_in_time')?.value ?? undefined,
|
||||
[payload],
|
||||
);
|
||||
const slots = useMemo(() => buildArrivalSlots(checkIn), [checkIn]);
|
||||
|
||||
/** ★ 서버 렌더에서는 false — 날짜를 HTML 에 굽지 않기 위한 게이트(머리주석). */
|
||||
const [days, setDays] = useState<DayCell[] | null>(null);
|
||||
useEffect(() => setDays(buildDays(new Date())), []);
|
||||
|
||||
const [dateIso, setDateIso] = useState<string | null>(null);
|
||||
const [slot, setSlot] = useState<string | null>(null);
|
||||
const [unitId, setUnitId] = useState<string | null>(units[0]?.unitId ?? null);
|
||||
const [guests, setGuests] = useState(2);
|
||||
const [submitted, setSubmitted] = useState(false);
|
||||
|
||||
const selectedDay = days?.find((day) => day.iso === dateIso) ?? null;
|
||||
const selectedUnit = units.find((unit) => unit.unitId === unitId) ?? null;
|
||||
const maxGuests = selectedUnit?.maxCapacity ?? 8;
|
||||
|
||||
const price = selectedDay && selectedUnit
|
||||
? (selectedDay.isWeekend ? selectedUnit.weekendPrice ?? selectedUnit.weekdayPrice : selectedUnit.weekdayPrice)
|
||||
: undefined;
|
||||
|
||||
const ready = Boolean(dateIso && selectedUnit && (slots.length === 0 || slot));
|
||||
|
||||
// 객실을 바꾸면 인원이 최대치를 넘을 수 있다 — 고른 값이 조용히 규정을 어기게 두지 않는다.
|
||||
useEffect(() => {
|
||||
setGuests((current) => Math.min(current, selectedUnit?.maxCapacity ?? 8));
|
||||
}, [selectedUnit]);
|
||||
|
||||
if (units.length === 0) return null;
|
||||
|
||||
return (
|
||||
<div
|
||||
className="mt-4 overflow-hidden rounded-2xl border border-black/8 lg:mt-6"
|
||||
style={{backgroundColor: 'var(--color-surface)'}}
|
||||
>
|
||||
<div className="border-b border-black/8 px-4 py-3 sm:px-5">
|
||||
<p className="flex items-center gap-2 text-xs font-bold">
|
||||
<CalendarDays className="size-3.5 opacity-50" />
|
||||
<span>날짜 · 시간 선택</span>
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* 서버 렌더 · 자바스크립트 꺼짐: 달력 대신 사실만 내보낸다(머리주석). */}
|
||||
{days === null ? (
|
||||
<p className="px-4 py-6 text-xs leading-relaxed opacity-60 sm:px-5">
|
||||
날짜 선택은 브라우저에서 열립니다. 실제 예약 가능 여부와 결제는 아래 예약 창구에서
|
||||
확인해 주세요.
|
||||
</p>
|
||||
) : submitted ? (
|
||||
<ConfirmPanel
|
||||
payload={payload}
|
||||
onReset={() => setSubmitted(false)}
|
||||
summary={[
|
||||
selectedDay ? `${selectedDay.month}월 ${selectedDay.day}일(${WEEKDAY_LABEL[selectedDay.weekday]})` : null,
|
||||
slot ? `도착 ${slot}` : null,
|
||||
selectedUnit?.name ?? null,
|
||||
`${guests}명`,
|
||||
]
|
||||
.filter((part): part is string => Boolean(part))
|
||||
.join(' · ')}
|
||||
/>
|
||||
) : (
|
||||
<div className="space-y-5 p-4 sm:p-5">
|
||||
{/* ── 날짜 ─────────────────────────────────────── */}
|
||||
<div>
|
||||
<p className="mb-2 text-[11px] font-semibold opacity-55">날짜</p>
|
||||
<ul className="-mx-1 flex gap-1.5 overflow-x-auto px-1 pb-1">
|
||||
{days.map((day) => {
|
||||
const active = day.iso === dateIso;
|
||||
return (
|
||||
<li key={day.iso}>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setDateIso(day.iso)}
|
||||
aria-pressed={active}
|
||||
className="flex w-13 shrink-0 flex-col items-center gap-0.5 rounded-xl border px-2 py-2 text-xs transition-colors"
|
||||
style={{
|
||||
borderColor: active ? 'var(--color-brand)' : 'rgba(0,0,0,0.10)',
|
||||
backgroundColor: active ? 'var(--color-brand)' : 'var(--color-surface-alt)',
|
||||
color: active ? '#fff' : undefined,
|
||||
}}
|
||||
>
|
||||
<span className="text-[10px] opacity-70">{WEEKDAY_LABEL[day.weekday]}</span>
|
||||
<span className="font-bold">{day.day}</span>
|
||||
</button>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
{selectedDay?.isWeekend && (
|
||||
<p className="mt-1.5 text-[11px] opacity-55">주말 요금이 적용되는 날짜입니다.</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* ── 도착 시간 (체크인 fact 가 있을 때만) ───────── */}
|
||||
{slots.length > 0 && (
|
||||
<div>
|
||||
<p className="mb-2 flex items-center gap-1.5 text-[11px] font-semibold opacity-55">
|
||||
<Clock className="size-3" />
|
||||
<span>도착 예정 시간 (체크인 {checkIn} 이후)</span>
|
||||
</p>
|
||||
<ul className="flex flex-wrap gap-1.5">
|
||||
{slots.map((time) => {
|
||||
const active = time === slot;
|
||||
return (
|
||||
<li key={time}>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setSlot(time)}
|
||||
aria-pressed={active}
|
||||
className="rounded-lg border px-3 py-1.5 text-xs font-medium transition-colors"
|
||||
style={{
|
||||
borderColor: active ? 'var(--color-brand)' : 'rgba(0,0,0,0.10)',
|
||||
backgroundColor: active ? 'var(--color-brand)' : 'var(--color-surface-alt)',
|
||||
color: active ? '#fff' : undefined,
|
||||
}}
|
||||
>
|
||||
{time}
|
||||
</button>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* ── 객실 ─────────────────────────────────────── */}
|
||||
<div>
|
||||
<p className="mb-2 text-[11px] font-semibold opacity-55">객실</p>
|
||||
<ul className="grid gap-1.5 sm:grid-cols-2">
|
||||
{units.map((unit) => {
|
||||
const active = unit.unitId === unitId;
|
||||
return (
|
||||
<li key={unit.unitId}>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setUnitId(unit.unitId)}
|
||||
aria-pressed={active}
|
||||
className="flex w-full items-center justify-between gap-2 rounded-xl border px-3 py-2.5 text-left text-xs transition-colors"
|
||||
style={{
|
||||
borderColor: active ? 'var(--color-brand)' : 'rgba(0,0,0,0.10)',
|
||||
backgroundColor: 'var(--color-surface-alt)',
|
||||
}}
|
||||
>
|
||||
<span className="font-semibold">{unit.name}</span>
|
||||
{unit.maxCapacity && (
|
||||
<span className="shrink-0 opacity-55">최대 {unit.maxCapacity}명</span>
|
||||
)}
|
||||
</button>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
{/* ── 인원 ─────────────────────────────────────── */}
|
||||
<div className="flex items-center justify-between">
|
||||
<p className="text-[11px] font-semibold opacity-55">인원</p>
|
||||
<div className="flex items-center gap-3">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setGuests((n) => Math.max(1, n - 1))}
|
||||
aria-label="인원 줄이기"
|
||||
className="flex size-7 items-center justify-center rounded-lg border border-black/10 transition-colors hover:bg-black/5"
|
||||
>
|
||||
<Minus className="size-3.5" />
|
||||
</button>
|
||||
<span className="w-10 text-center text-sm font-bold">{guests}명</span>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setGuests((n) => Math.min(maxGuests, n + 1))}
|
||||
aria-label="인원 늘리기"
|
||||
className="flex size-7 items-center justify-center rounded-lg border border-black/10 transition-colors hover:bg-black/5"
|
||||
>
|
||||
<Plus className="size-3.5" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* ── 요약 · 요청 ──────────────────────────────── */}
|
||||
<div className="rounded-xl border border-black/8 p-3" style={{backgroundColor: 'var(--color-surface-alt)'}}>
|
||||
<div className="flex items-baseline justify-between gap-3">
|
||||
<span className="text-xs opacity-60">
|
||||
{selectedDay
|
||||
? `${selectedDay.month}월 ${selectedDay.day}일 · ${selectedUnit?.name ?? ''} · ${guests}명`
|
||||
: '날짜를 골라 주세요'}
|
||||
</span>
|
||||
{price != null && (
|
||||
<span className="text-sm font-bold" style={{color: 'var(--color-brand)'}}>
|
||||
{price.toLocaleString('ko-KR')}원
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
{/* 요금은 확인된 요금 fact 를 그대로 읽은 값이지, 견적이 아니다. */}
|
||||
{price != null && (
|
||||
<p className="mt-1 text-[11px] opacity-50">
|
||||
1박 기준 안내 요금입니다. 인원 추가·성수기 요금은 예약 창구에서 확인됩니다.
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
disabled={!ready}
|
||||
onClick={() => setSubmitted(true)}
|
||||
className="w-full rounded-xl px-4 py-3 text-sm font-bold text-white transition-opacity disabled:cursor-not-allowed disabled:opacity-40"
|
||||
style={{backgroundColor: 'var(--color-brand)'}}
|
||||
>
|
||||
예약 요청 확인하기
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 확인 화면 — 고른 내용을 보여주고 예약 창구로 잇는다.
|
||||
*
|
||||
* ★ "접수됐다" 고 쓰지 않는다. 어디에도 보내지 않으므로 그건 사실이 아니고, 목업이라도
|
||||
* 화면에 없는 일을 일어난 것처럼 적으면 그때부터는 목업이 아니라 거짓말이다.
|
||||
* 반대로 "접수되지 않았다" 는 안내도 두지 않는다(2026-09-09 결정) — 흐름만 보여주는
|
||||
* 화면이라 경고문이 오히려 흐름을 가린다. 그래서 **선택 내용 확인**까지만 말한다.
|
||||
*/
|
||||
function ConfirmPanel({
|
||||
payload,
|
||||
summary,
|
||||
onReset,
|
||||
}: {
|
||||
payload: SitePayload;
|
||||
summary: string;
|
||||
onReset: () => void;
|
||||
}) {
|
||||
const phone = payload.place.phone;
|
||||
|
||||
return (
|
||||
<div className="space-y-4 p-4 sm:p-5">
|
||||
<div className="flex items-start gap-2.5">
|
||||
<span
|
||||
className="mt-0.5 flex size-7 shrink-0 items-center justify-center rounded-full text-white"
|
||||
style={{backgroundColor: 'var(--color-brand)'}}
|
||||
>
|
||||
<Check className="size-4" />
|
||||
</span>
|
||||
<div className="min-w-0">
|
||||
<p className="text-sm font-bold">예약 내용 확인</p>
|
||||
<p className="mt-0.5 text-xs leading-relaxed opacity-70">{summary}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col gap-2 sm:flex-row">
|
||||
{phone && (
|
||||
<a
|
||||
href={`tel:${phone}`}
|
||||
className="flex flex-1 items-center justify-center gap-2 rounded-xl px-4 py-3 text-sm font-bold text-white transition-opacity hover:opacity-90"
|
||||
style={{backgroundColor: 'var(--color-brand)'}}
|
||||
>
|
||||
<Phone className="size-4" />
|
||||
<span>전화로 예약하기 {phone}</span>
|
||||
</a>
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
onClick={onReset}
|
||||
className="flex items-center justify-center gap-1.5 rounded-xl border border-black/10 px-4 py-3 text-xs font-semibold transition-colors hover:bg-black/5"
|
||||
>
|
||||
<RotateCcw className="size-3.5" />
|
||||
<span>다시 고르기</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,209 +0,0 @@
|
||||
import {ArrowUpRight, BedDouble, CalendarCheck, Phone, ShieldCheck} from 'lucide-react';
|
||||
import {useSite} from '@/lib/site-context';
|
||||
import {bookingCtaLabel, channelLabel, sectionName, stayBookingView} from '@/lib/derive';
|
||||
import {StayBookingDemo} from './StayBookingDemo';
|
||||
|
||||
/**
|
||||
* 숙박 예약 구성 — 손님이 **이 방을 · 이 값에 · 이 창구로** 예약할 수 있는 자리.
|
||||
*
|
||||
* ★ 왜 `BookingSection` 과 따로 있나
|
||||
* 그쪽이 읽는 fact(`reservation_required`·`reservation_channel`)는 **숙박 스키마에 없다.**
|
||||
* 그래서 펜션·민박으로 발행하면 서버 기본표가 켜 두는 "실시간 예약" 섹션에 전화번호
|
||||
* 한 줄만 남았다 — 요금도 인원도 취소 규정도 없는 예약 섹션이었다. 숙박은 예약이
|
||||
* 곧 매출이고, "얼마예요 / 몇 명까지 / 어떻게 예약해요" 가 이 업종 질의의 대부분이다.
|
||||
*
|
||||
* ★ 예약을 **처리하지 않는다.** 우리는 빈 방 재고도 결제도 갖지 않는다(PRODUCT.md 6절 —
|
||||
* "사이트는 예약 채널로 보낸다. 거래를 품지 않는다"). 그래서 날짜 선택기·예약 폼을
|
||||
* 그리지 않는다. 없는 기능을 화면으로 흉내내면 손님은 예약한 줄 알고 안 오고,
|
||||
* 그 클레임은 사장님이 받는다. 대신 **예약에 필요한 사실**과 **실제로 예약이 되는 창구**를
|
||||
* 한자리에 모은다.
|
||||
*
|
||||
* ★ 지어낸 값이 없다. 요금·인원·취소 규정은 확인된 fact 뿐이고(`stayBookingView`),
|
||||
* 예약 버튼은 확정된 채널 URL 뿐이다. 근거가 하나도 없으면 섹션째 그리지 않는다 —
|
||||
* 그 판단도 `stayBookingView()` 한 곳이 한다(상단 내비·하단 탭이 같은 함수를 본다).
|
||||
*
|
||||
* ★ 기준 요금 숫자는 `unitBaseRate`(seo/jsonld.ts)가 고른 값이다. JSON-LD `makesOffer.price`
|
||||
* 와 같은 숫자여야 절대규칙 3(화면 = 구조화 데이터) 대조를 통과한다.
|
||||
*/
|
||||
export function StayBookingSection() {
|
||||
const payload = useSite();
|
||||
const view = stayBookingView(payload);
|
||||
|
||||
if (!view) return null;
|
||||
|
||||
const {offers, notices, links, contacts, phone} = view;
|
||||
|
||||
return (
|
||||
<section
|
||||
id="booking"
|
||||
aria-labelledby="booking-heading"
|
||||
className="w-full border-b border-black/8 py-16 sm:py-24"
|
||||
style={{backgroundColor: 'var(--color-surface-alt)'}}
|
||||
>
|
||||
<div className="shell">
|
||||
<p className="mb-2 flex items-center gap-2 text-xs font-semibold uppercase tracking-wider opacity-50">
|
||||
<CalendarCheck className="size-4" />
|
||||
<span>Reservation</span>
|
||||
</p>
|
||||
|
||||
<h2
|
||||
id="booking-heading"
|
||||
className="serif mb-2 text-2xl font-bold tracking-tight sm:text-3xl lg:text-4xl"
|
||||
>
|
||||
{sectionName(payload, 'booking', '예약 안내')}
|
||||
</h2>
|
||||
{/* ★ "여기서 결제되지 않는다"를 먼저 말한다. 예약 버튼을 누른 뒤에 알게 되면
|
||||
손님은 속은 것으로 느끼고, 그 인상은 업소가 가져간다. */}
|
||||
<p className="mb-8 max-w-2xl text-xs leading-relaxed opacity-60 sm:text-sm">
|
||||
빈 방 확인과 결제는 아래 예약 창구에서 진행됩니다. 이 페이지에서는 요금과 이용 조건만
|
||||
안내합니다.
|
||||
</p>
|
||||
|
||||
<div className="grid grid-cols-1 gap-4 lg:grid-cols-5 lg:gap-6">
|
||||
{/* ── 객실별 요금 · 인원 ───────────────────────────────── */}
|
||||
{offers.length > 0 && (
|
||||
<div
|
||||
className="overflow-hidden rounded-2xl border border-black/8 lg:col-span-3"
|
||||
style={{backgroundColor: 'var(--color-surface)'}}
|
||||
>
|
||||
<p className="flex items-center gap-2 border-b border-black/8 px-4 py-3 text-xs font-bold sm:px-5">
|
||||
<BedDouble className="size-3.5 opacity-50" />
|
||||
<span>객실별 요금 · 인원</span>
|
||||
</p>
|
||||
|
||||
<ul className="divide-y divide-black/5">
|
||||
{offers.map((offer) => (
|
||||
<li key={offer.unitId} className="p-4 sm:p-5">
|
||||
<div className="flex flex-wrap items-baseline justify-between gap-x-3 gap-y-1">
|
||||
<h3 className="serif text-base font-bold sm:text-lg">{offer.name}</h3>
|
||||
{offer.baseRateText && (
|
||||
<span className="text-sm font-bold" style={{color: 'var(--color-brand)'}}>
|
||||
{offer.baseRateText}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{offer.capacityText && (
|
||||
<p className="mt-1 text-xs opacity-60">{offer.capacityText}</p>
|
||||
)}
|
||||
|
||||
{offer.rateRows.length > 0 && (
|
||||
<dl className="mt-3 flex flex-wrap gap-x-4 gap-y-1.5">
|
||||
{offer.rateRows.map((row) => (
|
||||
<div key={row.label} className="flex items-baseline gap-1.5 text-xs">
|
||||
<dt className="opacity-50">{row.label}</dt>
|
||||
<dd className="font-semibold">{row.value}</dd>
|
||||
</div>
|
||||
))}
|
||||
</dl>
|
||||
)}
|
||||
|
||||
{/* 사진·전체 스펙은 객실 섹션이 갖고 있다. 한 장 사이트라 앵커다. */}
|
||||
<a
|
||||
href={offer.href}
|
||||
className="mt-3 inline-flex items-center gap-1 text-xs font-semibold underline decoration-black/20 underline-offset-4 transition-opacity hover:opacity-70"
|
||||
>
|
||||
<span>{offer.name} 사진 · 상세 보기</span>
|
||||
</a>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* ── 예약 창구 ──────────────────────────────────────── */}
|
||||
<div
|
||||
className="flex h-fit flex-col gap-3 rounded-2xl border border-black/8 p-4 sm:p-5 lg:col-span-2"
|
||||
style={{backgroundColor: 'var(--color-surface)'}}
|
||||
>
|
||||
<p className="text-xs font-bold">예약 창구</p>
|
||||
|
||||
{phone && (
|
||||
<a
|
||||
href={`tel:${phone}`}
|
||||
className="flex items-center justify-center gap-2 rounded-xl px-4 py-3 text-sm font-bold text-white transition-opacity hover:opacity-90"
|
||||
style={{backgroundColor: 'var(--color-brand)'}}
|
||||
>
|
||||
<Phone className="size-4" />
|
||||
<span>전화 예약 {phone}</span>
|
||||
</a>
|
||||
)}
|
||||
|
||||
{/* ★ 확정된 채널만 나간다 — 확정 전 URL 은 동명 업소의 예약 페이지일 수 있다.
|
||||
눌렀는데 남의 숙소가 뜨면 그 예약은 영영 우리 것이 아니다. */}
|
||||
{links.map((link) => (
|
||||
<a
|
||||
key={link.url}
|
||||
href={link.url}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="flex items-center justify-between gap-2 rounded-xl border border-black/10 px-4 py-3 text-xs font-semibold transition-colors hover:bg-black/5"
|
||||
style={{backgroundColor: 'var(--color-surface-alt)'}}
|
||||
>
|
||||
<span>{bookingCtaLabel(link)}</span>
|
||||
<ArrowUpRight className="size-3.5 shrink-0" />
|
||||
</a>
|
||||
))}
|
||||
|
||||
{contacts.length > 0 && (
|
||||
<div className="mt-1 border-t border-black/8 pt-3">
|
||||
<p className="mb-2 text-xs opacity-50">문의</p>
|
||||
<ul className="flex flex-wrap gap-2">
|
||||
{contacts.map((link) => (
|
||||
<li key={link.url}>
|
||||
<a
|
||||
href={link.url}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="inline-flex items-center gap-1 rounded-lg border border-black/10 px-2.5 py-1.5 text-xs transition-colors hover:bg-black/5"
|
||||
>
|
||||
<span>{channelLabel(link)}</span>
|
||||
<ArrowUpRight className="size-3" />
|
||||
</a>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{links.length === 0 && (
|
||||
// 채널이 하나도 확정되지 않은 업소 — 전화가 유일한 창구다. 그 사실을 말해 준다.
|
||||
<p className="text-xs leading-relaxed opacity-55">
|
||||
온라인 예약 채널은 등록되지 않았습니다. 예약은 전화로 문의해 주세요.
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* ── 날짜 · 시간 선택 (화면 안에서만 도는 목업) ────────── */}
|
||||
<StayBookingDemo />
|
||||
|
||||
{/* ── 예약 전 확인 ────────────────────────────────────── */}
|
||||
{notices.length > 0 && (
|
||||
<div
|
||||
className="mt-4 overflow-hidden rounded-2xl border border-black/8 lg:mt-6"
|
||||
style={{backgroundColor: 'var(--color-surface)'}}
|
||||
>
|
||||
<p className="flex items-center gap-2 border-b border-black/8 px-4 py-3 text-xs font-bold sm:px-5">
|
||||
<ShieldCheck className="size-3.5 opacity-50" />
|
||||
<span>예약 전 확인</span>
|
||||
</p>
|
||||
|
||||
{/* 확인된 fact 만 줄이 된다 — "확인 중" 이라는 빈 줄을 그리면 손님은 그걸 규정으로 읽는다. */}
|
||||
<dl className="grid grid-cols-1 divide-y divide-black/5 sm:grid-cols-2 sm:divide-y-0">
|
||||
{notices.map((row) => (
|
||||
<div
|
||||
key={row.label}
|
||||
className="flex flex-col gap-1 p-4 sm:flex-row sm:items-start sm:justify-between sm:gap-4 sm:p-5"
|
||||
>
|
||||
<dt className="shrink-0 text-xs opacity-55">{row.label}</dt>
|
||||
<dd className="text-xs font-semibold sm:max-w-[60%] sm:text-right">{row.value}</dd>
|
||||
</div>
|
||||
))}
|
||||
</dl>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -6,9 +6,6 @@ export {EssentialInfoSection} from './EssentialInfoSection';
|
||||
export {UnitsSection} from './UnitsSection';
|
||||
export {RulesSection} from './RulesSection';
|
||||
export {BookingSection} from './BookingSection';
|
||||
// 숙박은 예약 구성이 통째로 다르다 — 이유는 StayBookingSection 머리주석.
|
||||
export {StayBookingSection} from './StayBookingSection';
|
||||
export {StayBookingDemo} from './StayBookingDemo';
|
||||
export {SpaceSection} from './SpaceSection';
|
||||
export {InquirySection} from './InquirySection';
|
||||
export {ExhibitionSection} from './ExhibitionSection';
|
||||
|
||||
@@ -1,304 +0,0 @@
|
||||
/**
|
||||
* 숙박 예약 구성 — 이 검사가 지키는 것.
|
||||
*
|
||||
* 1. 미검증 fact·확정 전 링크가 예약 화면에 새지 않는다(절대규칙 1).
|
||||
* 예약은 틀리면 바로 클레임이 나는 자리다 — 확인 안 된 요금이나 남의 숙소 예약 링크가
|
||||
* 한 번 나가면 손님은 헛걸음하고, 그 전화는 사장님이 받는다.
|
||||
* 2. 화면의 요금과 JSON-LD 의 `makesOffer.price` 가 **같은 숫자**다(절대규칙 3).
|
||||
* 갈라지면 발행 게이트가 사이트를 막는다 — 조용히 틀리는 게 아니라 발행이 멈추는 종류다.
|
||||
* 3. 예약 액션이 **실제로 예약이 되는 URL** 만 가리킨다.
|
||||
* 확정 전 채널을 `potentialAction` 에 넣으면 AI 가 그 주소로 손님을 보낸다.
|
||||
*/
|
||||
import {describe, expect, it} from 'vitest';
|
||||
|
||||
import {
|
||||
LinkChannel,
|
||||
PlaceCategory,
|
||||
FactStatus,
|
||||
sanitizePayloadForPublish,
|
||||
type SitePayload,
|
||||
} from '@o2o/shared';
|
||||
import {MOONLIGHT_STAY_PAYLOAD} from '@/fixtures/moonlight-stay';
|
||||
import {stayBookingView} from '@/lib/derive';
|
||||
import {collectJsonLd} from '@/seo/jsonld';
|
||||
import {renderLlmsTxt} from '@/seo/llms';
|
||||
import {verifyJsonLd, visibleText} from '@/seo/verify';
|
||||
import {render} from '@/entry-server';
|
||||
import {homeMeta} from '@/seo/meta';
|
||||
import {renderHead} from '@/seo/head';
|
||||
|
||||
const PAGE = {title: '달빛스테이 제주', description: '제주 애월 독채 펜션'};
|
||||
|
||||
/** 확정 전 야놀자 링크 — fixture 가 일부러 남겨 둔 값이다. */
|
||||
const UNCONFIRMED_URL = 'https://www.yanolja.com/pension/0000000';
|
||||
|
||||
/**
|
||||
* 프리렌더가 굽는 문서와 **같은 모양**으로 만든다.
|
||||
*
|
||||
* ★ 앱 마크업만 놓고 대조하면 안 된다 — canonical·og:image 처럼 head 로 나가는 값과
|
||||
* 하이드레이션 블롭이 빠져서, 멀쩡한 값이 "화면에 없다" 로 잡힌다(실측 12건).
|
||||
* 검사는 **나갈 그 HTML** 에 대고 해야 의미가 있다(verify.ts 머리주석).
|
||||
* ★ 자산 경로는 이 검사와 무관하므로 고정 문자열을 쓴다.
|
||||
*/
|
||||
function html(input: SitePayload = MOONLIGHT_STAY_PAYLOAD): string {
|
||||
const payload = sanitizePayloadForPublish(input);
|
||||
const meta = homeMeta(payload);
|
||||
const head = renderHead({
|
||||
payload,
|
||||
meta,
|
||||
scriptSrc: '/assets/index.js',
|
||||
cssHrefs: ['/assets/index.css'],
|
||||
});
|
||||
return [
|
||||
'<!doctype html><html lang="ko"><head>',
|
||||
head,
|
||||
'</head><body>',
|
||||
`<div id="root">${render(payload)}</div>`,
|
||||
`<script>window.__SITE_PAYLOAD__=${JSON.stringify(payload)}</script>`,
|
||||
'</body></html>',
|
||||
].join('\n');
|
||||
}
|
||||
|
||||
describe('stayBookingView — 예약에 쓸 값을 고르는 자리', () => {
|
||||
it('숙박이 아니면 아무것도 돌려주지 않는다 — 다른 업종은 BookingSection 이 그린다', () => {
|
||||
const cafe = {
|
||||
...MOONLIGHT_STAY_PAYLOAD,
|
||||
place: {...MOONLIGHT_STAY_PAYLOAD.place, category: PlaceCategory.CAFE},
|
||||
};
|
||||
expect(stayBookingView(cafe)).toBeNull();
|
||||
});
|
||||
|
||||
it('확정된 예약 채널만 창구가 된다 — 확정 전 URL 은 동명 업소일 수 있다', () => {
|
||||
const view = stayBookingView(MOONLIGHT_STAY_PAYLOAD)!;
|
||||
expect(view.links.map((link) => link.url)).not.toContain(UNCONFIRMED_URL);
|
||||
expect(view.links).toHaveLength(1); // 네이버 플레이스만 확정됨
|
||||
});
|
||||
|
||||
it('미검증 fact 는 예약 전 확인에 오르지 않는다', () => {
|
||||
const withUnverifiedPolicy = {
|
||||
...MOONLIGHT_STAY_PAYLOAD,
|
||||
facts: MOONLIGHT_STAY_PAYLOAD.facts.map((fact) =>
|
||||
fact.key === 'cancel_policy' ? {...fact, status: FactStatus.UNVERIFIED} : fact,
|
||||
),
|
||||
};
|
||||
const labels = stayBookingView(withUnverifiedPolicy)!.notices.map((row) => row.label);
|
||||
expect(labels).not.toContain('취소·환불 규정');
|
||||
// 확인된 나머지는 그대로 남는다 — 한 건이 빠졌다고 표가 사라지면 안 된다.
|
||||
expect(labels).toContain('체크인 시간');
|
||||
});
|
||||
|
||||
it('근거가 하나도 없으면 null 이다 — 눌러도 아무 일 없는 예약 메뉴를 만들지 않는다', () => {
|
||||
const bare: SitePayload = {
|
||||
...MOONLIGHT_STAY_PAYLOAD,
|
||||
place: {...MOONLIGHT_STAY_PAYLOAD.place, phone: undefined},
|
||||
facts: [],
|
||||
units: [],
|
||||
links: [],
|
||||
};
|
||||
expect(stayBookingView(bare)).toBeNull();
|
||||
});
|
||||
|
||||
it('기준 요금 표기는 어느 요금인지 밝힌다 — 밝히지 않은 가격은 그 자체로 오해다', () => {
|
||||
const offers = stayBookingView(MOONLIGHT_STAY_PAYLOAD)!.offers;
|
||||
expect(offers[0].baseRateText).toBe('주중 1박 280,000원');
|
||||
expect(offers[0].capacityText).toBe('기준 2명 · 최대 4명');
|
||||
});
|
||||
});
|
||||
|
||||
describe('발행 HTML — 예약 섹션이 실제로 나가는가', () => {
|
||||
it('요금 · 인원 · 취소 규정 · 예약 창구가 한자리에 있다', () => {
|
||||
const text = visibleText(html());
|
||||
expect(text).toContain('예약 창구');
|
||||
expect(text).toContain('주중 1박 280,000원');
|
||||
expect(text).toContain('기준 2명 · 최대 4명');
|
||||
expect(text).toContain('전화 예약 0507-1345-8821');
|
||||
expect(text).toContain('네이버 플레이스에서 예약');
|
||||
});
|
||||
|
||||
it('여기서 결제되지 않는다는 사실을 먼저 말한다 — 우리는 재고도 결제도 갖지 않는다', () => {
|
||||
expect(visibleText(html())).toContain('빈 방 확인과 결제는 아래 예약 창구에서 진행됩니다');
|
||||
});
|
||||
|
||||
it('확정 전 예약 링크는 화면에 없다', () => {
|
||||
expect(html()).not.toContain(UNCONFIRMED_URL);
|
||||
});
|
||||
|
||||
it('booking 항목이 없는 payload 에서도 예약 안내가 나간다 — 옛 payload·fixture', () => {
|
||||
const withoutBooking = {
|
||||
...MOONLIGHT_STAY_PAYLOAD,
|
||||
theme: {
|
||||
...MOONLIGHT_STAY_PAYLOAD.theme,
|
||||
sections: MOONLIGHT_STAY_PAYLOAD.theme.sections.filter((s) => s.id !== 'booking'),
|
||||
},
|
||||
};
|
||||
expect(visibleText(html(withoutBooking))).toContain('예약 창구');
|
||||
});
|
||||
|
||||
it('사장님이 끈 예약 섹션은 되살리지 않는다 — 껐다와 항목이 없다는 다르다', () => {
|
||||
const disabled = {
|
||||
...MOONLIGHT_STAY_PAYLOAD,
|
||||
theme: {
|
||||
...MOONLIGHT_STAY_PAYLOAD.theme,
|
||||
sections: MOONLIGHT_STAY_PAYLOAD.theme.sections.map((s) =>
|
||||
s.id === 'booking' ? {...s, enabled: false} : s,
|
||||
),
|
||||
},
|
||||
};
|
||||
expect(visibleText(html(disabled))).not.toContain('예약 창구');
|
||||
});
|
||||
});
|
||||
|
||||
describe('구조화 데이터 — 예약 값이 화면과 어긋나지 않는가 (절대규칙 3)', () => {
|
||||
it('makesOffer · potentialAction 을 포함한 전체 JSON-LD 가 화면 대조를 통과한다', () => {
|
||||
const nodes = collectJsonLd(MOONLIGHT_STAY_PAYLOAD, PAGE);
|
||||
expect(verifyJsonLd(html(), nodes)).toEqual([]);
|
||||
});
|
||||
|
||||
it('객실별 요금이 makesOffer 로 나가고, 가격은 화면과 같은 숫자다', () => {
|
||||
const [business] = collectJsonLd(MOONLIGHT_STAY_PAYLOAD, PAGE);
|
||||
const offers = business.makesOffer as {name: string; price: number}[];
|
||||
expect(offers.map((offer) => [offer.name, offer.price])).toEqual([
|
||||
['Moonlight A동', 280000],
|
||||
['Starlight B동', 300000],
|
||||
]);
|
||||
expect(visibleText(html())).toContain('280,000');
|
||||
});
|
||||
|
||||
it('빈 방 재고를 모르므로 availability 를 주장하지 않는다', () => {
|
||||
const [business] = collectJsonLd(MOONLIGHT_STAY_PAYLOAD, PAGE);
|
||||
for (const offer of business.makesOffer as Record<string, unknown>[]) {
|
||||
expect(offer.availability).toBeUndefined();
|
||||
}
|
||||
});
|
||||
|
||||
it('예약 액션은 확정된 채널만 가리킨다', () => {
|
||||
const [business] = collectJsonLd(MOONLIGHT_STAY_PAYLOAD, PAGE);
|
||||
const action = business.potentialAction as {target: {urlTemplate: string}};
|
||||
expect(action.target.urlTemplate).toBe('https://m.place.naver.com/accommodation/1234567890');
|
||||
});
|
||||
|
||||
it('예약 채널이 하나도 확정되지 않으면 예약 액션을 내보내지 않는다', () => {
|
||||
const noChannel = {
|
||||
...MOONLIGHT_STAY_PAYLOAD,
|
||||
links: MOONLIGHT_STAY_PAYLOAD.links.map((link) => ({...link, confirmed: false})),
|
||||
};
|
||||
const [business] = collectJsonLd(noChannel, PAGE);
|
||||
expect(business.potentialAction).toBeUndefined();
|
||||
// 요금은 그대로 나간다 — 예약 창구가 전화뿐인 업소도 요금은 사실이다.
|
||||
expect((business.makesOffer as unknown[]).length).toBe(2);
|
||||
});
|
||||
|
||||
it('숙박이 아니면 예약 오퍼·액션을 붙이지 않는다', () => {
|
||||
const cafe = {
|
||||
...MOONLIGHT_STAY_PAYLOAD,
|
||||
place: {...MOONLIGHT_STAY_PAYLOAD.place, category: PlaceCategory.CAFE},
|
||||
};
|
||||
const [business] = collectJsonLd(cafe, PAGE);
|
||||
expect(business.makesOffer).toBeUndefined();
|
||||
expect(business.potentialAction).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('예약 버튼은 예약 화면으로 바로 간다', () => {
|
||||
/** 네이버 예약 링크가 붙은 payload — 수집이 플레이스 응답에서 받아온 주소. */
|
||||
const withBooking: SitePayload = {
|
||||
...MOONLIGHT_STAY_PAYLOAD,
|
||||
links: [
|
||||
...MOONLIGHT_STAY_PAYLOAD.links,
|
||||
{
|
||||
channel: LinkChannel.NAVER_BOOKING,
|
||||
url: 'https://m.booking.naver.com/booking/6/bizes/1067685',
|
||||
title: undefined,
|
||||
confirmed: true,
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
it('네이버 예약이 플레이스보다 먼저 나온다 — 플레이스는 한 번 더 눌러야 한다', () => {
|
||||
const links = stayBookingView(withBooking)!.links;
|
||||
expect(links[0].channel).toBe(LinkChannel.NAVER_BOOKING);
|
||||
expect(links.map((l) => l.channel)).toContain(LinkChannel.NAVER_PLACE);
|
||||
});
|
||||
|
||||
it('버튼 문구가 "네이버 예약에서 예약" 이 되지 않는다', () => {
|
||||
const text = visibleText(html(withBooking));
|
||||
expect(text).toContain('네이버 예약으로 바로 예약하기');
|
||||
expect(text).not.toContain('네이버 예약에서 예약');
|
||||
});
|
||||
|
||||
it('예약 액션과 오퍼 URL 이 예약 화면을 가리킨다 — 화면 버튼과 같은 곳이다', () => {
|
||||
const [business] = collectJsonLd(withBooking, PAGE);
|
||||
const action = business.potentialAction as {target: {urlTemplate: string}};
|
||||
expect(action.target.urlTemplate).toBe('https://m.booking.naver.com/booking/6/bizes/1067685');
|
||||
for (const offer of business.makesOffer as {url?: string}[]) {
|
||||
expect(offer.url).toBe('https://m.booking.naver.com/booking/6/bizes/1067685');
|
||||
}
|
||||
});
|
||||
|
||||
it('검색 결과 주소는 예약 버튼이 되지 않는다 — 눌러도 검색 화면이다', () => {
|
||||
const searchOnly: SitePayload = {
|
||||
...MOONLIGHT_STAY_PAYLOAD,
|
||||
links: [
|
||||
{
|
||||
channel: LinkChannel.NAVER_PLACE,
|
||||
url: 'https://map.naver.com/p/search/%EC%8A%A4%ED%85%8C%EC%9D%B4?c=15.00,0,0,0,dh',
|
||||
title: '네이버 플레이스',
|
||||
confirmed: true,
|
||||
},
|
||||
],
|
||||
};
|
||||
expect(stayBookingView(searchOnly)!.links).toHaveLength(0);
|
||||
// 창구가 전화뿐이라는 사실을 말해 준다 — 버튼만 조용히 사라지면 안 된다.
|
||||
expect(visibleText(html(searchOnly))).toContain('온라인 예약 채널은 등록되지 않았습니다');
|
||||
});
|
||||
});
|
||||
|
||||
describe('예약 데모 — 정적 HTML 에 무엇이 굽히나', () => {
|
||||
it('날짜가 HTML 에 박히지 않는다 — 발행 시각의 날짜는 한 달 뒤 거짓이 된다', () => {
|
||||
const baked = html();
|
||||
// 서버 렌더에서는 달력을 그리지 않는다(mounted 게이트). 날짜 칩이 없어야 한다.
|
||||
expect(baked).not.toContain('aria-pressed');
|
||||
expect(visibleText(baked)).toContain('날짜 선택은 브라우저에서 열립니다');
|
||||
});
|
||||
|
||||
it('구조화 데이터는 데모의 영향을 받지 않는다 — 예약 가능 여부를 주장하지 않는다', () => {
|
||||
const nodes = collectJsonLd(MOONLIGHT_STAY_PAYLOAD, PAGE);
|
||||
expect(verifyJsonLd(html(), nodes)).toEqual([]);
|
||||
const [business] = nodes;
|
||||
for (const offer of business.makesOffer as Record<string, unknown>[]) {
|
||||
expect(offer.availability).toBeUndefined();
|
||||
}
|
||||
});
|
||||
|
||||
it('llms.txt 에 데모가 예약 창구로 실리지 않는다', () => {
|
||||
const txt = renderLlmsTxt(MOONLIGHT_STAY_PAYLOAD);
|
||||
expect(txt).not.toContain('날짜 선택');
|
||||
expect(txt).toContain('이 홈페이지는 빈 방 재고와 결제를 처리하지 않습니다.');
|
||||
});
|
||||
|
||||
it('객실이 없으면 데모를 그리지 않는다 — 고를 것이 없다', () => {
|
||||
const noUnits = {...MOONLIGHT_STAY_PAYLOAD, units: []};
|
||||
expect(visibleText(html(noUnits))).not.toContain('날짜 선택은 브라우저에서 열립니다');
|
||||
});
|
||||
});
|
||||
|
||||
describe('llms.txt — AI 가 예약 경로를 읽는 자리', () => {
|
||||
it('재고와 결제를 우리가 갖지 않는다고 명시한다', () => {
|
||||
expect(renderLlmsTxt(MOONLIGHT_STAY_PAYLOAD)).toContain(
|
||||
'이 홈페이지는 빈 방 재고와 결제를 처리하지 않습니다.',
|
||||
);
|
||||
});
|
||||
|
||||
it('예약 창구와 기준 요금이 위쪽 블록에 있다 — 아래에만 있으면 답에 안 실린다', () => {
|
||||
const txt = renderLlmsTxt(MOONLIGHT_STAY_PAYLOAD);
|
||||
expect(txt).toContain('- 전화 예약: 0507-1345-8821');
|
||||
expect(txt).toContain('- 기준 요금 — Moonlight A동: 주중 1박 280,000원');
|
||||
expect(txt.indexOf('## 예약')).toBeLessThan(txt.indexOf('## 이용 정보'));
|
||||
});
|
||||
|
||||
it('확정 전 채널은 예약 블록에 없다', () => {
|
||||
const txt = renderLlmsTxt(MOONLIGHT_STAY_PAYLOAD);
|
||||
const booking = txt.slice(txt.indexOf('## 예약'), txt.indexOf('## 이용 정보'));
|
||||
expect(booking).not.toContain(UNCONFIRMED_URL);
|
||||
});
|
||||
});
|
||||
@@ -1,5 +1,4 @@
|
||||
import {
|
||||
LinkChannel,
|
||||
PlaceCategory,
|
||||
factBool,
|
||||
factValue,
|
||||
@@ -9,7 +8,6 @@ import {
|
||||
selectPublishableFaqs,
|
||||
type FactEntry,
|
||||
type SitePayload,
|
||||
type UnitInfo,
|
||||
} from '@o2o/shared';
|
||||
|
||||
/**
|
||||
@@ -193,129 +191,10 @@ export function businessJsonLd(payload: SitePayload): Json {
|
||||
amenityFeature: amenityFeatures(payload.facts),
|
||||
sameAs: sameAs(payload),
|
||||
[spec.type === 'MenuItem' ? 'hasMenu' : 'containsPlace']: unitNodes(payload),
|
||||
makesOffer: stayOffers(payload),
|
||||
potentialAction: reserveAction(payload),
|
||||
...categoryExtras(payload),
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 객실 기준 요금 — **화면과 JSON-LD 가 같은 숫자를 쓰게 하는 단일 출처.**
|
||||
*
|
||||
* ★ 왜 여기 있나
|
||||
* 화면의 요금 표기(`derive.unitPriceText`)와 JSON-LD 의 `makesOffer.price` 가 각자
|
||||
* 계산하면 둘이 갈라질 수 있고, 갈라지는 순간 절대규칙 3(화면 = 구조화 데이터) 위반이라
|
||||
* 발행 게이트가 사이트를 막는다. 그래서 숫자를 고르는 함수는 하나뿐이고, 양쪽이 이걸 쓴다.
|
||||
* ★ 주중 요금을 기준으로 삼는다 — 손님이 "얼마부터"로 읽는 값이고, 주말/성수기는 그보다 비싸다.
|
||||
* `label` 을 같이 돌려주는 이유: 화면이 "주중 280,000원" 이라고 쓰면 구조화 데이터의
|
||||
* `unitText` 도 같은 말이어야 한다. 어느 요금인지 안 밝힌 가격은 그 자체로 오해다.
|
||||
*/
|
||||
export function unitBaseRate(unit: UnitInfo): {price: number; label: string} | undefined {
|
||||
for (const [key, label] of [
|
||||
['weekday_price', '주중 1박'],
|
||||
['price', '1박'],
|
||||
['weekend_price', '주말 1박'],
|
||||
['peak_price', '성수기 1박'],
|
||||
] as const) {
|
||||
const price = Number(factValue(unit.facts, key)?.replace(/[^0-9]/g, ''));
|
||||
if (Number.isFinite(price) && price > 0) return {price, label};
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* makesOffer — 객실별 1박 요금. **숙박만** 낸다.
|
||||
*
|
||||
* ★ 왜 `containsPlace` 안이 아니라 여기인가
|
||||
* `HotelRoom` 은 Accommodation 이라 `offers` 가 정식 속성이 아니다. 요금을 파는 주체는
|
||||
* 사업장이므로 Organization 계열의 `makesOffer` 가 맞는 자리다. 대조기(verify.ts)도
|
||||
* 이 속성을 이름·가격 쌍으로 따로 검사한다.
|
||||
* ★ `availability` 는 넣지 않는다. 우리는 빈 방 재고를 모른다 — 모르는 것을 InStock 으로
|
||||
* 주장하면 그게 거짓이고, 예약 채널이 마감인데 AI 가 "예약 가능" 이라고 답하게 된다.
|
||||
* ★ `url` 은 확정된 예약 채널뿐이다. 없으면 넣지 않는다(자기 페이지로 돌려보내는 예약 URL 은
|
||||
* 예약 경로가 아니다).
|
||||
*/
|
||||
function stayOffers(payload: SitePayload): Json[] {
|
||||
if (payload.place.category !== PlaceCategory.LODGING) return [];
|
||||
const spec = UNIT_SPEC[payload.place.category];
|
||||
const reserveUrl = bookingChannelUrl(payload);
|
||||
|
||||
return sanitizeUnits(payload.units)
|
||||
.map((unit) => {
|
||||
const rate = unitBaseRate(unit);
|
||||
if (!rate) return null;
|
||||
const offer: Json = compact({
|
||||
'@type': 'Offer',
|
||||
name: unit.name,
|
||||
price: rate.price,
|
||||
priceCurrency: 'KRW',
|
||||
priceSpecification: compact({
|
||||
'@type': 'UnitPriceSpecification',
|
||||
price: rate.price,
|
||||
priceCurrency: 'KRW',
|
||||
unitText: rate.label,
|
||||
}),
|
||||
itemOffered: {'@id': `${siteUrl(payload, spec.path, unit.slug)}#unit`},
|
||||
url: reserveUrl,
|
||||
});
|
||||
return offer;
|
||||
})
|
||||
.filter((offer): offer is Json => offer !== null);
|
||||
}
|
||||
|
||||
/**
|
||||
* 예약을 실제로 받는 채널 URL 하나. 화면의 예약 버튼과 같은 목록에서 고른다
|
||||
* (`derive.bookingLinks` — 야놀자·여기어때·네이버 플레이스, 확정된 것만).
|
||||
*
|
||||
* ★ 목록을 두 곳에 적지 않으려면 derive 를 부르는 쪽이 자연스럽지만, 의존 방향이
|
||||
* derive → jsonld 라 반대로 부를 수 없다. 채널 코드 목록은 이 파일에 두고
|
||||
* derive 가 이걸 쓴다.
|
||||
*/
|
||||
export const BOOKING_CHANNELS: readonly LinkChannel[] = [
|
||||
// ★ 순서가 곧 우선순위다. 예약 화면으로 **바로 가는** 채널이 앞이다.
|
||||
// 네이버 예약(m.booking.naver.com)은 눌렀을 때 예약 화면 그 자체가 뜨고,
|
||||
// 네이버 플레이스는 잘해야 가게 홈이라 예약을 한 번 더 눌러야 한다.
|
||||
// 실측(2026-09-08): 자동 발견이 물어온 플레이스 URL 이 검색 결과 주소였던 사장님은
|
||||
// "예약" 을 눌렀는데 검색 화면을 봤다. 예약하러 온 손님은 거기서 끝난다.
|
||||
LinkChannel.NAVER_BOOKING,
|
||||
LinkChannel.YANOLJA,
|
||||
LinkChannel.GOODCHOICE,
|
||||
LinkChannel.NAVER_PLACE,
|
||||
];
|
||||
|
||||
/**
|
||||
* 예약 화면으로 보낼 URL 하나. **가장 앞선 채널**을 고른다(BOOKING_CHANNELS 순서).
|
||||
*
|
||||
* 화면의 예약 버튼과 `makesOffer.url`·`potentialAction` 이 같은 함수를 쓰므로,
|
||||
* 구조화 데이터가 가리키는 곳과 손님이 눌러서 가는 곳이 어긋날 수 없다.
|
||||
*/
|
||||
function bookingChannelUrl(payload: SitePayload): string | undefined {
|
||||
for (const channel of BOOKING_CHANNELS) {
|
||||
const hit = payload.links.find((link) => link.confirmed && link.channel === channel);
|
||||
if (hit) return hit.url;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* potentialAction — "이 업소를 예약하는 방법" 을 기계가 읽는 형태로.
|
||||
*
|
||||
* AI 검색이 "여기 예약 어떻게 해요?" 에 답할 때 근거로 쓰는 자리다. 확정된 예약 채널이
|
||||
* 없으면 내보내지 않는다 — 예약을 받지 않는 곳에 예약 액션을 붙이면 그게 거짓이다.
|
||||
* ★ `actionPlatform` 은 쓰지 않는다. 값이 schema.org URL 이라 화면 대조에서 "화면에 없는
|
||||
* URL" 로 잡히고, 플랫폼 구분은 이 사이트에서 아무 의미도 없다.
|
||||
*/
|
||||
function reserveAction(payload: SitePayload): Json | undefined {
|
||||
if (payload.place.category !== PlaceCategory.LODGING) return undefined;
|
||||
const url = bookingChannelUrl(payload);
|
||||
if (!url) return undefined;
|
||||
return {
|
||||
'@type': 'ReserveAction',
|
||||
target: {'@type': 'EntryPoint', urlTemplate: url, inLanguage: 'ko-KR'},
|
||||
result: {'@type': 'LodgingReservation'},
|
||||
};
|
||||
}
|
||||
|
||||
/** 최저~최고 요금. 단위 fact 의 숫자만 모은다 — 확인 안 된 요금은 애초에 안 들어온다. */
|
||||
function priceRange(payload: SitePayload): string | undefined {
|
||||
const prices = sanitizeUnits(payload.units)
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import {
|
||||
PlaceCategory,
|
||||
factText,
|
||||
joinUrl,
|
||||
sanitizeUnits,
|
||||
@@ -7,7 +6,7 @@ import {
|
||||
selectPublishableFaqs,
|
||||
type SitePayload,
|
||||
} from '@o2o/shared';
|
||||
import {BOOKING_CHANNELS, SCHEMA_TYPE, UNIT_SPEC, unitBaseRate} from './jsonld';
|
||||
import {SCHEMA_TYPE, UNIT_SPEC} from './jsonld';
|
||||
|
||||
/**
|
||||
* llms.txt — LLM 이 이 가게를 설명할 때 쓸 사실 목록.
|
||||
@@ -55,9 +54,6 @@ export function renderLlmsTxt(payload: SitePayload): string {
|
||||
}
|
||||
lines.push('');
|
||||
|
||||
// ── 예약 (숙박) ──────────────────────────────────────
|
||||
pushStayBooking(lines, payload);
|
||||
|
||||
// ── 확인된 이용 정보 ──────────────────────────────────
|
||||
if (facts.length > 0) {
|
||||
lines.push('## 이용 정보');
|
||||
@@ -139,43 +135,6 @@ export function renderLlmsTxt(payload: SitePayload): string {
|
||||
return lines.join('\n');
|
||||
}
|
||||
|
||||
/**
|
||||
* 예약 — 숙박에서 가장 많이 묻는 질의("어떻게 예약해요 / 얼마예요")의 답을 한 블록에 모은다.
|
||||
*
|
||||
* ★ 이용 정보·객실 절에 흩어져 있는 값을 한 번 더 쓰는 것이지만, LLM 은 이 파일을 위에서부터
|
||||
* 읽고 답을 만든다. 예약 경로가 "공식 채널" 절 맨 아래에만 있으면 답에 안 실린다.
|
||||
* ★ **재고와 결제를 우리가 갖지 않는다는 사실을 명시한다.** 이 문장이 없으면 LLM 이
|
||||
* "공식 홈페이지에서 바로 예약할 수 있다"고 답한다 — 그건 거짓이고, 손님은 헛걸음한다.
|
||||
* ★ 예약 채널은 확정된 것만이다. 확정 전 URL 은 동명 업소의 예약 페이지일 수 있다.
|
||||
*/
|
||||
function pushStayBooking(lines: string[], payload: SitePayload) {
|
||||
if (payload.place.category !== PlaceCategory.LODGING) return;
|
||||
|
||||
const links = payload.links.filter(
|
||||
(link) => link.confirmed && BOOKING_CHANNELS.includes(link.channel),
|
||||
);
|
||||
const rates = sanitizeUnits(payload.units)
|
||||
.map((unit) => {
|
||||
const rate = unitBaseRate(unit);
|
||||
return rate ? `${unit.name}: ${rate.label} ${rate.price.toLocaleString('ko-KR')}원` : null;
|
||||
})
|
||||
.filter((line): line is string => line !== null);
|
||||
|
||||
if (!payload.place.phone && links.length === 0 && rates.length === 0) return;
|
||||
|
||||
lines.push('## 예약');
|
||||
lines.push('');
|
||||
lines.push(
|
||||
'이 홈페이지는 빈 방 재고와 결제를 처리하지 않습니다. ' +
|
||||
'예약 가능 여부와 결제는 아래 창구에서 확인해야 합니다.',
|
||||
);
|
||||
lines.push('');
|
||||
if (payload.place.phone) lines.push(`- 전화 예약: ${payload.place.phone}`);
|
||||
for (const link of links) lines.push(`- ${link.title ?? '예약 채널'}: ${link.url}`);
|
||||
for (const rate of rates) lines.push(`- 기준 요금 — ${rate}`);
|
||||
lines.push('');
|
||||
}
|
||||
|
||||
function pushFact(lines: string[], label: string, value: string | null | undefined) {
|
||||
lines.push(`- ${label}: ${value?.trim() ? value : '정보 없음'}`);
|
||||
}
|
||||
|
||||
@@ -52,23 +52,6 @@ describe('visibleText', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('verifyJsonLd — 표기 차이로 사실을 막지 않는다', () => {
|
||||
it('속성의 & 이스케이프를 표기 차이로 흡수한다 — 화면에 있는 이미지였다', () => {
|
||||
// 실측(2026-09-07): 쿼리스트링 있는 이미지 URL 을 쓰는 사이트가 전부 발행 불가였다.
|
||||
// HTML 속성에서는 & 가 & 로 나가는데 JSON-LD 는 원본 & 를 갖고 있다.
|
||||
const url = 'https://cdn.example.com/a.jpg?auto=format&fit=crop';
|
||||
const body = `<img src="https://cdn.example.com/a.jpg?auto=format&fit=crop" alt="객실">`;
|
||||
expect(verifyJsonLd(page(body), [{'@type': 'LodgingBusiness', image: [url]}])).toEqual([]);
|
||||
});
|
||||
|
||||
it('그래도 없는 이미지는 잡는다 — 이스케이프를 되돌려도 못 찾으면 실패다', () => {
|
||||
const problems = verifyJsonLd(page(BODY), [
|
||||
{'@type': 'LodgingBusiness', image: ['https://cdn.example.com/none.jpg?a=1&b=2']},
|
||||
]);
|
||||
expect(problems).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('verifyJsonLd — 거짓을 잡는다', () => {
|
||||
it('화면에 없는 전화번호를 주장하면 잡는다', () => {
|
||||
const problems = verifyJsonLd(page(BODY), [
|
||||
|
||||
@@ -24,7 +24,6 @@ const STRUCTURAL = new Set([
|
||||
'priceCurrency',
|
||||
// ★ ㎡의 ISO 코드('MTK'). priceCurrency 와 같은 성격이라 화면에 나올 값이 아니다 —
|
||||
// 빠져 있어서 객실 면적(room_size)이 있는 사업장은 전부 발행이 막혔다(실측: 가은채 객실 12개).
|
||||
// ★ 사람이 읽는 단위 표기(`unitText`)는 여기 넣지 않는다 — 그건 화면에 있어야 하는 말이다.
|
||||
'unitCode',
|
||||
// ★ units.length 로 만든 파생 카운트다. 화면에는 객실 카드가 그 개수만큼 있을 뿐
|
||||
// '12' 라는 숫자가 글자로 있지는 않다. 객실이 2~3개인 사업장만 우연히 통과했다.
|
||||
@@ -141,18 +140,6 @@ function asShown(value: Scalar): string[] {
|
||||
*/
|
||||
export function verifyJsonLd(html: string, nodes: Json[]): string[] {
|
||||
const text = visibleText(html);
|
||||
/**
|
||||
* URL 대조용 사본 — 엔티티를 되돌린 HTML.
|
||||
*
|
||||
* ★ 왜 필요한가 (실측 2026-09-07, 데모 payload)
|
||||
* `<img src="…?auto=format&fit=crop">` 는 HTML 로 나갈 때 `&` 가 `&` 로 이스케이프된다.
|
||||
* JSON-LD 의 `image` 는 원본 `&` 를 갖고 있으므로 원본 HTML 문자열에서는 절대 안 찾아진다 —
|
||||
* **화면에 실제로 있는 이미지가 "화면에 없다"로 잡혀** 발행이 막혔다. 쿼리스트링 있는
|
||||
* 이미지 URL 을 쓰는 사이트는 전부 이 오탐에 걸린다.
|
||||
* 숫자 표기 차이를 `asShown()` 으로 흡수하는 것과 같은 이유다 — **표기 차이는 거짓이 아니다.**
|
||||
* ★ 반대로 느슨해지지는 않는다: 되돌린 사본에서도 못 찾으면 그대로 실패다.
|
||||
*/
|
||||
const unescaped = unescapeHtml(html);
|
||||
const problems: string[] = [];
|
||||
|
||||
const seen = new Set<string>();
|
||||
@@ -175,9 +162,7 @@ export function verifyJsonLd(html: string, nodes: Json[]): string[] {
|
||||
const token = String(value);
|
||||
// URL·이미지는 본문 텍스트가 아니라 요소 속성(src/href)에 있다.
|
||||
if (token.startsWith('http://') || token.startsWith('https://')) {
|
||||
if (!html.includes(token) && !unescaped.includes(token)) {
|
||||
report(`${prop}: '${token}' 이 화면에 없다`);
|
||||
}
|
||||
if (!html.includes(token)) report(`${prop}: '${token}' 이 화면에 없다`);
|
||||
continue;
|
||||
}
|
||||
if (asShown(value).some((shown) => text.includes(shown))) continue;
|
||||
|
||||
Reference in new issue
Block a user