Compare commits

...
Author SHA1 Message Date
Haewon KamandClaude Fable 5.1 730f7822c3 docs: 제품 핸드오버에 §8 인사이트 12건, 월요일(09-14) 시작 절차 반영
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-11 19:51:22 +09:00
Haewon KamandClaude Fable 5.1 f26ba37948 docs: 주변 안내 복원과 '기존 페이지를 덮어쓰지 않는다' 함정 기록
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-11 18:29:04 +09:00
Haewon KamandClaude Fable 5.1 dca494fc21 feat(supporters): 주변 안내(/stay·/en/stay) 뷰 샘플에 추가 · 내비·언어 짝·사이트맵·스타일 이식, 구조 기준선 갱신
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-11 18:28:13 +09:00
Haewon KamandClaude Fable 5.1 daf6350c49 docs: 제품 핸드오버에 발행(색인) 단계와 완료 정의 추가
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-11 15:28:51 +09:00
Haewon KamandClaude Fable 5.1 6c3e2888a7 docs: AI Discovery Product 빌드 핸드오버 (제품 여정·상태, 브랜치·배포 지도, 빌드 순서, 결정 대기, 함정)
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-11 14:22:58 +09:00
Haewon KamandClaude Fable 5.1 93509bf9b3 chore(supporters): 플래너 추천 장소 설명을 관광공사 데이터 유무에 따라 표기
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-11 13:11:25 +09:00
Haewon KamandClaude Fable 5.1 94d7edec45 style(supporters): 지도 출처 줄을 행 밖으로 옮겨 지도 상자와 카드 아래선을 맞춤
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-11 11:51:53 +09:00
Haewon KamandClaude Fable 5.1 d13ac35365 style(supporters): 오시는 길 지도를 카드 높이에 맞춰 늘림 (열 비율 1.5:1, invalidateSize)
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-11 11:48:49 +09:00
Haewon KamandClaude Fable 5.1 587462552b feat(supporters): 오시는 길 지도·길찾기 (VisitMap) 방문 안내와 영어 홈에 추가
- OpenStreetMap 타일 + Leaflet(cdnjs) 지도, 병원 핀, 주소 복사, 문의 전화, 네이버·카카오 길찾기(영어 화면은 구글 길찾기 추가). 벤치마크 2026-09-11
- 좌표는 factSheet.geo(운영 기록 source 는 화면에 내지 않음), 없으면 관광공사 수집 메타, 둘 다 없으면 지도 없이 주소·버튼만

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-11 11:38:07 +09:00
Haewon KamandClaude Fable 5.1 6b01cc9f7b chore(supporters): 플래너 검증·출처 줄을 Productize 템플릿과 동일하게 (관광 데이터 없을 때 건너뜀)
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-11 11:28:05 +09:00
Haewon KamandClaude Fable 5.1 65fb9be9c6 refactor(supporters): 플래너 히어로의 시술 목록·기준점 문구를 데이터(procedures.json 라벨, places.json origin)에서 읽음 · 병원별 이식 준비
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-11 11:20:06 +09:00
Haewon KamandClaude Fable 5.1 83b8343262 feat(supporters): 회복 일정 플래너에 한국관광공사 TourAPI 데이터 합침 + 옛 주소 리다이렉트 + 404 페이지
- src/lib/tour.ts: 사전 수집 JSON(medicalTourismKo/medicalTourism)을 추천 후보로 변환. 관광지·문화시설→관광, 쇼핑, 음식점(일반식 단계에서만), 숙박→숙소. 사우나·스파는 회복기 금지라 제외. 거리로 외출 등급(600m·3km)
- 큐레이션(places.json) 1순위, TourAPI 2순위 가점. 타임라인 추천에 이동 시간 라벨과 '관광공사' 표시
- 체류 기간과 겹치는 행사 섹션(가까운 순 6곳, 자유 외출 단계 도달일 표시), 자유 외출(L3) 날에 행사 1건 추가
- 숙소 그리드에 TourAPI 숙박 가까운 순 6곳 추가(예약 검색은 영문 이름으로)
- scripts/fetch_medical_tourism.py: Productize 브랜치의 수집 스크립트 가져옴(화면 경로 주석 갱신)
- vercel.json: /recovery·/stay·/en/recovery·/en/stay → /plan·/en/plan 영구 리다이렉트. src/pages/404.astro 사이트 스타일 404
- 테스트 14건(어댑터·우선순위·유동식 제외·축제)

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-11 11:01:32 +09:00
24 changed files with 8439 additions and 28 deletions

No files matched your search

@@ -0,0 +1,120 @@
# 다음 세션 핸드오버 · 2026-09-14(월) · INFINITH AI Discovery Product 빌드
작성 2026-09-11 (금요일 종료 시점) · 작성자 Claude (haewon 세션) · 상태: 초안(haewon 검토 전) · 다음 세션은 2026-09-14 월요일부터 Product 개발을 이어간다.
하위 문서: 서포터즈 사이트 빌드 절차 `~/orca/workspaces/INFINITH/Productize/docs/NEXT_SESSION_2026-09-12_PRODUCT_BUILD.md`, 자동 빌드 상세 `…/NEXT_SESSION_SUPPORTERS_AUTOBUILD_v3.md`, 자동 채점 `docs/AI_DISCOVERY_BUILD2_HANDOVER.md`, 회고 `docs/INFINITH_AI_Discovery_Retrospective_2026-09-08.md`.
## 0. 세션 시작 시 붙여 넣을 프롬프트
```
INFINITH AI Discovery Product 빌드 세션. 제품은 "병원 URL 하나 → AI 답변 준비도 진단(AEO/GEO v2) → 서포터즈 사이트 자동 빌드(글·영상·뉴스룸·회복 일정 플래너·오시는 길) → 병원 확인·재빌드 → 측정(질문뱅크·감성·GA4·크롤러 로그)" 파이프라인이다.
코드 위치: 프런트·스크립트·문서는 메인 체크아웃 ~/Claude/Agentic Marketing/INFINITH (브랜치 feature/ai-sentiment-rubric, 프로덕션 main → infinith-demo.vercel.app),
워커·템플릿·큐는 워크트리 ~/orca/workspaces/INFINITH/Productize (브랜치 feature/supporters-autobuild), 랜딩 리드 CTA 는 브랜치 feature/discovery-url-cta(미머지).
먼저 docs/NEXT_SESSION_2026-09-12_AI_DISCOVERY_PRODUCT.md 를 읽는다(§8 인사이트 포함). 시작 절차: (1) 두 저장소 git status 와 .vercel 연결을 확인하고 다른 세션이 열려 있지 않은지 haewon 에게 묻는다 (2) §1 표의 "확인" 칸을 git log·Supabase 로 실제 확인한다 (3) §5 결정 대기의 답을 받는다 (4) §4 순서대로 진행하되 1번 브랜치 통합을 먼저 끝낸다. 한 세션은 한 저장소·한 배포 대상만 다룬다.
원칙: 근거 없는 사실은 생성하지 않는다("확인 대기"). 사람 게이트(의학 검토·게시 승인·이미지 육안·채널 확인·구조 기준선)는 자동화하지 않는다. 언급률·점수는 "스키마를 넣으면 인용된다"고 약속하지 않는다(정직성 규약).
고객 화면에 운영자 어휘 금지. 존댓말, 엠대시 금지(커밋 메시지 포함), 은유 금지, 흰 배경 위 연보라 텍스트 금지(인디고 #1D0024). INFINITH 리포트 PDF 는 PPTX 덱(infinith-deck 스킬)으로 만든 뒤 변환한다.
클라이언트 격리: INFINITH 문서·코드에 다른 서비스 이름을 쓰지 않는다. 산출 전 grep.
```
## 1. 제품 여정과 현재 상태
| 단계 | 고객이 보는 것 | 구현 | 위치 | 상태 |
|---|---|---|---|---|
| 1 진입 | `/discovery` 랜딩, "URL 입력으로 시작" | `DiscoveryLandingPage.tsx`, `DiscoveryLeadModal` → Supabase `discovery_leads` | 메인, 브랜치 feature/discovery-url-cta | 프리뷰만. **미머지, 마이그레이션 `20260831_discovery_leads.sql` 적용 여부 확인** |
| 2 진단 | `/discovery/:id` 리포트 (AEO 100 + GEO 100, v2 기준표), 덱·PDF | `scripts/audit_aeo_geo.py`(auto 22항목) → `src/data/discovery_<id>.ts` → `DiscoveryReportPage.tsx`; `scripts/build_discovery_report.ts` → HTML/PDF; 덱 빌더 `docs/reports/<clinic>/01_readiness_report/build_*_deck*.py` | 메인 + Productize(v2 기준표 `src/data/aeoGeoRubricV2.ts`, `src/lib/discoveryScoreV2.ts`) | 반자동. 결과가 소스 파일 커밋 방식이라 병원마다 코드 배포가 필요하다. **v2 기준표가 main(프로덕션)에 머지됐는지 확인** |
| 3 서포터즈 사이트 | `supporters-<clinic>.vercel.app` 미리보기(noindex): 글·영상·뉴스룸·방문 안내(지도·길찾기)·회복 일정 플래너 `/plan`·`/en/plan` | 워커 `workers/supporters-build/run.mjs` 15단계(evidence→…→tourism→recovery→planner→…→deploy), 템플릿 `templates/supporters-astro`, 게이트 `scripts/gate/rules.mjs` | Productize | 동작. 뷰(수작업 샘플 `view-supporters-sample`)·원진·오라클 3곳 배포. 병원당 약 $0.6, 30분 |
| 4 병원 확인 | `/supporters/:id` 또는 리포트 안 `ClinicInputsPanel`: 채널 확인, 의료진, 검토·승인, 자유 답변 | Supabase `supporter_builds`·`supporter_inputs`, `apply_inputs.mjs`, 재빌드 `run.mjs --from data --from-supabase --build-id` | 메인(UI) + Productize(반영) | 동작하되 **재빌드 자동 트리거 없음**(supporter_inputs insert → 큐 연결 필요) |
| 5 운영 | 큐 → 빌드 → 미리보기 링크 | `poll.mjs` + Mac launchd 5분 폴러, `supporter_builds` 큐 | Productize | 파일럿 수준. Mac 이 켜져 있어야 돈다. 실제 랜딩 신청 1건이 큐 → 완주까지 간 적 없음 |
| 6 측정 | 질문뱅크 언급률(2엔진), 감성, GA4 AI 유입, AI 크롤러 히트, 공식 vs 서포터즈 재채점 | `scripts/run_question_bank_openai.py`·`merge_qb_results.py`·`sentiment_qb.py`·`ga4_ai_traffic.py`, `data/ai_channels.json`, 리포트 Integrity 절 "측정 가능 범위" | 메인(QB·감성) + Productize(GA4) | 스크립트 단위. 리포트 카드 자동 갱신 없음. GA4 는 GCP 계정 대기 |
| 7 계약·가격 | 상담 기반 계약 | 가격 문서 `docs/INFINITH_가격정책_사업부보고서_v1.1.docx`(2026-04, 이전 제품 INSIGHT/INTELLIGENCE 티어), AI Discovery 가격 제안은 `docs/INFINITH_vs_FrostAI_비교_및_가격제안_2026-09-08.html` | 메인 | **AI Discovery 전용 티어 미확정** |
2026-09-10~11 추가: 회복 일정 플래너 `/plan`(설계 v0.2 §13, 관광공사 데이터 합침), 주변 안내 `/stay`(장소·축제·동선 지도·날씨, 플래너와 별개 페이지로 복원), 오시는 길 지도·길찾기, 전역 언어 전환·영어 홈(뷰), 모바일 헤더, 발행(색인) 단계. 전부 템플릿·워커에 통합됨.
## 2. 코드·브랜치·배포 지도
| 무엇 | 어디 | 브랜치 | 배포 |
|---|---|---|---|
| 제품 프런트(랜딩·리포트·확인 패널) | 메인 `src/` | main(프로덕션), feature/ai-sentiment-rubric(감성·플래너 작업), feature/discovery-url-cta(리드 CTA) | `infinith-demo.vercel.app` (main 에서 `vercel --prod`, Gitea 자동 트리거 없음) |
| 채점·질문뱅크·감성·리포트 스크립트 | 메인 `scripts/`, `docs/reports/` | feature/ai-sentiment-rubric | 로컬 실행 |
| 워커·템플릿·게이트·GA4 뼈대·v2 기준표 | Productize `workers/`, `supporters/`, `templates/`, `scripts/fetch_medical_tourism.py` | feature/supporters-autobuild | 병원별 `supporters-<clinic>` (워커가 강제 link) |
| 뷰 수작업 샘플 | 메인 `supporters/` | feature/ai-sentiment-rubric | `view-supporters-sample` 수동 |
| Supabase | `supabase/migrations/` (`supporter_builds`, `supporter_builds_queue`, `discovery_leads`) + Edge Functions(기존 리포트 파이프라인) | 메인 | 적용 상태 확인 필요(CLI 토큰 만료 이력) |
| 키 | Productize `.env`(TOUR_API·NAVER·OPENAI·YOUTUBE), 메인 `.env`(진단·QB) | | 회사 계정. 세션 시작 때 `grep -E "^KEY=." .env` 로 값 존재만 확인 |
세 브랜치는 서로 머지되지 않았다. `supporters/` 폴더가 양쪽에 있고 Base.astro 구현이 다르다(메인: i18n.ts 전역 전환·영어 홈; Productize: langswitch·영어 입구 /en/plan). 플래너·지도·헤더 CSS 는 같다.
## 3. 지금 되는 것 / 안 되는 것 (한 줄씩)
되는 것
- 병원 이름·URL 로 채널 발견·근거 수집·자동 채점·리포트 HTML/PDF·덱(뷰·원진·오라클·태하 사례).
- 워커 한 번으로 서포터즈 사이트 초안 발행(글 6~8편, 영상, 뉴스룸, 이미지 규칙, 지도, 플래너, 관광공사 데이터). 게이트 41건 테스트.
- 병원 확인 패널 입력 → 수동 재빌드.
- 질문뱅크 120문항 2엔진 실측, 감성 판정, Before/After 페이지(`scripts/build_before_after.py`).
안 되는 것
- 랜딩 신청 → 큐 → 빌드 → 미리보기 링크 회신이 사람 손 없이 이어지지 않는다(리드 테이블과 큐가 분리, CTA 브랜치 미머지).
- 진단 결과가 코드 파일(`discovery_<id>.ts`)이라 병원마다 프런트 배포가 필요하다. 런타임 데이터(Supabase 또는 JSON 스토리지)로 옮겨야 "URL 입력 → 리포트 링크"가 된다.
- 측정 지표가 리포트 카드에 자동으로 들어가지 않는다(스크립트 산출물을 사람이 옮긴다).
- 워커가 Mac 에 묶여 있다. 규칙표 잠정값·큐레이션 장소·의료진 후보·이미지·채널 12건은 사람 확인 대기.
- 색인 작업의 사람 몫(네이버 등록·GSC 소유자·도메인·법무)이 체크리스트 파일로만 나오고, 담당자에게 알림·요청하는 UI 가 아직 없다(§4-9).
- AI Discovery 가격·계약 조건 미확정. 랜딩 FAQ 의 해지·환불 항목 삭제 상태.
## 4. Product 빌드 순서 (권장)
1. **브랜치 정리**: `main` 기준으로 feature/supporters-autobuild(워커·템플릿·v2 기준표·GA4) → feature/ai-sentiment-rubric(감성·플래너·지도·설계 v0.2) → feature/discovery-url-cta(리드 CTA) 순으로 머지. 충돌 지점은 `supporters/`(Base.astro 두 구현)와 `src/data/aeoGeoRubric*`·`discoveryScoreV2`. 결정: `supporters/` 는 템플릿(Productize) 구현을 정본으로 하고 뷰 샘플은 워커 폴더로 옮긴다(§5-4).
2. **리드 → 큐 연결**: `discovery_leads` 마이그레이션 적용 → insert 시 `supporter_builds` 큐에 행 생성(DB 트리거 또는 폴러가 leads 도 읽기) → 워커가 evidence 부터 완주 → 미리보기 URL 을 `supporter_builds.preview_url` 에 기록 → 신청자에게 링크 회신(초기에는 수동 메일, `o2oteam@o2o.kr`).
3. **진단 결과 런타임화**: `audit_aeo_geo.py` 출력 JSON 을 Supabase(`discovery_results`) 또는 스토리지에 저장하고 `/discovery/:id` 가 런타임에 읽는다. 기존 `DISCOVERY_RESULTS` 레지스트리는 샘플(뷰) 전용으로 남긴다. 사람 판정(v2Results 4항목)은 확인 패널에서 입력.
4. **재빌드 자동화**: `supporter_inputs` insert → 큐 → `run.mjs --from data --from-supabase`. 색인 허용 빌드(`PUBLIC_INDEXABLE=true`)는 `approvedAt` 있는 글만 낸다는 규칙 유지.
5. **측정 카드**: 질문뱅크·감성·GA4·크롤러 히트 결과를 `discovery_results` 에 붙이고 리포트 Integrity 절과 Before/After 에 자동 표시. 언급률은 신뢰구간과 함께.
6. **운영 이관**: Mac launchd 폴러 → Trigger.dev(또는 동등)로. 키·비용 로그(`status.json` costUsd)·실패 알림.
7. **가격·계약**: AI Discovery 티어(진단만 / 진단+서포터즈 / +측정·관리) 확정, 랜딩 FAQ·계약서·해지 조건. FrostAI 비교 문서의 제안을 출발점으로.
8. **다음 병원**: 톡스앤필·차앤박(피부과), 레지스트리 73곳 중 회귀 병원. 한 화면 비교 산출물은 만들지 않는다.
9. **발행(색인) 단계**: "서포터즈 사이트 완료"의 정의는 배포가 아니라 색인 작업과 사람 체크리스트까지 끝난 상태다(haewon 결정 2026-09-11). 워커 `publish` 단계(`supporters/scripts/publish_site.mjs`)가 자동으로 하는 것: 라이브 확인(홈·robots·sitemap·noindex 헤더), IndexNow 로 사이트맵 URL 전부 알림(빙·네이버 공용, 색인 허용 빌드일 때만), Google Search Console 사이트맵 제출과 URL 색인 상태 조회(서비스 계정 `GOOGLE_SERVICE_ACCOUNT_JSON` 있을 때), 검색엔진 소유 확인 메타 태그(site.json `googleSiteVerification`·`naverSiteVerification`), IndexNow 키 파일(`public/<key>.txt`) 자동 생성, `--indexable` 로 noindex 헤더 제거·승인 글만 발행, `--domain` 으로 정식 도메인 연결. 사람에게 남기는 것(`~/supporters-builds/<clinic>/publish-checklist.md`, `status.humanTasks`): 네이버 서치어드바이저 등록·소유 확인·사이트맵/RSS 제출(공개 API 없음), Google Search Console 소유자 추가(첫 1회), 정식 도메인 결정, 색인 허용 전환 전 법무 3건·게시 승인, 병원 자산에서 백링크·sameAs, 네이버 블로그 재작성 트랙. 하지 않는 것: Google Indexing API(채용·라이브 방송 전용), 색인 보장 약속. 제품에서는 이 체크리스트를 확인 패널(`ClinicInputsPanel`) 또는 운영자 알림으로 사람에게 요청하게 만드는 것이 다음 일이다.
## 5. haewon 결정 대기
1. **Product 1.0 범위**: (a) 진단 리포트만, (b) 진단 + 서포터즈 사이트 초안, (c) b + 측정·관리 구독. 랜딩 CTA 의 약속 범위가 달라진다.
2. **가격 티어**(§4-7)와 계약 최소 기간·해지 조건(2026-04 문서의 P0 두 항목이 그대로 미결).
3. **뷰 샘플 통일**: 메인 `supporters/` 를 워커 폴더(`~/supporters-builds/viewclinic`)로 옮기고 `view-supporters-sample` 을 워커 배포로 바꿀지. 옮기면 뷰의 영어 홈 `/en` 은 템플릿에 없으므로 템플릿에 영어 홈을 추가할지 함께 결정.
4. **법무**: 외국인환자 유치업 등록 여부(플래너·숙소 링크), 의료광고 사전심의 대상 여부, 지원 관계 고지 문구(sponsorNotice). 이 세 가지는 색인 허용 전환의 전제.
5. **도메인**: 별도 도메인 vs 병원 서브도메인(설계 v0.1 §3 2안). 서포터즈 실명 모집 방식.
6. **워커 호스팅**과 GCP 계정(GA4 서비스 계정).
7. **규칙표 잠정값**: 뷰·원진·오라클 `procedures.json` 의 provisional 값(출국 최소일·입원·실밥)을 병원 확인 뒤 공개할지, 공개 전까지 "병원 확인 전" 배지로 둘지.
8. 서포터즈 빌드 하위 결정(하위 문서 §4)과 오라클 핸드오버 §3 미결은 그대로.
## 6. 함정 (제품 관점)
- **한 Vercel 프로젝트에 두 폴더**: 2026-09-11 Productize/supporters 와 메인 supporters 가 같은 프로젝트에 배포해 `/plan` 이 404 됐다. 지금은 Productize 쪽 연결을 껐다. 배포는 병원 폴더와 메인 supporters 에서만.
- **페이지를 덮어쓰지 않는다**: 플래너 통합 때 `/stay`(주변 안내)를 `/plan` 으로 리다이렉트해 세 사이트에서 주변 안내가 사라졌다(09-11 17시 복원). 새 기능이 기존 페이지와 '같은 주제'로 보여도 haewon 확인 전에는 기존 페이지를 지우거나 리다이렉트하지 않는다.
- **세 브랜치 분산**: 같은 파일(`supporters/`)이 두 브랜치에서 다르게 진화했다. 머지 전에 "템플릿이 정본"을 정하고 뷰 샘플을 옮긴다.
- **진단 결과가 코드**: `discovery_<id>.ts` 커밋 방식은 병원 수가 늘면 배포 병목이다(§4-3).
- **게이트는 고객 화면 전체를 본다**: 운영 어휘("실측"·"API 집계"·"임베드")가 데이터 값을 타고 화면에 나가면 빌드가 막힌다. 운영 기록은 데이터에만.
- **원문 문장은 걸러야 한다**: 병원 페이지 원문 32문장 중 14건이 홍보문·정형 고지였다. 워커 planner 단계 필터(CARE/NOT_CARE) 없이는 "병원 안내 기준" 배지가 의료광고 위반이 된다.
- **헤드리스 크롬 모바일 캡처**: 창 최소 폭 때문에 400px 직접 캡처가 틀린다. 1280 창 안 390px iframe 하네스로.
- **lint**: 메인 체크아웃은 한때 tsc 가 없어 `npm run lint` 가 가짜 통과였다. 실제 0 에러인지 `npx tsc --noEmit` 로 본다.
- **엠대시·타 서비스 이름**: 커밋 메시지와 문서에서 두 번 잡혔다. 산출 전 엠대시 검색(`grep -cP "\x{2014}"`)과 타 서비스명 격리 grep(전역 CLAUDE.md 의 목록).
## 7. 파일 참조
- 진단: `src/data/aeoGeoRubricV2.ts`, `src/lib/discoveryScoreV2.ts`, `src/pages/DiscoveryReportPage.tsx`, `scripts/audit_aeo_geo.py`, `docs/AEO_GEO_RUBRIC_v2.md`
- 랜딩·리드: `src/pages/DiscoveryLandingPage.tsx`, `src/components/discovery/`, `supabase/migrations/20260831_discovery_leads.sql`
- 확인 패널·큐: `src/components/discovery/ClinicInputsPanel.tsx`, `src/pages/SupportersBuildPage.tsx`, `supabase/migrations/20260907_supporter_builds*.sql`
- 워커·템플릿: Productize `workers/supporters-build/`, `supporters/scripts/`, `templates/supporters-astro/`, 브리프 `supporters/briefs/<clinic>/`
- 플래너·지도: 템플릿 `src/components/Planner.astro`·`VisitMap.astro`, `src/lib/plan.ts`·`tour.ts`, `supporters/scripts/build_planner_data.mjs`, 설계 `docs/INFINITH_Viewclinic_Supporters_Site_Design_v0.2.md` §13
- 측정: `scripts/run_question_bank_openai.py`, `scripts/sentiment_qb.py`, `docs/AI_ANSWER_SENTIMENT_RUBRIC_v0.1.md`, Productize `scripts/ga4_ai_traffic.py`, `data/ai_channels.json`
- 가격·경쟁: `docs/INFINITH_vs_FrostAI_비교_및_가격제안_2026-09-08.html`, `docs/INFINITH_가격정책_사업부보고서_v1.1.docx`
- PRD: `docs/prd/INFINITH_AI-Discovery_PRD_20260828_v02.md`, `docs/prd/INFINITH_Global_Medical_Hub_PRD_v0.1.html`(Productize 에 v0.2), `docs/prd/INFINITH_Dermatology_Supporters_PRD_v0.1.html`
## 8. 이번 이틀(09-10~11)의 인사이트 · 다음 개발에 그대로 적용할 것
1. **한 세션 = 한 저장소 = 한 배포 대상.** 두 세션이 같은 Vercel 프로젝트와 같은 `supporters/` 폴더를 다른 브랜치에서 건드려 `/plan` 404 와 주변 안내 실종이 났다. 세션 시작 때 `git status`·`.vercel/project.json`·열린 세션 여부를 확인하고, 그 세션이 맡지 않은 자산은 손대지 않는다. 브랜치 통합(§4-1)이 이 문제의 근본 해결이므로 월요일 첫 일로 한다.
2. **"완료"를 산출물이 아니라 고객 결과로 정의하면 자동·사람 경계가 드러난다.** 서포터즈 사이트 완료 = 색인 작업 + 사람 체크리스트로 바꾸자 IndexNow·GSC 는 자동, 네이버 등록·소유자 추가는 사람으로 갈렸고 워커 단계가 그 경계를 코드로 가졌다. 진단(사람 판정 4항목), 병원 확인(재빌드 트리거)도 같은 방식으로 "완료 정의 → 자동 부분 → 사람 요청"을 명시한다.
3. **병원 원문은 인용 전에 걸러야 한다.** 원문 32문장 중 14건이 홍보문·정형 고지·표 조각이었다. 원문을 데이터로 쓰는 모든 경로(recoveryNotes, OCR, 뉴스 제목)에 화이트리스트 필터와 "제외된 문장 목록 눈으로 보기"를 둔다. 필터 없는 "병원 안내 기준" 배지는 의료광고 위반이다.
4. **게이트는 데이터 값도 본다.** 좌표 출처의 "실측"이 화면에 새어 나가 빌드가 막혔다. 데이터 필드마다 고객 노출 여부를 정하고 운영 기록(source·coordSource·note)은 렌더하지 않는다.
5. **규칙표를 먼저 쓰면 코드·테스트가 따라온다.** 설계 v0.2 §13 의 status(clinic/provisional)·출처 필수 규칙이 그대로 procedures.json 스키마와 게이트 테스트가 됐다. 새 기능은 데이터 규칙표부터 문서화한다.
6. **관광공사 데이터는 공급이지 수요가 아니다.** 선호는 화면에서 직접 묻고, 큐레이션이 1순위, 외부 데이터는 보강(2순위)이라는 우선순위를 점수로 코드화했다. 외부 API 를 붙일 때마다 같은 질문(공급인가 수요인가, 누가 1순위인가)을 먼저 한다.
7. **디자인 규칙은 텍스트가 아니라 리듬이다.** "흰 카드만 쌓인 페이지"는 홈·영상 페이지의 섹션 리듬(다크 히어로+글래스 통계 → 틴트 → 다크 → 라이트 → 틴트 → 다크)을 안 따라서 완성도가 낮아 보였다. 새 페이지는 기존 페이지 두 개의 구성을 먼저 분석하고 같은 리듬으로 짠다. 웜 그라디언트는 CTA 카드 한 장에만.
8. **전역 CSS 와 컴포넌트 클래스는 접두어로 분리한다.** `.kpi` 충돌로 그라디언트가 되살아났다. 컴포넌트 클래스는 `plan-`·`vm-` 처럼 접두어를 쓰고, 새 클래스는 전역 CSS 에 grep 한다.
9. **모바일 검증은 하네스로.** 헤드리스 크롬 창 최소 폭 때문에 400px 캡처가 틀렸고, 실제 문제(헤더 겹침)는 아이프레임 하네스에서만 보였다. 8페이지×3사이트 그리드 캡처를 배포 전 기본 절차로 둔다.
10. **언어 전환은 전역 하나.** 페이지별 토글은 사용자 관점에서 틀렸다. 영어 홈이 없는 사이트는 영어 입구(/en/plan)를 정해야 하고, 템플릿에 영어 홈을 넣을지는 §5-3 결정에 달렸다.
11. **기존 페이지는 haewon 확인 전에 지우거나 리다이렉트하지 않는다.** 새 기능이 기존 페이지와 같은 주제로 보여도 병존이 기본이다(주변 안내 `/stay` 와 회복 일정 `/plan`).
12. **제품 병목은 세 가지로 좁혀졌다.** 진단 결과가 코드 파일, 리드→큐 미연결, 브랜치 3개 분산. 이 셋을 풀어야 "URL 입력 → 리포트 링크 → 서포터즈 미리보기"가 사람 손 없이 이어진다.
+585
View File
@@ -0,0 +1,585 @@
#!/usr/bin/env python3
"""의료관광 연결 데이터 수집 (한국관광공사 TourAPI 다국어). 병원별로 돈다.
병원 좌표를 중심으로 숙박·음식점·관광지·문화시설·쇼핑을 모으고, 진행 중인 축제를
거리와 함께 붙여 프론트가 쓸 JSON 으로 낸다. 영문(EngService2)과 국문(KorService2)을
한 번에 만들 수 있다.
왜 사전 수집인가
영문 서비스는 도심 커버리지가 얇고 관광지 항목의 대부분이 의료기관이라 필터링이 많이
필요하다. 그 처리를 수집 시점에 끝내고 프론트는 정제된 결과만 그린다. 미팅 데모 중
외부 API 상태에 화면이 종속되지도 않는다.
무엇을 만들지 않는가
없는 값을 채우지 않는다. 평점·리뷰·영업시간은 TourAPI 가 주지 않으므로 비워 두고,
Google Places 승인 후 별도 단계에서 붙인다. 식이 적합성은 병원 입력이며 여기서
판정하지 않는다. 좌표도 지어내지 않는다. 주소를 좌표로 바꾸지 못하면 종료 코드 1 로 멈춘다.
기준 좌표를 정하는 순서
1. --lat --lng 를 직접 주면 그대로 쓴다 (coordSource: 명령 인자).
2. --address 와 --name 을 주면 네이버 지역검색(NAVER_CLIENT_ID/SECRET)으로 상호를 찾고,
결과의 도로명 주소가 준 주소의 도로명·번지와 같을 때만 그 좌표를 쓴다.
네이버가 못 찾으면 TourAPI 키워드 검색(국문·영문)으로 한 번 더 찾는다.
3. 아무 인자도 없으면 .env 의 TOUR_API_ORIGIN_LAT/LNG (초기 샘플 사이트용).
어느 경우든 meta.origin.coordSource 에 출처와 날짜를 적는다.
출력은 서포터즈 사이트(Astro)의 데이터다. 화면은 회복 일정 플래너 src/components/Planner.astro(/plan 국문, /en/plan 영문)이며
src/lib/tour.ts 가 이 JSON 을 추천 후보·숙소·축제로 바꾼다. 외국인 환자와 보호자가 보는 곳이다.
# 워커가 부르는 형태 (팩트 시트 주소 기준, 영문·국문 동시)
python3 scripts/fetch_medical_tourism.py --clinic oracle --name "오라클피부과" \
--address "서울 강남구 선릉로 612 한일빌딩" --label "오라클피부과 (선릉로 612)" \
--out-en ~/supporters-builds/oracle/tourism/medicalTourism.json \
--out-ko ~/supporters-builds/oracle/tourism/medicalTourismKo.json
# 좌표를 직접 줄 때
python3 scripts/fetch_medical_tourism.py --lat 37.5049823 --lng 127.0254182 --label "..." --out-en a.json --out-ko b.json
# 이전 방식 (.env 좌표, 언어 하나)
python3 scripts/fetch_medical_tourism.py --lang ko --out supporters/src/data/medicalTourismKo.json
"""
import argparse, io, json, math, os, re, ssl, sys, time, urllib.parse, urllib.request
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# 영문 관광지(76)의 대부분은 관광지가 아니라 의료관광 등록업소다. 반경 5km 100건 중 92건이
# 분류코드 A02020500 = "Medical Tourism Sites"(categoryCode2 로 확인)이며 병원과 유치 에이전시가
# 여기 들어 있다. 제목 키워드로는 "하이안과", "닥파인더코리아" 같은 것을 놓치므로 코드로 거른다.
CAT_MEDICAL_TOURISM = "A02020500"
# 스파·찜질방은 수술 후 회복 여정에 맞으므로 관광이 아니라 별도 범주로 뺀다.
CAT_WELLNESS = ("A02020300", "A02020400") # Hot Springs & Spa, Jjimjilbang
# 다국어 ContentTypeId. 국문과 코드가 다르다.
# 반경은 목적에 따라 다르다. 회복기에 매일 가는 곳(숙박·식사·스파)은 가깝게, 관광은 넓게 본다.
SEASON = {3: "spring", 4: "spring", 5: "spring", 6: "summer", 7: "summer", 8: "summer",
9: "autumn", 10: "autumn", 11: "autumn", 12: "winter", 1: "winter", 2: "winter"}
# ContentTypeId 는 다국어와 국문이 다르다. 같은 코드로 부르면 엉뚱한 것이 온다.
TYPES_EN = {
"76": ("attraction", "10000"),
"78": ("culture", "10000"),
"79": ("shopping", "10000"),
"80": ("stay", "5000"),
"82": ("restaurant", "5000"),
}
TYPES_KO = {
"12": ("attraction", "10000"),
"14": ("culture", "10000"),
"38": ("shopping", "10000"),
"32": ("stay", "5000"),
"39": ("restaurant", "5000"),
}
# 언어별 타입 표는 collect() 가 lang 에 맞게 고른다.
def ssl_ctx():
try:
import certifi; return ssl.create_default_context(cafile=certifi.where())
except Exception:
return ssl.create_default_context()
def load_env(path):
""".env 파일을 읽고, 같은 이름의 환경변수가 있으면 그 값을 우선한다.
워커(run.mjs)나 클라우드 실행은 파일 없이 환경변수만 줄 수 있다."""
d = {}
if os.path.exists(path):
for line in io.open(path, encoding="utf-8"):
line = line.strip()
if line and not line.startswith("#") and "=" in line:
k, v = line.split("=", 1); d[k.strip()] = v.strip().strip('"').strip("'")
for k, v in os.environ.items():
if k.startswith(("TOUR_API_", "NAVER_CLIENT_")) and v:
d[k] = v
return d
def haversine_km(lat1, lng1, lat2, lng2):
r = 6371.0
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 * r * math.asin(math.sqrt(a))
def call(env, op, extra, rows=100, retries=3, page=1):
base, svc, key = env["TOUR_API_BASE"], env["TOUR_API_SERVICE"], env["TOUR_API_KEY"]
p = {"MobileOS": "ETC", "MobileApp": "INFINITH", "_type": "json",
"numOfRows": str(rows), "pageNo": str(page), **extra}
url = f"{base}/{svc}/{op}?serviceKey={key}&" + urllib.parse.urlencode(p)
for i in range(retries):
try:
with urllib.request.urlopen(url, timeout=30, context=ssl_ctx()) as r:
body = r.read().decode("utf-8", "replace")
if body.lstrip().startswith("<"):
raise RuntimeError(f"XML 응답(인증·한도 확인): {body[:160]}")
j = json.loads(body)["response"]
if j["header"].get("resultCode") != "0000":
raise RuntimeError(f"{j['header'].get('resultCode')} {j['header'].get('resultMsg')}")
b = j.get("body", {}); items = b.get("items")
return b.get("totalCount", 0), ([] if not items or items == "" else items["item"])
except Exception as e:
if i == retries - 1: raise
time.sleep(1.5 * (i + 1))
def call_all(env, op, extra, max_pages=6, rows=100):
"""전 페이지를 모은다. 관광지는 거리순 상위 100건이 거의 다 의료관광업소라 한 페이지로는 부족하다."""
got, total = [], None
for page in range(1, max_pages + 1):
total, items = call(env, op, extra, rows=rows, page=page)
got += items
if not items or len(got) >= (total or 0): break
time.sleep(0.2)
return total, got
def walk_min(m):
"""도보 분. 80m/분(4.8km/h) 기준. 참고 사이트의 표기를 역산해 맞춘 값이다
(135m→2분, 248m→3분, 297m→4분, 566m→7분)."""
return max(1, round(m / 80))
def drive_min(km):
"""차 이동 분. 직선거리 km x 1.2. 역시 역산값이다(25km→30분, 33km→40분)."""
return max(1, round(km * 1.2))
def travel(m):
"""이동 수단과 소요 시간.
2km 까지는 걸을 수 있는 거리로 본다(약 25분). 그 위는 차·지하철이다.
짧은 거리의 차 시간은 주차와 신호 때문에 의미가 없으므로 최소 5분으로 둔다."""
if m is None: return None
if m <= 2000: return {"mode": "walk", "minutes": walk_min(m), "label": f"{walk_min(m)} min walk"}
mins = max(5, drive_min(m / 1000))
return {"mode": "drive", "minutes": mins, "label": f"{mins} min by car"}
def fetch_overview(env, content_id, cache):
"""detailCommon2 의 overview(설명문)와 homepage. locationBasedList2 는 주지 않는다.
설명문이 없으면 카드가 이름과 주소뿐이라 사람이 고를 수 없다."""
if content_id in cache: return cache[content_id]
try:
_, rows = call(env, "detailCommon2", {"contentId": content_id}, rows=1)
except Exception:
cache[content_id] = ("", ""); return cache[content_id]
if not rows: cache[content_id] = ("", ""); return cache[content_id]
r = rows[0]
ov = re.sub(r"<[^>]+>", " ", r.get("overview") or "")
ov = re.sub(r"\s+", " ", ov).strip()
hp = re.sub(r"<[^>]+>", " ", r.get("homepage") or "").strip()
hp = (re.search(r"https?://\S+", hp) or [None])[0] if hp else ""
cache[content_id] = (ov, hp or "")
return cache[content_id]
def fetch_image(env, content_id, cache):
"""locationBasedList2 의 firstimage 가 비어 있을 때 detailImage2 로 한 번 더 찾는다.
이미지 전용 오퍼레이션이라 목록 API 에 없는 사진이 여기 있다(도산공원 7장, 몽마르뜨공원 5장).
실측: 사진 없던 38건 중 15건을 여기서 살렸다. 나머지 23건은 TourAPI 에 사진이 없다."""
key = ("img", content_id)
if key in cache: return cache[key]
try:
_, rows = call(env, "detailImage2", {"contentId": content_id, "imageYN": "Y"}, rows=5)
except Exception:
cache[key] = ""; return ""
url = ""
for r in rows or []:
u = (r.get("originimgurl") or r.get("smallimageurl") or "").strip()
if u: url = u.replace("http://", "https://", 1); break
cache[key] = url
return url
def call_kor(env, op, extra, rows=10):
"""국문 서비스(KorService2). 영문 항목에 사진이 없어도 국문 항목에는 있는 경우가 있다.
같은 한국관광공사 사진이라 출처가 달라지지 않는다."""
p = {"MobileOS": "ETC", "MobileApp": "INFINITH", "_type": "json",
"numOfRows": str(rows), "pageNo": "1", **extra}
url = f"{env['TOUR_API_BASE']}/KorService2/{op}?serviceKey={env['TOUR_API_KEY']}&" + urllib.parse.urlencode(p)
try:
with urllib.request.urlopen(url, timeout=25, context=ssl_ctx()) as r:
body = r.read().decode("utf-8", "replace")
if body.lstrip().startswith("<"): return []
j = json.loads(body)["response"]
if j["header"].get("resultCode") != "0000": return []
it = j["body"].get("items")
return [] if not it or it == "" else it["item"]
except Exception:
return []
def korean_name(title):
m = re.search(r"\(([^)]+)\)\s*$", title or "")
return (m.group(1) if m else (title or "")).strip()
def fetch_image_kor(env, p):
"""국문 서비스에서 같은 이름의 항목을 찾아 사진을 가져온다. 실측 23건 중 10건이 여기서 나왔다."""
ko = korean_name(p.get("title"))
if not re.search(r"[가-힣]", ko): return ""
rows = []
if p.get("lat"):
rows = call_kor(env, "locationBasedList2",
{"mapX": str(p["lng"]), "mapY": str(p["lat"]), "radius": "300", "keyword": ko})
if not rows: rows = call_kor(env, "searchKeyword2", {"keyword": ko})
key = ko.replace(" ", "")
for r in rows:
if key in (r.get("title") or "").replace(" ", ""):
u = (r.get("firstimage") or r.get("firstimage2") or "").strip()
if u: return u.replace("http://", "https://", 1)
return ""
def fetch_image_og(url):
"""업체 공식 홈페이지의 대표 이미지(og:image). 업체가 스스로 올린 사진이라 목록에 쓰기에 무리가 없다.
검색 결과 이미지를 긁어 쓰면 식당·블로그·언론사의 저작물이라 환자용 페이지에 올릴 수 없다."""
if not url or not url.startswith("http"): return ""
try:
req = urllib.request.Request(url, headers={"User-Agent": "Mozilla/5.0"})
with urllib.request.urlopen(req, timeout=12, context=ssl_ctx()) as r:
head = r.read(120000).decode("utf-8", "replace")
base = r.geturl()
except Exception:
return ""
m = re.search(r'<meta[^>]+(?:property|name)=["\']og:image["\'][^>]*content=["\']([^"\']+)', head, re.I) \
or re.search(r'<meta[^>]+content=["\']([^"\']+)["\'][^>]+(?:property|name)=["\']og:image', head, re.I)
if not m: return ""
u = m.group(1).strip()
if u.startswith("//"): u = "https:" + u
elif u.startswith("/"):
from urllib.parse import urlparse
pr = urlparse(base); u = f"{pr.scheme}://{pr.netloc}{u}"
return u if u.startswith("https://") else ""
def usable_image(url):
"""실제로 이미지가 오는지 열어 본다. og:image 가 이미지가 아니거나(빈 content-type)
인스타 CDN 처럼 핫링크를 403 으로 막는 경우가 있어 화면에서 빈 칸이 된다."""
if not url: return False
try:
req = urllib.request.Request(url, headers={"User-Agent": "Mozilla/5.0"})
with urllib.request.urlopen(req, timeout=10, context=ssl_ctx()) as r:
return r.status == 200 and (r.headers.get("content-type") or "").startswith("image")
except Exception:
return False
def fetch_image_naver(env, p):
"""마지막 폴백. Naver 이미지 검색 API.
주의: 결과는 제3자 저작물이다. 내부 시연 목적으로만 쓰고, 공개 배포 전에는
imageSource 가 'naver' 인 항목을 걷어내거나 라이선스가 있는 사진으로 교체한다.
구글 HTML 크롤링 대신 이걸 쓰는 이유는 공식 API 라 차단되지 않고 결과가 일정해서다."""
cid, sec = env.get("NAVER_CLIENT_ID"), env.get("NAVER_CLIENT_SECRET")
if not (cid and sec): return ""
ko = korean_name(p.get("title"))
if not ko: return ""
# 지역을 붙이면 정확도가 오르지만 결과가 아예 없는 경우가 있다. 넓혀 가며 시도한다.
plain = re.sub(r"\s*\(.*\)\s*", "", p.get("title") or "").strip()
for q in (f"{ko} 서울", ko, plain):
if not q: continue
qs = urllib.parse.urlencode({"query": q, "display": "3", "sort": "sim"})
req = urllib.request.Request("https://openapi.naver.com/v1/search/image.json?" + qs,
headers={"X-Naver-Client-Id": cid, "X-Naver-Client-Secret": sec})
try:
with urllib.request.urlopen(req, timeout=15, context=ssl_ctx()) as r:
items = json.loads(r.read().decode()).get("items", [])
except Exception:
continue
for it in items:
u = (it.get("link") or "").strip()
if u.startswith("https://"): return u
return ""
def bucket(it):
"""분류코드로 범주를 정한다. None 이면 버린다."""
cat3 = (it.get("cat3") or "").strip()
if cat3 == CAT_MEDICAL_TOURISM: return None
if cat3 in CAT_WELLNESS: return "wellness"
return "keep"
def clean(it, lat, lng):
"""TourAPI 원본에서 화면이 쓸 필드만 남긴다. mapx=경도, mapy=위도 (이름과 반대라 자주 틀린다)."""
try:
ilng, ilat = float(it.get("mapx") or 0), float(it.get("mapy") or 0)
except ValueError:
ilng = ilat = 0.0
dist = it.get("dist")
return {
"id": it.get("contentid"),
"title": (it.get("title") or "").strip(),
"address": (it.get("addr1") or "").strip(),
# TourAPI 는 이미지 URL 을 http 로 준다. https 사이트에서 혼합 콘텐츠로 차단되므로 올린다.
# tong.visitkorea.or.kr 은 https 로도 같은 파일을 준다(실측 확인).
"image": (lambda u: u.replace("http://", "https://", 1) if u else None)(
it.get("firstimage") or it.get("firstimage2") or None),
"imageSource": "tourapi" if (it.get("firstimage") or it.get("firstimage2")) else "",
"tel": (it.get("tel") or "").strip() or None,
"lat": ilat or None, "lng": ilng or None,
"distanceM": round(float(dist)) if dist else (
round(haversine_km(lat, lng, ilat, ilng) * 1000) if ilat and ilng else None),
"travel": travel(round(float(dist)) if dist else (
round(haversine_km(lat, lng, ilat, ilng) * 1000) if ilat and ilng else None)),
# detailCommon2 로 따로 채운다(locationBasedList2 는 설명문을 주지 않는다).
"overview": "", "homepage": "",
# TourAPI 가 주지 않는 값. Google Places 승인 후 채운다. 지금은 비워 둔다.
"rating": None, "reviewCount": None, "openingHours": None,
}
# ---------- 기준 좌표 ----------
def road_key(address):
"""주소에서 도로명과 건물번호를 뽑는다. "서울 강남구 선릉로 612 한일빌딩" → ("선릉로", "612").
비교에만 쓴다. 없으면 (None, None)."""
m = re.search(r"([가-힣A-Za-z0-9]*?(?:대로|로|길))\s*(\d+(?:-\d+)?)(?!\s*길)", address or "")
return (m.group(1), m.group(2)) if m else (None, None)
def addr_match(want, got):
"""검색 결과 주소가 준 주소와 같은 도로명·번지인지. 도로명과 번지 사이 공백은 무시하고,
번지 바로 뒤에 숫자나 '-' 가 붙으면(612 와 6120, 612-1) 다른 곳으로 본다.
"봉은사로 107 1, 3-5층" 처럼 공백 뒤에 층이 오는 것은 같은 곳이다."""
road, num = road_key(want)
if not road: return False
return re.search(re.escape(road) + r"\s*" + re.escape(num) + r"(?![\d-])", got or "") is not None
def strip_tags(s):
return re.sub(r"<[^>]+>", "", s or "").strip()
def geocode_naver(env, name, address):
"""네이버 지역검색으로 상호를 찾아 좌표를 얻는다. mapx/mapy 는 WGS84 경위도 x 10^7 이다.
주소만으로는 결과가 없다(실측). 상호를 넣고, 결과의 도로명 주소가 준 주소와 같을 때만 받는다."""
cid, sec = env.get("NAVER_CLIENT_ID"), env.get("NAVER_CLIENT_SECRET")
if not (cid and sec): return None, "NAVER_CLIENT_ID/SECRET 없음"
road, num = road_key(address)
queries = []
if road: queries.append(f"{name} {road} {num}")
queries += [f"{name} {address}", name]
tried = []
for q in queries:
qs = urllib.parse.urlencode({"query": q, "display": "5", "sort": "random"})
req = urllib.request.Request("https://openapi.naver.com/v1/search/local.json?" + qs,
headers={"X-Naver-Client-Id": cid, "X-Naver-Client-Secret": sec})
try:
with urllib.request.urlopen(req, timeout=15, context=ssl_ctx()) as r:
items = json.loads(r.read().decode()).get("items", [])
except Exception as e:
tried.append(f"'{q}': 요청 실패 {e}"); continue
for it in items:
got = it.get("roadAddress") or it.get("address") or ""
if not addr_match(address, got): continue
try:
lng, lat = int(it["mapx"]) / 1e7, int(it["mapy"]) / 1e7
except (KeyError, ValueError):
continue
if not (33 <= lat <= 39 and 124 <= lng <= 132): continue
return {"lat": lat, "lng": lng, "matched": strip_tags(it.get("title")), "matchedAddress": got,
"coordSource": f"네이버 지역검색 '{strip_tags(it.get('title'))}' ({got}) {time.strftime('%Y-%m-%d')}"}, ""
tried.append(f"'{q}': {len(items)}건, 주소 일치 없음")
return None, "; ".join(tried)
def geocode_tourapi(env, name, address):
"""TourAPI 키워드 검색(국문·영문)으로 병원 항목을 찾는다. 등재된 병원만 나오므로 보조 수단이다."""
tried = []
for svc in ("KorService2", "EngService2"):
e = dict(env, TOUR_API_SERVICE=svc)
try:
_, rows = call(e, "searchKeyword2", {"keyword": name}, rows=20, retries=1)
except Exception as ex:
tried.append(f"{svc}: 요청 실패 {ex}"); continue
for it in rows:
got = it.get("addr1") or ""
if not addr_match(address, got): continue
try:
lng, lat = float(it.get("mapx") or 0), float(it.get("mapy") or 0)
except ValueError:
continue
if not (33 <= lat <= 39 and 124 <= lng <= 132): continue
return {"lat": lat, "lng": lng, "matched": (it.get("title") or "").strip(), "matchedAddress": got,
"coordSource": f"한국관광공사 TourAPI {svc} contentid {it.get('contentid')} ({got}) {time.strftime('%Y-%m-%d')}"}, ""
tried.append(f"{svc}: {len(rows)}건, 주소 일치 없음")
return None, "; ".join(tried)
def resolve_origin(env, a):
"""기준 좌표와 출처. 못 정하면 (None, 이유)."""
if a.lat is not None or a.lng is not None:
if a.lat is None or a.lng is None: return None, "--lat 와 --lng 는 함께 줘야 합니다"
return {"lat": a.lat, "lng": a.lng, "address": a.address or "",
"coordSource": f"명령 인자 --lat/--lng {time.strftime('%Y-%m-%d')}"}, ""
if a.address:
if not a.name: return None, "--address 에는 --name(검색할 상호)이 필요합니다. 주소만으로는 지역검색 결과가 없습니다"
road, num = road_key(a.address)
if not road: return None, f"주소에서 도로명·번지를 찾지 못했습니다: {a.address}"
found, why1 = geocode_naver(env, a.name, a.address)
if found: return dict(found, address=a.address), ""
found, why2 = geocode_tourapi(env, a.name, a.address)
if found: return dict(found, address=a.address), ""
return None, f"주소를 좌표로 바꾸지 못했습니다. 네이버 지역검색: {why1} / TourAPI: {why2}"
lat, lng = env.get("TOUR_API_ORIGIN_LAT"), env.get("TOUR_API_ORIGIN_LNG")
if not (lat and lng): return None, "기준 좌표가 없습니다. --address --name 또는 --lat --lng 를 주거나 .env 의 TOUR_API_ORIGIN_LAT/LNG 를 채우세요"
return {"lat": float(lat), "lng": float(lng), "address": "",
"coordSource": f".env TOUR_API_ORIGIN_LAT/LNG {time.strftime('%Y-%m-%d')}"}, ""
# ---------- 수집 ----------
def collect(env, lang, origin, a):
"""한 언어의 데이터를 모아 dict 로 돌려준다. 파일은 쓰지 않는다."""
types = TYPES_KO if lang == "ko" else TYPES_EN
env = dict(env, TOUR_API_SERVICE="KorService2" if lang == "ko" else "EngService2")
lat, lng = origin["lat"], origin["lng"]
print(f"\n[{lang}] {env['TOUR_API_SERVICE']} · 기준 {lat}, {lng}")
out = {"places": {}, "festivals": [], "filters": {}, "meta": {}}
filtered_log = {}
wellness = []
for ct, (name, radius) in types.items():
total, rows = call_all(env, "locationBasedList2",
{"mapX": str(lng), "mapY": str(lat), "radius": radius,
"contentTypeId": ct, "arrange": "E"})
kept, dropped = [], []
for it in rows:
b = bucket(it)
if b is None:
dropped.append((it.get("title") or "").strip()); continue
(wellness if b == "wellness" else kept).append(clean(it, lat, lng))
kept.sort(key=lambda x: x["distanceM"] if x["distanceM"] is not None else 10 ** 9)
out["places"][name] = kept[:a.per_type]
filtered_log[name] = {"apiTotal": total, "fetched": len(rows), "radiusM": int(radius),
"droppedMedicalTourism": len(dropped), "kept": len(kept),
"shown": len(out["places"][name]), "droppedSample": dropped[:5]}
print(f" {name:<11} r={radius:>5}m · API {total:>4} · 받음 {len(rows):>3} · 의료관광업소 제외 {len(dropped):>3} · 담음 {len(out['places'][name])}")
wellness.sort(key=lambda x: x["distanceM"] if x["distanceM"] is not None else 10 ** 9)
out["places"]["wellness"] = wellness[:a.per_type]
filtered_log["wellness"] = {"note": "관광지에서 스파·찜질방 분류만 분리", "shown": len(out["places"]["wellness"])}
print(f" {'wellness':<11} 스파·찜질방 분리 · 담음 {len(out['places']['wellness'])}")
# 영문 축제는 areacode 필드가 비어 있어 지역 필터를 쓸 수 없다. 좌표로 거리를 계산해 거른다.
today = time.strftime("%Y%m%d")
total, rows = call(env, "searchFestival2", {"eventStartDate": today, "arrange": "A"}, rows=300)
near, nocoord = [], 0
for it in rows:
c = clean(it, lat, lng)
if c["lat"] is None: nocoord += 1; continue
km = haversine_km(lat, lng, c["lat"], c["lng"])
if km > a.festival_km: continue
sd = it.get("eventstartdate") or ""
c.update(startDate=sd, endDate=it.get("eventenddate"),
distanceKm=round(km, 1), month=(int(sd[4:6]) if len(sd) == 8 else None),
season=SEASON.get(int(sd[4:6]), "") if len(sd) == 8 else "")
near.append(c)
near.sort(key=lambda x: x["startDate"] or "")
out["festivals"] = near[:a.per_type]
print(f" festival API {total:>4}건 · 받음 {len(rows):>3} · 좌표없음 {nocoord} · {a.festival_km:.0f}km 이내 {len(near)}")
# 설명문은 항목마다 detailCommon2 를 한 번씩 부른다. 카드에 이름과 주소만 있으면 고를 수 없다.
cache: dict = {}
targets = [p for v in out["places"].values() for p in v] + out["festivals"]
print(f" 설명문 수집 {len(targets)}건", end="", flush=True)
for i, p in enumerate(targets):
if not p.get("id"): continue
ov, hp = fetch_overview(env, p["id"], cache)
p["overview"] = ov[:600]
p["homepage"] = hp
if not p.get("image"):
# 1) 같은 언어 detailImage2 → 2) 국문 서비스 → 3) 업체 홈페이지 og:image → 4) Naver 이미지 검색
src = ""
img = fetch_image(env, p["id"], cache)
if img: src = "tourapi"
if not img and lang == "en":
img = fetch_image_kor(env, p); src = "tourapi-kor" if img else src
if not img:
cand = fetch_image_og(p.get("homepage") or "")
if cand and usable_image(cand): img, src = cand, "homepage"
if not img and not a.no_naver_images:
img = fetch_image_naver(env, p); src = "naver" if img else src
p["image"] = img or None
p["imageSource"] = src
if i % 20 == 0: print(".", end="", flush=True)
time.sleep(0.12)
got = sum(1 for p in targets if p["overview"])
pic = sum(1 for p in targets if p.get("image"))
print(f" 완료 · 설명문 {got}/{len(targets)} · 사진 {pic}/{len(targets)}")
# 도보 시간 구간별 건수. 화면의 필터 칩이 이 수를 쓴다.
allp = [p for v in out["places"].values() for p in v]
# 누적 기준이다. "15분 이내"는 5분 이내도 포함한다. 사람이 고르는 방식에 맞춘다.
def walk_upto(mins):
return sum(1 for p in allp if p.get("travel") and p["travel"]["mode"] == "walk"
and p["travel"]["minutes"] <= mins)
out["filters"] = {
"total": len(allp),
"walk5": walk_upto(5),
"walk15": walk_upto(15),
"walkAll": sum(1 for p in allp if p.get("travel") and p["travel"]["mode"] == "walk"),
"drive": sum(1 for p in allp if not p.get("travel") or p["travel"]["mode"] != "walk"),
}
out["meta"] = {
"lang": lang,
"clinic": a.clinic or "",
"source": "한국관광공사 TourAPI " + env["TOUR_API_SERVICE"],
"fetchedAt": time.strftime("%Y-%m-%dT%H:%M:%S"),
"origin": {"lat": lat, "lng": lng, "label": a.label or origin.get("matched") or origin.get("address") or "",
"address": origin.get("address", ""), "coordSource": origin["coordSource"]},
"radiusByType": {n: int(r) for n, r in types.values()}, "festivalRadiusKm": a.festival_km,
"counts": filtered_log,
# 화면이 한계를 그대로 표시할 수 있게 데이터에 적어 둔다. 없는 값을 채우지 않는다.
"limits": [
"영문 서비스는 도심 숙박·음식점 커버리지가 국문보다 얇다.",
"관광지 항목 중 분류코드 A02020500 \"Medical Tourism Sites\"(병원·유치업체)는 제외했다.",
"평점·리뷰·영업시간은 TourAPI 가 제공하지 않는다. Google Places 승인 후 채운다.",
"영문 축제는 areacode 필드가 비어 있어 좌표 거리로 걸렀다.",
"수술 전후 식이 적합성은 병원이 입력한 가이드로만 표시한다. 이 파일에는 없다.",
],
}
return out
def main():
ap = argparse.ArgumentParser(description="병원 주변 관광 데이터 수집 (TourAPI)")
ap.add_argument("--clinic", default="", help="병원 id (meta.clinic)")
ap.add_argument("--name", default="", help="지역검색에 쓸 상호. --address 와 함께 준다")
ap.add_argument("--address", default="", help="병원 주소. 네이버 지역검색으로 좌표를 찾는다")
ap.add_argument("--lat", type=float, default=None); ap.add_argument("--lng", type=float, default=None)
ap.add_argument("--label", default="", help="화면에 보일 기준점 이름 (meta.origin.label)")
ap.add_argument("--out-en", default="", help="영문 JSON 경로 (절대 또는 현재 폴더 기준)")
ap.add_argument("--out-ko", default="", help="국문 JSON 경로")
ap.add_argument("--festival-km", type=float, default=60.0, help="이 거리 안의 축제만 담는다")
ap.add_argument("--per-type", type=int, default=24, help="타입별 최대 건수")
ap.add_argument("--no-naver-images", action="store_true", help="네이버 이미지 검색 폴백을 끈다 (공개 배포용)")
ap.add_argument("--lang", choices=["en", "ko"], default="en", help="(이전 방식) --out 하나만 낼 때의 언어")
ap.add_argument("--out", default="", help="(이전 방식) 저장소 루트 기준 경로")
a = ap.parse_args()
env = load_env(os.path.join(ROOT, ".env"))
for k in ("TOUR_API_KEY", "TOUR_API_BASE"):
if not env.get(k): sys.exit(f"{k} 가 비어 있습니다 (.env 또는 환경변수)")
origin, why = resolve_origin(env, a)
if not origin:
print(f"기준 좌표 실패: {why}", file=sys.stderr); sys.exit(1)
print(f"기준 좌표 {origin['lat']}, {origin['lng']} · {origin['coordSource']}")
jobs = []
if a.out_en: jobs.append(("en", os.path.abspath(a.out_en)))
if a.out_ko: jobs.append(("ko", os.path.abspath(a.out_ko)))
if not jobs:
rel = a.out or ("supporters/src/data/medicalTourism.json" if a.lang == "en" else "supporters/src/data/medicalTourismKo.json")
jobs.append((a.lang, os.path.join(ROOT, rel)))
for lang, path in jobs:
out = collect(env, lang, origin, a)
os.makedirs(os.path.dirname(path), exist_ok=True)
io.open(path, "w", encoding="utf-8").write(json.dumps(out, ensure_ascii=False, indent=2))
print(f"→ {path} · 장소 {out['filters']['total']} · 축제 {len(out['festivals'])}")
if __name__ == "__main__":
main()
@@ -16,6 +16,7 @@
"a",
"a",
"a",
"a",
"a.lang-switch",
"a.cta",
"main",
@@ -287,6 +288,7 @@
"a",
"a",
"a",
"a",
"a.lang-switch",
"a.cta",
"div.backbar-wrap",
@@ -515,6 +517,7 @@
"a",
"a",
"a",
"a",
"a.lang-switch",
"a.cta",
"div.backbar-wrap",
+32
View File
@@ -2,10 +2,12 @@
import { readFileSync } from 'node:fs';
import assert from 'node:assert/strict';
import { buildPlan, addDays, decodeHash, encodeHash, bookingUrl, googleFlightsUrl, buildIcs } from '../../src/lib/plan.ts';
import { tourToPlaces, festivalsDuring, levelByDistance, bookingName } from '../../src/lib/tour.ts';
const here = (p) => new URL(p, import.meta.url);
const P = JSON.parse(readFileSync(here('../../src/data/procedures.json'), 'utf8'));
const PL = JSON.parse(readFileSync(here('../../src/data/places.json'), 'utf8'));
const TKO = JSON.parse(readFileSync(here('../../src/data/medicalTourismKo.json'), 'utf8'));
const byId = (id) => P.procedures.find((x) => x.id === id);
const nat = (code) => P.nationalities.list.find((x) => x.code === code);
@@ -95,4 +97,34 @@ ok('규칙표 정합성: 숫자마다 status, provisional 은 source 없어도
for (const pl of PL.places) { assert.ok(PL.categories[pl.category], `${pl.id} 카테고리`); assert.ok(pl.name.ko && pl.name.en, `${pl.id} 이름`); }
});
const HAS_TOUR = Object.values(TKO.places ?? {}).some((v) => Array.isArray(v) && v.length); // 템플릿 빈 데이터면 관광공사 검사는 건너뛴다
ok('TourAPI 어댑터: 카테고리 매핑, 사우나 제외, 음식점은 일반식만, 거리 등급', () => {
assert.equal(levelByDistance(400), 1); assert.equal(levelByDistance(2500), 2); assert.equal(levelByDistance(9000), 3);
assert.equal(bookingName('K-그랜드 호스텔 강남 1(K-GRAND HOSTEL GANGNAM1)'), 'K-GRAND HOSTEL GANGNAM1');
if (!HAS_TOUR) { console.log(' (관광공사 데이터 없음: 변환 검사 건너뜀)'); return; }
const tp = tourToPlaces(TKO, 'ko');
assert.ok(tp.length > 50, `변환 ${tp.length}건`);
assert.ok(tp.every((p) => p.source === 'tourapi'));
assert.ok(!tp.some((p) => p.id.startsWith('tour-wellness-')), '사우나·스파가 후보에 들어감');
assert.ok(tp.filter((p) => p.category === 'food').every((p) => p.dietOk.length === 1 && p.dietOk[0] === 'normal'));
});
ok('큐레이션이 TourAPI 보다 먼저 나오고 유동식 단계에는 TourAPI 음식점이 없음', () => {
if (!HAS_TOUR) return;
const tp = tourToPlaces(TKO, 'ko');
const all = [...PL.places.map((x) => ({ ...x, source: 'curated' })), ...tp];
const plan = buildPlan({ procedure: byId('contour'), surgeryDate: '2026-11-03', nationality: null, prefs: ['food'] }, all);
for (const d of plan.days.filter((d) => d.diet === 'liquid')) for (const p of d.picks) assert.ok(!(p.source === 'tourapi' && p.category === 'food'), `${d.date} ${p.id}`);
const first = plan.days.find((d) => d.picks.length);
assert.equal(first.picks[0].source, 'curated');
});
ok('축제: 체류 기간과 겹치는 것만, L3 날에만 붙음', () => {
if (!HAS_TOUR) return;
const fest = festivalsDuring(TKO, '2026-11-01', '2026-11-17');
for (const f of fest) assert.ok(f.start <= '2026-11-17' && f.end >= '2026-11-01');
const plan = buildPlan({ procedure: byId('skin'), surgeryDate: '2026-11-03', nationality: null, prefs: [], festivals: fest }, PL.places);
for (const d of plan.days) if (d.festivals.length) assert.ok(d.level >= 3, `${d.date} L${d.level}`);
});
console.log(`plan.test: ${n}건 통과`);
+40 -13
View File
@@ -6,12 +6,18 @@ import '../styles/plan.css';
import strings from '../data/planStrings.json';
import P from '../data/procedures.json';
import PL from '../data/places.json';
import TKO from '../data/medicalTourismKo.json';
import TEN from '../data/medicalTourism.json';
import { tourToPlaces } from '../lib/tour';
interface Props { lang: 'ko' | 'en' }
const { lang } = Astro.props;
const t = strings[lang];
const tour = tourToPlaces((lang === 'en' ? TEN : TKO) as any, lang);
const nProcs = P.procedures.length;
const nPlaces = PL.places.filter((x) => x.category !== 'hotel').length;
const nHotels = PL.places.filter((x) => x.category === 'hotel').length;
const nPlaces = PL.places.filter((x) => x.category !== 'hotel').length + tour.filter((x) => x.category !== 'hotel').length;
const nHotels = PL.places.filter((x) => x.category === 'hotel').length + tour.filter((x) => x.category === 'hotel').length;
const procList = (P.procedures as any[]).map((x) => x.label[lang]).join(lang === 'ko' ? '·' : ', ');
const originLabel = (PL as any).origin?.label?.[lang] ?? '';
---
<section class="section dark plan-hero">
<div class="wrap-wide">
@@ -21,8 +27,8 @@ const nHotels = PL.places.filter((x) => x.category === 'hotel').length;
<p class="lede"><strong>{t.title}</strong> {t.lede}</p>
</div>
<div class="stats">
<div class="stat"><b>{nProcs}</b><span class="label">{t.stat_procs}</span><span class="desc">{t.stat_procs_d}</span></div>
<div class="stat"><b>{nPlaces}</b><span class="label">{t.stat_places}</span><span class="desc">{t.stat_places_d}</span></div>
<div class="stat"><b>{nProcs}</b><span class="label">{t.stat_procs}</span><span class="desc">{procList}</span></div>
<div class="stat"><b>{nPlaces}</b><span class="label">{t.stat_places}</span><span class="desc">{(tour.length ? t.stat_places_d : t.stat_places_d_curated).replace('{origin}', originLabel)}</span></div>
<div class="stat"><b>{nHotels}</b><span class="label">{t.stat_hotels}</span><span class="desc">{t.stat_hotels_d}</span></div>
<div class="stat"><b>0</b><span class="label">{t.stat_privacy}</span><span class="desc">{t.stat_privacy_d}</span></div>
</div>
@@ -39,12 +45,19 @@ const nHotels = PL.places.filter((x) => x.category === 'hotel').length;
import PL from '../data/places.json';
import STR from '../data/planStrings.json';
import factSheet from '../data/factSheet.json';
import TKO from '../data/medicalTourismKo.json';
import TEN from '../data/medicalTourism.json';
import { tourToPlaces, festivalsDuring } from '../lib/tour';
import { buildPlan, encodeHash, decodeHash, bookingUrl, googleFlightsUrl, mapUrl, buildIcs, summaryText, isIsoDate, addDays } from '../lib/plan';
import type { Lang, Procedure, Place, Nationality, Plan, PlanDay } from '../lib/plan';
type Strings = Record<string, string>;
const procedures = P.procedures as unknown as Procedure[];
const places = PL.places as unknown as Place[];
const curated = (PL.places as unknown as Place[]).map((x) => ({ ...x, source: 'curated' as const }));
const root0 = document.getElementById('planner')!;
const tourData = ((root0.dataset.lang === 'en' ? TEN : TKO) as any);
const places: Place[] = [...curated, ...tourToPlaces(tourData, root0.dataset.lang === 'en' ? 'en' : 'ko')];
const tourDate: string = String(tourData?.meta?.fetchedAt ?? '').slice(0, 10);
const nationalities = P.nationalities.list as Nationality[];
const PREFS = ['sightseeing', 'shopping', 'food', 'kpop', 'care'];
const root = document.getElementById('planner')!;
@@ -134,7 +147,8 @@ const nHotels = PL.places.filter((x) => x.category === 'hotel').length;
}
function pickHtml(p: Place): string {
const t = T();
const meta = `<small>${p.distanceKm <= 0.6 ? esc(t.walk) : esc(t.taxi)} ${esc(fill(t.km, { km: p.distanceKm }))}${p.indoor ? ' · ' + esc(t.indoor) : ''}</small>`;
const dist = p.travelLabel ? esc(p.travelLabel) : `${p.distanceKm <= 0.6 ? esc(t.walk) : esc(t.taxi)} ${esc(fill(t.km, { km: p.distanceKm }))}`;
const meta = `<small>${dist}${p.indoor ? ' · ' + esc(t.indoor) : ''}${p.source === 'tourapi' ? ' · ' + esc(t.tour_badge) : ''}</small>`;
return p.mapQuery ? `<a href="${mapUrl(p.mapQuery)}" rel="noopener" target="_blank" title="${L(p.note)}">${L(p.name)} ${meta}</a>` : `<span class="pick" title="${L(p.note)}">${L(p.name)} ${meta}</span>`;
}
@@ -198,7 +212,8 @@ const nHotels = PL.places.filter((x) => x.category === 'hotel').length;
const days = plan.days.map((d) => {
const ev = eventLabel(d);
const lvl = lv(d.level);
const picks = d.picks.length ? `<div class="picks">${d.picks.map(pickHtml).join('')}</div>` : d.level === 0 || d.isSurgery ? `<div class="rest">${esc(t.noPicks)}</div>` : '';
const festPicks = d.festivals.map((f) => `<a href="#fest-${esc(f.id)}" class="fest"><span class="tag l3">${esc(t.festival_pick)}</span> ${esc(f.title)}</a>`).join('');
const picks = d.picks.length || festPicks ? `<div class="picks">${festPicks}${d.picks.map(pickHtml).join('')}</div>` : d.level === 0 || d.isSurgery ? `<div class="rest">${esc(t.noPicks)}</div>` : '';
const dietTag = d.offset >= 0 && d.diet !== 'normal' ? `<span class="tag diet" title="${L(diets[d.diet].desc)}">${esc(t.diet)}: ${L(diets[d.diet].label)}</span>` : '';
return `<div class="day ${ev ? 'mark' : ''}"><div class="d"><b>${esc(fmtDate(d.date))}</b><span>${esc(dayLabel(d))}</span>${ev ? `<span class="ev">${esc(ev)}</span>` : ''}</div><div class="body"><div class="tags"><span class="tag l${d.level}">${esc(t.level)}: ${L(lvl.label)}</span>${dietTag}<span class="desc">${L(lvl.desc)}</span></div>${picks}</div></div>`;
}).join('');
@@ -208,10 +223,19 @@ const nHotels = PL.places.filter((x) => x.category === 'hotel').length;
<div class="timeline">${days}</div>
</div></section>`;
// 다크 섹션: 예약과 저장
// 라이트 섹션: 체류 기간의 행사 (TourAPI)
const firstL3 = plan.days.find((d) => d.level >= 3)?.date ?? null;
const festCards = lastFest.map((f) => {
const from = firstL3 && firstL3 <= f.end ? fill(t.fest_from, { d: fmtDate(firstL3 < f.start ? f.start : firstL3) }) : t.fest_notYet;
return `<div class="card fest-card" id="fest-${esc(f.id)}">${f.image ? `<img src="${esc(f.image)}" alt="${esc(f.title)}" loading="lazy" onerror="this.remove()" />` : ''}<div class="cat">${esc(fill(t.fest_when, { a: f.start.slice(5).replace('-', '.'), b: f.end.slice(5).replace('-', '.') }))} · ${esc(f.travelLabel ?? fill(t.km, { km: f.distanceKm }))}</div><h3>${esc(f.title)}</h3><p>${esc(f.blurb)}</p><p class="fine"><span class="tag ${firstL3 && firstL3 <= f.end ? 'l3' : 'l0'}">${esc(from)}</span> ${f.url ? `<a href="${esc(f.url)}" rel="noopener" target="_blank">${esc(t.readMoreShort)}</a> · ` : ''}<a href="${mapUrl(f.title)}" rel="noopener" target="_blank">${esc(t.map)}</a></p></div>`;
}).join('');
const festSec = `<section class="section light"><div class="wrap-wide">${secHead('Events', t.h_fest, t.sub_fest)}${festCards ? `<div class="grid">${festCards}</div>` : `<p class="sub" style="color:var(--slate-500)">${esc(t.fest_none)}</p>`}${tourDate ? `<p class="fine" style="margin-top:1rem">${esc(fill(t.source_tour, { date: tourDate }))}</p>` : ''}</div></section>`;
// 다크 섹션: 예약과 저장 (큐레이션 숙소 + TourAPI 숙박 가까운 순 6곳)
const checkin = plan.arriveBy, checkout = plan.earliestDeparture ?? addDays(plan.surgeryDate, 14);
const hotels = places.filter((x) => x.category === 'hotel').sort((a, b) => a.distanceKm - b.distanceKm).map((h) => `
<div class="card"><div class="cat">${L(h.area)} · ${esc(fill(t.km, { km: h.distanceKm }))}</div><h3>${L(h.name)}</h3><p>${L(h.note)}</p>
const hotelList = [...places.filter((x) => x.category === 'hotel' && x.source !== 'tourapi'), ...places.filter((x) => x.category === 'hotel' && x.source === 'tourapi').sort((a, b) => a.distanceKm - b.distanceKm).slice(0, 6)];
const hotels = hotelList.map((h) => `
<div class="card"><div class="cat">${L(h.area)} · ${esc(h.travelLabel ?? fill(t.km, { km: h.distanceKm }))}${h.source === 'tourapi' ? ' · ' + esc(t.tour_badge) : ''}</div><h3>${L(h.name)}</h3><p>${L(h.note)}</p>
<div class="links"><a href="${bookingUrl(h.bookingQuery ?? (h.name as any).en, checkin, checkout, state.lang)}" rel="noopener sponsored" target="_blank">${esc(t.hotelSearch)}</a>${h.mapQuery ? `<a href="${mapUrl(h.mapQuery)}" rel="noopener" target="_blank">${esc(t.map)}</a>` : ''}</div></div>`).join('');
const srcs = p.sources.map((id) => (P as any).clinicSources.find((s: any) => s.id === id)).filter(Boolean).map((s: any) => `<li><a href="${esc(s.url)}" rel="noopener" target="_blank">${L(s.label)}</a></li>`).join('');
const bookSec = `<section class="section dark"><div class="wrap-wide">
@@ -224,19 +248,22 @@ const nHotels = PL.places.filter((x) => x.category === 'hotel').length;
<div class="card"><div class="cat">Save</div><h3>${esc(t.ics)}</h3><p>${esc(t.hotelHint)}</p><div class="plan-actions"><button type="button" class="btn ghost small" data-action="ics">${esc(t.ics)}</button><button type="button" class="btn ghost small" data-action="share">${esc(t.shareLink)}</button><button type="button" class="btn ghost small" data-action="print">${esc(t.print)}</button></div></div>
</div>
<p class="disclosure">${esc(t.affiliate)} ${esc(t.medical)}</p>
${srcs ? `<p class="note" style="margin-top:0.6rem">${esc(t.sourceLabel)}</p><ul class="sources-list">${srcs}</ul>` : ''}
<p class="note" style="margin-top:0.6rem">${esc(t.sourceLabel)}</p><ul class="sources-list">${srcs}${tourDate ? `<li>${esc(fill(t.source_tour, { date: tourDate }))}</li>` : ''}</ul>
</div></section>`;
return scheduleSec + rulesSec + daysSec + bookSec;
return scheduleSec + rulesSec + daysSec + festSec + bookSec;
}
let lastPlan: Plan | null = null;
let lastFest: ReturnType<typeof festivalsDuring> = [];
function render() {
const p = currentProc();
lastPlan = null;
let result = renderEmpty();
if (p && isIsoDate(state.date)) {
lastPlan = buildPlan({ procedure: p, surgeryDate: state.date, nationality: currentNat(), prefs: state.prefs }, places);
const pre = buildPlan({ procedure: p, surgeryDate: state.date, nationality: currentNat(), prefs: state.prefs }, places);
lastFest = festivalsDuring(tourData, pre.arriveBy, pre.earliestDeparture ?? addDays(pre.surgeryDate, 14));
lastPlan = buildPlan({ procedure: p, surgeryDate: state.date, nationality: currentNat(), prefs: state.prefs, festivals: lastFest }, places);
result = renderResult(lastPlan, p);
}
root.innerHTML = renderInput() + result;
+103
View File
@@ -0,0 +1,103 @@
---
// 오시는 길: 지도 + 주소 복사 + 길찾기 버튼. 방문 안내(/visit) 3. 찾아가기와 영어 홈 Getting Here 에서 쓴다.
// 좌표는 factSheet.geo {lat,lng,source} 를 먼저 보고(source 는 운영 기록이라 화면에 내지 않는다), 없으면 관광공사 수집 메타(medicalTourismKo.json meta.origin)를 쓴다. 둘 다 없으면 지도 없이 주소·버튼만 낸다.
// 지도는 OpenStreetMap 타일 + Leaflet(cdnjs). 길찾기는 네이버·카카오 지도의 공개 URL 형식(벤치마크 2026-09-11 확인)이고, 영어 화면에는 구글 지도 길찾기를 더한다.
import { fact, has, v } from '../lib';
import tour from '../data/medicalTourismKo.json';
interface Props { lang?: 'ko' | 'en'; nameEn?: string; addressEn?: string; title?: string; sub?: string; compact?: boolean; hideHead?: boolean }
const { lang = 'ko', nameEn, addressEn, title, sub, compact = false, hideHead = false } = Astro.props;
const f = fact as Record<string, any>;
const origin = (tour as any)?.meta?.origin ?? {};
const geo = f.geo && f.geo.lat && f.geo.lng ? f.geo : (origin.lat && origin.lng ? { lat: origin.lat, lng: origin.lng, source: origin.coordSource || '관광공사 수집 기준 좌표' } : null);
const nameKo = v(f.shortName, '병원');
const name = lang === 'en' ? (nameEn || f.shortNameEn || f.nameEn || nameKo) : nameKo;
const address = lang === 'en' ? (addressEn || f.address?.fullEn || f.address?.full || '') : (f.address?.full || '');
const phone: string = f.phone || '';
const enc = encodeURIComponent;
const naverUrl = geo ? `https://map.naver.com/p/directions/-/${geo.lng},${geo.lat},${enc(nameKo)}/-/transit` : (has(f.address?.full) ? `https://map.naver.com/p/search/${enc(f.address.full)}` : '');
const kakaoUrl = geo ? `https://map.kakao.com/link/to/${enc(nameKo)},${geo.lat},${geo.lng}` : (has(f.address?.full) ? `https://map.kakao.com/link/search/${enc(f.address.full)}` : '');
const googleUrl = geo ? `https://www.google.com/maps/dir/?api=1&destination=${geo.lat},${geo.lng}&destination_place_id=&travelmode=transit` : (address ? `https://www.google.com/maps/search/?api=1&query=${enc(address)}` : '');
const T = lang === 'en'
? { title: title ?? 'Getting Here', sub: sub ?? 'Address, and directions from where you are.', address: 'Address', copy: 'Copy', copied: 'Copied', phone: 'Phone', naver: 'Naver Map directions', kakao: 'Kakao Map directions', google: 'Google Maps directions', noMap: 'Map is added once the clinic confirms its location.', attribution: 'Map data © OpenStreetMap contributors' }
: { title: title ?? '오시는 길', sub: sub ?? '주소와 현재 위치에서 오는 길을 안내합니다.', address: '주소', copy: '복사', copied: '복사했습니다', phone: '문의', naver: '네이버 길찾기', kakao: '카카오 길찾기', google: '구글 지도 길찾기', noMap: '지도는 병원이 위치를 확인한 뒤 싣습니다.', attribution: '지도 데이터 © OpenStreetMap 기여자' };
const mapId = `visit-map-${Math.random().toString(36).slice(2, 8)}`;
---
{geo && <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.9.4/leaflet.min.css" crossorigin="" />}
<section class={`visit-map ${compact ? 'compact' : ''}`}>
{!compact && !hideHead && <div class="vm-head"><div class="eyebrow">Directions</div><h2 class="serif">{T.title}</h2><p class="sub">{T.sub}</p></div>}
<div class="vm-grid">
<div class="vm-map-wrap">
{geo
? <div class="vm-map" id={mapId} data-lat={geo.lat} data-lng={geo.lng} data-name={name} role="img" aria-label={`${name} ${T.title}`}></div>
: <div class="vm-map vm-empty"><p>{T.noMap}</p></div>}
</div>
<div class="vm-card">
<div class="vm-label">{T.address}</div>
<div class="vm-address"><span>{address || v(null)}</span>{address && <button type="button" class="vm-copy" data-copy={address} data-done={T.copied}><svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><path d="M16 1H4a2 2 0 0 0-2 2v14h2V3h12V1Zm3 4H8a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h11a2 2 0 0 0 2-2V7a2 2 0 0 0-2-2Zm0 16H8V7h11v14Z"/></svg><span>{T.copy}</span></button>}</div>
{phone && <p class="vm-phone">{T.phone}: <a href={`tel:${phone.replace(/-/g, '')}`}>{phone}</a></p>}
{lang === 'ko' && has(f.transit) && <p class="vm-transit">{f.transit}</p>}
<div class="vm-actions">
{lang === 'en' && googleUrl && <a class="vm-btn google" href={googleUrl} rel="noopener" target="_blank"><svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><path d="M21.7 2.3 2.6 10.5c-.9.4-.8 1.7.1 2l7.4 2.4 2.4 7.4c.3.9 1.6 1 2 .1l8.2-19.1c.4-.9-.5-1.8-1-1Z"/></svg>{T.google}</a>}
{naverUrl && <a class="vm-btn naver" href={naverUrl} rel="noopener" target="_blank"><svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><path d="M21.7 2.3 2.6 10.5c-.9.4-.8 1.7.1 2l7.4 2.4 2.4 7.4c.3.9 1.6 1 2 .1l8.2-19.1c.4-.9-.5-1.8-1-1Z"/></svg>{T.naver}</a>}
{kakaoUrl && <a class="vm-btn kakao" href={kakaoUrl} rel="noopener" target="_blank"><svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><path d="M21.7 2.3 2.6 10.5c-.9.4-.8 1.7.1 2l7.4 2.4 2.4 7.4c.3.9 1.6 1 2 .1l8.2-19.1c.4-.9-.5-1.8-1-1Z"/></svg>{T.kakao}</a>}
</div>
</div>
</div>
{geo && <p class="vm-attr">{T.attribution}</p>}
</section>
<style>
.visit-map { margin: 1.6rem 0 2.2rem; }
.vm-head { margin-bottom: 1.2rem; }
.vm-head h2 { margin: 0.2rem 0 0.2rem; font-size: 1.6rem; }
.vm-head .sub { margin: 0; color: var(--slate-600); }
.vm-grid { display: grid; grid-template-columns: minmax(0, 1.5fr) minmax(280px, 1fr); gap: 1.25rem; align-items: stretch; }
.vm-map-wrap { display: flex; flex-direction: column; min-height: 0; }
.vm-map { width: 100%; flex: 1 1 auto; min-height: 340px; border-radius: 16px; overflow: hidden; border: 1px solid var(--slate-100); box-shadow: var(--shadow); background: var(--primary-50); z-index: 0; }
.vm-empty { display: grid; place-items: center; color: var(--slate-500); font-size: 0.92rem; padding: 1rem; text-align: center; }
.vm-empty p { margin: 0; }
.vm-attr { font-size: 0.74rem; color: var(--slate-500); margin: 0.45rem 0 0; }
.vm-card { background: #fff; border: 1px solid var(--slate-100); border-radius: 16px; padding: 1.3rem 1.4rem; box-shadow: var(--shadow); display: grid; gap: 0.55rem; align-content: start; }
.vm-label { font-size: 0.78rem; color: var(--slate-500); font-weight: 600; letter-spacing: 0.02em; }
.vm-address { display: flex; flex-wrap: wrap; align-items: center; gap: 0.5rem 0.7rem; font-size: 1.08rem; font-weight: 700; color: var(--primary-900); line-height: 1.45; }
.vm-copy { display: inline-flex; align-items: center; gap: 0.3rem; border: 1px solid var(--slate-200); background: #fff; color: var(--slate-600); border-radius: 8px; padding: 0.25rem 0.55rem; font: inherit; font-size: 0.78rem; font-weight: 600; cursor: pointer; }
.vm-copy:hover { color: var(--primary-900); border-color: var(--primary-900); }
.vm-phone, .vm-transit { margin: 0; font-size: 0.92rem; color: var(--slate-600); }
.vm-actions { display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 0.6rem; margin-top: 0.5rem; }
.vm-btn { display: inline-flex; align-items: center; justify-content: center; gap: 0.45rem; border-radius: 12px; padding: 0.75rem 0.9rem; font-size: 0.92rem; font-weight: 700; text-decoration: none; color: #fff; box-shadow: var(--shadow); }
.vm-btn:hover { text-decoration: none; box-shadow: var(--shadow-hover); }
.vm-btn.naver { background: #03C75A; }
.vm-btn.kakao { background: #FEE500; color: #191919; }
.vm-btn.google { background: var(--primary-900); }
.visit-map.compact .vm-grid { grid-template-columns: 1fr; }
@media (max-width: 760px) { .vm-grid { grid-template-columns: 1fr; } .vm-map { flex: none; aspect-ratio: 4 / 3; min-height: 0; } }
@media print { .vm-map { break-inside: avoid; } .vm-actions { display: none; } }
</style>
<script>
// 주소 복사
document.querySelectorAll<HTMLButtonElement>('.vm-copy').forEach((b) => b.addEventListener('click', async () => {
try { await navigator.clipboard.writeText(b.dataset.copy || ''); const s = b.querySelector('span'); const orig = s?.textContent ?? ''; if (s) s.textContent = b.dataset.done || orig; setTimeout(() => { if (s) s.textContent = orig; }, 1400); } catch { /* 클립보드 권한 없음 */ }
}));
// 지도: Leaflet 을 필요할 때만 불러온다(지도가 있는 페이지에서만).
const maps = Array.from(document.querySelectorAll<HTMLElement>('.vm-map[data-lat]'));
if (maps.length) {
const s = document.createElement('script');
s.src = 'https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.9.4/leaflet.min.js';
s.crossOrigin = '';
s.onload = () => {
const L = (window as any).L;
for (const el of maps) {
const lat = Number(el.dataset.lat), lng = Number(el.dataset.lng);
const map = L.map(el, { scrollWheelZoom: false }).setView([lat, lng], 16);
L.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png', { maxZoom: 19, attribution: '&copy; <a href="https://www.openstreetmap.org/copyright" rel="noopener">OpenStreetMap</a> contributors' }).addTo(map);
const icon = L.divIcon({ className: 'vm-pin', html: '<svg width="34" height="44" viewBox="0 0 34 44" aria-hidden="true"><path d="M17 0C7.6 0 0 7.6 0 17c0 12.5 17 27 17 27s17-14.5 17-27C34 7.6 26.4 0 17 0Z" fill="#4F1DA1"/><circle cx="17" cy="17" r="6.5" fill="#fff"/></svg>', iconSize: [34, 44], iconAnchor: [17, 44], popupAnchor: [0, -40] });
L.marker([lat, lng], { icon }).addTo(map).bindPopup(`<b>${el.dataset.name ?? ''}</b>`);
// 카드 높이에 맞춰 늘어난 뒤 타일이 빈 곳 없이 채워지도록
const fix = () => map.invalidateSize();
requestAnimationFrame(fix); window.addEventListener('resize', fix, { passive: true }); if ('ResizeObserver' in window) new ResizeObserver(fix).observe(el);
}
};
document.head.appendChild(s);
}
</script>
+6 -1
View File
@@ -213,5 +213,10 @@
"sideEffectNotice": "수술 후 개인에 따라 염증, 출혈, 신경손상 등의 부작용이 있을 수 있습니다.",
"businessNo": "220-08-86777",
"checkedAt": "2026-09-04",
"nextCheck": "2026-10-04"
"nextCheck": "2026-10-04",
"geo": {
"lat": 37.5049823,
"lng": 127.0254182,
"source": "네이버 지역검색 실측 2026-09-09"
}
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+26 -6
View File
@@ -90,9 +90,8 @@
"h_input": "Build Your Schedule",
"sub_input": "세 가지만 고르면 일정표가 바로 나옵니다.",
"stat_procs": "시술",
"stat_procs_d": "가슴·윤곽·눈·코·지방·리프팅·피부·모발",
"stat_places": "추천 장소",
"stat_places_d": "신논현역 기준 도보·택시 거리와 실내 여부를 함께 표시",
"stat_places_d": "큐레이션과 한국관광공사 TourAPI. {origin} 기준 거리·이동 시간 표시",
"stat_hotels": "근처 숙소",
"stat_hotels_d": "병원 도보 10분 안, 엘리베이터·룸서비스·24시간 프런트",
"stat_privacy": "서버 저장",
@@ -105,7 +104,18 @@
"empty_sub": "수술일은 예상일이어도 됩니다.",
"stickyView": "일정표 보기",
"stickyStay": "{a} → {b} · {n}박",
"h_step1_hint": "국적을 고르면 시차와 무비자 체류 한도를 함께 봅니다."
"h_step1_hint": "국적을 고르면 시차와 무비자 체류 한도를 함께 봅니다.",
"h_fest": "Festivals During Your Stay",
"sub_fest": "체류 기간과 겹치는 행사입니다. 자유 외출 단계가 되는 날부터 갈 수 있습니다.",
"fest_none": "체류 기간과 겹치는 행사가 없습니다.",
"fest_when": "{a} ~ {b}",
"fest_from": "{d}부터 가능",
"fest_notYet": "이번 체류에서는 자유 외출 단계에 닿지 않습니다",
"source_tour": "장소·행사 데이터: 한국관광공사 TourAPI, {date} 기준. 영업 여부와 행사 일정은 방문 전에 확인하세요.",
"tour_badge": "관광공사",
"festival_pick": "행사",
"readMoreShort": "홈페이지",
"stat_places_d_curated": "큐레이션. {origin} 기준 거리 표시"
},
"en": {
"eyebrow": "Recovery Planner",
@@ -197,9 +207,8 @@
"h_input": "Build Your Schedule",
"sub_input": "Pick three things and your schedule appears.",
"stat_procs": "procedures",
"stat_procs_d": "Breast, contouring, eyes, nose, fat, lifting, skin, hair",
"stat_places": "curated places",
"stat_places_d": "With walk or taxi distance from Sinnonhyeon Station and indoor flags",
"stat_places_d": "Curated picks plus Korea Tourism Organization data, with distance and travel time from {origin}",
"stat_hotels": "hotels nearby",
"stat_hotels_d": "Within a 10-minute walk, with elevators, room service and 24-hour desks",
"stat_privacy": "stored on servers",
@@ -212,6 +221,17 @@
"empty_sub": "An estimated date is fine.",
"stickyView": "See schedule",
"stickyStay": "{a} → {b} · {n} nights",
"h_step1_hint": "Your nationality sets the jet-lag buffer and the visa-free stay check."
"h_step1_hint": "Your nationality sets the jet-lag buffer and the visa-free stay check.",
"h_fest": "Festivals During Your Stay",
"sub_fest": "Events that overlap your stay. You can go from the first full-day-out date.",
"fest_none": "No events overlap your stay.",
"fest_when": "{a} to {b}",
"fest_from": "From {d}",
"fest_notYet": "Your stay does not reach the full-day-out stage",
"source_tour": "Places and events: Korea Tourism Organization TourAPI, as of {date}. Check opening status and event dates before you go.",
"tour_badge": "KTO",
"festival_pick": "Event",
"readMoreShort": "Website",
"stat_places_d_curated": "Curated picks, with distance from {origin}"
}
}
+8
View File
@@ -0,0 +1,8 @@
{
"_comment": "시술 후 관리 안내(빈 값). 워커의 recovery 단계(scripts/collect_recovery.mjs)가 병원 시술 페이지 원문에서 채운다. items 가 비어 있으면 /stay·/en/stay 는 이 블록을 그리지 않는다.",
"clinic": "",
"generatedAt": "",
"sourceNote": "병원 홈페이지 시술 페이지 원문",
"items": [],
"counts": {}
}
+2
View File
@@ -63,6 +63,7 @@ const ld = jsonLd ? JSON.stringify({ '@context': 'https://schema.org', ...(Array
<a href="/posts">{u.nav_posts}</a>
<a href="/videos">{u.nav_videos}</a>
<a href="/newsroom">{u.nav_news}</a>
<a href="/stay">{u.nav_stay}</a>
<a href="/visit">{u.nav_visit}</a>
<a href="/plan">{u.nav_plan}</a>
<a href="/about">{u.nav_about}</a>
@@ -70,6 +71,7 @@ const ld = jsonLd ? JSON.stringify({ '@context': 'https://schema.org', ...(Array
) : (
<>
<a href="/en">{u.nav_home}</a>
<a href="/en/stay">{u.nav_stay}</a>
<a href="/en/plan">{u.nav_plan}</a>
<a href="/en#visit">{u.nav_visit}</a>
<a href="/en#clinic">{u.nav_clinic}</a>
+3 -2
View File
@@ -6,6 +6,7 @@ export type Lang = 'ko' | 'en';
const PAIRS: [string, string][] = [
['/', '/en'],
['/plan', '/en/plan'],
['/stay', '/en/stay'],
];
export function switchHref(pathname: string, to: Lang): string {
const p = pathname.replace(/\/index\.html$/, '/').replace(/\.html$/, '').replace(/\/$/, '') || '/';
@@ -21,7 +22,7 @@ export const UI: Record<Lang, Record<string, string>> = {
ko: {
sample: '샘플 사이트입니다. 정식 공개 전입니다.',
brand: '서포터즈',
nav_posts: '상담 전 질문', nav_videos: '의료진 영상', nav_news: '뉴스룸', nav_visit: '방문 안내', nav_plan: '회복 일정', nav_about: '매체 소개',
nav_posts: '상담 전 질문', nav_videos: '의료진 영상', nav_news: '뉴스룸', nav_stay: '주변 안내', nav_visit: '방문 안내', nav_plan: '회복 일정', nav_about: '매체 소개',
cta: '상담 예약',
back: '이전 페이지', backAria: '이전 페이지로 돌아가기', totop: '맨 위로',
switchLabel: 'EN', switchAria: 'Switch to English',
@@ -33,7 +34,7 @@ export const UI: Record<Lang, Record<string, string>> = {
en: {
sample: 'Sample site. Not yet public.',
brand: 'Supporters',
nav_home: 'Home', nav_plan: 'Recovery Planner', nav_visit: 'Getting Here', nav_clinic: 'Clinic Facts', nav_korean: '한국어 전체 보기',
nav_home: 'Home', nav_stay: 'Nearby', nav_plan: 'Recovery Planner', nav_visit: 'Getting Here', nav_clinic: 'Clinic Facts', nav_korean: '한국어 전체 보기',
cta: 'Book a consultation',
back: 'Back', backAria: 'Go back to the previous page', totop: 'Back to top',
switchLabel: 'KO', switchAria: '한국어로 보기',
+8 -4
View File
@@ -16,11 +16,13 @@ export interface Procedure {
export interface Place {
id: string; name: L10n; category: string; minLevel: number; dietOk?: string[]; distanceKm: number; indoor: boolean;
area: L10n; note: L10n; mapQuery: string | null; bookingQuery?: string; verify: boolean;
source?: 'curated' | 'tourapi'; travelLabel?: string; image?: string; url?: string;
}
export interface Nationality { code: string; label: L10n; visaFreeDays: number | null; longHaul: boolean }
export interface PlanInput { procedure: Procedure; surgeryDate: string; nationality?: Nationality | null; prefs: string[] }
export interface PlanDay { date: string; offset: number; level: number; diet: DietStep['type']; picks: Place[]; isSurgery: boolean; isHospital: boolean; isStitch: boolean; isArrival: boolean; isDeparture: boolean }
export interface PlanFestival { id: string; title: string; start: string; end: string }
export interface PlanInput { procedure: Procedure; surgeryDate: string; nationality?: Nationality | null; prefs: string[]; festivals?: PlanFestival[] }
export interface PlanDay { date: string; offset: number; level: number; diet: DietStep['type']; picks: Place[]; festivals: PlanFestival[]; isSurgery: boolean; isHospital: boolean; isStitch: boolean; isArrival: boolean; isDeparture: boolean }
export interface Plan {
arriveBy: string; surgeryDate: string; dischargeDate: string | null; stitchDate: string | null; earliestDeparture: string | null;
stayNights: number | null; preOpDays: number; days: PlanDay[];
@@ -57,6 +59,7 @@ export function scorePlace(place: Place, level: number, diet: DietStep['type'],
if (place.category === 'food' && place.dietOk && !place.dietOk.includes(diet)) return -1;
let s = 0;
if (prefs.length === 0 || prefs.includes(place.category)) s += 3;
if (place.source !== 'tourapi') s += 0.75; // 큐레이션(1순위)이 같은 조건이면 먼저 나온다
if (place.category === 'essentials' || place.category === 'care') s += 1; // 회복에 직접 필요한 것은 기본 가점
s += 2 - Math.min(2, level - place.minLevel); // 오늘 등급에 맞는 곳을 우선
s += Math.max(0, 1.5 - place.distanceKm / 4); // 가까울수록 가점(최대 1.5)
@@ -74,7 +77,7 @@ export function pickForDay(places: Place[], level: number, diet: DietStep['type'
}
export function buildPlan(input: PlanInput, places: Place[]): Plan {
const { procedure: p, surgeryDate, nationality, prefs } = input;
const { procedure: p, surgeryDate, nationality, prefs, festivals = [] } = input;
const preOp = effectivePreOpDays(p, nationality);
const arriveBy = addDays(surgeryDate, -preOp);
const nights = p.hospitalNights.value;
@@ -94,7 +97,8 @@ export function buildPlan(input: PlanInput, places: Place[]): Plan {
const recentSet = new Set(recent.slice(-6));
const picks = level === 0 || off === 0 ? [] : pickForDay(places, level, diet, prefs, recentSet);
recent.push(...picks.map((x) => x.id));
days.push({ date, offset: off, level, diet, picks, isSurgery: off === 0, isHospital, isStitch: stitchDate === date, isArrival: off === -preOp, isDeparture: earliestDeparture === date });
const dayFest = level >= 3 ? festivals.filter((f) => f.start <= date && f.end >= date).slice(0, 1) : []; // 행사는 자유 외출(L3) 날에만
days.push({ date, offset: off, level, diet, picks, festivals: dayFest, isSurgery: off === 0, isHospital, isStitch: stitchDate === date, isArrival: off === -preOp, isDeparture: earliestDeparture === date });
}
return { arriveBy, surgeryDate, dischargeDate, stitchDate, earliestDeparture, stayNights: dep === null ? null : preOp + dep, preOpDays: preOp, days };
}
+89
View File
@@ -0,0 +1,89 @@
// 한국관광공사 TourAPI 사전 수집 데이터(src/data/medicalTourism*.json)를 회복 일정 플래너의 장소·축제 후보로 바꾼다 (설계 v0.2 §13.5, 2순위 소스).
// 수집은 scripts/fetch_medical_tourism.py 가 병원 좌표 기준으로 미리 해 두고, 화면은 이 파일의 결과만 쓴다. 외부 호출 없음.
// 식이 적합성은 TourAPI 가 주지 않으므로 판정하지 않는다: 음식점은 일반식 단계에서만 후보가 되고, 죽·스무디 같은 회복 초기 식사는 큐레이션(places.json)이 맡는다.
import type { Place, L10n } from './plan';
export interface TourItem {
id: string; title: string; address: string; image: string | null; tel: string | null; lat: number; lng: number;
distanceM: number; travel: { mode: string; minutes: number; label: string } | null; overview: string; homepage: string;
startDate?: string; endDate?: string; season?: string;
}
export interface TourData {
places: Record<string, TourItem[]>;
festivals: TourItem[];
meta: { lang?: string; source: string; fetchedAt: string; origin?: { lat: number; lng: number; label: string } };
}
/** TourAPI 유형 → 플래너 카테고리. wellness(사우나·스파)는 회복기 금지 항목이라 후보에서 뺀다. */
const CATEGORY: Record<string, string | null> = { attraction: 'sightseeing', culture: 'sightseeing', shopping: 'shopping', restaurant: 'food', stay: 'hotel', wellness: null };
/** 거리로 외출 등급을 정한다: 600m 안 근거리(L1), 3km 안 반나절(L2), 그 밖은 자유 외출(L3). */
export const levelByDistance = (m: number): number => (m <= 600 ? 1 : m <= 3000 ? 2 : 3);
const both = (s: string): L10n => ({ ko: s, en: s });
/** 주소를 짧은 동네 표기로. 국문은 '구 도로명', 영문은 첫 쉼표 앞 도로명. */
const areaLabel = (address: string, lang: 'ko' | 'en'): string => {
const a = (address || '').trim();
if (lang === 'en') return a.split(',').map((x) => x.trim()).filter((x) => x && !/^\d+$/.test(x))[0] ?? a;
return a.replace(/^서울특별시\s*/, '').split(/\s+/).slice(0, 2).join(' ');
};
const firstSentence = (s: string, n = 140): string => {
const t = (s || '').replace(/\d+\s*m?\s*NAVER\s*©\s*NAVER Corp\.?/gi, '').replace(/\s+/g, ' ').trim();
if (t.length <= n) return t;
const cut = t.slice(0, n);
const stop = Math.max(cut.lastIndexOf('. '), cut.lastIndexOf('다. '), cut.lastIndexOf('。'));
return (stop > 40 ? cut.slice(0, stop + 1) : cut).trim() + (stop > 40 ? '' : '…');
};
/** "K-그랜드 호스텔 강남 1(K-GRAND HOSTEL GANGNAM1)" → 예약 검색용 영문 이름이 괄호 안에 있으면 그것을 쓴다. */
export const bookingName = (title: string): string => {
const m = title.match(/\(([^)]*[A-Za-z][^)]*)\)\s*$/);
return (m ? m[1] : title).trim();
};
export function tourToPlaces(data: TourData, lang: 'ko' | 'en'): Place[] {
const out: Place[] = [];
for (const [type, items] of Object.entries(data.places ?? {})) {
const category = CATEGORY[type];
if (!category) continue;
for (const it of items) {
if (!it.lat || !it.lng) continue;
const km = Math.round((it.distanceM / 1000) * 10) / 10;
out.push({
id: `tour-${type}-${it.id}`,
name: both(it.title),
category,
minLevel: category === 'hotel' ? 0 : levelByDistance(it.distanceM),
dietOk: category === 'food' ? ['normal'] : undefined,
distanceKm: km,
indoor: type === 'shopping' || type === 'culture' || type === 'restaurant' || type === 'stay',
area: both(areaLabel(it.address, lang)),
note: both(firstSentence(it.overview)),
mapQuery: it.title,
bookingQuery: category === 'hotel' ? bookingName(it.title) : undefined,
verify: true,
source: 'tourapi',
travelLabel: it.travel?.label ?? undefined,
image: it.image ?? undefined,
url: it.homepage || undefined,
});
}
}
return out;
}
export interface Festival { id: string; title: string; start: string; end: string; distanceKm: number; travelLabel?: string; blurb: string; image?: string; url?: string; address: string }
const iso = (d?: string) => (d && d.length === 8 ? `${d.slice(0, 4)}-${d.slice(4, 6)}-${d.slice(6, 8)}` : '');
/** 체류 기간 [from, to] 와 겹치는 행사만, 가까운 순. */
export function festivalsDuring(data: TourData, from: string, to: string, max = 6): Festival[] {
return (data.festivals ?? [])
.map((f) => ({ f, start: iso(f.startDate), end: iso(f.endDate) }))
.filter((x) => x.start && x.end && x.start <= to && x.end >= from)
.sort((a, b) => a.f.distanceM - b.f.distanceM)
.slice(0, max)
.map(({ f, start, end }) => ({
id: `fest-${f.id}`, title: f.title, start, end, distanceKm: Math.round((f.distanceM / 1000) * 10) / 10,
travelLabel: f.travel?.label ?? undefined, blurb: firstSentence(f.overview), image: f.image ?? undefined,
url: f.homepage || undefined, address: f.address,
}));
}
+17
View File
@@ -0,0 +1,17 @@
---
// 없는 주소. Vercel 이 dist/404.html 을 자동으로 쓴다. 옛 주소(/recovery, /stay)는 vercel.json 리다이렉트가 /plan 으로 먼저 보낸다.
import Base from '../layouts/Base.astro';
import { SITE_NAME } from '../lib';
const site = Astro.site!.toString().replace(/\/$/, '');
const ld = { '@type': 'WebPage', '@id': `${site}/404#page`, name: '페이지를 찾을 수 없음', url: `${site}/404`, inLanguage: 'ko', isPartOf: { '@id': `${site}/#website` }, publisher: { '@type': 'Organization', name: SITE_NAME, url: site } };
---
<Base title="페이지를 찾을 수 없음" description="주소가 바뀌었거나 없는 페이지입니다. 홈, 회복 일정, 방문 안내로 이동할 수 있습니다." jsonLd={ld} noindex={true}>
<section class="section dark" style="padding:5rem 0 4.5rem"><div class="wrap-wide">
<div class="sec-head"><div class="eyebrow" style="color:var(--purple-300)">404</div><h1 class="serif" style="font-size:2rem;display:inline-block;background:linear-gradient(to right,var(--purple-300),var(--blue-300));-webkit-background-clip:text;background-clip:text;color:transparent">Page Not Found</h1><p class="sub">주소가 바뀌었거나 없는 페이지입니다. 아래에서 이어서 보실 수 있습니다.</p></div>
<div class="grid">
<a class="card" href="/" style="text-decoration:none"><div class="cat">Home</div><h3>홈</h3><p>뷰성형외과를 알아보는 분들의 질문과 답</p></a>
<a class="card" href="/plan" style="text-decoration:none"><div class="cat">Recovery Planner</div><h3>회복 일정</h3><p>수술일 기준 입국·출국 계산과 회복기 외출 계획. 영어 화면은 /en/plan</p></a>
<a class="card" href="/visit" style="text-decoration:none"><div class="cat">Visit</div><h3>방문 안내</h3><p>예약, 가는 길, 주차, 도착 후 동선</p></a>
</div>
</div></section>
</Base>
+2
View File
@@ -4,6 +4,7 @@
import Base from '../../layouts/Base.astro';
import { fact, site as S, clinicSchema, surface, has, v } from '../../lib';
import EN from '../../data/factSheetEn.json';
import VisitMap from '../../components/VisitMap.astro';
const f = fact as Record<string, any>;
const site = Astro.site!.toString().replace(/\/$/, '');
const yt = surface('youtube'); const gu = surface('gangnamunni'); const gg = surface('google');
@@ -60,6 +61,7 @@ const ld = [
<div class="card"><div class="cat">From the airport</div><h3>Incheon to Sinnonhyeon</h3><p>{EN.airport}</p></div>
<div class="card"><div class="cat">On arrival</div><h3>Where to go in the building</h3><p>{EN.arrival}</p><p>{EN.parking}</p></div>
</div>
<VisitMap lang="en" hideHead nameEn={EN.shortName} addressEn={EN.address.full} />
<h3 style="margin-top:2rem">Opening hours</h3>
<div class="table-wrap"><table><thead><tr><th>Day</th><th>Hours</th></tr></thead><tbody>
{(f.hours?.rows ?? []).map((r: any) => <tr><td>{hoursDays[r.days] ?? r.days}</td><td>{r.open ? `${r.open} to ${r.close}` : EN.hoursClosed}</td></tr>)}
+514
View File
@@ -0,0 +1,514 @@
---
// 외국인 환자용 주변 안내(/en/stay). /stay 의 영문 짝이다. haewon 결정(2026-09-11): 주변 안내(/en/stay)와 회복 일정 플래너(/en/plan)는 별개 페이지다.
// 1. Around the clinic : 도보·차 소요 시간으로 거른 주변 장소
// 2. Festivals : 계절로 묶은 행사
// 3. Suggested days : 시간표와 지도가 붙은 동선
// + After-treatment care(#recovery-quote): 점프 칩 아래 접이식 블록. 워커 recovery 단계가 병원 시술 페이지 원문에서 고른 문장(번역)
//
// 데이터는 한국관광공사 TourAPI 영문(EngService2)에서 scripts/fetch_medical_tourism.py 가
// 미리 수집한 src/data/medicalTourism.json 이다. 설명문은 detailCommon2 의 overview 다.
// 기준 좌표는 워커(tourism 단계)가 팩트 시트 주소로 정한다. 병원 이름·주소·도시는 factSheet, 기준점은
// medicalTourism.meta.origin 에서만 읽는다. 이 파일에 특정 병원이나 지역 이름을 적지 않는다.
// 데이터가 비어 있으면(템플릿 기본값, origin lat 0) 목록 대신 "pending" 안내를 그리고 빌드는 그대로 된다.
//
// 만들지 않는 것
// - 평점·리뷰·영업시간: TourAPI 미제공. 싣지 않는다.
// - 링크: 공식 홈페이지가 있을 때만 걸고, 없으면 검색으로 보낸다. 주소를 지어내지 않는다.
// - 식이 적합성·회복 일수: 의학 판단이라 병원 확정값만 쓴다.
// - 일정의 시각: 진료 종료 시각을 가정으로 못박아 화면에 밝힌다. 병원 일정이 아니다.
import Base from '../../layouts/Base.astro';
import { fact, site as S, SITE_NAME, clinicSchema, has } from '../../lib';
import data from '../../data/medicalTourism.json';
import recovery from '../../data/recoveryNotes.json';
const f = fact as Record<string, any>;
const Sx = S as Record<string, any>;
const clinic = f.shortNameEn || f.nameEn || f.shortName || 'the clinic';
const site = Astro.site!.toString().replace(/\/$/, '');
const T = data as any;
// 기준점. 좌표가 없으면(템플릿 기본값) 아직 수집 전이다. 지어내지 않고 확인 대기로 그린다.
const origin = (T.meta?.origin ?? {}) as { lat?: number; lng?: number; label?: string; address?: string };
const ready = Boolean(origin.lat && origin.lng);
const total: number = T.filters?.total ?? 0;
const festivals: any[] = T.festivals ?? [];
const updated: string = (T.meta?.fetchedAt || '').slice(0, 10);
// 거리의 기준 주소. 영문 주소가 있으면 그것, 없으면 수집 때 쓴 주소, 그다음 팩트 시트 국문 주소.
const originAddress = f.address?.fullEn || origin.address || f.address?.full || '';
// 도시 이름은 영문 주소의 마지막 항목("..., Gangnam-gu, Seoul" 이면 Seoul)에서 읽는다. 없으면 Korea.
const cityEn = (f.address?.fullEn || '').split(',').pop()?.trim() || 'Korea';
const festKm: number = T.meta?.festivalRadiusKm || 0;
type Place = {
id: string; title: string; address: string; image: string | null; overview: string;
homepage: string; lat: number | null; lng: number | null; distanceM: number | null;
travel: { mode: string; minutes: number; label: string } | null;
};
const GROUPS: Array<{ key: string; label: string; note: string }> = [
{ key: 'restaurant', label: 'Food', note: 'Restaurants and cafés' },
{ key: 'stay', label: 'Hotels', note: 'Places to sleep' },
{ key: 'wellness', label: 'Rest', note: 'Spas and jjimjilbang' },
{ key: 'attraction', label: 'Sights', note: 'Streets, parks, landmarks' },
{ key: 'culture', label: 'Culture', note: 'Museums, theatres, halls' },
{ key: 'shopping', label: 'Shopping', note: 'Stores and markets' },
];
const SEASONS = [
{ key: 'spring', label: 'Spring' }, { key: 'summer', label: 'Summer' },
{ key: 'autumn', label: 'Autumn' }, { key: 'winter', label: 'Winter' },
];
const MONTHS = ['', 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
const nowSeason = ['winter', 'winter', 'spring', 'spring', 'spring', 'summer', 'summer', 'summer', 'autumn', 'autumn', 'autumn', 'winter'][new Date().getMonth()];
// 검색으로 보낸다. 없는 URL 을 만들지 않는다.
const searchUrl = (q: string) => `https://www.google.com/search?q=${encodeURIComponent(`${q} ${cityEn}`)}`;
// 칩은 누적 임계값으로 거른다. 카드에 이동수단과 도보 분을 실어 두면 스크립트가 판단한다.
const dt = (d: string | null) => (d && d.length === 8 ? `${MONTHS[+d.slice(4, 6)]} ${+d.slice(6, 8)}` : '');
// 사진이 없을 때 이름을 대신 넣는다. 빈 회색칸보다 낫고, 없는 사진을 지어내지도 않는다.
const shortName = (t: string) => {
const m = t.match(/\(([^)]+)\)\s*$/);
return (m ? m[1] : t).replace(/\s*\[.*\]\s*/g, '').trim();
};
const firstSentence = (s: string, n = 150) => {
if (!s) return '';
const cut = s.slice(0, n);
const stop = cut.lastIndexOf('. ');
return (stop > 60 ? cut.slice(0, stop + 1) : cut) + (s.length > n ? '…' : '');
};
/* ── 동선. 실제 데이터에서 만들고, 시각은 가정임을 화면에 밝힌다. ── */
const oLat = origin.lat ?? 0, oLng = origin.lng ?? 0;
const pick = (key: string, maxMin: number, n: number): Place[] =>
(((T.places ?? {})[key] ?? []) as Place[])
.filter((p) => p.travel && p.travel.mode === 'walk' && p.travel.minutes <= maxMin && p.lat)
.slice(0, n);
const pickAny = (key: string, n: number): Place[] => (((T.places ?? {})[key] ?? []) as Place[]).filter((p) => p.lat).slice(0, n);
const hhmm = (m: number) => `${String(Math.floor(m / 60) % 24).padStart(2, '0')}:${String(m % 60).padStart(2, '0')}`;
function buildRoute(startMin: number, stops: Array<{ p: Place | null; label: string; stay: number; note: string }>) {
let t = startMin;
const out: any[] = [];
stops.forEach((s, i) => {
const move = i === 0 ? 0 : (s.p?.travel?.minutes ?? 5);
t += move;
const from = t;
t += s.stay;
out.push({ ...s, moveMin: move, from: hhmm(from), to: hhmm(t), lat: s.p?.lat ?? oLat, lng: s.p?.lng ?? oLng });
});
return { stops: out, total: t - startMin, from: hhmm(startMin), to: hhmm(t) };
}
const clinicStop = (label: string, stay: number, note: string) => ({ p: null, label, stay, note });
const ROUTES = [
{
id: 'near', title: 'The day of a check-up', who: 'When you come back to the clinic often',
blurb: 'Everything within a short walk. You do not need a taxi.',
route: buildRoute(15 * 60, [
clinicStop(clinic, 40, 'Your appointment ends here.'),
...pick('restaurant', 10, 1).map((p) => ({ p, label: p.title, stay: 50, note: firstSentence(p.overview, 90) })),
...pick('wellness', 12, 1).map((p) => ({ p, label: p.title, stay: 60, note: firstSentence(p.overview, 90) })),
]),
},
{
id: 'short', title: 'A short outing', who: 'When you can walk a little further',
blurb: 'Still close, but out of the block.',
route: buildRoute(13 * 60, [
clinicStop(clinic, 20, 'Start from the clinic.'),
...pickAny('shopping', 1).map((p) => ({ p, label: p.title, stay: 60, note: firstSentence(p.overview, 90) })),
...pickAny('restaurant', 2).slice(1, 2).map((p) => ({ p, label: p.title, stay: 60, note: firstSentence(p.overview, 90) })),
]),
},
{
id: 'city', title: 'When you can travel', who: 'Later in your stay',
blurb: 'Sights across the city. Expect to take a taxi or the subway.',
route: buildRoute(10 * 60, [
clinicStop(clinic, 10, 'Set off from the clinic.'),
...pickAny('attraction', 2).map((p) => ({ p, label: p.title, stay: 70, note: firstSentence(p.overview, 90) })),
...pickAny('culture', 1).map((p) => ({ p, label: p.title, stay: 70, note: firstSentence(p.overview, 90) })),
]),
},
].filter((r) => r.route.stops.length > 1);
/* OpenStreetMap 타일을 좌표로 직접 깔아 지도를 만든다. 지도 라이브러리를 부르지 않는다.
빈 회색 칸에 점만 찍으면 어디인지 알 수 없어서, 실제 거리·블록이 보이게 한다.
타일은 OSM 정책상 출처를 반드시 표기한다. */
const TILE = 256, MAPW = 680, MAPH = 340;
const lngToPx = (lng: number, z: number) => ((lng + 180) / 360) * TILE * 2 ** z;
const latToPx = (lat: number, z: number) => {
const r = (lat * Math.PI) / 180;
return ((1 - Math.log(Math.tan(r) + 1 / Math.cos(r)) / Math.PI) / 2) * TILE * 2 ** z;
};
function miniMap(stops: any[]) {
const lats = stops.map((s) => s.lat), lngs = stops.map((s) => s.lng);
const [la0, la1] = [Math.min(...lats), Math.max(...lats)];
const [ln0, ln1] = [Math.min(...lngs), Math.max(...lngs)];
// 모든 지점이 여백 안에 들어오는 가장 확대된 배율을 고른다.
let z = 17;
for (; z > 10; z--) {
const w = lngToPx(ln1, z) - lngToPx(ln0, z);
const h = latToPx(la0, z) - latToPx(la1, z);
if (w <= MAPW - 90 && h <= MAPH - 90) break;
}
const cx = (lngToPx(ln0, z) + lngToPx(ln1, z)) / 2;
const cy = (latToPx(la0, z) + latToPx(la1, z)) / 2;
const left = cx - MAPW / 2, top = cy - MAPH / 2;
const tiles: Array<{ src: string; x: number; y: number }> = [];
for (let tx = Math.floor(left / TILE); tx <= Math.floor((left + MAPW) / TILE); tx++) {
for (let ty = Math.floor(top / TILE); ty <= Math.floor((top + MAPH) / TILE); ty++) {
const n = 2 ** z;
if (tx < 0 || ty < 0 || tx >= n || ty >= n) continue;
tiles.push({ src: `https://tile.openstreetmap.org/${z}/${tx}/${ty}.png`, x: tx * TILE - left, y: ty * TILE - top });
}
}
const pins = stops.map((s, i) => ({
x: +(lngToPx(s.lng, z) - left).toFixed(1),
y: +(latToPx(s.lat, z) - top).toFixed(1),
n: i + 1, label: s.label,
}));
return { tiles, pins, z };
}
// 시술 후 관리 안내. 워커 recovery 단계(scripts/collect_recovery.mjs)가 병원 시술 페이지 원문에서 고른 문장이다.
// en 이 비어 있는 문장(번역 실패·키 없음)은 한글 원문을 그대로 보이고 (Korean) 표시를 붙인다. items 가 비어 있으면 블록을 그리지 않는다.
type RecoveryItem = { procedure: string; procedureEn?: string; area?: string; url: string; fetchedAt?: string; ko: string[]; en: string[]; ocr?: boolean };
const RN = recovery as { generatedAt?: string; items?: RecoveryItem[] };
const recoveryItems: RecoveryItem[] = (RN.items ?? []).filter((it) => it.ko?.length);
const recoveryDate = RN.generatedAt || '';
const allPlaces: Array<Place & { cat: string }> = GROUPS.flatMap((g) =>
(((T.places ?? {})[g.key] ?? []) as Place[]).map((p) => ({ ...p, cat: g.key })));
const ld = [
{ '@type': 'WebPage', '@id': `${site}/en/stay#page`, name: `Recovery schedule at ${clinic}`, url: `${site}/en/stay`, inLanguage: 'en', isPartOf: { '@id': `${site}/#website` }, about: { '@id': `${f.url}/#clinic` }, publisher: { '@type': 'Organization', name: SITE_NAME, url: site } },
clinicSchema(site),
];
---
<Base
lang="en"
title={`Around ${clinic}: food, rest, sights, festivals, day routes`}
description={`For international patients at ${clinic} in ${cityEn}: where to eat and rest, what to see, which festivals are on, and how to shape your days. Distances and walking times from the clinic. Source: Korea Tourism Organization.`}
jsonLd={ld}
>
<article class="wrap-wide stay">
<header class="article-head">
<div class="eyebrow">Nearby</div>
<h1 class="serif">Around The Clinic</h1>
<p class="lede">
<strong>Around {clinic}.</strong> {ready
? `Everything below is measured from the clinic at ${originAddress || 'its address'}.`
: 'Distances and walking times will appear once the clinic\'s location is confirmed.'}
Names, photographs and descriptions come from the Korea Tourism Organization.
For the clinic's own hours and phone, see <a href="/clinic" hreflang="ko">Clinic information<span class="lang-tag">KO</span></a>. To plan arrival and departure around your surgery date, use the <a href="/en/plan">Recovery Planner</a>.
</p>
{!ready && <p class="pending-note">This guide is pending. Food, hotels, rest, sights and festivals near the clinic will be listed once its address is confirmed.</p>}
</header>
<!-- 오늘 날씨. 빌드 시점이 아니라 브라우저에서 받는다. 정적 빌드에 넣으면 배포 시각의
날씨가 굳는다. 값을 못 받으면 이 블록은 통째로 사라진다(틀린 날씨를 보이지 않는다).
Open-Meteo 는 키가 필요 없고 CORS 를 허용한다. -->
<aside id="weather" class="wx" hidden>
<div class="wx-now">
<span class="wx-temp"><span id="wx-t">–</span><span class="wx-unit">°C</span></span>
<div>
<div class="wx-cond" id="wx-c">Loading</div>
<div class="wx-meta" id="wx-m"></div>
</div>
</div>
<p class="wx-note" id="wx-n"></p>
</aside>
<!-- 섹션이 길어 스크롤이 부담스럽다. 머리말 아래 붙여 어디서든 건너뛰게 한다. -->
<nav class="jump" aria-label="Jump to a section">
{recoveryItems.length > 0 && <a href="#recovery-quote">Care<b>{recoveryItems.length}</b></a>}
{GROUPS.filter((g) => allPlaces.some((p) => p.cat === g.key)).map((g) => (
<a href={`#g-${g.key}`}>{g.label}<b>{allPlaces.filter((p) => p.cat === g.key).length}</b></a>
))}
<a href="#festivals">Festivals<b>{festivals.length}</b></a>
<a href="#days">Days<b>{ROUTES.length}</b></a>
</nav>
<!-- ── 0. After-treatment care ── 병원 시술 페이지 원문 인용(번역). 기본은 접힘, summary 가 버튼이다(haewon 2026-09-11).
동선 카드(.route)·정차(.stop) 룩을 그대로 쓴다. id="recovery-quote" 는 발행 게이트(check.mjs)가 홈페이지 40자 일치 검사에서 이 인용 블록만 빼는 표식이다. -->
{recoveryItems.length > 0 && (
<details class="route recovery" id="recovery-quote">
<summary class="btn primary"><span class="show">Show after-treatment care · {recoveryItems.length} treatments</span><span class="hide">Hide after-treatment care</span></summary>
<div class="route-head">
<div>
<h3>After-treatment care, as published by the clinic</h3>
<p class="who">From {clinic}'s own treatment pages · {recoveryItems.length} treatments</p>
</div>
{recoveryDate && <div class="clock">Checked {recoveryDate}</div>}
</div>
<p class="blurb">These lines are quoted from {clinic}'s own treatment pages (Korean), translated for reference. They differ by treatment and by person. Confirm at your consultation.</p>
<ol class="timeline">
{recoveryItems.map((it, i) => (
<li>
<details open={i < 3}>
<summary>
<span class="stop">
<span class="n">{i + 1}</span>
<span>
<span class="stop-t">{it.area ? `${it.area} · ` : ''}{it.ko.length} {it.ko.length === 1 ? 'line' : 'lines'} · tap to open</span>
<h4>{it.procedureEn || it.procedure}</h4>
{it.procedureEn && <span class="stop-t" lang="ko">{it.procedure}</span>}
</span>
</span>
</summary>
<ul>
{it.ko.map((s, k) => it.en?.[k]
? <li>{it.en[k]}</li>
: <li lang="ko">{s} <span class="lang-tag">Korean</span></li>)}
</ul>
<p><a class="go" href={it.url} rel="noopener nofollow" hreflang="ko">Clinic page (Korean) ↗</a>{it.fetchedAt ? ` · checked ${it.fetchedAt}` : ''}</p>
</details>
</li>
))}
</ol>
</details>
)}
<!-- ── 1. 주변 ── -->
<section id="around">
<div class="sec-head">
<h2>Around the clinic</h2>
<span class="upd">{updated ? `Updated ${updated}` : 'Pending'}</span>
</div>
<p class="sub">{total > 0 ? `${total} places, sorted by how long they take to reach on foot.` : 'Listings will follow once the clinic\'s location is confirmed.'}</p>
{total > 0 && <div class="chips" id="walkchips" role="group" aria-label="Filter by travel time">
<button class="chip on" data-max="all">All <b>{T.filters.total}</b></button>
<button class="chip" data-max="5">Within 5 min walk <b>{T.filters.walk5}</b></button>
<button class="chip" data-max="15">Within 15 min walk <b>{T.filters.walk15}</b></button>
<button class="chip" data-max="walk">Walking distance <b>{T.filters.walkAll}</b></button>
<button class="chip" data-max="drive">By car <b>{T.filters.drive}</b></button>
</div>}
{GROUPS.map((g) => {
const items = allPlaces.filter((p) => p.cat === g.key);
if (!items.length) return null;
return (
<div class="grp" id={`g-${g.key}`} data-group={g.key}>
<h3>{g.label} <small>{g.note}</small></h3>
<div class="cards">
{items.map((p) => (
<article class="card" data-mode={p.travel?.mode ?? 'drive'} data-walk={p.travel?.mode === 'walk' ? p.travel.minutes : ''}>
<div class="thumb">
{p.image ? <img src={p.image} alt={`${p.title} : ${g.label.toLowerCase()} near ${clinic}`} loading="lazy" referrerpolicy="no-referrer" /> : <span class="nophoto">{shortName(p.title)}</span>}
{p.travel && <span class="badge">{p.travel.label} <em>{p.distanceM! < 1000 ? `${p.distanceM} m` : `${(p.distanceM! / 1000).toFixed(1)} km`}</em></span>}
</div>
<div class="body">
<h4>{p.title}</h4>
<p class="desc">{firstSentence(p.overview) || 'No description provided by the tourism data.'}</p>
<p class="addr">{p.address}</p>
{p.homepage
? <a class="go" href={p.homepage} rel="noopener nofollow">Official site ↗</a>
: <a class="go" href={searchUrl(p.title.replace(/\s*\(.*\)\s*$/, ''))} rel="noopener nofollow">Open in search ↗</a>}
</div>
</article>
))}
</div>
</div>
);
})}
<p class="src">Source · Korea Tourism Organization TourAPI. Walking time is estimated at 80 m per minute and is not a routed distance.</p>
</section>
<!-- ── 2. 축제 ── -->
<section id="festivals">
<div class="sec-head"><h2>Festivals and events</h2></div>
<p class="sub">{festivals.length > 0
? `${festivals.length} events${festKm ? ` within ${festKm} km` : ''}, grouped by season. Right now it is `
: 'Events will follow once the clinic\'s location is confirmed. Right now it is '}<strong>{nowSeason}</strong>.</p>
{festivals.length > 0 && <div class="chips" role="group" aria-label="Filter by season">
<button class="chip on" data-season="all">All <b>{festivals.length}</b></button>
{SEASONS.map((s) => {
const n = festivals.filter((e: any) => e.season === s.key).length;
return n ? <button class="chip" data-season={s.key}>{s.label} <b>{n}</b></button> : null;
})}
</div>}
<div class="cards fest">
{festivals.map((e: any) => (
<article class="card" data-season={e.season}>
<div class="thumb">
{e.image ? <img src={e.image} alt={`${e.title} : festival near ${clinic}`} loading="lazy" referrerpolicy="no-referrer" /> : <span class="nophoto">{shortName(e.title)}</span>}
<span class="badge mono">{MONTHS[e.month] ?? ''}</span>
</div>
<div class="body">
<h4>{e.title}</h4>
<p class="when">{dt(e.startDate)} – {dt(e.endDate)} · {e.travel ? e.travel.label : `${e.distanceKm} km`}</p>
<p class="desc">{firstSentence(e.overview) || 'No description provided by the tourism data.'}</p>
<p class="addr">{e.address}</p>
<a class="go" href={searchUrl(e.title.replace(/\s*\(.*\)\s*$/, ''))} rel="noopener nofollow">Open in search ↗</a>
</div>
</article>
))}
</div>
<p class="src">Source · Korea Tourism Organization TourAPI. Dates can change at the organiser's discretion.</p>
</section>
<!-- ── 3. 동선 ── -->
<section id="days">
<div class="sec-head"><h2>Shaping your days</h2></div>
<p class="sub">
Three routes built from the places above. The clock times assume an appointment ending at the hour shown, and are an example, not your schedule.
</p>
{Sx.recoveryStagesEn
? <p><strong>What {clinic} advises.</strong> {Sx.recoveryStagesEn}</p>
: <p class="pending-note">Which of these you can do, and on which day, is a medical question. {clinic} has not yet published English guidance. Ask at your consultation.</p>}
{ROUTES.map((r) => {
const pins = miniMap(r.route.stops);
return (
<div class="route">
<div class="route-head">
<div>
<h3>{r.title}</h3>
<p class="who">{r.who}</p>
</div>
<div class="clock">{r.route.from}–{r.route.to} · {Math.floor(r.route.total / 60)}h {r.route.total % 60}m</div>
</div>
<p class="blurb">{r.blurb}</p>
<div class="map" role="img" aria-label={`Map of ${pins.pins.length} stops: ${pins.pins.map((p) => p.label).join(', ')}`}>
<div class="map-tiles">
{/* 타일은 장식이다. 지도의 뜻은 감싸는 요소의 aria-label 이 전한다.
img 대신 배경으로 두어 스크린리더가 256개 조각을 읽지 않게 한다. */}
{pins.tiles.map((t) => (
<div class="tile" style={`left:${t.x}px;top:${t.y}px;background-image:url('${t.src}')`} />
))}
</div>
<svg class="map-pins" viewBox={`0 0 ${MAPW} ${MAPH}`} aria-hidden="true">
<polyline points={pins.pins.map((p) => `${p.x},${p.y}`).join(' ')} fill="none" stroke="#0A1128" stroke-width="3" stroke-dasharray="6 5" opacity="0.65" />
{pins.pins.map((p) => (
<g><circle cx={p.x} cy={p.y} r="13" fill="#0A1128" stroke="#fff" stroke-width="2.5" /><text x={p.x} y={p.y + 4.5} text-anchor="middle" font-size="12" font-weight="700" fill="#fff">{p.n}</text></g>
))}
</svg>
<span class="map-credit">© OpenStreetMap contributors</span>
</div>
<ol class="timeline">
{r.route.stops.map((s: any, i: number) => (
<li>
{i > 0 && <div class="move">↓ {s.moveMin} min</div>}
<div class="stop">
<span class="n">{i + 1}</span>
<div>
<div class="stop-t">{s.from}–{s.to}</div>
<h4>{s.label}</h4>
<p>{s.note}</p>
</div>
</div>
</li>
))}
</ol>
</div>
);
})}
</section>
<section id="limits">
<h2>What this page does not tell you</h2>
<ul>
<li>No ratings, review counts or opening hours. The tourism data does not carry them.</li>
<li>No claim that any place suits your recovery. That is for {clinic} to say.</li>
<li>{total > 0
? `English tourism listings near the clinic are limited. Only ${T.filters.walk5} places sit within a five minute walk, and ${T.filters.drive} of ${total} need a car.`
: 'Listings near the clinic are pending until its location is confirmed.'}</li>
<li>We are not a travel agency, take no booking and no commission.</li>
</ul>
<p class="botnote">
{has(f.urlEn) && <a class="btn primary" href={f.urlEn} rel="noopener" hreflang="en">Book a consultation in English</a>}
</p>
<p class="disclosure">{f.sideEffectNoticeEn || f.sideEffectNotice}</p>
</section>
</article>
<script is:inline define:vars={{ WX_LAT: origin.lat ?? 0, WX_LNG: origin.lng ?? 0 }}>
// 이동 시간 필터. 임계값은 누적이라 "15분 이내"가 5분 이내도 포함한다.
// 걸러져 비게 된 그룹은 제목만 남지 않도록 통째로 숨긴다.
(function () {
var chips = document.querySelectorAll('#walkchips .chip');
chips.forEach(function (c) {
c.addEventListener('click', function () {
chips.forEach(function (x) { x.classList.toggle('on', x === c); });
var want = c.dataset.max;
document.querySelectorAll('#around .card').forEach(function (card) {
var mode = card.dataset.mode, w = parseInt(card.dataset.walk || '', 10);
var show = want === 'all' ? true
: want === 'walk' ? mode === 'walk'
: want === 'drive' ? mode !== 'walk'
: mode === 'walk' && w <= parseInt(want, 10);
card.hidden = !show;
});
document.querySelectorAll('#around .grp').forEach(function (g) {
g.hidden = ![].slice.call(g.querySelectorAll('.card')).some(function (x) { return !x.hidden; });
});
});
});
// 점프 칩 '시술 후 관리'는 접힌 블록으로 가므로 눌렀을 때 함께 연다.
document.querySelectorAll('a[href="#recovery-quote"]').forEach(function (a) { a.addEventListener('click', function () { var d = document.getElementById('recovery-quote'); if (d) d.open = true; }); });
// 지금 화면에 있는 섹션의 버튼을 켠다. 섹션이 많아 어디쯤인지 알기 어렵다.
var links = [].slice.call(document.querySelectorAll('.jump a'));
var targets = links.map(function (a) { return document.querySelector(a.getAttribute('href')); });
if ('IntersectionObserver' in window) {
var seen = {};
var io = new IntersectionObserver(function (entries) {
entries.forEach(function (e) { seen[e.target.id] = e.isIntersecting ? e.intersectionRatio : 0; });
var best = null, top = 0;
targets.forEach(function (t) {
if (t && (seen[t.id] || 0) > top) { top = seen[t.id]; best = t.id; }
});
links.forEach(function (a) { a.classList.toggle('on', best !== null && a.getAttribute('href') === '#' + best); });
}, { rootMargin: '-150px 0px -55% 0px', threshold: [0, 0.15, 0.4, 0.75, 1] });
targets.forEach(function (t) { if (t) io.observe(t); });
}
// 오늘 날씨. Open-Meteo, 키 없음. 실패하면 블록을 숨긴 채 둔다.
// 문구는 이 페이지의 목록에만 연결한다. 무엇을 해도 되는지는 의학 판단이라 말하지 않는다.
(function () {
var WMO = {
0: 'Clear sky', 1: 'Mainly clear', 2: 'Partly cloudy', 3: 'Overcast',
45: 'Fog', 48: 'Rime fog', 51: 'Light drizzle', 53: 'Drizzle', 55: 'Dense drizzle',
56: 'Freezing drizzle', 57: 'Freezing drizzle', 61: 'Light rain', 63: 'Rain', 65: 'Heavy rain',
66: 'Freezing rain', 67: 'Freezing rain', 71: 'Light snow', 73: 'Snow', 75: 'Heavy snow',
77: 'Snow grains', 80: 'Light showers', 81: 'Showers', 82: 'Violent showers',
85: 'Snow showers', 86: 'Snow showers', 95: 'Thunderstorm', 96: 'Thunderstorm with hail', 99: 'Thunderstorm with hail'
};
var WET = [51,53,55,56,57,61,63,65,66,67,71,73,75,77,80,81,82,85,86,95,96,99];
var LAT = WX_LAT, LNG = WX_LNG;
if (!LAT || !LNG) return; // 기준 좌표가 없으면(확인 대기) 날씨도 띄우지 않는다
fetch('https://api.open-meteo.com/v1/forecast?latitude=' + LAT + '&longitude=' + LNG +
'&current=temperature_2m,apparent_temperature,weather_code,wind_speed_10m&timezone=auto')
.then(function (r) { if (!r.ok) throw 0; return r.json(); })
.then(function (j) {
var c = j.current; if (!c || c.temperature_2m == null) throw 0;
var code = c.weather_code;
document.getElementById('wx-t').textContent = Math.round(c.temperature_2m);
document.getElementById('wx-c').textContent = WMO[code] || 'Current conditions';
document.getElementById('wx-m').textContent =
'Feels like ' + Math.round(c.apparent_temperature) + '°C · wind ' +
Math.round(c.wind_speed_10m) + ' km/h · observed ' + String(c.time).replace('T', ' ');
document.getElementById('wx-n').textContent = WET.indexOf(code) >= 0
? 'Wet outside. The Culture and Shopping listings below are indoors.'
: (c.temperature_2m >= 30
? 'Hot today. The Culture and Shopping listings below are indoors.'
: (c.temperature_2m <= 0
? 'Below freezing. The Culture and Shopping listings below are indoors.'
: 'Dry at the moment. The walking times below are on foot from the clinic.'));
document.getElementById('weather').hidden = false;
})
.catch(function () { /* 못 받으면 숨긴 채 둔다 */ });
})();
var sc = document.querySelectorAll('#festivals .chip');
sc.forEach(function (c) {
c.addEventListener('click', function () {
sc.forEach(function (x) { x.classList.toggle('on', x === c); });
var want = c.dataset.season;
document.querySelectorAll('#festivals .card').forEach(function (card) {
card.hidden = !(want === 'all' || card.dataset.season === want);
});
});
});
})();
</script>
</Base>
+2
View File
@@ -12,6 +12,8 @@ export const GET: APIRoute = async ({ site }) => {
{ loc: `${base}/clinic`, lastmod: today },
{ loc: `${base}/visit`, lastmod: today },
{ loc: `${base}/en`, lastmod: today },
{ loc: `${base}/stay`, lastmod: today },
{ loc: `${base}/en/stay`, lastmod: today },
{ loc: `${base}/plan`, lastmod: today },
{ loc: `${base}/en/plan`, lastmod: today },
{ loc: `${base}/newsroom`, lastmod: today },
+515
View File
@@ -0,0 +1,515 @@
---
// 주변 안내(한국어). /en/stay 의 한국어 짝이다. haewon 결정(2026-09-11): 주변 안내(/stay)와 회복 일정 플래너(/plan)는 별개 페이지다. 이 페이지는 병원 주변 장소·축제·동선이고, 시술 후 관리 안내는 접이식으로 둔다. 데이터는 국문 서비스(KorService2)라
// 영문보다 훨씬 많다(음식점 338건·숙박 43건 대 18건·4건).
// 구조는 /en/stay 와 같다. 세 부분이다.
// 1. 병원 주변 : 도보·차 소요 시간으로 거른 주변 장소
// 2. Festivals : 계절로 묶은 행사
// 3. Suggested days : 시간표와 지도가 붙은 동선
// + 시술 후 관리 안내(#recovery-quote): 점프 칩 아래 접이식 블록. 워커 recovery 단계가 병원 시술 페이지 원문에서 고른 문장
//
// 데이터는 한국관광공사 TourAPI 국문(KorService2)에서 scripts/fetch_medical_tourism.py 가
// 미리 수집한 src/data/medicalTourismKo.json 이다. 설명문은 detailCommon2 의 overview 다.
// 기준 좌표는 워커(tourism 단계)가 팩트 시트 주소로 정한다. 병원 이름·주소는 factSheet, 기준점은
// medicalTourismKo.meta.origin 에서만 읽는다. 이 파일에 특정 병원을 적지 않는다.
// 데이터가 비어 있으면(템플릿 기본값, origin lat 0) 목록 대신 "확인 대기"를 그리고 빌드는 그대로 된다.
//
// 만들지 않는 것
// - 평점·리뷰·영업시간: TourAPI 미제공. 싣지 않는다.
// - 링크: 공식 홈페이지가 있을 때만 걸고, 없으면 검색으로 보낸다. 주소를 지어내지 않는다.
// - 식이 적합성·회복 일수: 의학 판단이라 병원 확정값만 쓴다.
// - 일정의 시각: 진료 종료 시각을 가정으로 못박아 화면에 밝힌다. 병원 일정이 아니다.
import Base from '../layouts/Base.astro';
import { fact, site as S, SITE_NAME, clinicSchema, has, v, reservationUrl } from '../lib';
import data from '../data/medicalTourismKo.json';
import recovery from '../data/recoveryNotes.json';
const f = fact as Record<string, any>;
const Sx = S as Record<string, any>;
const clinic = f.shortName || '병원';
const site = Astro.site!.toString().replace(/\/$/, '');
const T = data as any;
// 기준점. 좌표가 없으면(템플릿 기본값) 아직 수집 전이다. 지어내지 않고 "확인 대기"로 그린다.
const origin = (T.meta?.origin ?? {}) as { lat?: number; lng?: number; label?: string; address?: string };
const ready = Boolean(origin.lat && origin.lng);
const total: number = T.filters?.total ?? 0;
const festivals: any[] = T.festivals ?? [];
const updated: string = (T.meta?.fetchedAt || '').slice(0, 10);
// 거리의 기준 주소. 수집 때 쓴 주소가 있으면 그것, 없으면 팩트 시트 주소.
const originAddress = origin.address || f.address?.full || '';
const festKm: number = T.meta?.festivalRadiusKm || 0;
type Place = {
id: string; title: string; address: string; image: string | null; overview: string;
homepage: string; lat: number | null; lng: number | null; distanceM: number | null;
travel: { mode: string; minutes: number; label: string } | null;
};
const GROUPS: Array<{ key: string; label: string; note: string }> = [
{ key: 'restaurant', label: '식사', note: '음식점과 카페' },
{ key: 'stay', label: '숙박', note: '묵을 곳' },
{ key: 'wellness', label: '휴식', note: '스파와 찜질방' },
{ key: 'attraction', label: '관광', note: '거리, 공원, 명소' },
{ key: 'culture', label: '문화', note: '미술관, 공연장' },
{ key: 'shopping', label: '쇼핑', note: '백화점과 시장' },
];
const SEASONS = [
{ key: 'spring', label: '봄' }, { key: 'summer', label: '여름' },
{ key: 'autumn', label: '가을' }, { key: 'winter', label: '겨울' },
];
const MONTHS = ['', '1월', '2월', '3월', '4월', '5월', '6월', '7월', '8월', '9월', '10월', '11월', '12월'];
const nowSeasonKey = ['winter', 'winter', 'spring', 'spring', 'spring', 'summer', 'summer', 'summer', 'autumn', 'autumn', 'autumn', 'winter'][new Date().getMonth()];
const nowSeason = ({ spring: '봄', summer: '여름', autumn: '가을', winter: '겨울' } as Record<string, string>)[nowSeasonKey];
// 검색으로 보낸다. 없는 URL 을 만들지 않는다.
// 없는 URL 을 만들지 않는다. 공식 홈페이지가 없으면 검색으로 보낸다.
const searchUrl = (q: string) => `https://search.naver.com/search.naver?query=${encodeURIComponent(q)}`;
// 칩은 누적 임계값으로 거른다. 카드에 이동수단과 도보 분을 실어 두면 스크립트가 판단한다.
const dt = (d: string | null) => (d && d.length === 8 ? `${+d.slice(4, 6)}.${+d.slice(6, 8)}` : '');
// 사진이 없을 때 이름을 대신 넣는다. 빈 회색칸보다 낫고, 없는 사진을 지어내지도 않는다.
const shortName = (t: string) => {
const m = t.match(/\(([^)]+)\)\s*$/);
return (m ? m[1] : t).replace(/\s*\[.*\]\s*/g, '').trim();
};
// travel.label 은 데이터에 영문으로 들어 있다. 한국어 화면에서는 여기서 만든다.
const travelLabel = (t: { mode: string; minutes: number } | null) =>
!t ? '' : t.mode === 'walk' ? `도보 ${t.minutes}분` : `차로 ${t.minutes}분`;
const firstSentence = (s: string, n = 150) => {
if (!s) return '';
const cut = s.slice(0, n);
const stop = cut.lastIndexOf('. ');
return (stop > 60 ? cut.slice(0, stop + 1) : cut) + (s.length > n ? '…' : '');
};
/* ── 동선. 실제 데이터에서 만들고, 시각은 가정임을 화면에 밝힌다. ── */
const oLat = origin.lat ?? 0, oLng = origin.lng ?? 0;
const pick = (key: string, maxMin: number, n: number): Place[] =>
(((T.places ?? {})[key] ?? []) as Place[])
.filter((p) => p.travel && p.travel.mode === 'walk' && p.travel.minutes <= maxMin && p.lat)
.slice(0, n);
const pickAny = (key: string, n: number): Place[] => (((T.places ?? {})[key] ?? []) as Place[]).filter((p) => p.lat).slice(0, n);
const hhmm = (m: number) => `${String(Math.floor(m / 60) % 24).padStart(2, '0')}:${String(m % 60).padStart(2, '0')}`;
function buildRoute(startMin: number, stops: Array<{ p: Place | null; label: string; stay: number; note: string }>) {
let t = startMin;
const out: any[] = [];
stops.forEach((s, i) => {
const move = i === 0 ? 0 : (s.p?.travel?.minutes ?? 5);
t += move;
const from = t;
t += s.stay;
out.push({ ...s, moveMin: move, from: hhmm(from), to: hhmm(t), lat: s.p?.lat ?? oLat, lng: s.p?.lng ?? oLng });
});
return { stops: out, total: t - startMin, from: hhmm(startMin), to: hhmm(t) };
}
const clinicStop = (label: string, stay: number, note: string) => ({ p: null, label, stay, note });
const ROUTES = [
{
id: 'near', title: '진료 다녀오는 날', who: '병원에 자주 오는 동안',
blurb: '전부 걸어서 갈 수 있는 곳입니다. 택시가 필요 없습니다.',
route: buildRoute(15 * 60, [
clinicStop(clinic, 40, '진료가 끝나는 곳입니다.'),
...pick('restaurant', 10, 1).map((p) => ({ p, label: p.title, stay: 50, note: firstSentence(p.overview, 90) })),
...pick('wellness', 12, 1).map((p) => ({ p, label: p.title, stay: 60, note: firstSentence(p.overview, 90) })),
]),
},
{
id: 'short', title: '가까운 곳 나들이', who: '조금 더 걸을 수 있을 때',
blurb: '가깝지만 한 블록 밖입니다.',
route: buildRoute(13 * 60, [
clinicStop(clinic, 20, '병원에서 출발합니다.'),
...pickAny('shopping', 1).map((p) => ({ p, label: p.title, stay: 60, note: firstSentence(p.overview, 90) })),
...pickAny('restaurant', 2).slice(1, 2).map((p) => ({ p, label: p.title, stay: 60, note: firstSentence(p.overview, 90) })),
]),
},
{
id: 'city', title: '멀리 나갈 수 있을 때', who: '체류 후반에',
blurb: '시내 곳곳입니다. 택시나 지하철을 탑니다.',
route: buildRoute(10 * 60, [
clinicStop(clinic, 10, '병원에서 나섭니다.'),
...pickAny('attraction', 2).map((p) => ({ p, label: p.title, stay: 70, note: firstSentence(p.overview, 90) })),
...pickAny('culture', 1).map((p) => ({ p, label: p.title, stay: 70, note: firstSentence(p.overview, 90) })),
]),
},
].filter((r) => r.route.stops.length > 1);
/* OpenStreetMap 타일을 좌표로 직접 깔아 지도를 만든다. 지도 라이브러리를 부르지 않는다.
빈 회색 칸에 점만 찍으면 어디인지 알 수 없어서, 실제 거리·블록이 보이게 한다.
타일은 OSM 정책상 출처를 반드시 표기한다. */
const TILE = 256, MAPW = 680, MAPH = 340;
const lngToPx = (lng: number, z: number) => ((lng + 180) / 360) * TILE * 2 ** z;
const latToPx = (lat: number, z: number) => {
const r = (lat * Math.PI) / 180;
return ((1 - Math.log(Math.tan(r) + 1 / Math.cos(r)) / Math.PI) / 2) * TILE * 2 ** z;
};
function miniMap(stops: any[]) {
const lats = stops.map((s) => s.lat), lngs = stops.map((s) => s.lng);
const [la0, la1] = [Math.min(...lats), Math.max(...lats)];
const [ln0, ln1] = [Math.min(...lngs), Math.max(...lngs)];
// 모든 지점이 여백 안에 들어오는 가장 확대된 배율을 고른다.
let z = 17;
for (; z > 10; z--) {
const w = lngToPx(ln1, z) - lngToPx(ln0, z);
const h = latToPx(la0, z) - latToPx(la1, z);
if (w <= MAPW - 90 && h <= MAPH - 90) break;
}
const cx = (lngToPx(ln0, z) + lngToPx(ln1, z)) / 2;
const cy = (latToPx(la0, z) + latToPx(la1, z)) / 2;
const left = cx - MAPW / 2, top = cy - MAPH / 2;
const tiles: Array<{ src: string; x: number; y: number }> = [];
for (let tx = Math.floor(left / TILE); tx <= Math.floor((left + MAPW) / TILE); tx++) {
for (let ty = Math.floor(top / TILE); ty <= Math.floor((top + MAPH) / TILE); ty++) {
const n = 2 ** z;
if (tx < 0 || ty < 0 || tx >= n || ty >= n) continue;
tiles.push({ src: `https://tile.openstreetmap.org/${z}/${tx}/${ty}.png`, x: tx * TILE - left, y: ty * TILE - top });
}
}
const pins = stops.map((s, i) => ({
x: +(lngToPx(s.lng, z) - left).toFixed(1),
y: +(latToPx(s.lat, z) - top).toFixed(1),
n: i + 1, label: s.label,
}));
return { tiles, pins, z };
}
// 시술 후 관리 안내. 워커 recovery 단계(scripts/collect_recovery.mjs)가 병원 시술 페이지 원문에서 고른 문장이다.
// 병원 확정값(site.recoveryStagesKo)과 역할이 다르다. 확정값은 "병원 안내" 문단, 이것은 원문 인용이라 출처 링크와 확인일을 붙인다.
// items 가 비어 있으면(템플릿 기본값) 블록을 아예 그리지 않는다.
type RecoveryItem = { procedure: string; area?: string; url: string; fetchedAt?: string; ko: string[]; en: string[]; ocr?: boolean };
const RN = recovery as { generatedAt?: string; items?: RecoveryItem[] };
const recoveryItems: RecoveryItem[] = (RN.items ?? []).filter((it) => it.ko?.length);
const recoveryDate = RN.generatedAt || '';
const allPlaces: Array<Place & { cat: string }> = GROUPS.flatMap((g) =>
(((T.places ?? {})[g.key] ?? []) as Place[]).map((p) => ({ ...p, cat: g.key })));
const ld = [
{ '@type': 'WebPage', '@id': `${site}/stay#page`, name: `${clinic} 주변 안내`, url: `${site}/stay`, inLanguage: 'ko', isPartOf: { '@id': `${site}/#website` }, about: { '@id': `${f.url}/#clinic` }, publisher: { '@type': 'Organization', name: SITE_NAME, url: site } },
clinicSchema(site),
];
---
<Base
title={`${clinic} 주변 안내 · 식사, 숙박, 휴식, 관광, 축제, 하루 동선`}
description={`${clinic} 주변에서 어디서 먹고 묵고 쉴 수 있는지, 무엇을 볼 수 있는지, 어떤 축제가 열리는지를 병원에서의 거리와 도보 시간으로 정리했습니다. 출처는 한국관광공사입니다.`}
jsonLd={ld}
>
<article class="wrap-wide stay">
<header class="article-head">
<div class="eyebrow">Nearby</div>
<h1 class="serif">Around The Clinic</h1>
<p class="lede">
<strong>{clinic} 주변입니다.</strong> {ready
? `아래 거리와 시간은 모두 ${v(originAddress)} 기준입니다.`
: '병원 위치가 확인되면 거리와 도보 시간이 채워집니다.'}
상호와 사진, 설명은 한국관광공사 자료입니다. 병원의 진료시간과 전화는 <a href="/clinic">병원 정보</a>에, 수술일 기준 입국·출국 계산은 <a href="/plan">회복 일정</a>에 있습니다.
</p>
{!ready && <p class="pending-note">주변 안내는 확인 대기입니다. 병원 주소를 확인한 뒤 식사·숙박·휴식·관광·축제 목록이 채워집니다.</p>}
</header>
<!-- 오늘 날씨. 빌드 시점이 아니라 브라우저에서 받는다. 정적 빌드에 넣으면 배포 시각의
날씨가 굳는다. 값을 못 받으면 이 블록은 통째로 사라진다(틀린 날씨를 보이지 않는다).
Open-Meteo 는 키가 필요 없고 CORS 를 허용한다. -->
<aside id="weather" class="wx" hidden>
<div class="wx-now">
<span class="wx-temp"><span id="wx-t">–</span><span class="wx-unit">°C</span></span>
<div>
<div class="wx-cond" id="wx-c">불러오는 중</div>
<div class="wx-meta" id="wx-m"></div>
</div>
</div>
<p class="wx-note" id="wx-n"></p>
</aside>
<!-- 섹션이 길어 스크롤이 부담스럽다. 머리말 아래 붙여 어디서든 건너뛰게 한다. -->
<nav class="jump" aria-label="섹션으로 이동">
{recoveryItems.length > 0 && <a href="#recovery-quote">시술 후 관리<b>{recoveryItems.length}</b></a>}
{GROUPS.filter((g) => allPlaces.some((p) => p.cat === g.key)).map((g) => (
<a href={`#g-${g.key}`}>{g.label}<b>{allPlaces.filter((p) => p.cat === g.key).length}</b></a>
))}
<a href="#festivals">축제<b>{festivals.length}</b></a>
<a href="#days">동선<b>{ROUTES.length}</b></a>
</nav>
<!-- ── 0. 시술 후 관리 안내 ── 병원 시술 페이지 원문 인용. 기본은 접힘, summary 가 버튼이다(haewon 2026-09-11).
동선 카드(.route)·정차(.stop) 룩을 그대로 쓴다. id="recovery-quote" 는 발행 게이트(check.mjs)가 홈페이지 40자 일치 검사에서 이 인용 블록만 빼는 표식이다. -->
{recoveryItems.length > 0 && (
<details class="route recovery" id="recovery-quote">
<summary class="btn primary"><span class="show">시술 후 관리 안내 보기 · 시술 {recoveryItems.length}개</span><span class="hide">시술 후 관리 안내 접기</span></summary>
<div class="route-head">
<div>
<h3>시술 후 관리 안내</h3>
<p class="who">{clinic} 홈페이지 시술 페이지 기준 · 시술 {recoveryItems.length}개</p>
</div>
{recoveryDate && <div class="clock">{recoveryDate} 확인</div>}
</div>
<p class="blurb">아래 문장은 {clinic} 홈페이지 시술 페이지에 적힌 안내를 그대로 옮긴 것입니다. 시술마다 다르고 개인차가 있으니 상담에서 확인하세요.</p>
<ol class="timeline">
{recoveryItems.map((it, i) => (
<li>
<details open={i < 3}>
<summary>
<span class="stop">
<span class="n">{i + 1}</span>
<span>
<span class="stop-t">{it.area ? `${it.area} · ` : ''}{it.ko.length}문장 · 눌러서 펼치기</span>
<h4>{it.procedure}</h4>
</span>
</span>
</summary>
<ul>
{it.ko.map((s) => <li>{s}</li>)}
</ul>
<p><a class="go" href={it.url} rel="noopener nofollow">병원 페이지 보기 ↗</a>{it.fetchedAt ? ` · ${it.fetchedAt} 확인` : ''}</p>
</details>
</li>
))}
</ol>
</details>
)}
<!-- ── 1. 주변 ── -->
<section id="around">
<div class="sec-head">
<h2>병원 주변</h2>
<span class="upd">{updated ? `${updated} 갱신` : '확인 대기'}</span>
</div>
<p class="sub">{total > 0 ? `${total}곳입니다. 병원에서 걸어가는 시간 순으로 놓았습니다.` : '병원 위치를 확인한 뒤에 채워집니다. 확인 대기.'}</p>
{total > 0 && <div class="chips" id="walkchips" role="group" aria-label="이동 시간으로 거르기">
<button class="chip on" data-max="all">전체 <b>{T.filters.total}</b></button>
<button class="chip" data-max="5">도보 5분 이내 <b>{T.filters.walk5}</b></button>
<button class="chip" data-max="15">도보 15분 이내 <b>{T.filters.walk15}</b></button>
<button class="chip" data-max="walk">걸어갈 수 있는 곳 <b>{T.filters.walkAll}</b></button>
<button class="chip" data-max="drive">차로 가는 곳 <b>{T.filters.drive}</b></button>
</div>}
{GROUPS.map((g) => {
const items = allPlaces.filter((p) => p.cat === g.key);
if (!items.length) return null;
return (
<div class="grp" id={`g-${g.key}`} data-group={g.key}>
<h3>{g.label} <small>{g.note}</small></h3>
<div class="cards">
{items.map((p) => (
<article class="card" data-mode={p.travel?.mode ?? 'drive'} data-walk={p.travel?.mode === 'walk' ? p.travel.minutes : ''}>
<div class="thumb">
{p.image ? <img src={p.image} alt={`${p.title}, ${clinic} 주변 ${g.label}`} loading="lazy" referrerpolicy="no-referrer" /> : <span class="nophoto">{shortName(p.title)}</span>}
{p.travel && <span class="badge">{travelLabel(p.travel)} <em>{p.distanceM! < 1000 ? `${p.distanceM} m` : `${(p.distanceM! / 1000).toFixed(1)} km`}</em></span>}
</div>
<div class="body">
<h4>{p.title}</h4>
<p class="desc">{firstSentence(p.overview) || '관광 자료에 설명이 없습니다.'}</p>
<p class="addr">{p.address}</p>
{p.homepage
? <a class="go" href={p.homepage} rel="noopener nofollow">공식 홈페이지 ↗</a>
: <a class="go" href={searchUrl(p.title.replace(/\s*\(.*\)\s*$/, ''))} rel="noopener nofollow">검색으로 열기 ↗</a>}
</div>
</article>
))}
</div>
</div>
);
})}
<p class="src">출처 · 한국관광공사 TourAPI. 도보 시간은 분당 80m로 어림한 값이며 실제 경로 거리가 아닙니다.</p>
</section>
<!-- ── 2. 축제 ── -->
<section id="festivals">
<div class="sec-head"><h2>계절별 축제</h2></div>
<p class="sub">{festivals.length > 0
? `${festKm ? `${festKm}km 안의 ` : ''}행사 ${festivals.length}건을 계절로 묶었습니다. 지금은 `
: '병원 위치를 확인한 뒤에 채워집니다. 확인 대기. 지금은 '}<strong>{nowSeason}</strong>입니다.</p>
{festivals.length > 0 && <div class="chips" role="group" aria-label="계절로 거르기">
<button class="chip on" data-season="all">전체 <b>{festivals.length}</b></button>
{SEASONS.map((s) => {
const n = festivals.filter((e: any) => e.season === s.key).length;
return n ? <button class="chip" data-season={s.key}>{s.label} <b>{n}</b></button> : null;
})}
</div>}
<div class="cards fest">
{festivals.map((e: any) => (
<article class="card" data-season={e.season}>
<div class="thumb">
{e.image ? <img src={e.image} alt={`${e.title}, ${clinic} 주변 축제`} loading="lazy" referrerpolicy="no-referrer" /> : <span class="nophoto">{shortName(e.title)}</span>}
<span class="badge mono">{MONTHS[e.month] ?? ''}</span>
</div>
<div class="body">
<h4>{e.title}</h4>
<p class="when">{dt(e.startDate)} – {dt(e.endDate)} · {e.travel ? travelLabel(e.travel) : `${e.distanceKm}km`}</p>
<p class="desc">{firstSentence(e.overview) || '관광 자료에 설명이 없습니다.'}</p>
<p class="addr">{e.address}</p>
<a class="go" href={searchUrl(e.title.replace(/\s*\(.*\)\s*$/, ''))} rel="noopener nofollow">검색으로 열기 ↗</a>
</div>
</article>
))}
</div>
<p class="src">출처 · 한국관광공사 TourAPI. 일정은 주최 측 사정으로 바뀔 수 있습니다.</p>
</section>
<!-- ── 3. 동선 ── -->
<section id="days">
<div class="sec-head"><h2>하루 동선</h2></div>
<p class="sub">
위 장소들로 짠 동선 세 가지입니다. 시각은 진료가 그 시각에 끝난다고 가정한 예시이며 실제 일정이 아닙니다.
</p>
{Sx.recoveryStagesKo
? <p><strong>{clinic} 안내.</strong> {Sx.recoveryStagesKo}</p>
: <p class="pending-note">어느 날 무엇을 해도 되는지는 의학 판단이라 {clinic}이 정합니다. 아직 확인 대기입니다. 상담 때 확인하세요.</p>}
{ROUTES.map((r) => {
const pins = miniMap(r.route.stops);
return (
<div class="route">
<div class="route-head">
<div>
<h3>{r.title}</h3>
<p class="who">{r.who}</p>
</div>
<div class="clock">{r.route.from}–{r.route.to} · {Math.floor(r.route.total / 60) ? `${Math.floor(r.route.total / 60)}시간 ` : ''}{r.route.total % 60}분</div>
</div>
<p class="blurb">{r.blurb}</p>
<div class="map" role="img" aria-label={`동선 지도, 정차 ${pins.pins.length}곳: ${pins.pins.map((p) => p.label).join(', ')}`}>
<div class="map-tiles">
{/* 타일은 장식이다. 지도의 뜻은 감싸는 요소의 aria-label 이 전한다.
img 대신 배경으로 두어 스크린리더가 256개 조각을 읽지 않게 한다. */}
{pins.tiles.map((t) => (
<div class="tile" style={`left:${t.x}px;top:${t.y}px;background-image:url('${t.src}')`} />
))}
</div>
<svg class="map-pins" viewBox={`0 0 ${MAPW} ${MAPH}`} aria-hidden="true">
<polyline points={pins.pins.map((p) => `${p.x},${p.y}`).join(' ')} fill="none" stroke="#0A1128" stroke-width="3" stroke-dasharray="6 5" opacity="0.65" />
{pins.pins.map((p) => (
<g><circle cx={p.x} cy={p.y} r="13" fill="#0A1128" stroke="#fff" stroke-width="2.5" /><text x={p.x} y={p.y + 4.5} text-anchor="middle" font-size="12" font-weight="700" fill="#fff">{p.n}</text></g>
))}
</svg>
<span class="map-credit">© OpenStreetMap contributors</span>
</div>
<ol class="timeline">
{r.route.stops.map((s: any, i: number) => (
<li>
{i > 0 && <div class="move">↓ {s.moveMin}분</div>}
<div class="stop">
<span class="n">{i + 1}</span>
<div>
<div class="stop-t">{s.from}–{s.to}</div>
<h4>{s.label}</h4>
<p>{s.note}</p>
</div>
</div>
</li>
))}
</ol>
</div>
);
})}
</section>
<section id="limits">
<h2>이 페이지가 답하지 못하는 것</h2>
<ul>
<li>평점·리뷰 수·영업시간은 없습니다. 관광 자료가 주지 않습니다.</li>
<li>어떤 곳이 회복에 맞는지는 말하지 않습니다. {clinic}이 정할 일입니다.</li>
<li>{total > 0
? `도보 5분 안에는 ${T.filters.walk5}곳뿐이고, ${total}곳 중 ${T.filters.drive}곳은 차로 가야 합니다.`
: '주변 장소 목록은 병원 위치를 확인한 뒤에 채워집니다.'}</li>
<li>여행사가 아닙니다. 예약을 받지 않고 수수료도 받지 않습니다.</li>
</ul>
<p class="botnote">
{has(reservationUrl) && <a class="btn primary" href={reservationUrl} rel="noopener">{clinic} 상담 예약</a>}
</p>
<p class="disclosure">{f.sideEffectNoticeEn || f.sideEffectNotice}</p>
</section>
</article>
<script is:inline define:vars={{ WX_LAT: origin.lat ?? 0, WX_LNG: origin.lng ?? 0 }}>
// 이동 시간 필터. 임계값은 누적이라 "15분 이내"가 5분 이내도 포함한다.
// 걸러져 비게 된 그룹은 제목만 남지 않도록 통째로 숨긴다.
(function () {
var chips = document.querySelectorAll('#walkchips .chip');
chips.forEach(function (c) {
c.addEventListener('click', function () {
chips.forEach(function (x) { x.classList.toggle('on', x === c); });
var want = c.dataset.max;
document.querySelectorAll('#around .card').forEach(function (card) {
var mode = card.dataset.mode, w = parseInt(card.dataset.walk || '', 10);
var show = want === 'all' ? true
: want === 'walk' ? mode === 'walk'
: want === 'drive' ? mode !== 'walk'
: mode === 'walk' && w <= parseInt(want, 10);
card.hidden = !show;
});
document.querySelectorAll('#around .grp').forEach(function (g) {
g.hidden = ![].slice.call(g.querySelectorAll('.card')).some(function (x) { return !x.hidden; });
});
});
});
// 점프 칩 '시술 후 관리'는 접힌 블록으로 가므로 눌렀을 때 함께 연다.
document.querySelectorAll('a[href="#recovery-quote"]').forEach(function (a) { a.addEventListener('click', function () { var d = document.getElementById('recovery-quote'); if (d) d.open = true; }); });
// 지금 화면에 있는 섹션의 버튼을 켠다. 섹션이 많아 어디쯤인지 알기 어렵다.
var links = [].slice.call(document.querySelectorAll('.jump a'));
var targets = links.map(function (a) { return document.querySelector(a.getAttribute('href')); });
if ('IntersectionObserver' in window) {
var seen = {};
var io = new IntersectionObserver(function (entries) {
entries.forEach(function (e) { seen[e.target.id] = e.isIntersecting ? e.intersectionRatio : 0; });
var best = null, top = 0;
targets.forEach(function (t) {
if (t && (seen[t.id] || 0) > top) { top = seen[t.id]; best = t.id; }
});
links.forEach(function (a) { a.classList.toggle('on', best !== null && a.getAttribute('href') === '#' + best); });
}, { rootMargin: '-150px 0px -55% 0px', threshold: [0, 0.15, 0.4, 0.75, 1] });
targets.forEach(function (t) { if (t) io.observe(t); });
}
// 오늘 날씨. Open-Meteo, 키 없음. 실패하면 블록을 숨긴 채 둔다.
// 문구는 이 페이지의 목록에만 연결한다. 무엇을 해도 되는지는 의학 판단이라 말하지 않는다.
(function () {
var WMO = {
0: '맑음', 1: '대체로 맑음', 2: '구름 조금', 3: '흐림',
45: '안개', 48: '서리 안개', 51: '약한 이슬비', 53: '이슬비', 55: '강한 이슬비',
56: '언 이슬비', 57: '언 이슬비', 61: '약한 비', 63: '비', 65: '강한 비',
66: '언 비', 67: '언 비', 71: '약한 눈', 73: '눈', 75: '강한 눈',
77: '싸락눈', 80: '약한 소나기', 81: '소나기', 82: '강한 소나기',
85: '진눈깨비', 86: '진눈깨비', 95: '뇌우', 96: '우박을 동반한 뇌우', 99: '우박을 동반한 뇌우'
};
var WET = [51,53,55,56,57,61,63,65,66,67,71,73,75,77,80,81,82,85,86,95,96,99];
var LAT = WX_LAT, LNG = WX_LNG;
if (!LAT || !LNG) return; // 기준 좌표가 없으면(확인 대기) 날씨도 띄우지 않는다
fetch('https://api.open-meteo.com/v1/forecast?latitude=' + LAT + '&longitude=' + LNG +
'&current=temperature_2m,apparent_temperature,weather_code,wind_speed_10m&timezone=auto')
.then(function (r) { if (!r.ok) throw 0; return r.json(); })
.then(function (j) {
var c = j.current; if (!c || c.temperature_2m == null) throw 0;
var code = c.weather_code;
document.getElementById('wx-t').textContent = Math.round(c.temperature_2m);
document.getElementById('wx-c').textContent = WMO[code] || '현재 날씨';
document.getElementById('wx-m').textContent =
'체감 ' + Math.round(c.apparent_temperature) + '°C · 바람 ' +
Math.round(c.wind_speed_10m) + ' km/h · ' + String(c.time).replace('T', ' ') + ' 관측';
document.getElementById('wx-n').textContent = WET.indexOf(code) >= 0
? '비가 옵니다. 아래 문화·쇼핑 항목은 실내입니다.'
: (c.temperature_2m >= 30
? '더운 날입니다. 아래 문화·쇼핑 항목은 실내입니다.'
: (c.temperature_2m <= 0
? '영하입니다. 아래 문화·쇼핑 항목은 실내입니다.'
: '지금은 비가 오지 않습니다. 아래 시간은 병원에서 걸어가는 기준입니다.'));
document.getElementById('weather').hidden = false;
})
.catch(function () { /* 못 받으면 숨긴 채 둔다 */ });
})();
var sc = document.querySelectorAll('#festivals .chip');
sc.forEach(function (c) {
c.addEventListener('click', function () {
sc.forEach(function (x) { x.classList.toggle('on', x === c); });
var want = c.dataset.season;
document.querySelectorAll('#festivals .card').forEach(function (card) {
card.hidden = !(want === 'all' || card.dataset.season === want);
});
});
});
})();
</script>
</Base>
+2
View File
@@ -2,6 +2,7 @@
// 방문 안내. 병원 정보(/clinic)가 사실 표라면 이 페이지는 "예약하고, 찾아가고, 도착해서 뭘 하는지"의 행동 순서다. 값은 모두 factSheet.json에서 가져온다.
import Base from '../layouts/Base.astro';
import Gallery from '../components/Gallery.astro';
import VisitMap from '../components/VisitMap.astro';
import '../styles/plan.css';
import { fact, site as S, SITE_NAME, clinicSchema, reservationUrl, v, has } from '../lib';
const f = fact as Record<string, any>;
@@ -32,6 +33,7 @@ const ld = [
<p><strong>주소</strong> {v(f.address?.full)}{has(f.address?.postalNote) && <> (지번 {f.address.postalNote})</>}</p>
<p><strong>지하철</strong> {v(f.transit)}.{has(f.transitNote) && <> {f.transitNote}</>}</p>
<p><strong>차로 올 때</strong> {v(f.parking, `주차 안내 ${v(null)}`)}.</p>
<VisitMap hideHead />
{S.visitMaps?.length > 0 && <Gallery cols={2} items={S.visitMaps} />}
<h2>4. 도착하면</h2>
+177
View File
@@ -279,3 +279,180 @@ td { color: var(--slate-700); }
.site-header .nav a { margin-left: 0; flex: none; font-size: 0.9rem; }
}
/* ── /en/stay ── */
.stay { padding-bottom: 4rem; }
.stay .lede { color: var(--slate-600, #475569); margin-top: 0.6rem; }
.stay section { margin-top: 3.4rem; }
.stay .sec-head { display: flex; align-items: baseline; justify-content: space-between; gap: 1rem; flex-wrap: wrap; }
.stay .sec-head h2 { margin: 0; }
.stay .upd { font-size: 0.8rem; color: var(--slate-500, #64748B); }
.stay .sub { color: var(--slate-600, #475569); margin: 0.4rem 0 1rem; }
.stay .src { font-size: 0.84rem; color: var(--slate-500, #64748B); margin-top: 1rem; }
.stay .chips { display: flex; flex-wrap: wrap; gap: 0.5rem; margin: 0.2rem 0 1.6rem; }
.stay .chip {
border: 1px solid var(--line, #E2E8F0); background: #fff; border-radius: 999px;
padding: 0.36rem 0.85rem; font: inherit; font-size: 0.86rem; color: var(--slate-600, #475569);
cursor: pointer; transition: background 0.15s, color 0.15s, border-color 0.15s;
}
.stay .chip b { font-weight: 700; opacity: 0.55; margin-left: 0.25em; }
.stay .chip:hover { border-color: var(--primary-900, #0A1128); }
.stay .chip.on { background: var(--primary-900, #0A1128); border-color: var(--primary-900, #0A1128); color: #fff; }
.stay .chip.on b { opacity: 0.7; }
.stay .grp { margin-bottom: 2.2rem; }
.stay .grp h3 { margin: 0 0 0.9rem; }
.stay .grp h3 small { font-weight: 400; font-size: 0.82rem; color: var(--slate-500, #64748B); margin-left: 0.45em; }
.stay .cards { display: grid; grid-template-columns: repeat(auto-fill, minmax(248px, 1fr)); gap: 1rem; }
.stay .card {
background: #fff; border: 1px solid var(--line, #E2E8F0); border-radius: 14px;
overflow: hidden; display: flex; flex-direction: column;
box-shadow: 3px 4px 12px rgba(0, 0, 0, 0.05);
}
.stay .card .thumb { position: relative; height: 148px; background: #EEF1F6; display: flex; align-items: center; justify-content: center; }
.stay .card .thumb img { width: 100%; height: 148px; object-fit: cover; display: block; }
.stay .card .nophoto {
font-size: 1.02rem; font-weight: 700; color: var(--slate-500, #64748B);
padding: 0 1rem; text-align: center; line-height: 1.35; word-break: keep-all;
}
.stay .card .badge {
position: absolute; left: 0.6rem; bottom: 0.6rem;
background: rgba(10, 17, 40, 0.82); color: #fff; border-radius: 6px;
padding: 0.18rem 0.45rem; font-size: 0.74rem; font-weight: 600;
}
.stay .card .badge em { font-style: normal; opacity: 0.7; margin-left: 0.25em; }
.stay .card .badge.mono { letter-spacing: 0.06em; }
.stay .card .body { padding: 0.85rem 0.95rem 1rem; display: flex; flex-direction: column; flex: 1; }
.stay .card h4 { margin: 0 0 0.35rem; font-size: 0.98rem; }
.stay .card .when { font-size: 0.8rem; color: var(--slate-600, #475569); margin: 0 0 0.4rem; }
.stay .card .desc { font-size: 0.86rem; color: var(--slate-600, #475569); margin: 0 0 0.5rem; }
.stay .card .addr { font-size: 0.78rem; color: var(--slate-500, #64748B); margin: 0 0 0.6rem; }
.stay .card .go { font-size: 0.82rem; margin-top: auto; }
.stay .route { border: 1px solid var(--line, #E2E8F0); border-radius: 16px; padding: 1.3rem 1.4rem; margin-bottom: 1.4rem; background: #fff; }
.stay .route-head { display: flex; justify-content: space-between; align-items: flex-start; gap: 1rem; flex-wrap: wrap; }
.stay .route-head h3 { margin: 0; }
.stay .route .who { font-size: 0.84rem; color: var(--slate-500, #64748B); margin: 0.15rem 0 0; }
.stay .route .clock { font-size: 0.86rem; font-weight: 600; color: var(--primary-900, #0A1128); white-space: nowrap; }
.stay .route .blurb { color: var(--slate-600, #475569); margin: 0.7rem 0 1rem; }
.stay .route .map { width: 100%; height: auto; display: block; border-radius: 12px; }
.stay .route .maphint { font-size: 0.76rem; color: var(--slate-500, #64748B); margin: 0.4rem 0 1rem; }
.stay .timeline { list-style: none; padding: 0; margin: 0; }
.stay .timeline .move { font-size: 0.8rem; color: var(--slate-500, #64748B); margin: 0.35rem 0 0.35rem 1.05rem; }
.stay .timeline .stop { display: flex; gap: 0.8rem; align-items: flex-start; }
.stay .timeline .n {
flex: none; width: 26px; height: 26px; border-radius: 50%;
background: var(--primary-900, #0A1128); color: #fff;
font-size: 0.8rem; font-weight: 700; display: grid; place-items: center; margin-top: 0.1rem;
}
.stay .timeline .stop-t { font-size: 0.8rem; color: var(--slate-500, #64748B); }
.stay .timeline h4 { margin: 0.1rem 0 0.2rem; font-size: 0.98rem; }
.stay .timeline p { margin: 0; font-size: 0.86rem; color: var(--slate-600, #475569); }
.stay .botnote { margin-top: 1.6rem; }
/* 시술 후 관리 안내(병원 원문 인용). 동선 카드(.route)·정차(.stop) 룩을 그대로 쓰고 접이식 동작만 더한다. 새 색·크기 없음. */
.stay details.recovery > summary.btn { list-style: none; cursor: pointer; }
.stay details.recovery > summary.btn::-webkit-details-marker { display: none; }
.stay details.recovery > summary.btn .hide { display: none; }
.stay details.recovery[open] > summary.btn .show { display: none; }
.stay details.recovery[open] > summary.btn .hide { display: inline; }
.stay details.recovery[open] > summary.btn { margin-bottom: 1.1rem; }
.stay details.recovery > .timeline { margin-top: 0.2rem; }
.stay .recovery .timeline > li { border-top: 1px solid var(--line, #E2E8F0); padding: 0.7rem 0; }
.stay .recovery .timeline > li:first-child { border-top: 0; padding-top: 0; }
.stay .recovery summary { cursor: pointer; list-style: none; }
.stay .recovery summary::-webkit-details-marker { display: none; }
.stay .recovery summary .stop { display: flex; }
.stay .recovery summary h4 { margin: 0.1rem 0 0; }
.stay .recovery details[open] summary h4 { text-decoration: underline; text-underline-offset: 0.2em; text-decoration-color: var(--slate-200, #E2E8F0); }
.stay .recovery details > ul { margin: 0.7rem 0 0.5rem 2.2rem; padding-left: 1.1rem; }
.stay .recovery details > ul li { font-size: 0.9rem; color: var(--slate-700, #334155); margin-bottom: 0.35rem; }
.stay .recovery details > p { margin: 0 0 0 2.2rem; font-size: 0.84rem; color: var(--slate-500, #64748B); }
@media (max-width: 640px) { .cards { grid-template-columns: 1fr; } }
/* 섹션 점프. 머리말 아래에 붙어 스크롤을 따라온다. 헤더(68px) 아래에 걸리게 top 을 맞춘다. */
.stay .jump {
position: sticky; top: 68px; z-index: 9;
display: flex; flex-wrap: wrap; gap: 0.45rem;
margin: 1.4rem 0 2.4rem;
padding: 0.62rem 0.68rem;
background: rgba(255, 255, 255, 0.58);
backdrop-filter: blur(16px) saturate(1.5);
-webkit-backdrop-filter: blur(16px) saturate(1.5);
border: 1px solid rgba(255, 255, 255, 0.6);
border-radius: 18px;
box-shadow: 0 8px 28px rgba(10, 17, 40, 0.09), inset 0 1px 0 rgba(255, 255, 255, 0.7);
}
.stay .jump a {
display: inline-flex; align-items: center; gap: 0.42rem;
padding: 0.46rem 0.9rem;
border-radius: 999px;
font-size: 0.86rem; font-weight: 600; letter-spacing: -0.005em;
color: var(--primary-900, #0A1128);
text-decoration: none; white-space: nowrap;
background: #fff;
border: 1px solid var(--line, #E2E8F0);
box-shadow: 0 1px 2px rgba(10, 17, 40, 0.06);
transition: transform 0.14s ease, box-shadow 0.14s ease, background 0.14s, border-color 0.14s, color 0.14s;
}
.stay .jump a:hover {
text-decoration: none;
transform: translateY(-1px);
border-color: #C5CBF5;
box-shadow: 0 4px 12px rgba(10, 17, 40, 0.12);
}
.stay .jump a:active { transform: translateY(0); box-shadow: 0 1px 2px rgba(10, 17, 40, 0.08); }
.stay .jump a b {
font-weight: 700; font-size: 0.72rem; line-height: 1;
padding: 0.2rem 0.4rem; border-radius: 999px;
background: #EFF0FF; color: #3A3F7C;
}
/* 지금 보고 있는 섹션 */
.stay .jump a.on {
background: linear-gradient(to right, #4F1DA1, #021341);
border-color: transparent; color: #fff;
box-shadow: 0 4px 14px rgba(79, 29, 161, 0.32);
}
.stay .jump a.on b { background: rgba(255, 255, 255, 0.22); color: #fff; }
/* 점프로 이동했을 때 제목이 스티키 바에 가리지 않게 */
.stay section, .stay .grp { scroll-margin-top: 152px; }
@media (max-width: 640px) {
.stay .jump { top: 60px; gap: 0.35rem; padding: 0.5rem; border-radius: 14px; }
.stay .jump a { padding: 0.4rem 0.72rem; font-size: 0.8rem; }
}
/* 필터 칩도 눌리는 것처럼 보이게 */
.stay .chip {
box-shadow: 0 1px 2px rgba(10, 17, 40, 0.05);
transition: transform 0.14s ease, box-shadow 0.14s ease, background 0.15s, color 0.15s, border-color 0.15s;
}
.stay .chip:hover { transform: translateY(-1px); box-shadow: 0 4px 12px rgba(10, 17, 40, 0.1); }
.stay .chip:active { transform: translateY(0); }
.stay .chip.on { box-shadow: 0 4px 14px rgba(10, 17, 40, 0.22); }
/* 오늘 날씨. 값을 못 받으면 hidden 이라 아예 그려지지 않는다. */
.stay .wx {
display: flex; align-items: center; justify-content: space-between;
gap: 1.2rem; flex-wrap: wrap;
margin-top: 1.6rem; padding: 1rem 1.2rem;
background: linear-gradient(to right, #fff3eb, #e4cfff, #f5f9ff);
border-radius: 16px;
}
.stay .wx-now { display: flex; align-items: center; gap: 0.9rem; }
.stay .wx-temp { font-family: 'Playfair Display', serif; font-size: 2.5rem; font-weight: 700; line-height: 1; color: var(--primary-900, #0A1128); }
.stay .wx-unit { font-size: 1.1rem; vertical-align: 0.9rem; margin-left: 0.06em; opacity: 0.6; }
.stay .wx-cond { font-weight: 700; color: var(--primary-900, #0A1128); }
.stay .wx-meta { font-size: 0.8rem; color: var(--slate-600, #475569); margin-top: 0.15rem; }
.stay .wx-note { margin: 0; font-size: 0.88rem; color: var(--slate-700, #334155); max-width: 30rem; }
/* 동선 지도. OSM 타일을 좌표로 깔고 그 위에 핀을 얹는다. 출처 표기는 OSM 정책상 필수다. */
.stay .route .map {
position: relative; width: 100%; max-width: 680px; height: 340px;
border-radius: 12px; overflow: hidden; background: #E8EDF3;
border: 1px solid var(--line, #E2E8F0);
}
.stay .route .map-tiles { position: absolute; inset: 0; }
.stay .route .map-tiles .tile { position: absolute; width: 256px; height: 256px; background-size: 256px 256px; background-repeat: no-repeat; }
.stay .route .map-pins { position: absolute; inset: 0; width: 100%; height: 100%; }
.stay .route .map-credit {
position: absolute; right: 0; bottom: 0;
background: rgba(255, 255, 255, 0.82); color: var(--slate-600, #475569);
font-size: 0.66rem; padding: 0.1rem 0.35rem; border-top-left-radius: 6px;
}
+8
View File
@@ -100,6 +100,14 @@ button.btn { font: inherit; cursor: pointer; border: 0; }
.day .rest { font-size: 0.88rem; color: var(--slate-500); }
@media (max-width: 640px) { .day { grid-template-columns: 1fr; } }
/* 체류 기간의 행사 카드 (TourAPI 이미지) */
.fest-card { padding: 0; overflow: hidden; }
.fest-card img { width: 100%; aspect-ratio: 16 / 9; object-fit: cover; display: block; }
.fest-card .cat, .fest-card h3, .fest-card p { margin-left: 1.5rem; margin-right: 1.5rem; }
.fest-card .cat { margin-top: 1.2rem; }
.fest-card > p:last-child { margin-bottom: 1.3rem; }
.day .picks a.fest { border-color: var(--st-good-border); background: var(--st-good-bg); }
/* 예약 (다크 섹션 위 흰 카드) */
.hotel-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(230px, 1fr)); gap: 1.25rem; }
.hotel-grid .card small { color: var(--slate-500); font-size: 0.78rem; }
+14 -2
View File
@@ -21,5 +21,17 @@
}
],
"cleanUrls": true,
"trailingSlash": false
}
"trailingSlash": false,
"redirects": [
{
"source": "/recovery",
"destination": "/plan",
"permanent": true
},
{
"source": "/en/recovery",
"destination": "/en/plan",
"permanent": true
}
]
}