Bookings
Bookable resources with weekly hours, services with buffers, open slots computed in SQL, holds that expire, double bookings refused by an exclusion constraint, and public booking through a share link.
bookings lets customers book time on a resource: a person, a room or a
piece of equipment. Postgres computes the open slots, and an exclusion
constraint refuses two bookings that overlap on the same seat, so a race
between two customers can never double-book.
better-supabase add bookingsimport { createBookings } from "better-supabase/blocks/bookings";The module requires memberships and access, and installs the btree_gist
extension in the extensions schema for its exclusion constraint (see
ADR 0023).
With jobs a hold expires itself, with share-links and rate-limit
guests book through a link, with calendar confirmed bookings appear on the
resource's calendar, with reminders customers get reminders, and with
outbox its events are recorded. With activities
and options.bookings, a confirmed booking is logged as a meeting on the
booker's contact.
Tables
| Table | Holds |
|---|---|
booking_resources | A bookable resource in an organization: name, kind, capacity (overlapping seats), an IANA tz, a calendar_id, a host_id and check_busy |
booking_availability | Weekly hours: a weekday (1 is Monday) with a starts_at and ends_at time in the resource's zone |
booking_exceptions | A during range that closes the resource, or opens it outside its hours with available |
booking_services | What is booked: duration, buffer_before, buffer_after, the resource_kinds that serve it, step and min_notice |
bookings | resource_id, service_id, seat, during, status (hold, confirmed, cancelled), hold_expires_at, customer |
Each booking also stores blocked, its during widened by the service's
buffers. The constraint is on that range:
constraint bookings_no_overlap_excl exclude using gist
(resource_id with =, seat with =, blocked with &&)
where (status <> 'cancelled')A resource with a capacity of 3 has seats 1 to 3, and each seat takes one
booking at a time. Members read through the tables' policies, and a customer
always sees their own bookings. Every write goes through a function: resources,
hours and services need bookings.manage; members book with bookings.create
and read with bookings.read.
Resources and services
Server code calls the bookings instance on db, in the caller's organization. With gen.hooks set, better-supabase gen writes the hooks:
export const { useList: useBookings } = defineDataHooks(
"bookings",
(db: AppDb) => db.bookings,
);const { id: resourceId } = await db.bookings
.saveResource(organizationId, {
name: "Ann",
kind: "staff",
tz: "Europe/Amsterdam",
})
.orThrow();
await db.bookings
.setAvailability(resourceId, [
{ weekday: 1, start: "09:00", end: "17:00" },
{ weekday: 2, start: "09:00", end: "17:00" },
])
.orThrow();
const { id: serviceId } = await db.bookings
.saveService(organizationId, {
name: "Haircut",
duration: Temporal.Duration.from({ minutes: 30 }),
bufferAfter: "PT15M",
resourceKinds: ["staff"],
})
.orThrow();"use client";
import { useBookings } from "@/lib/supabase/hooks";
const rows = useBookings({ limit: 50 });Hours are wall-clock times in the resource's zone, so 09:00 stays 09:00 across
a daylight saving change. addException closes a range (a holiday, a
dentist appointment) or, with available: true, opens one outside the weekly
hours. Durations take a Temporal.Duration or an ISO 8601 string.
resources({ organizationId }) and services({ organizationId }) list them by name, so a booking page can offer a choice without reading the tables. Inactive ones come back only with includeInactive: true. A service carries its duration, buffers and resourceKinds.
Slots
available_slots(service, range_start, range_end, tz) is a SQL function, and
availableSlots calls it. It builds each resource's open windows from its
hours and exceptions, steps through them by the service's step (default its
duration), and keeps the slots where the slot plus its buffers fits and a seat
is free. Slots start no sooner than min_notice from now, and one call covers
at most 62 days.
const slots = await bookings
.availableSlots(
serviceId,
{
from: Temporal.Instant.from("2030-03-04T00:00:00Z"),
until: Temporal.Instant.from("2030-03-11T00:00:00Z"),
},
{ tz: "America/New_York" },
)
.orThrow();
// [{ resourceId, startsAt, endsAt, localStart, seats }, ...]localStart is the start in the zone you pass, else the resource's zone.
slotsByDay(slots) groups them by local date for a day-by-day picker.
Holds and confirmation
hold reserves a slot for the service's holdFor (default 10 minutes) while
the customer finishes, and confirm books it. hold(..., { confirm: true })
books in one step. A member books for themselves, with their email filled in;
a manager can book for any customer.
const held = await bookings
.hold(serviceId, slot.resourceId, slot.startsAt, { name: "Bo" })
.orThrow();
await bookings.confirm(held.id).orThrow();
await bookings.cancel(held.id, "Ill").orThrow();The function checks the slot again before it inserts, and the constraint
settles a race: the second caller gets BOOKING_SLOT_UNAVAILABLE. Each new
booking also returns an accessToken, shown once and stored hashed, that
confirms or cancels it without signing in, for a link in a confirmation email.
With jobs installed, each hold enqueues a job on bookings.expire-holds that
runs when the hold ends. Add the handler to your drain route:
import { BOOKING_EXPIRE_QUEUE } from "better-supabase/blocks/bookings";
export const GET = jobs.drainRoute({
secret: process.env.CRON_SECRET,
handlers: { [BOOKING_EXPIRE_QUEUE]: bookings.job },
});expireHolds() (service only) cancels every hold whose time is up and records
booking.expired. A new hold on the same time also clears an expired hold
first, so a missed job never blocks a slot.
When a booking is confirmed and the calendar block is installed, it is copied
into the resource's calendar_id with the uid booking-<id>. With reminders,
a customer with a user id gets a reminder for each of the service's
reminderOffsets (minutes before the start, default one day). Cancelling
removes both.
| Method | Does |
|---|---|
saveResource(organizationId, input) | Inserts a resource, or updates the one with input.id |
setAvailability(resourceId, hours) | Replaces the weekly hours |
addException, deleteException | Closes or opens a range |
saveService(organizationId, input) | Inserts a service, or updates the one with input.id |
availableSlots(serviceId, range, opts) | The open slots, optionally for one resourceId and in a tz |
hold(serviceId, resourceId, at, ...) | Holds a slot, or books it with confirm |
confirm(id), cancel(id, reason) | Confirms a live hold, or cancels a hold or booking |
list(organizationId, range, opts) | The bookings that overlap the range, as the caller's policies allow |
expireHolds(), job | Cancels expired holds; job is the handler for bookings.expire-holds |
Archive and restore
archive(bookingId) hides a cancelled booking, or one that has ended, from
list and forCustomer and records booking.archived. An upcoming booking
that is not cancelled fails with BOOKING_ACTIVE. list takes
includeArchived: true to show archived bookings too, and restore(bookingId)
brings one back and records booking.restored. Both need bookings.manage.
The archived_at column is new, so an app table made before it maps
archivedAt: null in columns.bookings to leave the pair out.
await bookings.archive(booking.id).orThrow();
await bookings.restore(booking.id).orThrow();Recurring bookings
Turn on recurring to book a series: a weekly class, a standing appointment.
The option is off by default; it adds a booking_series table, a series_id
column on bookings and the series functions. Over a bookings table of
your own, the block adds series_id when the table lacks it, or uses the
column columns.bookings.series maps.
blocks: {
bookings: { options: { recurring: true } },
},A rule has a freq (daily or weekly), an interval (1 to 52), the ISO
weekdays for a weekly rule (1 is Monday), and a count (at most 366), an
until, or both. Occurrences keep their local start time in the rule's tz
(the resource's zone by default), so a 09:00 class stays at 09:00 across a
daylight saving change. parseRecurrence reads the RRULE subset the series
supports (FREQ, INTERVAL, BYDAY, COUNT, UNTIL) and throws a
RangeError for anything else; formatRecurrence writes a rule back. Both read
and write through the shared recurrence parser, and
booking_series_starts expands the rule with rrule_occurrences, so a series
follows the same daylight saving rules as the calendar. The recurrence module is
installed with bookings.
import { parseRecurrence } from "better-supabase/blocks/bookings";
const booked = await bookings
.bookSeries(
serviceId,
resourceId,
Temporal.Instant.from("2030-03-18T08:00:00Z"),
parseRecurrence("FREQ=WEEKLY;BYDAY=MO,WE;COUNT=8"),
{ name: "Bo" },
)
.orThrow();
booked.series.id; // every occurrence carries it as seriesId
booked.skipped; // empty unless skipConflicts was setEach occurrence is placed like a confirmed booking, through the same slot
check and the same bookings_no_overlap_excl exclusion constraint, so a series can
never double-book a seat. When an occurrence is taken the whole series fails
with BOOKING_SERIES_CONFLICT and nothing is booked; pass
{ skipConflicts: true } to book the open occurrences and get the taken
starts back in skipped.
reschedule(bookingId, startsAt) moves one occurrence, or any single booking.
With { scope: "following" } it moves this occurrence and every later live
one in the series by the same shift. Each move frees the booking's own seat
first, checks the new time is an open slot and lets the constraint settle a
race, so a move that collides fails with BOOKING_SLOT_UNAVAILABLE and leaves
every occurrence where it was. The calendar copy and the reminders move with
the booking, and each move records booking.rescheduled.
cancelSeries(bookingId) cancels this occurrence and the ones after it, and
ends the series; { scope: "one" } cancels one occurrence. series(seriesId)
returns the series with its bookings.
| Method | Does |
|---|---|
bookSeries(serviceId, resourceId, at, rule) | Books every occurrence, or the open ones with skipConflicts |
reschedule(bookingId, at, { scope }) | Moves one booking, or it and the following occurrences |
cancelSeries(bookingId, { scope, reason }) | Cancels the following occurrences (default) or one; returns a count |
series(seriesId) | The series and its bookings, as the caller's policies allow |
To pay for classes with a pack of credits, see class credits.
Appointment schedules
An appointment schedule is a page where others book time with a member. Build
it from a resource the member hosts: set hostUserId and checkBusy, and the
slots also skip every time the calendar block
reports the host as busy (their own events, invitations they accepted, focus
time, out of office and approved leave). The resource's weekly hours stay the
bookable window; the host's working hours don't narrow it.
const { id: resourceId } = await bookings
.saveResource(organizationId, {
name: "Office hours with Ada",
kind: "host",
tz: "Europe/Amsterdam",
hostUserId: ada,
checkBusy: true,
calendarId: adaCalendarId,
})
.orThrow();A booking confirmed on that resource is copied into its calendar. The slots
don't count that copy as the host being busy, so one booking only closes its
own time, padded by the service's buffers. checkBusy needs the calendar
module; without it the flag has no effect. Share the service through a link
(below) for a public schedule.
Rooms work the same way without a host: give the room a resource with kind: "room" and a capacity, and let services that need a room list room in
resourceKinds.
Public booking
With share-links installed, a share link to a service (subjectType: "booking_service") is a public booking page. The public_* functions are open
to anon, hash the token before the lookup, and refuse a revoked, expired or
unknown token, or a link whose organization is not the service's. A guest
must give a name and an email.
const link = await shareLinks
.create(organizationId, "booking_service", serviceId, "view")
.orThrow();
// On the public page, signed out. service.duration is a Temporal.Duration.
const service = await bookings.public.service(token).orThrow();
const slots = await bookings.public.slots(token, range).orThrow();
const held = await bookings.public
.hold(token, slot.resourceId, slot.startsAt, { name, email })
.orThrow();
await bookings.public.confirm(held.id, held.accessToken).orThrow();With rate-limit installed, every public call counts against the scope
bookings.public, keyed by the link and the first x-forwarded-for address.
The default is 30 calls a minute; set your own rule with
better_supabase.set_rate_limit('bookings.public', 10). Over the limit a call
returns a rate_limited error with the seconds to wait.
React
useAvailableSlots loads the open slots of a visible range and holds one. It
is typed structurally, so it needs no UI library. Pass token on a public page.
The hook is a registry item: install it with
npx shadcn add @better-supabase/use-bookings, which writes
hooks/use-bookings.ts into the app.
"use client";
import { useAvailableSlots } from "@/hooks/use-bookings";
const slots = useAvailableSlots({ serviceId, range: { start, end } });
slots.days.get("2030-03-04")?.map((slot) => (
<button key={String(slot.startsAt)} onClick={() => slots.hold(slot)}>
{slot.localStart.toPlainTime().toString({ smallestUnit: "minute" })}
</button>
));toEventCalendarBookings(bookings) turns bookings into resource-view events
for the staff side: each sits on its resource's row, holds are read-only and
cancelled bookings are left out.
Vue
useBlockController from better-supabase/vue runs
createAvailableSlotsController with its options; the controller needs no
provider. state is a shallow ref of the snapshot and actions are the
controller's actions. The work starts on mount, and the controller is
disposed with the component.
<script setup lang="ts">
import { useBlockController, useSupabase } from "better-supabase/vue";
import {
createAvailableSlotsController,
createBookings,
} from "better-supabase/blocks/bookings";
import { rpcTransport } from "better-supabase/blocks";
const { serviceId } = defineProps<{ serviceId: string }>();
const supabase = useSupabase();
const { state } = useBlockController(
createAvailableSlotsController,
{
client: createBookings({ transport: rpcTransport(supabase) }),
serviceId,
range: { start: new Date(), end: new Date(Date.now() + 7 * 86_400_000) },
},
false,
);
</script>
<template>
<ul>
<li v-for="slot in state.slots ?? []" :key="String(slot.startsAt)">
{{ String(slot.startsAt) }}
</li>
</ul>
</template>Call actions.setRange(range) when the visible range changes.
Svelte
useBlockController from better-supabase/svelte runs
createAvailableSlotsController with its options; the controller needs no
provider. It returns a readable store of the snapshot, read with
$, with the actions on .actions. The work starts on mount, and the
controller is disposed with the component.
<script lang="ts">
import {
betterSupabase,
useBlockController,
} from "better-supabase/svelte";
import {
createAvailableSlotsController,
createBookings,
} from "better-supabase/blocks/bookings";
import { rpcTransport } from "better-supabase/blocks";
let { serviceId }: { serviceId: string } = $props();
const { supabase } = betterSupabase();
const slots = useBlockController(createAvailableSlotsController, {
client: createBookings({ transport: rpcTransport(supabase) }),
serviceId,
range: { start: new Date(), end: new Date(Date.now() + 7 * 86_400_000) },
}, false);
</script>
<ul>
{#each $slots.slots ?? [] as slot (String(slot.startsAt))}
<li>{String(slot.startsAt)}</li>
{/each}
</ul>Solid
useBlockController from better-supabase/solid runs
createAvailableSlotsController with its options; the controller needs no
provider. state() reads the snapshot through from, and actions are
the controller's actions. The work starts on mount, and the controller is
disposed with the owner.
import { For } from "solid-js";
import { useBlockController, useSupabase } from "better-supabase/solid";
import {
createAvailableSlotsController,
createBookings,
} from "better-supabase/blocks/bookings";
import { rpcTransport } from "better-supabase/blocks";
export function Component(props: { serviceId: string }) {
const supabase = useSupabase();
const { state } = useBlockController(
createAvailableSlotsController,
{
client: createBookings({ transport: rpcTransport(supabase) }),
serviceId: props.serviceId,
range: { start: new Date(), end: new Date(Date.now() + 7 * 86_400_000) },
},
false,
);
return (
<ul>
<For each={state().slots ?? []}>
{(slot) => <li>{String(slot.startsAt)}</li>}
</For>
</ul>
);
}On a record page
bookingsBinding loads a customer's bookings, newest first, through bookings.forCustomer({ subject, limit }). The subject's id is the customer's user id, whatever its type. The organization comes from options.tenant: without it the call fails with TENANT_REQUIRED. The read runs as the caller, so an admin sees every booking of the customer and the customer sees their own. It shows at most limit bookings (default 50, up to 200) and goes stale on booking.* events. It has no writes, because a booking takes an instant, a service and a resource, which a Server Action can't carry.
Hooks
before_booking_reserve(tenant, service, resource, during, customer) runs before a booking is
placed and can raise to refuse it. after_booking_reserve(booking),
after_booking_confirm(booking) and after_booking_cancel(booking) run after
the change. Every occurrence of a series runs the same hooks. See block hooks.
A booking page in one read
bookings.page({ organizationId, serviceId, range }) returns the active services, the active resources and the open slots of one service. Without serviceId and range it skips the slot read and slots is empty. tz and resourceId narrow the slots as in availableSlots.
Errors
| Hint | When |
|---|---|
BOOKING_FORBIDDEN | The caller lacks the permission, or the access token does not match |
BOOKING_SLOT_UNAVAILABLE | The slot is outside the hours, too soon, not served by the resource's kind, or every seat is taken (exclusion) |
BOOKING_HOLD_EXPIRED | Confirming a hold whose time is up, or a cancelled booking |
BOOKING_STATUS_INVALID | A status other than confirmed or cancelled |
BOOKING_ACTIVE | archive on a booking that is upcoming and not cancelled |
BOOKING_NOT_FOUND | The booking does not exist |
BOOKING_RESOURCE_NOT_FOUND | The resource does not exist, is inactive, or is in another organization |
BOOKING_SERVICE_NOT_FOUND | The service does not exist or is inactive |
BOOKING_TZ_INVALID | tz is not an IANA time zone |
BOOKING_RANGE_INVALID | The range is empty or longer than 62 days |
BOOKING_LINK_INVALID | The share link is unknown, revoked, expired, or for another subject |
BOOKING_CUSTOMER_INVALID | A guest booking without a name or a valid email |
BOOKING_RATE_LIMITED | Too many public calls (rate_limited) |
BOOKING_RULE_INVALID | A recurrence rule with an unknown freq, an interval, weekdays or count out of range, or no end |
BOOKING_SERIES_CONFLICT | An occurrence of a series is not an open slot, or none is with skipConflicts |
BOOKING_SCOPE_INVALID | A scope other than one or following |
Availability is weekly hours plus exceptions; there is no RRULE for hours, and no deposit through the billing block yet.
With ReUI
ReUI's Time Picker renders useAvailableSlots' slots, with taken times
disabled; the free example c-time-picker-7 shows 30-minute slots with
booked times greyed out, and c-calendar-27 pairs a date picker with time
slots. For the staff side, the Event Calendar's resource view renders
toEventCalendarBookings. The Pro blocks in the application/schedule
category build full booking pages, such as a Calendly-style month calendar
with a slot picker; their source is licensed per user, so copy them into your
app from reui.io.
Your own fields
Columns you add to bookings with alter table in your own schema files are fields of the block (details):,
keyed by column name with their SQL type. Pass createBookings a Standard Schema
for them as fields: the customer object of hold and public.hold take them next to the block's own keys and
validate them (a bad value is a validation error), and every booking read return them
parsed. A column the module already uses is refused. See
your own fields.
const client = createBookings({
transport,
fields: z.object({ priority: z.number().int().positive().nullable() }),
});Without the client
db.bookings is this client. Code that does not go through bsb.db() builds it with a transport and an organization id:
const bookings = createBookings({ transport, service: serviceTransport });
const { id: resourceId } = await bookings
.saveResource(organizationId, {
name: "Ann",
kind: "staff",
tz: "Europe/Amsterdam",
})
.orThrow();
await bookings
.setAvailability(resourceId, [
{ weekday: 1, start: "09:00", end: "17:00" },
{ weekday: 2, start: "09:00", end: "17:00" },
])
.orThrow();
const { id: serviceId } = await bookings
.saveService(organizationId, {
name: "Haircut",
duration: Temporal.Duration.from({ minutes: 30 }),
bufferAfter: "PT15M",
resourceKinds: ["staff"],
})
.orThrow();Book in one call
book({ serviceId, startsAt, customer }) holds and confirms. Without resourceId it picks the resource that has a free slot at startsAt, and fails with not_found when none has. public.book({ token, resourceId, startsAt, customer }) does the same for a guest, using the access token the hold returns.
Paging bookings
page already reads free slots, so the booking list uses pageBookings, bookingFacets, countBookings and getBooking. Sorts are startsAt (the default), createdAt and customerName. Filters are status, resourceId, serviceId, customerId, from, to and archived, facets are status and resourceId, and q searches the customer name and email. getBooking(bookingId) returns one booking or a not_found error. Resources and services are not entities of the block, so they have no page. list is deprecated. The SQL functions are page_bookings and get_booking.
const page = await bookings
.pageBookings({
organizationId,
filters: { status: ["confirmed"] },
limit: 25,
})
.orThrow();Last updated on
Calendar
Calendars and events with RFC 5545 recurrence, per-occurrence edits, attendees, iCalendar import and export, and an iCal feed through a share link.
Time tracking
Timers and logged time on any record, one running timer per member and no overlapping entries enforced by Postgres, weekly timesheets approved through the approvals module, locked weeks, and a weekly grid shape for a data grid.