# Playbook: Bookings & shops

> Ship a reliable booking system or online shop with slot holds, inventory locks, deposit or cart checkout, 0%-fee Stripe billing, and branded receipts.

- Canonical: https://exaspark.ai/docs/playbook-bookings-stores/

## Why bookings and shops fail without concurrency guards

Unlike SaaS subscriptions, local service apps and online shops sell **finite real-world inventory** — a single Saturday 2:00 PM portrait studio room, or the last two bags of single-origin roast on your shelf.

When two customers click **Pay** within seconds of each other, naive apps that check availability before Checkout and write the database row only *after* Stripe finishes end up accepting two payments for one slot or selling stock into `-1`. Solving concurrency up front eliminates awkward apology emails and manual refunds.

| Architecture dimension | Local service & studio booking app | Branded online shop / DTC storefront |
| --- | --- | --- |
| **Scarce inventory unit** | Staff or room time slots (`slot_start` to `slot_end`) | SKU variants (`product_variants.stock_qty`) |
| **Concurrency guard** | **10-minute temporary slot hold** before Stripe Checkout | **Atomic conditional stock decrement** (`stock_qty >= qty`) or short cart reservation |
| **Pricing & tax model** | Upfront deposit (`$20–$50`) + remaining balance on-site or via link | Multi-item cart + flat/free shipping threshold + optional Stripe Tax |
| **Historical integrity** | Freeze `deposit_cents` and `balance_due_cents` at booking time | Snapshot `unit_price_cents`, title, and variant label on `order_items` |
| **Platform fee** | **0% ExaSpark platform fee** (standard Stripe card fees only) | **0% ExaSpark platform fee** (standard Stripe card fees only) |

## Blueprint A: Local service and studio booking architecture

Use this schema and reservation lifecycle for hair salons, pickleball courts, photography studios, personal coaches, wellness clinics, and equipment rentals.

### Availability, blackout dates, and double-booking prevention

```text
services
  id                          PK (uuid)
  name                        text, not null            -- "60-Min Studio Session"
  duration_minutes            integer, not null         -- 60
  buffer_minutes              integer, default 15       -- turnover cleanup gap
  total_price_cents           integer, not null         -- 15000 ($150.00)
  deposit_cents               integer, not null         -- 2500 ($25.00)
  is_active                   boolean, default true

staff_schedules
  id                          PK (uuid)
  resource_name               text, not null            -- "Studio A" or "Maya (Stylist)"
  weekday                     integer, not null         -- 0 (Sun) .. 6 (Sat)
  start_time_local            text, not null            -- "09:00"
  end_time_local              text, not null            -- "18:00"

blackout_dates
  id                          PK (uuid)
  resource_name               text, nullable            -- null = entire venue closed
  starts_at                   timestamp (UTC), not null
  ends_at                     timestamp (UTC), not null
  reason                      text, not null            -- "Holiday closure"

bookings
  id                          PK (uuid)
  user_id                     FK -> users.id, not null
  service_id                  FK -> services.id, not null
  resource_name               text, not null
  slot_start                  timestamp (UTC), not null
  slot_end                    timestamp (UTC), not null
  deposit_cents               integer, not null
  balance_due_cents           integer, not null
  status                      enum('held', 'confirmed', 'completed', 'canceled', 'no_show')
  hold_expires_at             timestamp (UTC), nullable
  reminder_24h_sent_at        timestamp (UTC), nullable
  stripe_checkout_session_id  text, unique, nullable
  created_at                  timestamp (UTC)
  INDEX (resource_name, slot_start, status)
```

### How the 10-minute atomic slot hold works

When Customer A selects Saturday 2:00 PM and clicks **Pay $25 deposit**, your server runs an atomic transaction confirming no overlapping booking exists for that resource with `status = 'confirmed'` or an unexpired `held` row (`hold_expires_at > now()`).

If clear, the server inserts a `held` row (`hold_expires_at = now + 10 minutes`) and launches Stripe Checkout. Customer B immediately sees Saturday 2:00 PM blocked.

- **Payment succeeds:** `checkout.session.completed` flips `status` to `confirmed`, clears `hold_expires_at`, and emails local-timezone details.
- **Checkout abandoned:** `checkout.session.expired` cancels the hold (or `hold_expires_at` passes automatically), freeing the slot with zero manual cleanup.

### Deposits, rescheduling, and staff check-in

Allow signed-in clients to reschedule confirmed bookings once up to **24 hours ahead**, transferring their paid deposit to the new verified slot. Give **Staff** and **Admin** roles a daily check-in view displaying `balance_due_cents` and one-tap **Arrived / balance paid** or **No-show** actions.

## Blueprint B: Branded online storefront architecture

### Variants, frozen price snapshots, and atomic stock locks

```text
products            (id, slug, title, description, is_published)
product_variants    (id, product_id, sku, option_label, price_cents, stock_qty)
orders              (id, order_number, customer_email, user_id?, subtotal_cents,
                     discount_cents, shipping_cents, tax_cents, total_cents,
                     shipping_address_json, carrier_name, tracking_number,
                     status, stripe_checkout_id, created_at)
order_items         (id, order_id, variant_id, product_title_snapshot,
                     variant_label_snapshot, unit_price_cents, quantity)
```

Two safeguards keep storefront accounting rock-solid:

- **Freeze line-item snapshots.** Copy `product_title_snapshot`, `variant_label_snapshot`, and `unit_price_cents` onto `order_items` at checkout so future price edits never rewrite historical receipts or refunds.
- **Decrement stock atomically.** Execute `SET stock_qty = stock_qty - qty WHERE id = $1 AND stock_qty >= qty` inside your database transaction rather than subtracting in app memory, preventing `-1` oversells on flash drops.

### Cart shipping rules, guest checkout, and fulfillment emails

Support guest checkout (`orders.user_id` nullable) alongside optional account creation so first-time shoppers buy smoothly without sign-up friction. Compute shipping rules (`$6` flat, `$0` at `$60+`) strictly server-side from database prices.

Use [Transactional email flows](https://exaspark.ai/docs/transactional-email-flows/) to trigger an itemized order receipt on `checkout.session.completed` and a shipping alert whenever an Admin enters `tracking_number`. Upload public catalog photos to managed storage (or craft transparent cutouts in Creative Studio on Starter/Pro) while keeping customer invoice PDFs private.

## Step-by-step launch path from Preview to first order

1. **Seed realistic test services or SKUs** — Generate your app and add 3–5 real services or variants in **Cloud → Preview** so calendar math and cart totals mirror production.
2. **Test concurrency and Stripe declines** — Open two windows to race for the same slot (or last item in stock), and test both approved (`4242...`) and declined Stripe test cards.
3. **Authenticate your custom sending domain** — On **Starter** (`1,000/mo`) or **Pro** (`10,000/mo`), verify SPF, DKIM, and DMARC so confirmations and shipping alerts land in inboxes.
4. **Connect your domain and polish mobile UX** — Enable custom DNS with SSL, remove the badge, and verify mobile tap targets in Browser Device Lab.
5. **Switch Stripe to Live and Publish** — Toggle Live mode, click **Publish**, run one personal-card `$1` checkout, confirm email arrival, and refund it cleanly.

## Copy-paste starter prompts

### Starter prompt A: Local studio & service booking app

> **Example prompt (App):** Build a studio booking app with Google/magic-link sign-in and Guest, Member, Staff, and Admin roles. Model `services` (`duration_minutes`, `buffer_minutes`, `total_price_cents`, `deposit_cents`), `staff_schedules`, `blackout_dates`, and `bookings` in integer cents, storing UTC timestamps formatted in `America/New_York`. Picking an open slot creates an atomic 10-minute `held` row blocking double bookings, launches Stripe Checkout for a `$25` deposit (`allow_promotion_codes: true`), and flips to `confirmed` via an idempotent `checkout.session.completed` webhook while auto-releasing expired holds. Send branded confirmation and 24-hour reminder emails, allow 24-hour self-serve rescheduling, and add a Staff check-in roster tracking `balance_due_cents`.

### Starter prompt B: Branded online storefront with variant stock locks

> **Example prompt (Web):** Build a branded online storefront supporting guest checkout plus optional member order history. Model `products`, `product_variants` (`sku`, `option_label`, `price_cents`, `stock_qty`), `orders`, and `order_items` (snapshotting title, variant label, and `unit_price_cents`). Serve lazy-loaded public product galleries with alt text. Calculate `$6` flat shipping (`$0` at `$60+`) server-side, collect shipping addresses and promo codes via Stripe Checkout, and run an idempotent webhook marking orders `paid`, decrementing stock atomically (`stock_qty >= qty`), and emailing itemized receipts. Include an Admin panel for inventory, tracking numbers (triggering shipping emails), and full or partial Stripe refunds.

## Common booking and storefront bugs to catch early

| Symptom | Most likely root cause | Reliable fix |
| --- | --- | --- |
| **Two clients booked one slot** | Row written only after Stripe Checkout finished | Insert an atomic 10-minute `held` row before launching Checkout |
| **Variant stock hit `-2`** | Stock subtracted in app memory without DB guard | Enforce `WHERE stock_qty >= qty` atomically inside SQL |
| **Slot off 1 hour after DST** | Stored fixed UTC offset instead of IANA timezone | Store UTC timestamps and format with an IANA zone (`America/New_York`) |
| **Past order total shifted** | UI joined live `product_variants.price_cents` | Snapshot `unit_price_cents` on `order_items` at purchase time |
| **Shipping email didn't send** | Edited tracking column directly in table view | Trigger `order_shipped:<order_id>` inside Admin **Mark shipped** route |

## Next steps

- [Coupons, trials & deposits](https://exaspark.ai/docs/coupons-trials-and-deposits/) — Configure launch promo codes, partial deposits, and balance-due links.
- [Transactional email flows](https://exaspark.ai/docs/transactional-email-flows/) — Build idempotent booking confirmations, reminders, and receipts.
- [Images, PDFs & upload safety](https://exaspark.ai/docs/media-uploads-and-limits/) — Serve fast public product galleries while keeping invoices private.

## From the blog

- [How to build a booking app](https://exaspark.ai/blog/how-to-build-a-booking-app/) — Scheduling, deposits, reminders, and staff check-in workflows explained.
- [Build a restaurant website](https://exaspark.ai/blog/how-to-build-a-restaurant-website/) — Menu showcases, reservations, and local mobile conversion tips.
- [How online payments work](https://exaspark.ai/blog/how-online-payments-work/) — Connect Stripe Checkout, webhooks, and direct bank payouts cleanly.
