부품 입력·예약
예약 요금 계산 booking-calculator
객실을 고르고 입실·퇴실 날짜와 인원을 넣으면 박 수를 평일·주말·성수기로 나눠 합계를 낸다. 기준 인원을 넘으면 1인 1박 추가 요금을 더한다. 예약 단추는 onSubmit 으로 조건을 받거나 href 로 조건을 주소 뒤에 붙여 보낸다.
설치
shadcn/ui 를 쓰는 Next.js 프로젝트에서 한 줄로 설치됩니다. 파일은 components/bpublish/booking-calculator.tsx 로 들어오고, 공통 토큰(base)과 함께 쓰는 부품(section-head)도 같이 설치됩니다. 테마는 테마에서 하나 고릅니다.
npx shadcn@latest add https://www.bpublish.com/r/booking-calculator.json레지스트리를 등록했다면 npx shadcn@latest add @bpublish/booking-calculator · 설치 안내
AI에게 맡기기
Claude Code, Cursor 같은 AI 코딩 도구에 붙여 넣으세요. MCP 서버를 연결해 두면 이름만 말해도 됩니다.
bpublish UI의 예약 요금 계산(booking-calculator) 부품으로 만들어 줘. 설치: npx shadcn@latest add https://www.bpublish.com/r/booking-calculator.json · 문서: https://www.bpublish.com/designs/components/booking-calculator사용 예시
import { BookingCalculator } from '@/components/bpublish/booking-calculator'
export default function Example() {
return (
<BookingCalculator
title="실시간 예약"
description="날짜와 객실, 인원을 고르시면 예상 요금이 계산됩니다."
rooms={[
{ id: 'sol-tent', code: 'A', name: '솔 텐트', detail: '기준 2인 · 최대 4인', base: 2, max: 4, prices: { weekday: 129000, weekend: 169000, peak: 199000 } },
{ id: 'forest-caravan', code: 'B', name: '숲 카라반', detail: '기준 2인 · 최대 4인', base: 2, max: 4, prices: { weekday: 159000, weekend: 199000, peak: 239000 } },
{ id: 'cabin', code: 'C', name: '별채 오두막', detail: '기준 4인 · 최대 6인', base: 4, max: 6, prices: { weekday: 219000, weekend: 269000, peak: 319000 } },
{ id: 'family-dome', code: 'D', name: '가족 돔', detail: '기준 4인 · 최대 6인', base: 4, max: 6, prices: { weekday: 199000, weekend: 249000, peak: 299000 } },
]}
extraPerson={20000}
peakSeasons={[{ from: [7, 15], to: [8, 24] }]}
labels={{ kidsNote: '24개월 이상 13세 이하', submit: '빈 객실 확인하기' }}
done={{
title: '선택하신 조건을 받았습니다',
body: '빈 객실을 확인한 뒤 예약자 정보 입력과 결제 화면으로 이어집니다. 급한 문의는 033-000-0000(09:00 – 21:00)으로 전화 주십시오.',
}}
/>
)
}속성
| 이름 | 형식 | 기본값 | 설명 |
|---|---|---|---|
rooms필수 | { id; name; code?; detail?; base?: number; max?: number; prices: { weekday; weekend; peak? } }[] | — | 객실. base 를 넘는 인원은 extraPerson 이 더해진다 |
extraPerson | number | 0 | 기준 인원을 넘는 1인 1박 요금 |
peakSeasons | { from: [month, day]; to: [month, day] }[] | — | 성수기 기간. 해를 넘겨도 된다 |
weekendNights | number[] | [5, 6] | 주말 요금을 받는 밤의 요일 (0 = 일요일). 기본 금·토요일 밤 |
weekendDates | string[] | — | 주말 요금을 받는 날짜 'YYYY-MM-DD' (공휴일 전날 등) |
showKids | boolean | true | 어린이 인원 칸 |
onSubmit | (quote: BookingQuote) => void | — | 조건과 계산 결과를 받는 함수. 부른 뒤 done 안내를 보인다 |
href | string | — | 예약 단추가 가는 주소. ?room=&checkIn=&checkOut=&adults=&kids= 를 붙여 보낸다 |
done | { title: string; body?: string } | — | 보낸 뒤 요금 칸의 안내 (href 가 없을 때) |
labels | Partial<BookingLabels> | — | 문구 바꾸기 (checkIn, submit, kidsNote, weekday, weekend, peak … {n} 자리 채움) |
title | string | — | 구역 제목 |
description | string | — | 제목 아래 설명 |
원본 코드
설치 명령 없이 그대로 복사해 넣어도 됩니다. React 외의 패키지는 쓰지 않습니다.
'use client'
/**
* bpublish UI — 예약 요금 계산. https://www.bpublish.com/designs/components/booking-calculator
* 객실을 고르고 입실·퇴실 날짜와 인원을 넣으면 박 수를 평일·주말·성수기로 나눠 합계를 낸다. 기준 인원을 넘으면 추가 요금을 더한다.
* 예약 단추는 onSubmit 으로 조건을 받거나, href 로 조건을 주소 뒤에 붙여 보낸다(?room=&checkIn=&checkOut=&adults=&kids=).
*/
import { useEffect, useMemo, useState, type ReactNode } from 'react'
import { SectionHead } from './section-head'
export type BookingRoom = {
id: string
name: string
/** 이름 앞 작은 기호 (A, B …) */
code?: string
/** 이름 아래 한 줄 (기준 2인 · 최대 4인) */
detail?: string
/** 기준 인원. 넘으면 1인 1박 extraPerson 이 더해진다 */
base?: number
/** 최대 인원 */
max?: number
/** 1박 요금. peak 가 없으면 성수기에도 주말 요금 */
prices: { weekday: number; weekend: number; peak?: number }
}
export type NightKind = 'weekday' | 'weekend' | 'peak'
export type BookingQuote = {
room: BookingRoom
checkIn: string
checkOut: string
adults: number
kids: number
nights: number
count: Record<NightKind, number>
extraPeople: number
extra: number
total: number
}
const LABELS = {
checkIn: '입실일',
checkOut: '퇴실일',
room: '객실',
guests: '인원',
adults: '성인',
kids: '어린이',
kidsNote: '',
minus: '한 명 줄이기',
plus: '한 명 늘리기',
summary: '예상 요금',
empty: '입실일과 퇴실일을 고르시면 요금이 나옵니다.',
weekday: '평일',
weekend: '주말',
peak: '성수기',
/** {n} 자리에 숫자 */
nights: '{n}박',
person: '{n}명',
from: '부터',
unit: '원',
extra: '추가 인원 {n}명 × {nights}박',
total: '합계',
errorDates: '퇴실일은 입실일보다 뒤여야 합니다.',
errorMax: '이 객실은 최대 {max}명까지 묵을 수 있습니다.',
submit: '예약하기',
again: '조건 다시 고르기',
}
export type BookingLabels = Partial<typeof LABELS>
export type BookingCalculatorProps = {
rooms: BookingRoom[]
/** 기준 인원을 넘는 1인 1박 요금 */
extraPerson?: number
/** 성수기 기간 (월, 일). 해를 넘겨도 된다 ({ from: [12, 20], to: [1, 5] }) */
peakSeasons?: { from: [number, number]; to: [number, number] }[]
/** 주말 요금을 받는 밤의 요일. 0 = 일요일. 기본은 금·토요일 밤 */
weekendNights?: number[]
/** 주말 요금을 받는 날짜 'YYYY-MM-DD' (공휴일 전날 등) */
weekendDates?: string[]
/** 어린이 인원 칸을 보인다 */
showKids?: boolean
/** 조건을 받는 함수. 주면 이 함수를 부르고 done 안내를 보인다 */
onSubmit?: (quote: BookingQuote) => void
/** 예약 단추가 가는 주소. 조건을 주소 뒤에 붙여 보낸다 */
href?: string
/** 보낸 뒤 요금 칸에 보이는 안내 (href 가 없을 때) */
done?: { title: string; body?: string }
labels?: BookingLabels
title?: string
eyebrow?: string
description?: string
dayNames?: string[]
className?: string
}
const comma = (n: number) => String(n).replace(/\B(?=(\d{3})+(?!\d))/g, ',')
const fill = (s: string, v: Record<string, string | number>) => s.replace(/\{(\w+)\}/g, (_, k) => String(v[k] ?? ''))
const parse = (v: string) => {
const [y, m, d] = v.split('-').map(Number)
return new Date(y, m - 1, d)
}
const iso = (d: Date) => `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`
const btnFocus = 'focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring'
function Stepper({ name, field, note, value, min, max, onChange, L }: { name: string; field: string; note?: string; value: number; min: number; max: number; onChange: (n: number) => void; L: typeof LABELS }) {
const btn = `flex size-11 items-center justify-center rounded-md border border-input text-foreground transition-colors hover:bg-muted disabled:pointer-events-none disabled:opacity-35 ${btnFocus}`
const icon = (plus: boolean) => (
<svg aria-hidden viewBox="0 0 24 24" className="size-5" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round">
<path d={plus ? 'M5 12h14M12 5v14' : 'M5 12h14'} />
</svg>
)
return (
<div className="flex items-center justify-between gap-4 border-t border-border py-4">
<div>
<p className="font-medium">{name}</p>
{note ? <p className="text-[13px] text-muted-foreground">{note}</p> : null}
</div>
<div className="flex items-center gap-3">
<button type="button" className={btn} aria-label={`${name} ${L.minus}`} disabled={value <= min} onClick={() => onChange(value - 1)}>
{icon(false)}
</button>
<output className="w-8 text-center text-lg font-semibold tabular-nums" aria-live="polite">
{value}
</output>
<input type="hidden" name={field} value={value} />
<button type="button" className={btn} aria-label={`${name} ${L.plus}`} disabled={value >= max} onClick={() => onChange(value + 1)}>
{icon(true)}
</button>
</div>
</div>
)
}
export function BookingCalculator({
rooms,
extraPerson = 0,
peakSeasons = [],
weekendNights = [5, 6],
weekendDates = [],
showKids = true,
onSubmit,
href,
done,
labels,
title,
eyebrow,
description,
dayNames = ['일', '월', '화', '수', '목', '금', '토'],
className = '',
}: BookingCalculatorProps) {
const L = { ...LABELS, ...labels }
const [today, setToday] = useState('')
const [checkIn, setCheckIn] = useState('')
const [checkOut, setCheckOut] = useState('')
const [roomId, setRoomId] = useState(rooms[0]?.id ?? '')
const [adults, setAdults] = useState(2)
const [kids, setKids] = useState(0)
const [sent, setSent] = useState(false)
useEffect(() => setToday(iso(new Date())), [])
const room = rooms.find((r) => r.id === roomId) ?? rooms[0]
const guests = adults + (showKids ? kids : 0)
const stepMax = Math.max(1, ...rooms.map((r) => r.max ?? 10))
const kindLabel: Record<NightKind, string> = { weekday: L.weekday, weekend: L.weekend, peak: L.peak }
const calc = useMemo(() => {
if (!room || !checkIn || !checkOut) return null
const a = parse(checkIn)
const b = parse(checkOut)
const nights = Math.round((b.getTime() - a.getTime()) / 86400000)
if (!(nights > 0)) return { error: L.errorDates } as const
const kindOf = (d: Date): NightKind => {
const md = (d.getMonth() + 1) * 100 + d.getDate()
for (const s of peakSeasons) {
const from = s.from[0] * 100 + s.from[1]
const to = s.to[0] * 100 + s.to[1]
if (from <= to ? md >= from && md <= to : md >= from || md <= to) return 'peak'
}
return weekendNights.includes(d.getDay()) || weekendDates.includes(iso(d)) ? 'weekend' : 'weekday'
}
const count: Record<NightKind, number> = { weekday: 0, weekend: 0, peak: 0 }
for (let i = 0; i < nights; i++) count[kindOf(new Date(a.getFullYear(), a.getMonth(), a.getDate() + i))]++
const price = (k: NightKind) => (k === 'peak' ? (room.prices.peak ?? room.prices.weekend) : room.prices[k])
const extraPeople = room.base != null ? Math.max(0, guests - room.base) : 0
const extra = extraPeople * extraPerson * nights
const base = (Object.keys(count) as NightKind[]).reduce((s, k) => s + count[k] * price(k), 0)
const label = (d: Date) => `${d.getMonth() + 1}.${d.getDate()} (${dayNames[d.getDay()]})`
return { nights, count, price, extraPeople, extra, total: base + extra, from: label(a), to: label(b) } as const
}, [room, checkIn, checkOut, guests, extraPerson, peakSeasons, weekendNights, weekendDates, dayNames, L.errorDates])
const overMax = room?.max != null && guests > room.max
const ok = Boolean(calc && !('error' in calc) && !overMax)
const change = <T,>(set: (v: T) => void) => (v: T) => {
set(v)
setSent(false)
}
const field = 'mt-2 block h-14 w-full rounded-md border border-input bg-card px-4 text-base font-medium text-foreground focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring'
const won = (n: number): ReactNode => (
<>
{comma(n)}
<span className="ml-0.5 text-[0.8em]">{L.unit}</span>
</>
)
return (
<section className={`py-16 md:py-24 ${className}`}>
<div className="shell">
{title ? <SectionHead title={title} eyebrow={eyebrow} description={description} align="stack" className="mb-10" /> : null}
<form
action={href}
method="get"
className="grid gap-10 lg:grid-cols-12"
onSubmit={(e) => {
if (!ok || !calc || 'error' in calc || !room) {
e.preventDefault()
return
}
if (href && !onSubmit) return
e.preventDefault()
onSubmit?.({ room, checkIn, checkOut, adults, kids: showKids ? kids : 0, nights: calc.nights, count: calc.count, extraPeople: calc.extraPeople, extra: calc.extra, total: calc.total })
setSent(true)
}}
>
<div className="lg:col-span-7">
<fieldset>
<legend className="sr-only">
{L.checkIn} · {L.checkOut}
</legend>
<div className="grid grid-cols-2 gap-4">
<label className="block text-sm font-semibold">
{L.checkIn}
<input
type="date"
name="checkIn"
required
className={field}
value={checkIn}
min={today || undefined}
onChange={(e) => {
const v = e.target.value
change(setCheckIn)(v)
if (v && (!checkOut || checkOut <= v)) {
const d = parse(v)
setCheckOut(iso(new Date(d.getFullYear(), d.getMonth(), d.getDate() + 1)))
}
}}
/>
</label>
<label className="block text-sm font-semibold">
{L.checkOut}
<input type="date" name="checkOut" required className={field} value={checkOut} min={checkIn || today || undefined} onChange={(e) => change(setCheckOut)(e.target.value)} />
</label>
</div>
</fieldset>
<fieldset className="mt-10">
<legend className="text-sm font-semibold">{L.room}</legend>
<div className="mt-3 grid gap-3 sm:grid-cols-2">
{rooms.map((r) => (
<label
key={r.id}
className="flex cursor-pointer items-start gap-3 rounded-lg border border-border bg-card p-4 transition-colors hover:border-input has-[:checked]:border-primary has-[:checked]:shadow-[inset_0_0_0_1px_var(--primary)] has-[:focus-visible]:outline-2 has-[:focus-visible]:outline-offset-2 has-[:focus-visible]:outline-ring"
>
<input type="radio" name="room" value={r.id} checked={roomId === r.id} onChange={() => change(setRoomId)(r.id)} className="mt-1 size-4 shrink-0 accent-primary" />
<span className="min-w-0">
<span className="block font-semibold">
{r.code ? <span className="mr-1.5 text-primary">{r.code}</span> : null}
{r.name}
</span>
{r.detail ? <span className="mt-0.5 block text-[13.5px] text-muted-foreground">{r.detail}</span> : null}
<span className="mt-1 block text-[13.5px] tabular-nums">
{L.weekday} {comma(r.prices.weekday)}
{L.unit}
{L.from}
</span>
</span>
</label>
))}
</div>
</fieldset>
<fieldset className="mt-10 border-b border-border">
<legend className="mb-3 text-sm font-semibold">{L.guests}</legend>
<Stepper name={L.adults} field="adults" value={adults} min={1} max={stepMax} onChange={change(setAdults)} L={L} />
{showKids ? <Stepper name={L.kids} field="kids" note={L.kidsNote || undefined} value={kids} min={0} max={stepMax} onChange={change(setKids)} L={L} /> : null}
</fieldset>
{overMax ? (
<p className="mt-3 text-sm font-medium text-destructive" role="alert">
{fill(L.errorMax, { max: room.max! })}
</p>
) : null}
</div>
<div className="lg:col-span-5">
<div className="rounded-lg bg-inverse p-7 text-inverse-foreground md:p-8 lg:sticky lg:top-28" aria-live="polite">
{sent && done ? (
<div>
<h3 className="heading text-[1.375rem]">{done.title}</h3>
{done.body ? <p className="mt-3 text-[15px] leading-[1.75] text-inverse-muted">{done.body}</p> : null}
<button
type="button"
onClick={() => setSent(false)}
className="mt-6 inline-flex h-12 items-center rounded-lg border border-inverse-border px-5 text-[15px] font-semibold transition-colors hover:bg-inverse-foreground hover:text-inverse focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-current"
>
{L.again}
</button>
</div>
) : (
<>
<p className="text-[13.5px] font-semibold text-inverse-muted">{L.summary}</p>
{room ? (
<p className="heading mt-2 text-xl">
{room.code ? `${room.code} ` : ''}
{room.name} · {fill(L.person, { n: guests })}
</p>
) : null}
{!calc ? <p className="mt-6 text-[15px] leading-[1.7] text-inverse-muted">{L.empty}</p> : null}
{calc && 'error' in calc ? (
<p className="mt-6 text-[15px] font-semibold" role="alert">
{calc.error}
</p>
) : null}
{calc && !('error' in calc) ? (
<>
<p className="mt-1 text-[15px] text-inverse-muted tabular-nums">
{calc.from} – {calc.to} · {fill(L.nights, { n: calc.nights })}
</p>
<dl className="mt-6 border-t border-inverse-border text-[15px] tabular-nums">
{(Object.keys(calc.count) as NightKind[])
.filter((k) => calc.count[k] > 0)
.map((k) => (
<div key={k} className="flex justify-between gap-4 border-b border-inverse-border py-3">
<dt className="text-inverse-muted">
{kindLabel[k]} {fill(L.nights, { n: calc.count[k] })}
</dt>
<dd className="font-semibold">{won(calc.count[k] * calc.price(k))}</dd>
</div>
))}
{calc.extraPeople > 0 && extraPerson > 0 ? (
<div className="flex justify-between gap-4 border-b border-inverse-border py-3">
<dt className="text-inverse-muted">{fill(L.extra, { n: calc.extraPeople, nights: calc.nights })}</dt>
<dd className="font-semibold">{won(calc.extra)}</dd>
</div>
) : null}
</dl>
<div className="mt-5 flex items-end justify-between gap-4">
<p className="text-[15px] font-semibold">{L.total}</p>
<p className="text-[2rem] leading-none font-semibold tracking-[-0.03em] tabular-nums">{won(calc.total)}</p>
</div>
</>
) : null}
<button
type="submit"
disabled={!ok}
className="mt-7 flex h-14 w-full items-center justify-center rounded-lg bg-primary text-base font-semibold text-primary-foreground transition-opacity hover:opacity-90 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-current disabled:bg-inverse-border disabled:text-inverse-muted disabled:hover:opacity-100"
>
{L.submit}
</button>
</>
)}
</div>
</div>
</form>
</div>
</section>
)
}