Build a Lodging Booking Widget with Correct Pricing
System DesignModel answerLast updated
Design and implement a reservation widget: date/guest inputs, dynamic price breakdown, validation, disabled booking on invalid or sold-out stays, and a confirm dialog.
You are asked to build a small booking widget for a single rental listing. It must:
- Accept a check-in date, a check-out date, and guest counts (adults and children). Compute a total price that reflects a night-by-night rate, the number of nights, and per-guest surcharges that kick in above the listing's included occupancy.
- Validate the selection: check-out must be strictly after check-in, check-in cannot be in the past, the stay must respect minimum and maximum night counts, every night in the stay must be available, at least one adult is required, and adults plus children must not exceed capacity.
- Keep a "Book Now" button disabled whenever the selection is invalid or the listing has no availability.
- Show a confirmation dialog on submit and only finalize after the user confirms.
Explain your component state, the domain data models, the derived vs. stored values, and your error states. Then walk through how you would test edge cases: minimum-night rules, partially available ranges, timezone and daylight-saving transitions, and rounding of prices and tax. Provide code for the core logic.
Hints
Hint 1
Separate pure domain functions (validate, price) from the UI shell so you can unit-test them without rendering anything.
Hint 2
Treat a stay as a list of nights from check-in inclusive to check-out exclusive, and represent dates as calendar dates, not timestamps.
Hint 3
Store money in integer cents and round exactly once at the tax step with an explicit rule.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Framing
The cleanest way to build this is a pure domain core wrapped in a thin, dumb UI. Validation, availability, and pricing are pure functions over immutable inputs; the component stores only what the user actually typed plus a submission phase. Everything else — errors, quote, button state — is recomputed on every render.
That single decision eliminates the most common class of bug: a stored total drifting out of sync with a changed checkIn. If you store derived values next to their inputs, they will eventually disagree.
State
Stored (raw input): checkIn, checkOut, adults, children, and phase.
Derived on every render: errors, quote, canBook.
phase follows a small state machine: EDITING → CONFIRMING → SUBMITTING → BOOKED | FAILED. Clicking "Book Now" moves to CONFIRMING and opens the dialog; confirming moves to SUBMITTING, which disables both dialog buttons so a double click cannot fire two requests; cancelling returns to EDITING. A server-side failure keeps the user's input and returns to EDITING with an error banner, never a reset.
canBook = phase == EDITING && errors.length === 0 && quote !== null.
Data model
- Night — keyed by a calendar date. A stay is the half-open set
[checkIn, checkOut); the check-out day is never a night. - Listing — capacity, included guest count, extra-adult and extra-child nightly fees, cleaning fee, tax rate, min/max nights, and a
calendar: date -> {available, priceCents}map. A date missing from the map is unavailable. - Quote — line items: nights subtotal, guest surcharges, cleaning fee, tax, total. Render the breakdown, not just the total.
Two modeling choices matter:
- Dates are calendar dates, not timestamps. Use ISO
YYYY-MM-DDstrings or date-only values, neverDateobjects carrying a time or epoch milliseconds. A DST transition makes one day 23 or 25 hours long; with timestamps, three nights can compute as 2.96 and round wrongly. With calendar dates, nights = a plain day difference and DST is invisible. - Money is integer cents. Sum per-night rates in exact integers. Round exactly once, at the tax step, using an explicit rule (
ROUND_HALF_UP). Never introduce floating point anywhere in the path.
Error states
Enumerate error codes and map each to copy and to a field: missing dates, check-out not after check-in, check-in in the past, below minimum nights, above maximum nights, some nights unavailable, no adults, over capacity, and sold out. Sold out is its own error so the button can be disabled with an explanatory label instead of silently doing nothing. The server is still authoritative: on submit it re-validates and re-prices, and the dialog shows the server's number if it disagrees with the client quote.
Code
from dataclasses import dataclass
from datetime import date, timedelta
from decimal import Decimal, ROUND_HALF_UP
from enum import Enum
from typing import Optional
class Err(str, Enum):
MISSING_DATES = "Select check-in and check-out dates"
CHECKOUT_NOT_AFTER_CHECKIN = "Check-out must be after check-in"
CHECKIN_IN_PAST = "Check-in cannot be in the past"
BELOW_MIN_NIGHTS = "Stay is shorter than the minimum nights"
ABOVE_MAX_NIGHTS = "Stay is longer than the maximum nights"
DATES_UNAVAILABLE = "Some selected nights are unavailable"
NO_ADULTS = "At least one adult is required"
OVER_CAPACITY = "Guest count exceeds capacity"
SOLD_OUT = "No availability"
@dataclass(frozen=True)
class NightInfo:
available: bool
price_cents: int
min_nights: int = 1
@dataclass(frozen=True)
class Listing:
max_guests: int
included_guests: int
extra_adult_cents: int
extra_child_cents: int
cleaning_fee_cents: int
tax_rate: Decimal
calendar: dict # date -> NightInfo; missing = unavailable
max_nights: int = 365
@dataclass(frozen=True)
class Quote:
nights: int
nights_subtotal_cents: int
guest_fees_cents: int
cleaning_fee_cents: int
tax_cents: int
total_cents: int
def stay_nights(check_in: date, check_out: date) -> list:
return [check_in + timedelta(days=i) for i in range((check_out - check_in).days)]
def is_sold_out(listing: Listing, today: date) -> bool:
return not any(d >= today and n.available for d, n in listing.calendar.items())
def validate(listing, check_in, check_out, adults, children, today) -> list:
errors = []
if is_sold_out(listing, today):
return [Err.SOLD_OUT]
if adults < 1:
errors.append(Err.NO_ADULTS)
if adults + children > listing.max_guests:
errors.append(Err.OVER_CAPACITY)
if check_in is None or check_out is None:
errors.append(Err.MISSING_DATES)
return errors
if check_in < today:
errors.append(Err.CHECKIN_IN_PAST)
if check_out <= check_in:
errors.append(Err.CHECKOUT_NOT_AFTER_CHECKIN)
return errors
nights = stay_nights(check_in, check_out)
if any(not listing.calendar.get(d, NightInfo(False, 0)).available for d in nights):
errors.append(Err.DATES_UNAVAILABLE)
first = listing.calendar.get(check_in)
if first is not None and len(nights) < first.min_nights:
errors.append(Err.BELOW_MIN_NIGHTS)
if len(nights) > listing.max_nights:
errors.append(Err.ABOVE_MAX_NIGHTS)
return errors
def price(listing, check_in, check_out, adults, children) -> Quote:
nights = stay_nights(check_in, check_out)
subtotal = sum(listing.calendar[d].price_cents for d in nights)
extra_adults = max(0, adults - listing.included_guests)
free_slots = max(0, listing.included_guests - adults)
extra_children = max(0, children - free_slots)
guest_fees = len(nights) * (extra_adults * listing.extra_adult_cents
+ extra_children * listing.extra_child_cents)
taxable = subtotal + guest_fees + listing.cleaning_fee_cents
tax = int((Decimal(taxable) * listing.tax_rate).quantize(Decimal("1"), rounding=ROUND_HALF_UP))
return Quote(len(nights), subtotal, guest_fees, listing.cleaning_fee_cents, tax, taxable + tax)
In React the widget mirrors this: useState for the five raw values, and useMemo(() => validate(...), [...]) / useMemo(() => price(...), [...]) for the derived pair.
Testing the edge cases
- Minimum nights lives on the check-in night. A one-night stay is invalid when
min_nights = 2, but a stay whose first night allows one night is fine even if a later night has a stricter minimum — decide the rule explicitly and test both. - Partial availability: a range that is available except for one blocked night must fail with
DATES_UNAVAILABLE, and every night, not just the endpoints, must be checked. - DST: run the same stay in a zone with a spring-forward and fall-back inside it; with calendar dates the night count and total are unchanged.
- Rounding: pick numbers whose tax lands on an exact half-cent (e.g. 7.5% of 1500) and assert the documented half-up result; also assert the sum of line items equals the total.
- Sold out / capacity / dual-submit and server price drift (server returns a higher total → dialog shows the server number).