feat(supporters): 회복 일정 플래너를 템플릿·워커에 통합 (/plan·/en/plan), /recovery·/stay 를 /plan 으로 정리
- 템플릿: Planner.astro, lib/plan.ts·tour.ts, styles/plan.css, planStrings, pages plan·en/plan·404. Base 내비 회복 일정 → /plan, 언어 짝 /plan↔/en/plan, 옛 주소 리다이렉트(vercel.json), 사이트맵 - 워커 planner 단계(recovery 다음): scripts/build_planner_data.mjs 가 업종별 기본 규칙표(scripts/template/planner/procedures.plastic|derm.json)에 병원 시술 페이지 원문(recoveryNotes)을 matchKeywords 로 붙이고, 장소는 briefs/<clinic>/planner.places.json(큐레이션) 또는 범용 기본표(관광공사 기준 좌표)로 만든다 - 브리프: viewclinic·oracle 큐레이션 장소. 빈 템플릿(관광 데이터 없음)도 빌드·검증 통과(plan.test 14건) - 이전 세션의 미커밋 작업(피부과 수집·OCR·게이트·언어 스위치, stay 페이지 제거)도 이 커밋에 함께 들어감. docs/prd 변경은 제외 Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
1 parent
5c08fa97ab
commit
aa5b05227f
126 files changed
+12916
-2068
No files matched your search
@@ -0,0 +1,177 @@
|
||||
// 회복기 스케줄러 계산 로직 (설계 v0.2 §13.3·§13.7·§13.8). 화면과 분리된 순수 함수만 둔다.
|
||||
// 입력: 시술 id, 수술일, 국적, 선호. 출력: 날짜별 외출 등급·식사·추천과 예약 링크. 서버 호출 없음.
|
||||
// 검증: node --experimental-strip-types scripts/gate/plan.test.mjs
|
||||
|
||||
export type Lang = 'ko' | 'en';
|
||||
export type L10n = Record<Lang, string>;
|
||||
export type Status = 'clinic' | 'provisional';
|
||||
export interface Valued { value: number | null; range?: [number, number]; status: Status; source?: string; note?: L10n }
|
||||
export interface LevelStep { fromDay: number; level: number; status: Status; source?: string; note?: L10n }
|
||||
export interface DietStep { fromDay: number; type: 'liquid' | 'soft' | 'mild' | 'normal'; status: Status; source?: string }
|
||||
export interface Procedure {
|
||||
id: string; label: L10n; group: L10n; readMore: string | null;
|
||||
preOpDays: Valued; hospitalNights: Valued; stitchRemovalDay: Valued; earliestDepartureDay: Valued;
|
||||
outingLevels: LevelStep[]; diet: DietStep[]; constraints: string[]; sources: string[];
|
||||
}
|
||||
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 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[];
|
||||
}
|
||||
|
||||
const DAY = 86_400_000;
|
||||
export const addDays = (iso: string, n: number): string => {
|
||||
const d = new Date(`${iso}T00:00:00Z`);
|
||||
return new Date(d.getTime() + n * DAY).toISOString().slice(0, 10);
|
||||
};
|
||||
export const isIsoDate = (s: unknown): s is string => typeof s === 'string' && /^\d{4}-\d{2}-\d{2}$/.test(s) && !Number.isNaN(Date.parse(`${s}T00:00:00Z`));
|
||||
|
||||
/** fromDay 오름차순 단계표에서 offset 에 해당하는 단계. 첫 단계 이전이면 첫 단계. */
|
||||
function stepAt<T extends { fromDay: number }>(steps: T[], offset: number): T {
|
||||
const sorted = [...steps].sort((a, b) => a.fromDay - b.fromDay);
|
||||
let cur = sorted[0];
|
||||
for (const s of sorted) if (offset >= s.fromDay) cur = s;
|
||||
return cur;
|
||||
}
|
||||
|
||||
/** 장거리 국적은 시차 회복으로 준비일에 1일을 더한다 (§13.3). */
|
||||
export function effectivePreOpDays(p: Procedure, nat?: Nationality | null): number {
|
||||
const base = p.preOpDays.value ?? 2;
|
||||
return base + (nat?.longHaul ? 1 : 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* 장소 점수. 선호 일치가 가장 크고, 등급이 딱 맞을수록, 가까울수록 높다.
|
||||
* 선호가 비어 있으면 카테고리 무관하게 거리와 등급만 본다.
|
||||
*/
|
||||
export function scorePlace(place: Place, level: number, diet: DietStep['type'], prefs: string[]): number {
|
||||
if (place.category === 'hotel') return -1;
|
||||
if (place.minLevel > level) return -1;
|
||||
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)
|
||||
return s;
|
||||
}
|
||||
|
||||
/** 하루에 최대 3곳. 직전 2일에 나온 곳은 뒤로 미뤄 날마다 다른 곳이 나오게 한다. */
|
||||
export function pickForDay(places: Place[], level: number, diet: DietStep['type'], prefs: string[], recent: Set<string>, max = 3): Place[] {
|
||||
return places
|
||||
.map((p) => ({ p, s: scorePlace(p, level, diet, prefs) - (recent.has(p.id) ? 2.5 : 0) }))
|
||||
.filter((x) => x.s >= 0)
|
||||
.sort((a, b) => b.s - a.s || a.p.distanceKm - b.p.distanceKm)
|
||||
.slice(0, max)
|
||||
.map((x) => x.p);
|
||||
}
|
||||
|
||||
export function buildPlan(input: PlanInput, places: Place[]): Plan {
|
||||
const { procedure: p, surgeryDate, nationality, prefs, festivals = [] } = input;
|
||||
const preOp = effectivePreOpDays(p, nationality);
|
||||
const arriveBy = addDays(surgeryDate, -preOp);
|
||||
const nights = p.hospitalNights.value;
|
||||
const dischargeDate = nights === null ? null : addDays(surgeryDate, nights);
|
||||
const stitchDate = p.stitchRemovalDay.value === null ? null : addDays(surgeryDate, p.stitchRemovalDay.value);
|
||||
const dep = p.earliestDepartureDay.value;
|
||||
const earliestDeparture = dep === null ? null : addDays(surgeryDate, dep);
|
||||
const lastOffset = dep ?? Math.max(14, ...p.outingLevels.map((l) => l.fromDay));
|
||||
const days: PlanDay[] = [];
|
||||
const recent: string[] = [];
|
||||
for (let off = -preOp; off <= lastOffset; off++) {
|
||||
const date = addDays(surgeryDate, off);
|
||||
const isHospital = nights !== null && off >= 0 && off < nights;
|
||||
const pre = off < 0;
|
||||
const level = pre ? 2 : isHospital ? 0 : stepAt(p.outingLevels, off).level;
|
||||
const diet = pre ? 'normal' : stepAt(p.diet, off).type;
|
||||
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));
|
||||
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 };
|
||||
}
|
||||
|
||||
// ---------- 예약 링크 (§13.7). 검색 결과 페이지 패턴만 쓴다. 제휴 ID 는 확정 후 aid 파라미터로 붙인다. ----------
|
||||
export function bookingUrl(query: string, checkin: string, checkout: string, lang: Lang, aid?: string): string {
|
||||
const u = new URL('https://www.booking.com/searchresults.html');
|
||||
u.searchParams.set('ss', query);
|
||||
u.searchParams.set('checkin', checkin);
|
||||
u.searchParams.set('checkout', checkout);
|
||||
u.searchParams.set('group_adults', '1');
|
||||
u.searchParams.set('no_rooms', '1');
|
||||
u.searchParams.set('lang', lang === 'ko' ? 'ko' : 'en-us');
|
||||
if (aid) u.searchParams.set('aid', aid);
|
||||
return u.toString();
|
||||
}
|
||||
export function googleFlightsUrl(arrive: string, depart: string, lang: Lang): string {
|
||||
const q = `Flights to ICN on ${arrive} returning ${depart}`;
|
||||
return `https://www.google.com/travel/flights?hl=${lang}&q=${encodeURIComponent(q)}`;
|
||||
}
|
||||
export function mapUrl(query: string): string {
|
||||
return `https://www.google.com/maps/search/?api=1&query=${encodeURIComponent(query)}`;
|
||||
}
|
||||
|
||||
// ---------- 공유 URL 해시 (서버 미전송) ----------
|
||||
export interface HashState { p?: string; d?: string; l?: Lang; n?: string; pref?: string[] }
|
||||
export function encodeHash(s: HashState): string {
|
||||
const q = new URLSearchParams();
|
||||
if (s.p) q.set('p', s.p);
|
||||
if (s.d) q.set('d', s.d);
|
||||
if (s.l) q.set('l', s.l);
|
||||
if (s.n) q.set('n', s.n);
|
||||
if (s.pref?.length) q.set('pref', s.pref.join(','));
|
||||
return q.toString();
|
||||
}
|
||||
export function decodeHash(hash: string): HashState {
|
||||
const q = new URLSearchParams(hash.replace(/^#/, ''));
|
||||
const l = q.get('l');
|
||||
return {
|
||||
p: q.get('p') ?? undefined,
|
||||
d: isIsoDate(q.get('d')) ? (q.get('d') as string) : undefined,
|
||||
l: l === 'ko' || l === 'en' ? l : undefined,
|
||||
n: q.get('n') ?? undefined,
|
||||
pref: (q.get('pref') ?? '').split(',').filter(Boolean),
|
||||
};
|
||||
}
|
||||
|
||||
// ---------- ICS (종일 일정 4개: 입국·수술·실밥·출국) ----------
|
||||
export function buildIcs(plan: Plan, titles: { arrive: string; surgery: string; stitch: string; departure: string }, calName: string): string {
|
||||
const ev = (date: string, title: string, uid: string) => [
|
||||
'BEGIN:VEVENT', `UID:${uid}@view-supporters`, `DTSTAMP:${new Date().toISOString().replace(/[-:]/g, '').slice(0, 15)}Z`,
|
||||
`DTSTART;VALUE=DATE:${date.replace(/-/g, '')}`, `DTEND;VALUE=DATE:${addDays(date, 1).replace(/-/g, '')}`, `SUMMARY:${title}`, 'END:VEVENT',
|
||||
];
|
||||
const lines = ['BEGIN:VCALENDAR', 'VERSION:2.0', 'PRODID:-//View Supporters//Recovery Planner//KO', `X-WR-CALNAME:${calName}`];
|
||||
lines.push(...ev(plan.arriveBy, titles.arrive, `arrive-${plan.arriveBy}`));
|
||||
lines.push(...ev(plan.surgeryDate, titles.surgery, `surgery-${plan.surgeryDate}`));
|
||||
if (plan.stitchDate) lines.push(...ev(plan.stitchDate, titles.stitch, `stitch-${plan.stitchDate}`));
|
||||
if (plan.earliestDeparture) lines.push(...ev(plan.earliestDeparture, titles.departure, `depart-${plan.earliestDeparture}`));
|
||||
lines.push('END:VCALENDAR');
|
||||
return lines.join('\r\n');
|
||||
}
|
||||
|
||||
/** 상담 신청에 붙여 보낼 요약문. */
|
||||
export function summaryText(plan: Plan, p: Procedure, lang: Lang, t: Record<string, string>): string {
|
||||
const pending = t.pending;
|
||||
const row = (k: string, v: string | null) => `${k}: ${v ?? pending}`;
|
||||
return [
|
||||
`${t.summaryTitle} (${p.label[lang]})`,
|
||||
row(t.arriveBy, plan.arriveBy),
|
||||
row(t.surgery, plan.surgeryDate),
|
||||
row(t.hospital, p.hospitalNights.value === null ? null : p.hospitalNights.value === 0 ? t.hospitalNone : t.hospitalNights.replace('{n}', String(p.hospitalNights.value))),
|
||||
row(t.stitch, plan.stitchDate),
|
||||
row(t.departure, plan.earliestDeparture),
|
||||
row(t.stayNights, plan.stayNights === null ? null : t.nights.replace('{n}', String(plan.stayNights))),
|
||||
].join('\n');
|
||||
}
|
||||
@@ -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,
|
||||
}));
|
||||
}
|
||||
Reference in new issue
Block a user