Skip to content

Online Booking and Client Portal

How clients book online (instant vs request-only), pay deposits, log in to the portal with a one-time code, check in as walk-ins, and get nudged after abandoning a booking.

21 min read

Overview

This page documents what the code does today for the client-facing booking and self-service surfaces. Client Surfaces gives the product-level overview and Scheduling & Calendar covers the staff calendar; this page adds the rules, limits and failure behaviour behind them. See "Key behaviours at a glance" near the end for a short summary.

Kagami online booking portal and self-service appointment scheduler with stylist selection

Five pieces make up the area:

Piece Public URL Staff surface
Phone-first booking page /book/{brand-slug} (also embedded at /book/{slug}/widget) Calendar, /dashboard/booking-requests
Deposits Step shown right after booking /dashboard/deposits
Client portal /book/{brand-slug}/portal /dashboard/settings/portal
Digital check-in and lobby board /checkin/{locationId}, /queue/{locationId} /dashboard/queue, Settings > Locations
Abandoned-booking recovery none (WhatsApp message) none

The booking page is white-labelled from brand_themes (logo, colours, font). If a brand has no row in booking_settings the code defaults apply and online booking counts as enabled.

Public booking flow

The page renders QuickBooking (quick-booking.tsx, SALO-2502). It books one service per booking, and the client never picks the stylist.

Steps:

  1. Phone. The client types a mobile number. Only Indian mobiles are accepted: 10 digits starting 6-9, or the same with a leading 91 or 0. Anything else shows "Enter a 10-digit Indian mobile number. For any other number, please call the salon to book."
  2. Code. A one-time code goes out by WhatsApp by default, falling back to SMS if WhatsApp is not configured, is refused at send time, or has a red quality rating. The client can re-request after a 30 second cooldown. See "Portal login and one-time codes" for the code rules.
  3. You. After the code is verified:
    • A known number (matched on the last 10 digits within the org) gets "Welcome back, {first name}." and skips ahead if a branch is already chosen.
    • A new number enters a name (2-100 characters) and, for multi-branch brands, picks a branch. The client record is created immediately (phone = +91xxxxxxxxxx) and a Meta "Lead" event is sent. The name of an existing client is never overwritten by this unauthenticated step.
    • ?location= pre-selects a branch; ?service_id= (used by "Book again" links) jumps straight to that service's times.
  4. Service. "Pick a service now?" then category, then a type-to-find list (5 shown at a time). Choosing "decide later" calls quickNeedsHelp, which pings staff with the alert "Wants help choosing a service" (link /dashboard/clients).
  5. Time. The server returns the first day (starting today) that has free slots, searching up to 10 days ahead, capped by advance_days. The client can move through day chips (5 shown) up to today + advance_days. Outside that range: "Please pick a day within the next N days."
  6. Book. Tapping Book registers a booking session (for recovery, see below), then calls quickBook. A time that was just taken shows "That time was just taken. Here are the latest free times." and the slot list reloads.
  7. Deposit (only if one is owed) then Done. A booking that completes inside an iframe posts a salonos-booking message to the host page (booking id, branch and service names, no personal data) so a host site can fire conversion tracking. UTM parameters and ?ref= are stored on the appointment.

How slots are computed

For each stylist skilled for the service at the branch, the engine builds free start times inside the stylist's shift for that day.

Rule Value
Slot grid booking_settings.slot_interval_min, default 15 min, aligned to the shift start
Same-day buffer The earliest slot today is 60 minutes from now, rounded up to the grid
Blocked by Time off (approved or pending), existing appointments, roster days off, store closed days
Skills Stylists are matched through staff_skills. A stylist with no skill rows at all is treated as a generalist when nobody at the branch is skilled for the service (SALO-2060)
Who gets the slot One entry per start time, given to the stylist with the most open slots that day (spreads load); the client never sees the name
Lookup failure Returns an error ("Could not load the available times. Please try again in a moment."), never an empty list that reads as "fully booked"

What happens on Book

quickBook re-verifies the stylist is still eligible, then calls createPublicBooking, which:

  1. Applies limits (below), validates the payload shape, rejects a start time in the past ("That time has already passed. Please pick a later slot.") and checks brand, branch, service and stylist all belong to the same brand.
  2. Rejects a service that is inactive or not online_bookable ("This service can't be booked online any more...").
  3. Runs the same availability guard as the slot pickers (skill, leave, shift, store hours, overlap, not in the past). There is no manager override on this path.
  4. Finds or creates the client, inserts an appointments row (status = scheduled, source = online) and one appointment_services row. If the service line fails to insert, the appointment is deleted again.
  5. Creates a booking_deposits row if a deposit is owed.
  6. Fires, without blocking the client: an appointment_booked staff alert (link /dashboard/calendar), the booking confirmation message, a WhatsApp "upgrade" (add-ons) message when WhatsApp is enabled for the brand, the reminder schedule, enrolment in the welcome journey, and Meta "Schedule" (plus "Lead" for a brand-new client) events.

A database exclusion conflict (error code 23P01) returns "That time slot is no longer available. Please choose another." There is no temporary slot hold: two clients racing for one slot are resolved by that constraint, and the second one sees the message.

Limits on the booking path

What Limit Message
Code sends per brand 300 per hour "We are getting a lot of requests right now. Please try again in a few minutes or call the salon."
createPublicBooking per IP (browser callers only) 20 per hour "Too many booking attempts. Please try again later."
createPublicBooking per phone (last 10 digits) 8 per hour same
Slot lookups per IP 120 per 10 min "Too many requests. Please wait a moment and try again."
quickRegister per brand and phone 10 per hour "Too many attempts. Please try again in a few minutes."
"Decide later" notice per brand and phone 3 per hour silently shows the thank-you
Booking pass valid 30 min "Your verification expired. Please enter your phone number again." (client returns to the phone step)

The signed booking pass is HMAC-signed with a purpose-bound key and held in browser memory (not a cookie, because cookies are blocked in the cross-site iframe). Every call after verification needs it.

The limiter fails closed: if the rate-limit store errors, the call is denied.

Instant bookings vs requests

Instant booking Booking request
Trigger A staff_id is supplied and request_only is not set. This is the phone-first page. No staff_id, or request_only: true
Stored in appointments with status = scheduled online_bookings with status = pending, client_id = null
Availability checked Yes (full guard) No: the preferred date and time are stored as typed
Client or message created Yes, confirmation sent No client record, nothing sent to the client
Deposit Yes, if owed None
Staff notice appointment_booked alert booking_request_received alert "New booking request" (link /dashboard/booking-requests)

Who produces requests:

  • The AI chat widget (ctx.channel === "widget") always sends request_only, so nothing goes to a typed-in, unverified number (SALO-2168). WhatsApp-channel AI bookings and the external API are "trusted callers" and book instantly. See AI.
  • A callback request (quickRequestCallback): shown when the one-time code cannot be delivered. It stores a request with no service, preferred_time = 00:00 and a note that starts CALLBACK REQUEST, plus a warning alert "Callback request: {name}". Limits: 5 per IP per hour, 3 per phone per day, 60 per brand per hour; one open callback per phone per 24 hours; a hidden honeypot field makes bots look successful while storing nothing. The number is not verified and no client record is created. Error: "Too many requests. Please call the salon to book."

Confirming or rejecting a request

Staff open /dashboard/booking-requests (store-filtered; requests with no branch show in every store). Confirm needs a stylist; the request must still be pending ("This booking request is already confirmed.").

  • Every requested service is chained back to back from the preferred time, using each service's duration and price. A missing service or zero duration returns a specific error.
  • With no branch on the request, the brand's first branch by name is used.
  • The guard runs with manager override, so shift, hours and overlap issues are allowed but tenant, skill and leave rules are not.
  • The request is claimed (pending to confirmed) before anything is written. If a later step fails, the request is put back to pending; if even that fails, the error says the request shows as confirmed with no appointment and must be reset by hand.
  • The client is looked up by email and created if missing (so phone-only requests such as callbacks create a client with an empty email). The appointment is created scheduled, source = online, linked back through confirmed_appointment_id.
  • Reject works only on pending ("This booking request is no longer pending. Refresh the list.") and saves optional staff notes.
  • Neither confirm nor reject sends the client a message in this code path.

Same-gender stylist matching

Opt-in per brand (booking_settings.same_gender_staff, default off; toggle in Settings > Booking). Needs staff_members.gender (male or female, set in the staff form) and optionally services.target_gender (unisex default, male, female).

The required stylist gender is the first of: the service's own target gender, the booking's for_gender hint, the client's stored gender. men/man/male and women/woman/female are normalised. If none applies (a unisex service and an unknown client), no restriction is applied. When a gender is required:

  • stylist lists and slot lookups drop stylists of the wrong gender, and stylists with no gender set (fails closed);
  • an explicit stylist of the wrong gender gets no slots;
  • createPublicBooking re-checks and returns "This stylist isn't available for this booking. Please choose another stylist."

On the phone-first page a new customer's gender is not collected, so for them only a gendered service triggers matching. A returning client's stored gender is used.

Deposits

When a deposit is owed

computeDepositMinor (shared by the quote and the real charge):

  1. If the service has deposit_required: deposit_type = fixed uses deposit_amount_minor; otherwise round(price x deposit_percent / 100).
  2. Else if the brand has booking_settings.require_deposit: round(price x deposit_pct / 100) (column default 30). A null or non-positive percent means no deposit.
  3. Otherwise none. A computed 0 creates no row.

Currency is always INR. The deposit settings (require_deposit, deposit_pct and the per-service deposit columns) are honoured when set, but they are not part of the Settings → Booking form, which saves the other booking settings only.

What the client sees

Booking creates the appointment first, then the deposit with status = pending. The deposit step shows the net amount and offers the providers configured for the deployment (Razorpay: UPI, cards, wallets; Stripe: card). There is no "pay later" button, only "Start over". The appointment stays scheduled whether or not the deposit is paid; an unpaid deposit does not release the slot or cancel the appointment.

  • Loyalty points can reduce the deposit: 1 point = ₹1, capped at the points balance and at what is still owed. A fully covered deposit settles without a provider ("Fully covered by your loyalty points."). Concurrent redemptions are guarded; on a clash the points are credited back ("This deposit just changed - please refresh and try again.").
  • Ownership proof. The booking hands the browser a signed ownerToken (2 hours). Every deposit action needs it. Without it: "Your booking session has expired. Please start the booking again." Only failed checks count against a limit of 30 per hour per deposit.
  • Reload safe. The deposit screen is kept in sessionStorage (key salonos:pending-deposit:{brandId}) until the token expires, and on restore the server is asked for the real status first. A deposit that was paid meanwhile goes to the confirmation screen.
  • No double charge. An existing open Razorpay order is reused; a captured one is settled; a succeeded Stripe intent is reconciled instead of creating a second.
  • Provider confirmation errors: "Payment could not be verified.", "No payment was started for this deposit.", "This deposit is already {status}.", "This payment method is not available."

Payment webhooks

Razorpay and Stripe webhooks update booking_deposits by provider_order_id: payment captured/succeeded sets paid (paid_at, payment_ref); payment failed sets failed (only from pending); refund processed sets refunded. A later successful payment webhook sets a deposit that was marked failed to paid.

What staff see

/dashboard/deposits (roles in the "operations" nav group) shows counts for pending, total collected (paid only) and total, with filter tabs for pending, paid, refunded and forfeited (a failed deposit shows only under "all"). Staff can add a manual deposit and move a deposit through the allowed transitions:

To Allowed from
paid pending
refunded paid
forfeited pending, paid
failed pending

Refund and forfeit ask for confirmation. "Refunded" only records the fact; the money is returned separately. A paid deposit is recorded on the deposit only and is not automatically applied to the invoice at checkout.

Portal login and one-time codes

The portal and the booking page share one code system (client_otp_tokens).

Rule Value
Code format SMS and WhatsApp: 6 characters from ABCDEFGHJKMNPQRSTUVWXYZ23456789 (no 0/O/1/I/L); entry is case-insensitive. Email: 6 digits.
Lifetime 10 minutes, single use
Sends 3 per 10 min per org and phone (or email), and 10 per 10 min per IP: "Too many OTP requests. Please wait 10 minutes and try again."
Verifies 10 per 10 min per identifier and 30 per 10 min per IP: "Too many attempts. Please request a new code."
Wrong guesses 5 per code, claimed atomically before comparing. After that: "Maximum attempts reached. Please request a new code." and the identifier is locked out until that code would have expired: "Too many incorrect attempts. Please wait 10 minutes and try again."
Wrong or expired "Invalid or expired code. Please try again."
New code Sending deletes any unused earlier code for that identifier first
Message text Kagami - {brand name} - {code}

Delivery:

  • SMS tries the configured providers in order (self-hosted Android SMS gateway, TextBee, httpSMS). An explicit SMS choice never falls back to WhatsApp.
  • WhatsApp is offered only when the org has WhatsApp enabled with credentials. The code goes out as the approved authentication template. A live health check runs if the cached one is older than 7 days; only a RED quality rating blocks it ("WhatsApp isn't available for this business right now. Please choose SMS or email instead."). With no WhatsApp: "WhatsApp isn't available for this business. Please choose SMS or email instead." WhatsApp sends are logged in outbound_messages (message_type = portal_otp) so a later delivery failure from Meta can be matched.
  • Email is available on the portal only.
  • If nothing could deliver: "Could not send verification code. Please try again or contact the salon for help." (In development mode the code is written to the server log instead.)

Session

A correct code sets an HttpOnly, SameSite=Lax cookie portal_session_{brandId without dashes} valid 7 days, holding brandId:identifier:expiry signed with HMAC-SHA256 (PORTAL_SECRET, compared in constant time). The identifier is the phone, or email:{address} when the email matches no client with a phone. Verifying a booking-page code also sets this cookie in that browser. Every portal read re-checks that the signed session matches the identifier asked for; phones match on the full number when both carry a country code, otherwise on the last 10 digits. Without a valid session reads return empty and actions return "Not authenticated."

Client portal

/book/{slug}/portal is a 404 for an unknown brand and shows "The client portal is not available." until the owner turns it on (portal_configs.is_enabled, default off) in Settings > Portal. The optional welcome message is shown under the brand name. Signed-out visitors see the login card (WhatsApp if available, SMS, or email); signed-in clients see tabs: bookings, history, loyalty (default), membership, vouchers, receipts, referral, profile.

Capability Rules
Appointments Last 20 non-cancelled appointments with services, stylist and paid total
Cancel Appointment must be open (scheduled, pending_confirmation, confirmed). Blocked inside portal_configs.cancellation_hours of the start: "Appointments cannot be cancelled within N hours of the start time." Without a portal config row the limit is 2 hours; a brand that saves Settings > Portal starts from 4. A concurrent salon update wins: "This appointment was just updated by the salon and can't be cancelled online. Please contact them." A cancellation message is sent to the client.
Reschedule Picks a date, sees real free slots for the same stylist and visit length, moves every line atomically through the same guard the AI uses. Closed visits: "This appointment is {status} and can't be moved." Appointments with no stylist or service line: "This appointment can't be moved online. Please contact the salon."
Add extras Shown for upcoming scheduled bookings. Mints a 30-day signed upgrade link, only when the service has active add-ons: "There are no extras available for this booking."
Rate a visit Only completed appointments, comment cut to 500 characters
Loyalty and rewards Points, current and next tier, spin wheel (10 spins per minute limit), won prizes, raffles with the client's entry codes
Money Wallet and store-credit balance, active packages, active gift cards the client purchased, last 20 paid invoices
Memberships Active memberships with discounts and renewal date
Referral The client's referral code and share link
Profile Name (required), email (set only when non-empty), notification preferences (WhatsApp reminders, email reminders, promotional)
Book again Completed visits link back to the booking page for the same service while online booking is enabled

GET /api/portal/lookup?brandId= (20 per minute per IP) returns the signed-in client's own online booking requests (up to 20, newest first), identified from the session only.

Owner settings in Settings > Portal are is_enabled, welcome_message and cancellation_hours. The form also stores booking_window_days, advance_booking_hours, require_phone and confirmation_message; these do not change portal or booking behaviour.

Digital check-in and the lobby board

Check-in is a walk-in queue sign-up, not an appointment check-in. It never looks up an appointment.

Owner setup. Settings > Locations > check-in editor sets locations.checkin_enabled (default off) and checkin_message (greeting; default "Welcome! Join the queue below."). The kiosk URL is /checkin/{locationId}; the lobby display is /queue/{locationId}. Both are in the (embed) route group, so they can be shown on a tablet or TV or iframed.

Client flow (POST /api/checkin, no login, no OTP):

  1. Page shows the branch name, greeting and how many people are waiting.
  2. Client enters name (required, up to 100), optional phone (up to 20), optional service (an active, online-bookable service of the brand) and optional notes (up to 500).
  3. A walk_in_queue row is inserted with status = waiting, and the client sees "You're in the queue!" with their position number.

Errors: name empty "Enter your name so the team knows who to call."; check-in off "Check-in is not enabled for this location" (404); bad service "Service not found"; network failure "Network error - could not reach the server. Check your connection and try again."

Lobby board. /queue/{locationId} returns 404 unless check-in is enabled for the branch. It refreshes every 15 seconds from GET /api/queue/{locationId} (30 requests per minute per IP, UUID required) and shows "Now Serving" and "Waiting (n)". Because it is unauthenticated, only the first name is exposed and check-in notes are never sent. If a refresh fails the board shows the cause (HTTP status or network error) and keeps the last data.

What staff see. /dashboard/queue lists waiting and serving entries with service, preferred stylist and notes, plus the last 50 done or cancelled. The calendar also shows queue entries and updates live. Actions:

  • Serve now moves the entry to serving and creates or links an appointment (walk_in_queue.appointment_id). Checkout then opens the bill for that appointment; completing the bill marks the queue entry done.
  • Cancel needs a reason (stored on the entry and on the linked appointment as a "Cancellation Note") and the bookings.cancel permission ("You don't have permission to cancel bookings."). A linked appointment that is already finished, billed or a no-show keeps its status.
  • Staff without the cross-staff permission can only manage entries preferring themselves ("You can only manage your own queue entries").

Abandoned-booking recovery

A WhatsApp nudge to people who started a booking and did not finish.

  1. Session. When the client taps Book on the phone-first page, POST /api/booking/session (30 per hour per IP) records booking_sessions (brand, phone as typed, name, service, stylist, slot) with status started. A phone with a started session in the last 2 hours reuses it (a unique index allows one started row per brand and phone).
  2. Complete. After quickBook succeeds, PATCH /api/booking/session (same limit) sets completed. The phone must equal the one the session was created with ("Booking session not found" otherwise). Completion happens when the booking is created, before any deposit is paid.
  3. Recover. The cron route finds started sessions older than 30 minutes (up to 200 per run), claims each by setting sending, sends the WhatsApp template abandoned_booking with the client's name, brand name and {site}/book/{slug}, then sets messaged. Five sends run at a time. A brand without WhatsApp credentials uses a stub provider that sends nothing but still marks the session messaged.

A session whose send throws stays in sending and is not retried. If the status update after a successful send fails, the row also stays sending (deliberately, to avoid a duplicate message). The route returns processed and failed counts and is protected by the x-cron-secret header (401 "Unauthorized" otherwise).

Not to be confused with api/cron/ai-chat-recovery, which follows up cold WhatsApp AI chats.

Background jobs

Job Schedule Purpose
salonos-abandoned-bookings (calls api/cron/abandoned-bookings) Every 15 minutes (*/15 * * * *, pg_cron migration 0176_pg_cron_recurring_jobs.sql) Abandoned-booking WhatsApp nudge
Reminder scheduling Triggered at booking time; the sender runs from api/cron/reminders every 15 minutes Appointment reminders for online bookings
Welcome journey Enrolled at booking; processed by api/cron/process-journeys every 15 minutes First-visit messages

Owner configuration

Setting Where Default Effect
Online booking on or off Settings > Booking (is_online_booking_enabled) on Off shows "Online booking is not available right now."
Advance days same (0-365) 30 How far ahead clients can pick
Slot interval same (1-480 min) 15 Slot grid
Show staff same (show_staff) off No effect on the phone-first page, which always auto-assigns the stylist
Same-gender stylists same off See above
Booking instructions same (max 2000 chars) none Not shown on the phone-first page
Cancellation hours same (0-720) 24 Only the legacy flow displays this; the portal enforces the separate portal setting
Portal on, welcome, cancellation hours Settings > Portal off, none, 4 See portal section
Check-in on and greeting Settings > Locations off See check-in section
Deposits Brand and service records (not in Settings) none See deposits section

Saving booking settings needs an admin role ("You don't have permission to change booking settings"); out-of-range numbers return the specific range message (for example "Advance days must be a whole number between 0 and 365").

Data model

Table Key columns
booking_settings one row per brand: is_online_booking_enabled, advance_days, slot_interval_min, cancellation_hours, require_deposit, deposit_pct, booking_instructions, show_staff, same_gender_staff
online_bookings request: client name/email/phone, service_ids (JSON), staff_member_id, location_id, preferred_date, preferred_time, status (pending/confirmed/rejected/cancelled), confirmed_appointment_id, staff_notes
booking_deposits appointment_id or online_booking_id, client_id, amount_minor, loyalty_discount_minor, currency, status (pending/paid/refunded/forfeited/failed), provider, provider_order_id, provider_payment_id, payment_ref, paid_at, refunded_at
services online_bookable, target_gender, deposit_required, deposit_type, deposit_amount_minor, deposit_percent
staff_members gender (male/female)
booking_sessions brand_id, phone, client_name, service_id, staff_id, slot_iso, status (started/sending/completed/messaged), completed_at
client_otp_tokens org_id, phone or email, otp_code, expires_at, used_at, attempts
portal_configs one row per brand: is_enabled, welcome_message, cancellation_hours (plus other stored fields that do not change behaviour)
locations checkin_enabled, checkin_message
walk_in_queue location_id, client_id, client_name, service_id, preferred_staff_id, notes, status (waiting/serving/done/cancelled), appointment_id, queued_at

Permissions

Action Who
Book, check in, view lobby board, use the portal Anyone (portal reads need the signed session)
Booking settings Admin roles
Confirm or reject booking requests Manager roles and front desk
Deposits page Shown in navigation to operations roles
Queue actions Location access; cancel needs bookings.cancel; cross-staff control needs the book-all-staff permission

See Roles & Permissions.

Edge cases and failure behaviour

Situation Result
Brand slug unknown 404
No branches active "No locations are currently accepting bookings."
No online-bookable services "No services are currently available for online booking."
No /book slug at all "This link is missing a salon." with tips for finding the link
Brand not found or switched off during a call "This booking page is not available. Please contact the salon." / "Online booking is turned off for this salon. Please contact the salon to book."
No stylist skilled at the branch "No stylist at this branch offers this service right now. Please choose another service or branch."
Service has no duration "This service has no duration set, so it can't be booked online. Please contact the salon."
Code spent but customer lookup fails The pass is still issued and the customer is treated as new, so they are not stranded
Network failure on any booking call "Could not reach the salon. Check your connection and try again."
Client creation race on the same phone The existing record is reused
Deposit row fails to insert The booking still succeeds with no deposit shown; staff can record one by hand

Key behaviours at a glance

  • The portal signs clients in with a one-time code and a 7-day cookie (there is no magic link).
  • Digital check-in creates a walk-in queue entry. It does not look up or mark an existing appointment.
  • The phone-first booking page auto-assigns the stylist, has no temporary slot hold (the database rejects double bookings) and creates the appointment before any deposit is paid.
  • Instant online bookings are created with status scheduled. Booking requests wait in pending until staff confirm or reject them.

Source

  • web/src/lib/booking/actions.ts (createPublicBooking, slots, same-gender), quick-actions.ts, quick-pass.ts, quick-slots.ts, availability.ts, same-gender.ts, deposit-amount.ts, deposit-actions.ts, deposit-owner-token.ts, pending-deposit-storage.ts, admin-actions.ts
  • web/src/lib/portal/otp-actions.ts, booking.ts, config.ts, admin-actions.ts; web/src/lib/otp/deliver.ts
  • web/src/lib/deposits/index.ts, admin-actions.ts
  • web/src/lib/checkin/index.ts, web/src/lib/queue/index.ts, admin-actions.ts
  • web/src/app/(client)/book/[slug]/ (quick-booking.tsx, deposit-step.tsx, portal/), web/src/app/(embed)/book|checkin|queue/
  • web/src/app/api/booking/session/route.ts, api/checkin/route.ts, api/queue/[locationId]/route.ts, api/portal/lookup/route.ts, api/cron/abandoned-bookings/route.ts, api/webhooks/razorpay, api/webhooks/stripe
  • web/src/app/(tenant)/dashboard/booking-requests, deposits, queue, settings/booking, settings/portal, settings/locations
  • Migrations: 0013, 0024, 0027, 0031, 0063, 0086, 0153, 0176, 0177, 0201, 0229