Orders
Carts for anonymous and signed-in shoppers, a checkout that prices from the catalog, quotes tax, reserves stock and takes the payment once, then fulfillments, returns, refunds and invoices.
orders turns catalog variants into orders. A cart
belongs to the signed-in user, which can be an anonymous Supabase user, so a
shopper can fill one before creating an account. Checkout prices the cart
from the catalog, quotes tax through a TaxProvider, places the order with
a number from numbering, reserves its stock when
inventory is installed, and creates the payment
through a PaymentProvider with an idempotency key. After the sale it
records fulfillments, returns, refunds and the invoice.
better-supabase add ordersServer code calls the orders instance on db, in the caller's organization. With gen.hooks set, better-supabase gen writes the hooks:
export const { useList: useOrders } = defineDataHooks(
"orders",
(db: AppDb) => db.orders,
);const rows = await db.orders.list({ limit: 50 }).orThrow();"use client";
import { useOrders } from "@/lib/supabase/hooks";
const rows = useOrders({ limit: 50 });The module needs tenant, permissions and catalog. It uses inventory for
reservations and stock movements, promotions for discount codes,
numbering for order and invoice numbers, state-machine for the
status column, and outbox for events, each when it is installed. The
providers are described on the commerce page; both
are optional, and without payments only free orders can be placed.
Permissions
| Key | What it allows |
|---|---|
orders.read | Read every cart and order in the organization |
orders.manage | Shipping rates, fulfillments, returns, refunds, cancelling orders and stations |
orders.prepare | Send orders to the kitchen and move their lines through the preparation states |
orders.override_credit | Place an order or issue a sales invoice over the customer's credit limit |
Shoppers need neither key: a user reads and edits their own carts and reads
their own orders. Placing an order, recording a payment, merging carts and
expiring orders are service-only, so pass a service transport as above.
Carts
await supabase.auth.signInAnonymously();
const cart = await orders
.createCart(organizationId, { currency: "EUR" })
.orThrow();
await orders.addToCart(cart.id, variantId, 2).orThrow();
await orders.setCartLine(cart.id, variantId, 1).orThrow(); // 0 removes the line
await orders
.setCartDetails(cart.id, {
email: "ada@example.com",
shippingAddress: {
line1: "Damrak 1",
city: "Amsterdam",
postalCode: "1012 LG",
country: "NL",
},
})
.orThrow();
const priced = await orders.priceCart(cart.id).orThrow();
// { lines, subtotal, discountTotal, shippingTotal, total, problems }createCart returns the caller's open cart for the organization and
currency, and creates one when there is none. Only variants of active
products can be added (ORDERS_VARIANT_UNAVAILABLE). priceCart reads
today's catalog price for each line; a line whose price changed carries
previousUnitAmount, and problems lists what keeps the cart from checkout
(an unavailable or unpriced line, a missing shipping rate or address).
When an anonymous shopper signs in to an existing account, Supabase gives them a different user id. Move their carts on the server:
await orders.mergeCarts(anonymousUserId, signedInUserId).orThrow();Lines for the same variant add up, and the cart's promotion codes move
with them. Linking an identity to the anonymous user
(supabase.auth.linkIdentity) keeps the id, so it needs no merge.
The invoice that checkout creates is titled options.titleTemplate (default Order {number}).
Shipping
await orders
.saveShippingRate(organizationId, {
name: "Standard",
countries: ["NL", "BE"],
amount: money(495n, "EUR"),
freeOver: money(5000n, "EUR"),
})
.orThrow();
const options = await orders.shippingOptions(cart.id).orThrow();
await orders.setShippingRate(cart.id, options[0].id).orThrow();A flat rate charges amount; a weight rate adds amountPerKg for each
started kilogram of the variants' weights. freeOver makes the rate free once
the discounted subtotal reaches it. A cart with only digital variants needs
no rate.
Checkout
const { order, payment } = await orders
.checkout(cart.id, { returnUrl: "https://shop.example.com/thanks" })
.orThrow();
// Hand payment.clientSecret to the browser to confirm the payment.checkout prices the cart, quotes tax for its lines and shipping, and
places the order in one transaction with the quote's total. If a price
changed in between, it fails with ORDERS_PRICE_CHANGED and the shopper
sees the new total. Placing converts the cart, assigns the order number
(SO-0001 from the order sequence when one is configured), copies each
line's SKU, title and price, redeems the cart's promotions and reserves the
stock at locationId, or at the location with the most available.
The order starts as pending_payment and holds its stock for 30 minutes
(the paymentWindowMinutes module option). The payment is created with the
idempotency key order:<id>:payment, so calling checkout again for the
same cart returns the same order and the same payment. A free order is paid
at once.
With the contacts block installed, placing an order
checks the credit limit contacts keeps on the shopper's person: what they
still owe on open orders in the cart's currency, plus the new total, can't
exceed credit_limit when credit_currency is that currency. Over the limit,
placing fails with ORDER_CREDIT_LIMIT_EXCEEDED, unless the shopper holds
orders.override_credit.
With the invoices block installed, the payment that
marks an order paid also creates its invoice: one line per order line (the
title and quantity, the net amount and the tax rate it was charged), a
shipping line, issued today and paid in full by the order's payment. The
order's invoice number is that invoice's identifier, and record_payment
returns its invoiceId.
Payment events
Route the provider's webhook to orders.webhook. It verifies the delivery,
then applies each payment and refund event:
export async function POST(request: Request) {
const outcomes = await orders.webhook(request).orThrow();
return Response.json({ handled: outcomes.length });
}When the captured amount reaches the total, the order becomes paid: its
reservations turn into sale movements, it gets an invoice number
(INV-00001 from the invoice sequence) and the sale is committed to the
tax provider. A failed commit is logged; retry it with commitTax(orderId).
With capture: "manual" the funds are held until orders.capture(orderId).
cancelOrder(orderId) cancels an unpaid order, releases its stock and its
open payments. Schedule orders.job to cancel orders whose payment window
passed:
await jobs.schedule("orders:expire", "*/5 * * * *", "orders.expire", {});After the sale
const shipment = await orders
.createFulfillment(order.id, { carrier: "PostNL" }) // every unit not fulfilled yet
.orThrow();
await orders
.shipFulfillment(shipment.id, { trackingNumber: "3SABC123" })
.orThrow();
await orders.deliverFulfillment(shipment.id).orThrow();
const ret = await orders
.requestReturn(order.id, [{ lineId, quantity: 1 }], "too small")
.orThrow();
await orders.receiveReturn(ret.id).orThrow(); // restocks tracked variants
await orders
.refund(order.id, { amount: money(2420n, "EUR"), returnId: ret.id })
.orThrow();
// { status: "succeeded", orderStatus: "paid", refundedTotal, taxReversal }
const invoice = await orders.invoice(order.id).orThrow();
// { number: "INV-00001", issuedAt, order }An order becomes fulfilled when every unit is in a fulfillment and
completed when they are all delivered. refund defaults to everything
paid and not refunded yet, refunds through the provider with the key
refund:<id>, and reverses the refunded share of each line's tax. Refunding
the whole total moves the order to refunded.
| Status | Next |
|---|---|
pending_payment | paid, cancelled |
confirmed | paid, fulfilled, cancelled |
paid | fulfilled, refunded |
fulfilled | paid (a cancelled fulfillment), completed, refunded |
completed | refunded |
To change these rules, register a state machine
on the orders status column; the module then leaves the check to it.
Orders from documents
Staff enter phone and wholesale orders, and other blocks turn their records into orders, without a cart:
const { order, created } = await orders
.fromLines(organizationId, {
currency: "EUR",
lines: [
{ variantId, quantity: 2 },
{ title: "Setup", quantity: 1, unitAmount: money(5000n, "EUR") },
],
email: "buyer@example.com",
locationId: warehouse.id,
origin: { type: "work_order", id: workOrder.id },
})
.orThrow();
// order.status === "confirmed"; created is false when the origin already had an order
const fromQuote = await orders.fromQuote(quote.id).orThrow();Both make a confirmed order: it is due, and it can be fulfilled before it
is paid. A line with a variantId takes the variant's price, title and SKU
unless you pass them, and with the inventory block
each line that ships allocates its stock at locationId (the first location
with stock by default), backordering what isn't there. A fulfillment ships
from the allocation, and cancelling the order releases it. Line quantities
are whole units unless you set options.quantityScale; see
Staff order fields.
fromQuote needs the quotes block and an accepted
quote (ORDERS_QUOTE_NOT_ACCEPTED). It copies the counted lines and the
quote's totals, and orders a quote once. A quote line counts as a variant
line when its product is a product_variant. A line with a fractional
quantity can't be ordered (ORDERS_QUANTITY_INVALID).
orderFromQuoteAction from better-supabase/blocks/orders is the quotes
conversion action: without a create, it calls orders.fromQuote on the
orders client in the action's clients.
Drafts and holds
Pass draft: true to fromLines or fromQuote to save the order as a
draft. A draft holds no stock, has no payment window and records
order.drafted instead of order.placed, so staff can prepare it. An
origin or a quote still orders once. confirmDraft
allocates its stock at locationId (the first location with stock by
default), moves it to confirmed and records order.placed.
cancelOrder cancels a draft that was never confirmed.
const { order } = await orders
.fromLines(organizationId, { currency: "EUR", lines, draft: true })
.orThrow();
await orders.confirmDraft(order.id, { locationId: warehouse.id }).orThrow();hold puts an order that waits for payment, or a confirmed one, on hold
with an optional reason. A held order has the status on_hold: it can't be
fulfilled and it doesn't expire, and it keeps its stock. releaseHold moves
it back to the status it was held from. A paid order can't be held; refund
it instead. A payment that arrives while an order is on hold is stored, and
the order becomes paid only after you release the hold and the payment is
recorded again.
await orders
.hold(order.id, { reason: "Waiting for credit approval" })
.orThrow();
await orders.releaseHold(order.id).orThrow();The orders table gains held_at, held_from and hold_reason columns, and
order.heldAt and order.holdReason carry them. Both calls need
orders.manage.
Drop ship
With the inventory block installed,
purchaseOrderFromOrder drafts a purchase order for an order's catalog lines,
which the supplier ships straight to the customer:
const { id } = await orders
.purchaseOrderFromOrder(order.id, { type: "company", id: supplierId })
.orThrow();
await db.inventory.placePurchaseOrder(id).orThrow();The purchase order's ship_to is the order's shipping address, and it
records the order as its origin. Its location is the one the order's lines
were reserved at, or the first active location, unless you pass locationId.
Each line costs the variant's average cost in the order's currency, or 0
without one, so edit the draft before placing it. Saving the draft needs
inventory.purchase, and a blocked supplier fails with
PURCHASE_ORDER_SUPPLIER_BLOCKED.
Staff order fields
fromLines and fromQuote take the fields a back office records on an
order (ADR 1224), and every order read returns them:
const { order, created } = await orders
.fromLines(organizationId, {
currency: "EUR",
lines: [
{
title: "Consulting",
quantity: 1.5,
unit: "h",
lineType: "service",
unitAmount: money(9000n, "EUR"),
},
{
variantId,
quantity: 2,
description: "Gift wrapped",
fields: { giftNote: "Happy birthday" },
},
],
channel: "phone",
source: "legacy_erp",
externalId: "SO-10442",
orderDiscount: money(500n, "EUR"),
paymentRequired: true,
deposit: money(2000n, "EUR"),
party: { type: "company", id: companyId },
})
.orThrow();| Field | What it does |
|---|---|
channel | A lowercase slug such as phone or b2b; a list filter and facet |
source, externalId | The order's id in another system, unique per organization and source; a repeat returns the first order with created: false |
invoicingPolicy | on_order (default) or on_delivery, for the invoicing code you write |
deliveryMethod | Free text, such as pickup |
quoteId | Set by fromQuote |
orderDiscount | Off the net subtotal after the line discounts, and included in discountTotal |
promotionId | The promotion that gave the discount |
paymentRequired, deposit | createFulfillment refuses with ORDERS_PAYMENT_REQUIRED until the deposit, or the total without one, is paid |
party | The contact or company the order is for, next to customerId |
A line takes unit, description, lineType (item, service or fee,
default item) and fields, the values of the columns your schema files add
to order_lines. options.quantityScale (0 to 6, default 0) sets how many
decimals a quantity may have: with 2, a line of 1.5 hours is valid, and the
line's money is the unit price times the quantity, rounded to a minor unit.
Quantities are numeric in the database and number in TypeScript.
| Hint | Cause |
|---|---|
ORDERS_SOURCE_REQUIRED | externalId without source |
ORDERS_AMOUNT_INVALID | a negative orderDiscount or deposit, or a discount over the subtotal |
ORDERS_PARTY_INVALID | a party without a type or id |
ORDERS_QUANTITY_INVALID | more decimals than quantityScale, or zero and below |
ORDERS_PAYMENT_REQUIRED | a fulfillment before the required payment |
Paging orders
orderPage pages the caller's orders by keyset (ADR 1077) from the SQL
function page_orders, which runs as the caller, so row security decides
which orders appear. Sorts are placedAt (the default, newest first),
number and total. status, customerId, partyId, channel, source
and currency filter, from and to bound the placed time, and q
searches the number, the email and the external id. The facets are status,
currency and channel. orderFacets and orderCount answer under the same
filters.
const page = await db.orders
.orderPage({
organizationId,
filters: { channel: ["phone"], status: ["confirmed"] },
q: "SO-104",
})
.orThrow();
const byChannel = await db.orders
.orderFacets({ organizationId, facets: ["channel"] })
.orThrow();A cursor belongs to the sort it came from. Block lists describes the options every block list shares.
Discount matrix
With options.discountMatrix: true and the catalog block installed, an order made from lines (order_from_lines) prices each line that names a catalog variant through the discount matrix for attrs.customerId. A line without a discount takes the rule's discount on its subtotal, and a line without a unitAmount takes the rule's fixed price before the catalog price. Values on the line win. The option is off by default.
Kitchen
With options.kitchen, each order line gets a preparation state at a
station, for a kitchen display and an order board. The option is off by
default and adds three tables: order_kitchen_stations, order_kitchen_routes (which
station prepares a product) and order_line_preparations.
export default defineConfig({
blocks: { orders: { options: { kitchen: true } } },
});const grill = await orders.kitchen
.saveStation(organizationId, {
key: "grill",
name: "Grill",
default: true,
productIds: [burgerId],
})
.orThrow();
await orders.kitchen.send(orderId, { [lineId]: "no onions" }).orThrow();
const tickets = await orders.kitchen
.queue(organizationId, { stationId: grill.id })
.orThrow();
// [{ orderId, number, sentAt, lines: [{ lineId, title, quantity, state, note }] }]
await orders.kitchen.setState(lineId, "preparing").orThrow();
await orders.kitchen.bump(orderId, "ready", grill.id).orThrow(); // every line at the grill
const cards = await orders.kitchen.board(organizationId).orThrow();
// [{ orderId, number, state, counts: { queued, preparing, ready, served } }]send queues each line of a paid or placed order at the station its product
is routed to, or at the default station, and skips lines already sent, so
calling it again is safe. A cancelled or refunded order can't be sent
(ORDERS_KITCHEN_CLOSED). A line moves through queued, preparing,
ready and served; setState can also move it back, which clears the
later timestamps. bump moves every line of the order (or of one station)
up to a state and leaves lines that are further along. The board shows the
orders sent since a day ago by the state of their least advanced line.
Each change broadcasts a preparation message with { lineId, orderId, stationId, state } on the private Realtime topic kitchen:<organizationId>,
which members with orders.read or orders.prepare can receive. The
KITCHEN_EVENT and kitchenTopic(organizationId) exports name them:
const kitchen = defineTopic("kitchen:{organizationId}");
useBroadcast(
kitchen,
{ organizationId },
{ [KITCHEN_EVENT]: () => router.refresh() },
);The kitchen display and order state board recipes build both screens from this API.
Events
| Event | When |
|---|---|
order.placed | checkout places the order, or a draft is confirmed |
order.paid | The captured amount reaches the total |
order.cancelled | cancelOrder or an expired payment window |
order.drafted | A draft order is saved |
order.hold_placed, order.hold_released | hold, releaseHold |
order.fulfilled, order.completed | Every unit is fulfilled, then delivered |
order.refunded | A refund succeeds |
fulfillment.shipped, fulfillment.delivered | A fulfillment step |
return.requested, return.received | A return step |
order.prepared | Every kitchen line is ready or served |
order.served | Every kitchen line is served |
They are subject events on the order subject (organizationId,
subjectType and subjectId), so the
watcher sink can notify an order's
watchers. The payloads are listed on the events
page.
Metrics
orderMetrics({ currency }) defines three metrics over the orders table: orders counts placed orders by placed_at, and revenue and average_order_value sum and average the total of paid orders in that currency by paid_at, in minor units. ORDER_METRIC_EVENTS maps order.placed and order.paid to them for the metrics sink.
import {
ORDER_METRIC_EVENTS,
orderMetrics,
} from "better-supabase/blocks/orders";
const metrics = orderMetrics({ currency: "EUR", tz: "Europe/Amsterdam" });
const app = createBlocks(
{ transport: service },
{
metrics: metricsBlock
.with({ sink: { on: ORDER_METRIC_EVENTS } })
.using((options) => createMetrics({ ...options, metrics })),
},
);Pass the same definitions to blocks.metrics.options.metrics. The commerce preset page adds units sold from the order lines.
Your own fields
Columns you add to orders with alter table in your own schema files are fields of the block (details). checkout writes them when it places the order from fields,
and checkout, getOrder, capture and invoice return them in fields. Pass a Standard Schema as fields
to type them: writes are validated before they reach the database (a
validation error), and reads are parsed. hooks refuses, rewrites or
observes any method; see extending blocks.
alter table "better_supabase"."orders" add column "register" text;const client = createOrders({
transport,
fields: v.object({ register: v.optional(v.picklist(["front", "back"])) }),
});
await client.checkout(cartId, { fields: { register: "front" } });Hooks
The SQL module calls before_order_place, after_order_place,
before_fulfillment_create, after_fulfillment_create,
before_refund_create and after_refund_create when you define them (see
blocks). The TypeScript client takes hooks keyed
by method name.
Not included
Orders doesn't export e-invoices (EN 16931), issue credit notes, sell subscriptions or license keys for digital goods, or handle B2B quotes and purchase orders from customers.
Over your own tables
Carts, cart lines, shipping rates, orders, order lines, payments,
fulfillments, returns and refunds can be tables your app already has (see
Over your own tables); the fulfillment
and return lines and the kitchen tables stay the block's own. The cart and
order email and billingAddress, the shipping rate freeOver, the order
cancelReason and taxTransaction, the fulfillment trackingUrl and the
return and refund reason may map to null. A call that sets one of them
then fails with an ORDERS_<COLUMN>_UNSUPPORTED hint, and reads return
null. Status columns may be enums or domains: the block casts what it
writes to the column's type.
Without the client
db.orders is this client. Code that does not go through bsb.db() builds it with a transport and an organization id:
import { fixedRates, stripePayments } from "better-supabase/commerce";
import { createOrders, sqlTransport } from "better-supabase/blocks/orders";
export const orders = createOrders({
transport: sqlTransport(ctx.postgres),
service: sqlTransport(servicePostgres),
payments: stripePayments({
stripe: { secretKey: env.STRIPE_SECRET_KEY },
webhookSecret: env.STRIPE_WEBHOOK_SECRET,
}),
tax: fixedRates({ rates: { NL: { standard: "0.21" } } }),
});Historical orders
import_order writes an order with its number, dates, final status, buyer
and totals as given, with free-text and variant lines, and no stock
movement. See importing historical documents.
Variants
Orders can be grouped as variants, for example a quoted order in two versions. setVariant(orderId, variantOf, label) puts an order into the group of another order (the first order of the group) and labels it, or takes it out of its group with null. A new member starts not selected. selectVariant(orderId) marks one order selected and the others not selected, and listVariants(orderId) returns the group. Invoicing accepts only the selected order of a group.
await bsb.orders.setVariant(second.id, first.id, "Wide format").orThrow();
await bsb.orders.selectVariant(second.id).orThrow();The SQL functions are set_order_variant, select_order_variant and list_order_variants.
| Hint | Cause |
|---|---|
ORDER_NOT_FOUND | no such order, or no order to group with |
ORDER_VARIANT_INVALID | different currencies, or the target isn't the group's first order |
ORDER_VARIANT_NOT_SELECTABLE | a cancelled or refunded order can't be selected |
Order helpers
markPaid({ orderId, reference }) records a manual payment for the full total and runs the after-payment step. returnAndRefund({ orderId, lines, reason, restock, locationId, amount }) requests the return, receives it and refunds, and returns { returnId, refund }. fulfilAll({ orderId, locationId, tracking }) creates a fulfilment for every open line and ships it when you pass tracking. Each helper stops at the first failing step and returns that error.
Orders by status
board({ organizationId, perStatus }) returns the orders page in one call from the SQL function order_status_board. Each column holds a status, its count, its totals per currency (total and paid, as text) and the latest perStatus orders (default 20). Columns follow the order lifecycle, from pending_payment to refunded. The function runs as the caller, so row security decides which orders appear.
const { columns } = await db.orders.board({ organizationId }).orThrow();
const open = columns.find((column) => column.status === "paid");Last updated on
Tax
Tax codes per organization and legal entity with dated rates, the tax of a document per code (margin scheme and credit restriction included), tax lines written when an invoice is issued, tax returns with box totals, and the intra-EU sales list per customer VAT number.
Promotions
Percentage, fixed and free-shipping promotions that apply automatically or by code, with usage limits, stacking rules and priorities, priced into orders carts and redeemed at checkout.