bookable-resources
npx skills add https://github.com/crystallizeapi/ai --skill bookable-resourcesCrystallize Bookable Resources
A bookable product is not counted down like stock — it is held for a window of time and given back. A digger rented Friday to Monday, a meeting room at 09:00, a photographer for an afternoon. The same product sells again and again; what is scarce is the calendar.
Crystallize serves this natively: a policy carries the rules, a pool carries the things that can be booked, and the Shop API holds them for a shopper while they shop, then hands them to the order.
Verified on 2026-09-24 and 2026-09-28 against the live Core API and Shop API on a tenant with bookable resources, including test reservations taken and released. Where a claim comes from one storefront build rather than from the API, this skill says so.
Five concepts
| Concept | What it is |
|---|---|
| Policy | The rules, all durations in seconds: how far ahead, buffers, how long a hold lives, cancellation window |
| Pool | What can be booked on one product: named units (machine 1, machine 2) or a plain capacity |
| Reservation | One hold on one window, in one cart line. It expires unless it is confirmed |
| Window | start and end, absolute times. Availability is asked and holds are taken per window |
| Confirmation | What turns a hold into a booking that survives. It must run after the cart has its orderId — see below |
Booking sits on the product; the price comes from the variant. A rental sold by the day, the weekend and the week is therefore one bookable product with three variants.
The pipeline
Core createBookingPolicy the rules — every duration in SECONDSCore setBookable(id, language) one pool per product: units[] OR capacity, never bothCore publishItem the Shop API reads published data only — publish after EVERY setBookable, reapplyBookablePolicy or clearBookableShop availability / checkBooking what is free, and would this exact booking be takenShop bookSkuItem a hold on the cart, in state PENDINGShop place re-checks the holds and extends them to placedHoldDurationShop createFromCart the order. It only snapshots the reservationsShop confirmCartBooking once the cart has its orderId (optionally also before payment)Which API does what
| Task | API and endpoint | Who calls it |
|---|---|---|
The pool, unit meta and policySnapshot on a product page |
Discovery (bookable { … }) |
Storefront server, cached |
Availability, nearestAvailability, checkBooking |
Shop API /cart |
Storefront server, after the product |
Hold, change, release; place; confirmCartBooking |
Shop API /cart |
Storefront server, payment webhook |
The order and its reservations snapshot |
Shop API /order (createFromCart) |
Payment webhook |
| Read or cancel any reservation, maintenance blocks, calendar | Shop API /booking/admin |
Staff tools, server only |
Policies, pools, reapplyBookablePolicy, publishing |
Core API | Setup scripts and admin, never a page |
Everything a storefront does is on Discovery and the Shop API, and every Shop API call runs on the server (a server action or route): the Shop token never reaches the browser. Core is for setup only. Discovery never serves availability. The API contract for the whole storefront is in [[storefront]].
Is this tenant bookable?
There is no feature flag: every tenant has booking policies, and role permissions are the gate. Ask for the policies to find out whether this session can manage them:
{ bookingPolicies(first: 1) { __typename ... on BookingPolicyConnection { totalCount } ... on BasicError { errorName message } }}A connection means yes. FORBIDDEN means the role lacks the bookingPolicies permission. That
usually happens on a custom role created before bookings existed, and it is fixed on the role, not in
the query. Putting a pool on a product is a second permission: setBookable, reapplyBookablePolicy
and clearBookable need productBookable on top of the right to edit the item. One earlier build
(2026-09) got ExperimentalFeaturesNotAvailableError here instead: then booking is not enabled on that
tenant, whatever the role.
Storefront rules
Learned on four storefront builds (machine rental, a hotel, design appointments, machine hire). Each is detailed in booking-flow.
- Customer first, full flow, even for seeds. A reservation records its customer only at
bookSkuItem/hydrate, and its order only from aconfirmCartBookingaftercreateFromCart. Reservations seeded withplaceand a confirm, without a customer or an order, show “No customer / No order” in the admin, and no cart call can repair them. - The availability buckets are the admission test. They already include the policy’s buffers on
both sides, so a window is free when every bucket of
[start, end)has room. - Lay the day slots on the booking grid, not on UTC midnight, or every hire looks a day longer.
- Write the refusal text yourself. A refusal’s
messageis only its type name; branch on__typename. - Validate bookable lines yourself. A plain
addSkuItemof any variant of a bookable product is accepted, and nothing is reserved. - Build the confirmation page from the order. Its meta carries a
reservationssnapshot, withorderIdafter the second confirm.OrderFromCartInputhas nometa: set it on the cart beforeplace. - Enforce the cancellation window yourself after the order. The cart cannot cancel an ordered
reservation, and
/booking/admincancelignores the window. A “cancel my booking” page compares the start withpolicySnapshot.cancellationWindowbefore it callscancelon the server.
Failure modes
Three of these are silent — a paid booking whose reservation has no order, a pool or policy change that has no effect, and a bookable SKU sold with nothing held. They are the reason this skill exists; the rest name themselves.
| Symptom | Cause | Fix |
|---|---|---|
| Admin shows “No order — not checked out” on a paid booking | confirmCartBooking ran before the cart had its orderId |
Confirm again after createFromCart — see booking-flow |
| An order for a bookable product with nothing reserved | The SKU went through addSkuItem or hydrate with no booking: a plain line |
Book with bookSkuItem, or send booking on the hydrate line |
NotBookable on a product you just made bookable |
The item is not published, or the query’s language is wrong |
Publish it; pass the language the item exists in |
| A pool or policy change has no effect in the Shop | Bookable edits are drafts; products keep the policySnapshot they were set with |
reapplyBookablePolicy for a policy change, then publish the product |
FORBIDDEN from createBookingPolicy |
The role has no bookingPolicies permission |
Grant it on the role |
Holds vanish within seconds, or InvalidRange on every date |
A duration was sent in minutes, hours or days | Every policy duration is seconds; read humanized back to check |
hydrate throws “A placed cart cannot be hydrated” |
The cart is placed; its contents are frozen | Change bookings before place, or through /booking/admin after |
ReservationConflict on a unit that looked free |
Someone took it between the availability query and the booking | Walk the other freeUnitIds and retry |
ReservationConflict whose message says the cart changed |
Another write landed on the same cart first, and nothing was booked | Read the cart back, then retry; serialize booking writes per cart |
ReservationConflict on a capacity pool with seats free |
Capacity counts every booking overlapping the window, not the busiest moment | Keep capacity windows uniform, or use units |
Cannot place this cart: <sku> (<reason>) |
place or hydrate could not keep a booking line; see the reason |
Nothing was saved: hydrate with another window or without the line |
InvalidRange on a date far ahead |
The window is past the policy’s advanceWindow |
Widen the policy, or cap the calendar at the shortest advanceWindow in the basket |
CancellationWindowClosed when removing a basket line |
The window applies to holds that were never bought | Re-hydrate the cart without that line instead |
Unexpected error. from addCartItem or removeCartItem |
They refuse a booking line | hydrate with the new quantity, or without the line |
| The calendar shows every hire one day longer | The availability range starts at UTC midnight, the periods at 07:00 local |
Start the range where the periods start |
| “Next free slot” offers a time the shop is closed | nearestAvailability knows no opening hours and searches the whole pool |
Use it as a hint; filter the starts to opening hours and units in code |
Field "product" of required type "ProductInput!" |
addExternalItem got a variant without product |
Send variant: { price, product: { id, path } } |
BookablePoolKindChangeError |
Capacity → units while a capacity pool is published | clearBookable, publish, cancel or wait out open reservations, then set units |
BookingPolicyInUseError on delete |
Products still reference the policy (stats.referencingProductCount) |
Move those products to another policy and publish them |
References
- references/policies-and-pools.md — Core: policies, unit and capacity pools, snapshots and reapplying, deleting and clearing.
- references/booking-flow.md — Shop API
/cart: availability, holds, checkout, the double confirmation, cancelling and moving a booking. - references/booking-admin.md — Shop API
/booking/admin: maintenance blocks, the reservation calendar and list, moving a reservation to another unit. - references/modelling.md — periods as variants, units as real machines, multi-day hires, what Discovery serves, and how a rental relates to the product it is a rental of.
Related: [[storefront]] for the API contract and the checkout request path, [[mutation]] for the Core API mutations themselves, [[query]] for Discovery and the Shop API query surface, [[pricing]] for what a booked variant costs, [[payments]] for the payment webhook that creates the order, and [[agentic-commerce]] for bookings made by an agent.
Reference Details
Booking administration (Shop API /booking/admin)
For back-office tools: taking a unit out of service, reading who holds what, and changing what a shopper cannot. Run it server-side only.
The token needs both the booking and booking:admin scopes, so ask for
"scopes": ["booking", "booking:admin"] when you mint it (see [[mutation]]). Post to
https://shop-api.crystallize.com/@{tenant}/booking/admin yourself: client.shopBookingApi in
@crystallize/js-api-client posts to /booking, which serves nothing and answers 404.
Refusals are GraphQL errors here, not union members. Branch on extensions.reason, under
extensions.code: "BOOKING_REJECTED": NotBookable, NotFound, Conflict, InvalidRange or
InvalidUnitId.
Take a unit out of service
Do not fake a cart hold, and do not remove the unit from the pool. Block it:
mutation { block( input: { productId: "6ab3…" sku: "RENT-GAS55-DAY" start: "2026-10-05T00:00:00Z" end: "2026-10-07T00:00:00Z" unitId: "GAS55-OSL-1" source: MAINTENANCE sourceReason: "annual service" language: "en" } ) { id unitId state }}sourceisMAINTENANCE,STAFF_HOLD,PARTNER_ALLOCATIONorOTHER.skuandlanguageare required because the pool is read through the variant, in one language.- Without a
unitId,quantity(default 1) takes that many of the pool, all or none. With aunitIdit must be 1. The answer is a list with one reservation per unit of quantity, and each needs its owncancel. - The
advanceWindowdoes not apply to a block; the policy’s buffers do. - A block never expires. It reads
state: PENDINGwithexpiresAt: nulland holds its window until youcancelit. Conflictmeans something already holds that window. Move it withassignUnit, or cancel it.bulkBlock(inputs:)takes several and answersresults, one{ ok, reservations, reason }per input in request order. It is not atomic, so reissue only the failed ones.
checkBooking(input:) is the dry run for a block. It takes the same fields as the /cart one plus a
required source, and refuses source: CART.
Read the reservations
| Query | Use it for |
|---|---|
calendar(filter:) |
A range, grouped by product. rangeStart and rangeEnd required; refused past 5,000 rows |
reservations(filter:, limit:, after:) |
A flat list, paged by nextCursor. limit defaults to 50, at most 5,000. Range optional |
reservationSummary(productId:, range:, states:) |
total, byState and bySource for one product |
reservation(id:) |
One row, with the customerId, frozenPolicy and meta the /cart query does not serve |
- Filters take
productIds,states,sources,unitId,orderId,cartIdandcustomerId. - Omit
statesand you get every state, finished ones included. Pass[PENDING, CONFIRMED]for what actually holds the calendar. orderIdonly finds rows confirmed after the cart had its order. For the others, filter bycartId: the order id is the cart id.- Rows carry
productIdandvariantSku, never names. Hydrate those from the Catalogue or Discovery. - These queries serve open reservations and 90 days of finished ones. An older booking is on its order,
in the
reservationsmeta. See booking-flow.
Change a reservation
cancel and bulkCancel are in booking-flow.
assignUnit(id:, unitId:, language:) moves a reservation to another unit of the pool, keeping its window,
and is refused with Conflict if that unit is taken. setMeta(id:, meta:, merge:) writes the
reservation’s own meta. All of these update the record on the order that bought the reservation.
The booking flow (Shop API /cart)
Everything the storefront does. All of it is on the /cart endpoint except the order itself, which is
/order. See [[mutation]] for tokens and endpoints.
The Shop API reads products from the Catalogue with the credentials on the request, and the Shop token is
not one of them. On a tenant whose Catalogue requires authentication, also send its
X-Crystallize-Static-Auth-Token, or its access token pair, on every call that reads a product.
1. What is free
query Availability($productId: String!, $sku: String!, $range: CartTimeRangeInput!, $language: String!) { availability(productId: $productId, sku: $sku, range: $range, granularitySec: 86400, language: $language) { start end free freeUnitIds bookable reason }}One slot per granularitySec across the range: 86400 for a day view, 3600 for hours. A query is
refused past 10,000 slots, or past 100,000 slots × units. free is how many units or seats are open.
freeUnitIds names the units you may pin, and is always [] on a capacity pool. bookable is the time
check alone (not elapsed, inside the advanceWindow), and reason explains a false. So a sold-out
slot reads { free: 0, bookable: true, reason: null }: a calendar needs both.
languageis required and it must be a language the item exists in. The wrong one reads like an unbookable product: a GraphQL error withextensions.reason: "NotBookable"fromavailabilityandnearestAvailability, and{ ok: false, reason: "NotBookable" }fromcheckBooking.bookSkuItemhas nolanguage. It reads the product in the cart’scontext.language, and ahydratethat sends nocontextmeansen. Hydrate the cart in the language you pass here.- Ask for the range the calendar shows, plus enough tail that the longest bookable period starting on the last visible day still fits.
- A run of open days does not prove the whole window is open. Each slot is counted alone, so one unit
can be free on Monday and another on Tuesday. Ask
checkBookingbefore booking across several slots. - The slots already include the policy’s buffers, on both sides of every booking. A booking 10:00–11:00
under a 15-minute buffer reads busy from 09:45 to 11:15 at 15-minute granularity: 09:45, because a new
booking ending at 10:00 would need its own buffer. So “this unit is free in every slot of
[start, end)” is the right admission test, andbookSkuItemrefused exactly where the slots said busy. (One build, 2026-10.) - Start the range on the booking grid, not on UTC midnight. With
granularitySec: 86400from UTC midnight, a 07:00→07:00 Oslo hire falls into two slots, so every hire looks a day longer. Start the range at the local period start (07:00) and the slots line up with the bookings. (Another build.)
nearestAvailability(productId, sku, around, durationSec, n, language) answers “the next n windows of
this length from this time” as { start, end } — the right query behind a “next free slot” button. n
defaults to 5, at most 100. It only walks forward, up to 30 days, in steps of durationSec: a 7-day
window is tried once a week, not every day. A durationSec under 260 is refused. The windows start at
the time of day of around.
nearestAvailability knows no opening hours and searches the whole pool. For a four-hour job it
offered 16:00–20:00, and it takes no unit or region filter. Use it as a hint (jump the calendar to that
week), then filter the slot starts to opening hours and to the units the shopper can use in code. Opening
hours are not a booking concept; to make closed hours unbookable, block them on
/booking/admin. (Observed in one build.)
checkBooking(input: CartCheckBookingInput!) is a dry run of one exact booking and returns
{ ok, reason }, not a union. reason is NotBookable, Conflict, InvalidRange or InvalidUnitId:
Conflict here, where bookSkuItem says ReservationConflict. It takes productId, sku, start,
end, language, and optionally unitId and quantity. Debounce it: it runs the same gates the booking
itself does.
2. Hold it
mutation Book($id: UUID, $input: CartBookingItemInput!) { bookSkuItem(id: $id, input: $input) { __typename ... on Cart { id items { lineId name meta } } ... on ReservationConflict { message } ... on NotBookable { message } ... on InvalidRange { message } ... on InvalidUnitId { message } }}{ "input": { "sku": "RENT-GAS55-DAY", "quantity": 1, "booking": { "start": "2026-10-01T08:00:00Z", "end": "2026-10-01T16:00:00Z", "unitId": "GAS55-OSL-1" }, "meta": [{ "key": "unitId", "value": "GAS55-OSL-1" }] }}bookSkuItem is addSkuItem with a window: the line is priced from the SKU like any other line.
Check __typename. The four refusals are results, not GraphQL errors, so a client that only looks at
errors treats a refused booking as a success. Their message is only the type name
({ __typename: "ReservationConflict", message: "ReservationConflict" }), apart from the cart-changed
conflict below, so the storefront writes its own text per __typename and per language.
quantity is units out of the pool, not the length of the window
This is the single thing most likely to produce a wrong price. Measured on a unit pool of 5, booking a two-day window on a one-day SKU priced at 39 net:
| Sent | Result |
|---|---|
quantity: 1 |
one reservation over the whole window, line 39 — not 78 |
quantity: 2 |
two reservations, both over the whole window, line 78 |
quantity: 6 (pool holds 5) |
ReservationConflict |
quantity: 2 with a unitId |
OUTPUT_VALIDATION_ERROR, with booking.unitId requires quantity 1 in extensions.errors |
So quantity: 2 means two machines, or two rooms, for the same window — never “two days” or “two
nights”. Nothing in the booking inputs prices by duration. A window twice as long costs the same
unless the price says otherwise, and the price only comes from the SKU.
Three ways out, and the first is the one to reach for:
- Sell the duration as variants — a day SKU, a weekend SKU, a week SKU — and book the SKU whose length matches the window. See modelling.md.
- When the shopper picks arbitrary dates (hotel nights, hourly hire), book one managed line for the
first unit of time and add the rest as an external line (
addExternalItem) that carries the remaining nights, tied back to the booked line by your ownmeta. Do not reprice the booked line:placerefuses a cart whose booked line went throughchangeCartItemPricingwithNotBookable, even though the reservation itself survives it. A group discount works as a negative external line. (From the Boutique Universe build, a hotel on nightly rates.) - When period prices matter (a weekend and a week cost less than seven days), chain period SKUs on
one unit: a 10-day hire is a weekend SKU plus a week SKU, the cheapest cover computed in the storefront,
booked back to back with one
bookSkuItemeach on the sameunitId. This needs zero buffers and periods that meet (every period 07:00→07:00). Each line carries its real SKU and price, a customer’s price list applies per line, and the calendar is blocked exactly. (Observed in a machine-hire build.)
addExternalItem needs the product on its variant: variant: { price, product: { id, path } }.
Without product it fails with Field "product" of required type "ProductInput!" was not provided.
A unitId and quantity: 1 belong together. To hold two named units, book twice — once per unit.
A bookable SKU with no window is a plain line. addSkuItem, or a hydrate line with no booking,
reserves nothing, and place and createFromCart let it through: the order exists and the calendar never
heard of it. That holds for every variant of a bookable product, not only the one you booked. Nothing
warns you, so validate in the storefront that every line of a bookable product has a booking, unless
you add such a line on purpose. One build did: one window for a set of installation jobs, booked
on the first job’s SKU, with the other jobs as plain lines tied to it by meta.
Put the customer on the cart before booking. The reservation records who holds it at
bookSkuItem/hydrate time, and only when the cart’s customer has an identifier. Nothing sets it later:
setCustomer after place does not reach it. Create the cart with hydrate(input: { customer, items: [] }),
or setCustomer before the first booking.
Seed bookings through the full flow too. A seed that books, places and confirms with no customer and
no order leaves reservations the admin shows as “No customer — admin-created / No order”: 705 of them in
the Boutique Universe build. The cart cannot cancel them once placed, and clearBookable + setBookable
keep them. Cancel them on /booking/admin (cancel, bulkCancel), or better, seed
with a customer, createFromCart and the second confirm, as a shopper would.
On ReservationConflict, walk the other freeUnitIds. Between the availability query and the
booking someone else may have taken that unit. The exception is a message that says the cart changed:
see below. Any other refusal is final — stop and tell the shopper.
A window past the policy’s advanceWindow is refused as InvalidRange, with nothing to say the
policy is what stopped it. Products that are booked together need the same window: a room on a 120-day
policy and a boat trip on a 60-day one means a summer booking can hold the room but not the trip. Cap
the calendar at the shortest advanceWindow in the basket. (Observed in the Boutique Universe build.)
The reservation id comes back on the line’s meta, not on the cart’s, comma-separated when the line
holds several:
"meta": { "reservationIds": "18a6b9d4-…", "booking.window": "2026-10-01T08:00:00.000Z/2026-10-01T16:00:00.000Z" }booking.window is written for you. Write the unitId into the line’s meta yourself. CartItem
has no booking field, and a pinned line re-hydrated without its unitId does not match its hold: it
is rebooked, possibly onto another unit. reservation(cartId:, id:) { unitId } can recover a lost one.
It is also how a storefront learns the unit of an unpinned booking, which takes the first free units in
pool order.
bookSkuItem ignores group and type on a new line. To group a booking with its services, set
group when you next hydrate.
Read one hold with reservation(cartId:, id:):
{ id, productId, variantSku, unitId, start, end, state, source, cartLineId, orderId, expiresAt }. It
answers null for a row this cart does not hold.
Look holds up one at a time. Several reservation(cartId:, id:) fields aliased into a single query
sometimes never answer — 3 of 10 attempts in the Boutique Universe build. One query per hold, with a
timeout.
One write at a time per cart
Every booking write is conditional on the version of the cart it read. Two bookSkuItem calls in flight
against one cart land one booking. The other answers ReservationConflict, its hold is released, and its
message says the cart changed and nothing was booked. A slot conflict has the bare message
ReservationConflict. hydrate, place, cancelReservation and rebookReservation lose the same race
with a GraphQL error: “The cart was changed by another request…”.
So serialize the booking writes for one cart — a queue or a lock per cart id — and when a write loses that race, read the cart back before retrying: the other request may have made this same booking.
3. Keep it while they shop
hydrate is the whole cart. A booking line you leave out is cancelled with it, and re-hydrating with
the line slides its expiry forward. There is no “extend the hold” mutation. Every hydrate gives all the
holds of the cart one deadline, set by the shortest pendingHoldDuration among them. bookSkuItem slides
nothing, not even the other holds on that cart.
That cuts both ways, and the second half is the useful one:
-
To keep a booking, send every line on every hydrate, with its window and unit:
{"sku": "RENT-GAS55-DAY","quantity": 1,"booking": { "start": "2026-10-01T08:00:00Z", "end": "2026-10-01T16:00:00Z", "unitId": "GAS55-OSL-1" },"meta": [{ "key": "unitId", "value": "GAS55-OSL-1" }]}A line is matched to its hold per SKU, by window and unit, so resend both unchanged. Lines that match nothing are paired in payload order and moved, so changing one date moves that line.
hydratedoes not uselineIdfor this.lineId(selectable onCartItem) is the line’s server-minted handle for the mutations that target one line, such aschangeCartItemPricing, which refuse a SKU shared by several lines without it. -
To change a booking, send it changed. A new line with a
bookingis reserved, and a newquantitytakes or releases the difference. A refusal is not a union member here: the whole hydrate fails withCannot place this cart: <sku> (ReservationConflict)and saves nothing. UsebookSkuItemfor a new booking when the shopper needs to know why. -
To remove one from the basket, re-hydrate without it.
removeCartItemrefuses a booking line. Do not usecancelReservation: the policy’s cancellation window applies to a hold that was never bought, so a rental starting tomorrow under a two-day window answersCancellationWindowClosedand the shopper cannot empty their own basket. Verified against a live tenant.
abandon(id) gives back every hold of a draft cart at once, rather than at their expiry.
cancelReservation(cartId:, reservationId:) succeeds only while the start is at least
cancellationWindow seconds away. It is right for a line that is far enough out, and
rebookReservation(cartId:, reservationId:, newBooking:) moves a hold to a new window atomically. It
moves every reservation on that line, so a quantity-3 line moves as one, each keeping its unit if that
unit is free in the new window. A unitId on such a line answers InvalidUnitId. Both mutations answer a
union, so check __typename. ReservationConflict is the only outcome worth retrying.
All of this is for a draft cart. Once the cart is placed, hydrate throws “A placed cart cannot be
hydrated”, and cancelReservation/rebookReservation fail with INPUT_STATE_ERROR. Finish every change
to the bookings before place.
4. Place, pay, order, confirm — in that order
place(id) re-checks every hold, extends to placedHoldDuration (0 = pendingHoldDuration)confirmCartBooking(cartId) OPTIONAL: the holds still stand, and are now committed — see below… take payment …createFromCart(id, input) the order (on /order). It snapshots the reservations… wait for cart.orderId … the cart is linked in the background, ~500 msconfirmCartBooking(cartId) REQUIRED: this is what writes orderId onto the reservationsconfirmCartBooking writes orderId onto the reservations only if the cart already has one. The
order id is the cart id, but createFromCart returns before it links the cart: it saves the order
and stamps orderId on the cart in the background. The cart therefore gets its orderId a few
hundred milliseconds after createFromCart returns, so a single confirm
before the order leaves every reservation { state: CONFIRMED, orderId: null }, and the admin shows
“No order — not checked out” for a booking that was paid for.
Poll the cart, then confirm again. It accepts an ordered cart and rows that are already confirmed:
async function linkReservations(cartId: string) { for (let i = 0; i < 20; i++) { const { cart } = await shop(`query($id: UUID!) { cart(id: $id) { orderId } }`, { id: cartId }); if (cart?.orderId) { await shop(`mutation($id: UUID!) { confirmCartBooking(cartId: $id) { __typename } }`, { id: cartId }); return; } await new Promise((r) => setTimeout(r, 250)); }}The first confirm commits the slot before the money moves. A CONFIRMED reservation never expires:
it blocks the calendar until its window ends. It is what proves the holds still stand before the
shopper is charged. If you keep it, cancel the reservations through /booking/admin when the payment
fails, or the machine stays blocked with no order behind it. If you drop it, place is still the
last check before payment, and the holds live for placedHoldDuration while payment runs. If that payment
fails, remove(id) deletes the cart and gives its unconfirmed holds back at once. It leaves CONFIRMED
rows alone, and abandon is refused on a placed cart.
confirmCartBooking answers Cart, NotPlaced, NothingToConfirm or ReservationNoLongerHeld. The
last one means a hold expired while payment was in flight; select its missing field for the ids. It
is all or nothing: the surviving holds stay PENDING, and the shopper has to pick another window for
the lost one.
Every step here runs on the server: a server action for place and the first confirm, and the payment
gateway’s webhook for createFromCart and the second confirm (see [[payments]]). The browser holds only
the cart id. The cart.orderId link took about 440 ms in one build and 500 ms in another, so the poll is
required, not defensive.
Order meta comes from the cart. OrderFromCartInput takes no meta; createFromCart copies the
cart’s meta onto the order. Write what the order needs (reference, the person who booked, the depot)
with the cart’s setMeta before place.
Give rentals their own pipeline when the tenant also takes ordinary orders: pass both in
createFromCart’s pipelines (ids, not names) — ordinary lines to an Orders pipeline, booked lines to a
Rentals pipeline. Do not set placeNewOrders: true on the first stage of more than one pipeline: every
new order then lands in all of them. (Tools Universe build.)
Do not call fulfill. createFromCart already moves the cart to ordered, and the order id is the
cart id.
After the order
-
A reservation on a placed or ordered cart cannot be cancelled through the cart: “A reservation cannot be cancelled through a cart that is no longer editable.” Cancel it on the Shop API’s
/booking/adminendpoint, which needs a token with both thebookingandbooking:adminscopes and ignores the cancellation window. Run it server-side only:mutation {cancel(id: "18a6b9d4-…", reason: "payment failed") {idstate}}bulkCancel(ids:, reason:)takes up to 100 ids and answers per id; it is not atomic. See booking-admin for the rest of that endpoint, including whyclient.shopBookingApicannot reach it. -
A hold lost after
placecannot be re-picked on that cart. A placed cart cannot be hydrated or rebooked. OnReservationNoLongerHeld, cancel the survivors (above), refund if the money has moved, and start a new cart for the new window. -
A reservation’s
stateis a string:PENDING,CONFIRMED,COMPLETED,CANCELLEDorEXPIRED. A hold that runs out becomesEXPIRED, up to a minute late, while its line stays in the cart. The nexthydratetakes it again if the window is still free. If not it fails withCannot place this cart: <sku> (ReservationConflict), saving nothing, so send the next one with another window or without that line. -
placerefuses a cart withCannot place this cart: <sku> (<reason>).HoldNoLongerHeldis a hold that ran out or was cancelled,UnitNoLongerInPoola pinned unit that left the published pool, andNotBookablea product no longer published or bookable. The cart stays a draft, so it can be fixed. -
/ordercarries what was booked:items { lineId booking { start end unitId } }, whereunitIdis the pinned unit only. The order’smetaaddsreservations, a JSON string with one record per reservation, real unit included, which outlives the reservation itself. Areservations.unconfirmedkey, there only when something went wrong, lists the ids no longer held. Watch for it: the order is created either way. -
The confirmation page needs no reservation lookup. Each
reservationsrecord carries the id,unitId, window,state,frozenPolicy,customerIdand the line’s meta, andorderIdonce the second confirm has run. Read it from the ordercreateFromCartreturned, or fromorder(id) { meta }. To verify{ state: CONFIRMED, orderId }server-side,/booking/adminreservation(id)reads any reservation without its cart id. -
Self-service cancellation is yours to gate. The cart refuses to cancel an ordered reservation, and
/booking/admincancelignores the cancellation window (it cancelled an ordered reservation in one build). A “cancel my booking” action therefore checks, on the server, that the start is at leastpolicySnapshot.cancellationWindowseconds away and that the session’s customer owns the order, then callscancel, then refunds through the payment provider.
Modelling a bookable catalogue
Booking is on the product, price is on the variant
setBookable takes an item id, so the calendar belongs to the product. The money belongs to the
variant. That one split decides the model: sell time as variants.
Product Bosch GAS 55 M dust extractor — rental bookable: 5 units, policy "heavy-equipment" ├─ RENT-GAS55-DAY 1 day attributes: { period: day } ├─ RENT-GAS55-WEEKEND weekend attributes: { period: weekend } ├─ RENT-GAS55-WEEK 1 week attributes: { period: week } └─ RENT-GAS55-4WEEKS 4 weeks attributes: { period: 4-weeks }The shopper picks a period and a start; the storefront turns that into start/end and books the
matching SKU. Keep the length of each period on the variant — a numeric duration-hours, or an
attribute — so the window is computed from data rather than from a hardcoded table. A weekend is rarely
48 hours: Friday 12:00 to Monday 08:00 is 68.
Price tiers per period, currency per market and VAT all work as they do for any other variant — see [[pricing]].
Give each period variant its own image. The admin’s booking calendar shows the variant’s image, not the product’s, so rate-plan variants without one show blank tiles. (Boutique Universe build.)
A window is one interval, so it may span the night: a 10-hour installation job booked Monday 07:00 to Tuesday 09:00 holds the team throughout. Counting working hours inside it is the storefront’s job.
For hires of arbitrary length, the variants can also be chained: see “quantity is units out of the
pool” in booking-flow.
Units are the real things
A unit id should be the thing in the world: an asset tag, a room number, a registration number. Put
everything that distinguishes it in meta:
{ "id": "GAS55-OSL-1", "meta": [ { "key": "depot", "value": "osl" }, { "key": "serial", "value": "TU316652" }, { "key": "hours", "value": "257" }, { "key": "lastService", "value": "2026-06-07" } ]}That is what lets a storefront filter by location (“available in Oslo this weekend”) without another
data source: read the pool from Discovery, group the freeUnitIds from availability by their depot
meta, and show one line per location.
Use a capacity pool instead when the units are interchangeable and nobody needs to know which one they got — seats on a course, bikes in a rack. You lose per-unit meta, so if the storefront must say which one, use units. Capacity is also only exact for bookings that share a window: see policies-and-pools before using it for hires of varying length.
What Discovery serves, and what it does not
Discovery carries the static bookable configuration on the item:
{ browse { rental(language: en, pagination: { limit: 24 }) { hits { itemId name path bookable { poolSize pool { __typename ... on BookableUnitPool { units { id meta { key value } } } ... on BookableCapacityPool { capacity } } } variants { sku attributes defaultPrice } } } }}bookable also serves policySnapshot { advanceWindow cancellationWindow … }, so a calendar can be capped
at the advanceWindow without a Shop call. Product shapes can filter, facet and sort on bookable_kind
and bookable_poolSize, as in filters: { bookable_kind: { equals: "units" } }.
A newly published bookable product on an already indexed shape appeared with its bookable pool about a
minute after publish, with no ignite (observed in one build). A new shape, and in one build even a new folder
on an existing shape, was not served until after igniteDiscoApi (another build); see [[query]].
Discovery never serves availability. Listing pages can say “5 machines, 3 depots” from poolSize and
the pool; anything about a date is a Shop API call. Design the page so the calendar loads after the
product, not as part of the listing query — one availability call per visible card is a lot of calls.
Rentals next to the thing being rented
A rental item and the product it is a rental of are two catalogue items. Relate them both ways: an item relation from the rental to the tool, and one back from the tool to its rental. The tool’s page can then offer “rent this instead”, and the rental page can show the tool’s specifications without duplicating them. See [[content-model]] for the relation component and [[information-architecture]] for where the rental folder sits.
Mark the rental folder with an externalReference (folder:/rental) so the storefront can recognise a
rental listing without matching on the path in four languages.
Services around a booking
Delivery, damage waiver, cleaning, an operator: sell them as ordinary products and add them to the cart
as normal lines, or as type: service lines. They are not bookable themselves; they follow the booking
they belong to. Give them and the booking line the same group so the basket can show them together.
Set group and type through hydrate: bookSkuItem ignores both on a new line.
Booking policies and pools (Core API)
Setup for bookable products. Admin-time work: a storefront never calls these.
The policy
A policy is a named set of rules shared by many products. Every duration is a number of seconds.
mutation CreatePolicy($input: CreateBookingPolicyInput!) { createBookingPolicy(input: $input) { __typename ... on BookingPolicy { id name version humanized { advanceWindow { value unit } cancellationWindow { value unit } } } ... on BasicError { errorName message } }}{ "input": { "name": "heavy-equipment", "advanceWindow": 10368000, "bufferBefore": 0, "bufferAfter": 14400, "cancellationWindow": 172800, "pendingHoldDuration": 900, "placedHoldDuration": 86400 }}| Field | Required | Meaning |
|---|---|---|
name |
yes | Unique per tenant — BookingPolicyNameTakenError otherwise |
advanceWindow |
yes | How far into the future a booking may be made (120 days = 10368000) |
bufferBefore |
yes | Dead time reserved before each booking |
bufferAfter |
yes | Dead time after — cleaning, charging, travel (4 hours = 14400) |
cancellationWindow |
yes | How close to the start a booking may still be cancelled (2 days = 172800) |
pendingHoldDuration |
yes | How long a hold in a live cart survives (15 minutes = 900) |
placedHoldDuration |
no | How long a hold survives after place, while payment happens (1 day = 86400) |
A placedHoldDuration of 0, or none, gives a placed cart a fresh pendingHoldDuration. Set it
when payment takes longer than a live hold, such as an invoice or a bank transfer.
pendingHoldDuration must be at least 1, or the policy is refused with InvalidNumberRangeError. Do not
send advanceWindow: 0 to mean “no limit”: bookSkuItem then refuses every future window as
InvalidRange while availability reports them bookable. Send a long window instead.
Read humanized back after writing. It returns the same values as { value, unit } in days, hours,
minutes or seconds, which is the cheapest way to catch a duration that was sent in the wrong unit. The
mistake is silent otherwise: a cancellationWindow of 2 is two seconds, not two days.
updateBookingPolicy(id, input) takes the same fields, all optional, and bumps version, even for a
rename, so a product’s policySnapshot.version behind the policy’s does not prove the terms differ.
bookingPolicies(first:) returns a connection (edges { node { … } }), not a list.
bookingPolicy(id:) reads one. BookingPolicy.stats.referencingProductCount says how many products use
it, and deleteBookingPolicy refuses with BookingPolicyInUseError while that count is above zero.
The pool
setBookable attaches a policy and says what can be booked. One product, one pool, and every SKU of the
product draws on it. language is required, but the pool is not per language: every language of the
product shares it, so set it and reapply it once per product. Mass operations have no intent for this:
it is one setBookable per product.
mutation SetBookable($id: String!, $language: String!, $input: GraphqlBookableInputInput!) { setBookable(id: $id, language: $language, input: $input) { __typename ... on BasicError { errorName message } }}Two kinds, and a product has exactly one of them:
{ "input": { "policyId": "6ab3…", "units": [{ "id": "GAS55-OSL-1", "meta": [{ "key": "depot", "value": "osl" }] }] } }{ "input": { "policyId": "6ab3…", "capacity": 8 } }| Pool | Use it for | What the shopper books |
|---|---|---|
units |
Real, distinguishable things: machine 1, room A, instructor Ada | One named unit, by unitId |
capacity |
Interchangeable seats: 8 places on a course, 20 bikes in a pile | One of N, no identity |
A unit’s meta is where its identity lives. Depot, serial number, running hours, last service — the
storefront reads it back from Discovery and can show “the machine in Oslo”. There is no other place to
put it.
A capacity pool counts every booking that overlaps the window, not the busiest moment. With capacity
6 and 4 seats booked on each of seven nights in a row, a 7-night request is refused with
ReservationConflict although 2 seats are free every night, and availability undercounts the same way.
It never oversells, and it is exact when bookings share one window, like a class at 09:00. When windows
vary in length, use units, even for things nobody tells apart.
Do not rename or remove a unit that holds live reservations. They keep the old id and still hold
their window. While one does, every pin on that window is refused with ReservationConflict and
freeUnitIds is empty even when free is not. A cart pinned to a unit that left the published pool fails
at place with UnitNoLongerInPool. Add the new id, publish, move the reservations with assignUnit (see
booking-admin), and only then drop the old id.
Units → capacity is allowed. Capacity → units answers BookablePoolKindChangeError while the
published pool is a capacity pool, because capacity-era reservations carry no unit. Clear it with
clearBookable, publish that, cancel or wait out the open reservations, then set the units.
clearBookable(id, language) removes the pool, but only from the draft: the Shop keeps taking bookings
until the product is published again. Unpublish to stop bookings at once. bookableProducts lists
products with a published bookable configuration only. A product configured but never published
is not in it. bookableProducts(filter: { policyId: "…" }) is how to find the products to reapply; each
node has productId, poolSize, policySnapshot and product(language:).
The snapshot
setBookable stamps the policy onto the product as a policySnapshot with its version, on every call,
so a pool edit also takes the policy’s current terms:
{ item(id: "6ab3…", language: "en") { ... on Product { bookable { policyId poolSize policySnapshot { version cancellationWindow } pool { __typename ... on BookableUnitPool { units { id meta { key value } } } ... on BookableCapacityPool { capacity } } } } }}Editing a policy does not reach the products that use it. They keep their snapshot until
reapplyBookablePolicy(id, language) runs on each one. It re-freezes the policy’s current terms and
leaves the pool untouched, so do not re-run setBookable for this. Change the window, reapply, check
the product’s policySnapshot, then publish. Until the publish, the Shop still books under the old
terms. This is the step that makes “we changed the cancellation window and nothing happened” go away.
Reservations already taken keep the terms they were admitted under. A policy edit never changes a booking a shopper already holds.
Product.bookable on the Core API always shows the draft, whatever versionLabel you ask for. A bookable
edit creates no item version either, so read bookableHasUnpublishedChanges on the product to see whether
a publish is still owed. bookableProducts, the Catalogue API and Discovery show what the Shop serves.
Publish
The Shop reads the published bookable configuration only. A bookable product that is not
published answers NotBookable on every Shop API call. setBookable, reapplyBookablePolicy and
clearBookable all write to the draft, so each one needs a publish before the Shop sees it. Publish per
item and language with publishItem. See [[mutation]]. The publish of any one language promotes the
shared pool, but the Shop reads the product per language, so publish every language you sell in.
publishItem only queues the work: the Shop sees the change a moment after it answers.
Crystallize AI