Inventory
Stock per catalog variant and location on the ledger block, in whole or fractional units, with lots, serials, expiry, bins, average cost, reservations, allocations with backorders, transfers, purchase requisitions, and purchase orders with their receipts.
inventory counts the stock of catalog variants at
each location. Every change is a transaction on the
ledger: each variant and location has a stock account,
and a movement posts against a counter account (suppliers, customers,
adjustments or in transit). One level row per variant and location keeps
on-hand, reserved, incoming, and available (on-hand minus reserved) in step
with it. On top of the ledger it adds reservations that expire, transfers
between locations, and purchase orders that you receive in parts.
better-supabase add inventoryimport { createInventory } from "better-supabase/blocks/inventory";
import { money } from "better-supabase/commerce";The module needs tenant, permissions and catalog, and emits events when
outbox is installed.
Permissions
| Key | What it allows |
|---|---|
inventory.read | Read locations, levels, movements and the other tables |
inventory.manage | Locations, adjustments, counts, reorder points, transfers |
inventory.reserve | Reserve, commit and release stock |
inventory.purchase | Create, place, receive and cancel purchase orders; decide requisitions |
The owner role holds *. Give the other roles the keys they need:
roles: {
admin: ["catalog.*", "inventory.*", "members.*"],
warehouse: ["catalog.read", "inventory.read", "inventory.manage", "inventory.purchase"],
member: ["catalog.read", "inventory.read"],
},Checkout code that runs as the customer usually reserves through a service
transport instead of granting inventory.reserve to every member.
Paging stock
Six lists follow the block list contract (ADR 1077) and take organizationId:
| Method | Rows | Sorts | Filters | q searches |
|---|---|---|---|---|
levelPage, levelFacets, levelCount, getLevel | stock per variant and location | available (default), onHand, variantId | status (in_stock, low, out), variantId, locationId | a variant or location id |
movementPage, movementFacets, movementCount, getMovement | stock.* ledger movements, newest first | effectiveAt (default), quantity | kind, variantId, productId, locationId, binId, lotId, documentType, documentId | the kind and the document id |
lotPage, lotFacets, lotCount, getLot | lots that hold stock, per location and bin | expiresOn (default), onHand, code | expiry (expired, soon, later, none), variantId, locationId | the lot code |
locationPage, locationFacets, locationCount | stock locations | code (default), name | kind (warehouse, store, virtual), active (true, false) | the code and the name |
binPage, binFacets, binCount | bins (with lots and bins enabled) | code | locationId, active, hold | the code and the name |
variantPage, variantCount | the catalog variants stock is kept for | sku (default), title | productId | the SKU and the title |
Every filter is a list of values and a row matches any of them. A movement row carries the variant's productId, the unit (null for the variant's default unit), the reason, the ledger note and the actorId who posted it. Quantities stay text. Every *Page pages by keyset through after, or by number through offset (the two do not combine), and total: true adds total and totalCapped to the page. A soon lot expires within 30 days. The location, bin and variant lists are lookups for a page that names or selects them, so active, hold take ["true"] or ["false"], and row level security decides which rows come back. variantFacets returns an empty list because variants declare no facets. The block holds no product titles, so a search by product name resolves the variants in the catalog first and passes them as variantId.
const low = await inventory
.levelPage({ organizationId, filters: { status: ["low", "out"] }, limit: 50 })
.orThrow();
const expiring = await inventory
.lotPage({ organizationId, filters: { expiry: ["expired", "soon"] } })
.orThrow();
const places = await inventory
.locationPage({ organizationId, q: "main", filters: { active: ["true"] } })
.orThrow();levels and movements keep working and are deprecated. A cursor belongs to the sort it came from, so start again from the first page when sort changes. A sort, filter, facet or text the entity does not declare returns an invalid_input error. Block lists describes the options every block list shares.
Locations
Server code calls the inventory instance on db, in the caller's organization. With gen.hooks set, better-supabase gen writes the hooks:
export const { useList: useInventory } = defineDataHooks(
"inventory",
(db: AppDb) => db.inventory,
);const warehouse = await db.inventory
.saveLocation(organizationId, { code: "WH-AMS", name: "Amsterdam" })
.orThrow();"use client";
import { useInventory } from "@/lib/supabase/hooks";
const rows = useInventory({ limit: 50 });kind is warehouse (the default), store or virtual. Codes are unique
per organization. setLocationActive(id, false) stops new reservations and
transfers at a location, and a location with stock history can't be deleted
(INVENTORY_LOCATION_IN_USE).
Location address
setLocationAddress stores where a location is, for shipping labels and
customs documents:
await db.inventory
.setLocationAddress(warehouse.id, {
line1: "Dam 1",
postalCode: "1012 JS",
city: "Amsterdam",
country: "NL",
})
.orThrow();The keys are line1, line2, postalCode, city, region and country,
all text, and country is a two-letter ISO 3166 code in capitals. Any other
key or a bad country fails with INVENTORY_ADDRESS_INVALID. Passing null
clears the address. Locations at the assets block keep their own columns, so
the address column exists only on inventory's own locations table.
Stock at the assets locations
With the assets block installed, turn the
inventory_locations table off and stock lives at the assets block's
locations instead of a second copy:
// better-supabase.config.ts
blocks: {
assets: {},
inventory: { tables: { locations: null } },
},Levels, movements, reservations, transfers, purchase orders, checkout in
orders and work order parts in dispatch then reference asset_locations.
An archived asset location is an inactive stock location, so
setLocationActive(id, false) archives it.
Your own fields
Columns you add to inventory_locations with alter table in your own schema files are fields of the block (details):,
keyed by column name with their SQL type. saveLocation writes them from fields and returns them under fields; a location you save without fields keeps its values. Pass a
Standard Schema as fields to type them,
parse them on reads and validate them on writes; a bad value is a
validation error before anything reaches the database (see
extending blocks):
import { z } from "zod";
const inventory = createInventory({
transport,
fields: z.object({ region: z.enum(["emea", "amer", "apac"]) }),
});
await inventory.saveLocation(organizationId, {
code: "WH-AMS",
name: "Amsterdam",
fields: { region: "emea" },
});The ledger
await inventory.adjustStock(variantId, warehouse.id, 40, "receipt").orThrow();
await inventory
.adjustStock(variantId, warehouse.id, -2, "damage", "dropped")
.orThrow();
// { movementId, onHand: 38, available: 38 }
await inventory
.countStock(variantId, warehouse.id, 36, "cycle count")
.orThrow();
// { movementId, delta: -2, onHand: 36 }adjustStock takes adjustment, damage, loss, return or receipt.
The other movement reasons (count, sale, transfer_out, transfer_in,
and the manufacturing block's consumption and
production) come from the functions that write them. A movement is a ledger transaction
of kind stock.<reason>, and movementId is its id. Ledger entries can't be
updated; a correction is a new movement. Read a variant's history with the
ledger client's entries(accountId) on its stock accounts (kind: "stock",
managedBy: "inventory").
When the catalog variant has trackInventory on and allowBackorder off,
the ledger refuses a movement that would take on-hand below zero, or take
available below zero for a sale or a transfer (INVENTORY_INSUFFICIENT). A
variant with allowBackorder can go negative.
setReorderPoint(variantId, locationId, 10) stores a threshold. When
available stock drops to it or below, the module emits
stock.reorder_point_reached, once per crossing.
setReorderQuantity({ variantId, locationId, reorderQuantity }) stores how much
to order when stock reaches that point (null clears it) in
stock_levels.reorder_quantity, so a reorder job reads both numbers from the
base table. It needs inventory.manage.
A catalog variant or product with stock history can't be deleted
(CATALOG_VARIANT_IN_USE, CATALOG_PRODUCT_IN_USE); archive it instead.
Reservations
const hold = await inventory
.reserve(variantId, warehouse.id, {
quantity: 2,
referenceType: "cart",
referenceId: cartId,
})
.orThrow();
// { id, expiresAt, available }
await inventory.commitReservation(hold.id).orThrow(); // writes a `sale` movement
await inventory.releaseReservation(hold.id).orThrow(); // false once closedA reservation holds stock until it is committed, released or expires, 15
minutes from now by default (expiresAt sets another instant in the future).
A strict variant can't reserve more than is available. Committing an expired
hold fails with INVENTORY_RESERVATION_EXPIRED.
Expired holds stop counting the next time someone reserves the same variant
at the same location. To release the rest, run expireReservations from a
scheduled job. It is a service-only function, so pass a service transport:
export const inventory = createInventory({
transport: sqlTransport(ctx.postgres),
service: sqlTransport(servicePostgres),
});await jobs.schedule("inventory:expire", "*/5 * * * *", "inventory.expire", {});
export const GET = jobs.drainRoute({
secret: process.env.CRON_SECRET,
handlers: { "inventory.expire": inventory.job },
});inventory.job reads an optional maxRows from the payload.
Units, lots and bins
A variant counts whole items until you give it a stock item. Set it before
the variant has stock (INVENTORY_ITEM_LOCKED after):
await inventory
.setStockItem(variantId, {
unit: "kg",
scale: 3,
tracking: "lot",
tracksExpiry: true,
costing: "average",
currency: "EUR",
})
.orThrow();
const quarantine = await inventory
.saveBin(warehouse.id, { code: "HOLD", name: "Quarantine", hold: true })
.orThrow();
await inventory
.adjustStock(variantId, warehouse.id, 10.5, "receipt", "first delivery", {
lot: { code: "L-0412", expiresOn: "2027-02-01" },
})
.orThrow();
await inventory.stockDetail(variantId, warehouse.id).orThrow();
// { onHand: 10.5, held: 0, available: 10.5, buckets: [{ lotCode: "L-0412", expiresOn: "2027-02-01", onHand: 10.5, ... }] }Quantities are numeric(20, 6), and scale (0 to 6) sets how many decimals
a variant's quantity may have (INVENTORY_QUANTITY_PRECISION past it). The
ledger keeps whole numbers: a movement posts the quantity times ten to the
scale, so 1.250 kg at scale 3 posts 1250 on an account whose code ends in
:kg:3.
Every movement takes a detail with binId, lotId or lot (a code, and
an expiry date to create it) and serials. A variant tracked by lot needs
a lot on every receipt; one tracked by serial needs one serial number per
unit, and a serial can't be in stock twice. Without a bin or lot, stock leaves
first-expiry-first-out: the lot that expires first, then the stock outside any
lot. A sale or a transfer out skips hold bins and expired lots, and stock in a
hold bin counts as held, so available is on hand minus reserved minus held.
pickSerials({ variantId, locationId, quantity, lotId? }) returns the serial
numbers to take for a pick, the oldest in stock first, from one lot when you
pass lotId. It changes nothing: pass the result in the detail of
adjustStock. It fails with INVENTORY_INSUFFICIENT when fewer serials are in
stock, and replaces app SQL that chose serials by hand.
expiringLots(organizationId, "2027-03-01") lists the lots with stock that
expire before a date. expireLots(organizationId) is a service function that
scraps the stock of lots that have expired, as expired movements.
Average cost
With costing: "average", a receipt carries its cost, and the stock's value
moves into the variant's value account on the same ledger transaction. A
purchase order receipt takes its line's unitCost. The average cost is
recomputed on each receipt, and a sale moves its value out to cost of goods
sold:
await inventory.stockValuation(variantId).orThrow();
// { costing: "average", averageCost: "200.000000", onHand: 10.5, value: money(2100n, "EUR"), ... }In the books
With the accounting block installed, a movement of an item with average cost books its value in the general journal: a receipt against payable, a sale or return against cost of goods sold, and an adjustment against expense. Transfers and items without costing book nothing.
Allocations
An allocation holds stock for a document line, such as an order or a work order, for as long as the document needs it. What isn't available waits on backorder, and every movement that adds stock fills open backorders, oldest first:
const allocation = await inventory
.allocate(organizationId, {
variantId,
locationId: warehouse.id,
quantity: 12,
documentType: "work_order",
documentId: workOrder.id,
lineId: "line-1",
})
.orThrow();
// { allocated: 10.5, backordered: 1.5, status: "open", ... }
await inventory.fulfillAllocation(allocation.id, 10).orThrow(); // a `sale` movement
await inventory.restoreAllocation(allocation.id, 1).orThrow(); // a `return` movement
await inventory
.releaseAllocations(organizationId, "work_order", workOrder.id)
.orThrow();releaseAllocation({ allocationId, quantity? }) releases one open allocation, and
transferAllocation({ allocationId, documentType, documentId, lineId?, quantity? }) moves
it to another document (such as a quote that became an order) and keeps what it
holds. They call the SQL functions release_allocation(allocation, quantity) and
transfer_allocation(allocation, document_type, document_id, line_id, quantity).
Without a quantity, or with all that is left, they act on the whole allocation. A smaller
quantity on a release lowers the allocation, freeing backorder first and then held stock. A smaller
quantity on a transfer splits the allocation: held stock moves first into a new allocation on the
new document, and the call resolves to that new allocation. A quantity of zero or above what is left
fails with INVENTORY_QUANTITY_INVALID. Both
fail with INVENTORY_ALLOCATION_CLOSED for an allocation that is no longer open
and with INVENTORY_ALLOCATION_NOT_FOUND for an unknown one. A release frees the
stock for waiting backorders and records allocation.released; a move records
allocation.transferred, with the old document in documentType and
documentId and the new one in toDocumentType and toDocumentId. They
replace app SQL that updated stock_allocations rows.
Pass backorder: false to refuse what isn't available
(INVENTORY_INSUFFICIENT). Orders allocate their lines themselves (see
orders from documents), sent
quotes hold theirs with holds, and
shipment lines ship from them.
Transfers
const transfer = await inventory
.createTransfer(organizationId, {
fromLocationId: warehouse.id,
toLocationId: store.id,
lines: [{ variantId, quantity: 5 }],
})
.orThrow();
await inventory.shipTransfer(transfer.id).orThrow(); // transfer_out at the source
await inventory.receiveTransfer(transfer.id).orThrow(); // transfer_in at the destinationA transfer goes from draft to in_transit to received. Cancelling an
in-transit transfer returns the stock to the source. The two locations must
differ (INVENTORY_TRANSFER_SAME_LOCATION), and a step out of order fails
with INVENTORY_TRANSFER_STATUS.
Purchase orders
const order = await inventory
.savePurchaseOrder(organizationId, {
locationId: warehouse.id,
supplier: { type: "company", id: supplierId },
currency: "EUR",
lines: [{ variantId, quantity: 100, unitCost: money(450n, "EUR") }],
})
.orThrow();
await inventory.placePurchaseOrder(order.id).orThrow(); // incoming += 100
await inventory
.receivePurchaseOrder(order.id, [{ lineId, quantity: 60 }])
.orThrow();
// { status: "partially_received", backordered: 40 }A purchase order can change only while it is a draft
(INVENTORY_PURCHASE_ORDER_LOCKED). Placing it counts its lines as incoming
stock at the location. Each receipt writes receipt movements and lowers
incoming; units still owed stay on backorder until a later receipt, and a
receipt above what is owed fails with INVENTORY_OVER_RECEIPT. Cancelling
removes the units still owed from incoming.
Unit costs are bigint minor units in the order's currency, checked against
the catalog's ISO 4217 list. The supplier is a config.recordTypes type and id,
such as a CRM company. With the contacts block
installed, a supplier whose supplier_status is blocked can't get a
purchase order: saving or placing one fails with
PURCHASE_ORDER_SUPPLIER_BLOCKED. Without contacts the module stores the pair
and doesn't check it.
Numbers and canceled quantities
An order can carry a number of its own, up to 50 characters and unique per
organization, through number on savePurchaseOrder (a repeat is
INVENTORY_PURCHASE_ORDER_NUMBER_TAKEN). Placing an order that has none gives
it the next all-digit number: one more than the organization's highest,
assigned under a transaction lock, so the numbers don't skip.
cancelPurchaseOrderQuantity gives up part of what a placed order still owes,
for a supplier that can't deliver it all:
await inventory
.cancelPurchaseOrderQuantity(order.id, [{ lineId, quantity: 40 }])
.orThrow();
// { status: "partially_received", backordered: 0 }Each quantity is at most what the line still owes (INVENTORY_OVER_CANCEL).
The units stop counting as incoming, receipts and the backorder count leave
them out, and an order with nothing left owed becomes received, or
cancelled when nothing was received. It records purchase_order.line_cancelled.
It needs inventory.purchase.
Tax lines
Give a line a taxRateBps (2100 is 21 percent) and an optional taxCode,
and saving the draft rebuilds the order's tax lines, one per code and rate:
await inventory
.savePurchaseOrder(organizationId, {
locationId: warehouse.id,
currency: "EUR",
lines: [
{
variantId,
quantity: 100,
unitCost: money(450n, "EUR"),
taxRateBps: 2100,
taxCode: "NL-21",
},
],
})
.orThrow();
const lines = await inventory.purchaseOrderTaxLines(order.id).orThrow();
// [{ taxCode: "NL-21", taxRateBps: 2100, net: €450.00, tax: €94.50, gross: €544.50 }]Each line's net is its quantity times its cost, rounded to a minor unit, and
its tax is that net at the line's rate, rounded the same way. The tax lines
add the lines up per code and rate; a line without a rate adds none. The
table is purchase_order_tax_lines, readable by inventory.read. Receiving
and cancelling leave the tax lines as they were saved.
Receipts
Every receivePurchaseOrder call writes one inventory_receipts row with an
inventory_receipt_lines row per received line, and returns its id as
receiptId. The invoices block reads
the received quantities from these lines when it matches a purchase bill.
To inspect incoming goods, install the
inspections block and set receiptInspection to
one of its kinds. Each receipt then schedules an inspection of that kind with
the receipt as its auditee, and stores its id on the receipt:
blocks: {
inventory: { options: { receiptInspection: "inspection" } },
},A kind missing from the inspections block's kinds option fails when the SQL
renders.
Requisitions
A requisition asks to buy stock before anyone writes a purchase order. Any
member with inventory.read can request one; it starts pending.
const requisition = await inventory
.requestPurchase(organizationId, {
locationId: warehouse.id,
lines: [{ variantId, quantity: 40, unitCost: money(450n, "EUR") }],
reason: "Restock before the spring sale",
})
.orThrow();
await inventory.decidePurchaseRequisition(requisition.id, true).orThrow();
const order = await inventory
.purchaseOrderFromRequisitions([requisition.id], {
supplier: { type: "company", id: supplierId },
})
.orThrow();Without the approvals block, a holder of
inventory.purchase approves or rejects a pending requisition with
decidePurchaseRequisition. With approvals installed, requestPurchase opens
an approval request for the purchase_requisition subject under the
organization's policy (a holder of inventory.purchase by default), and the
decision comes from that request: decidePurchaseRequisition then fails with
INVENTORY_REQUISITION_APPROVAL_PENDING.
purchaseOrderFromRequisitions turns approved requisitions of one
organization and location into one draft purchase order, summing their lines
per variant, and marks them ordered. Requisitions at different locations
fail with INVENTORY_REQUISITION_MIXED, and one that isn't approved fails with
INVENTORY_REQUISITION_STATUS. The supplier and currency default to the ones
the requisitions share.
Drop ship
db.orders.purchaseOrderFromOrder(orderId, supplier) drafts a purchase order
for an order's catalog lines with the order's shipping address as the purchase
order's ship_to, so the supplier ships to the customer. See
orders.
Stock counts
A stock count is a document that compares what the system expects with what is on the shelf. openStockCount(orgId, locationId, { note, variantIds }) snapshots the expected quantity of every bucket, loose remainder and serial at the location (only where something is on hand). recordCountLine(countId, { variantId, counted, binId, lotId, serial }) records what was counted at a position and replaces an earlier line for it. A position that wasn't in the snapshot takes the stock on hand as its expected quantity. Each line stores variance as counted minus expected.
const count = await db.inventory
.openStockCount(orgId, warehouse.id, { note: "Year end" })
.orThrow();
await db.inventory
.recordCountLine(count.id, { variantId, counted: "7", binId })
.orThrow();
const posted = await db.inventory.postStockCount(count.id).orThrow();
// { posted: true, movements: 1, variance: "-3" }postStockCount writes one movement with reason count for every line with a variance, through the same stock path as adjustStock, so average cost and the ledger valuation follow. The movement's reference is the count (stock_count), and each line keeps its movement_id. Posting a posted count writes nothing and returns posted: false. cancelStockCount closes an open count without movements. A closed count refuses new lines with INVENTORY_COUNT_CLOSED, and a missing count fails with INVENTORY_COUNT_NOT_FOUND.
The stock_count import target creates an open count from { locationId or location (a code), note, lines: [{ variantId, binId, lotId or lot, serial, counted, expected }] }, so a count sheet can be loaded repeatedly by its external key. An imported count stays open until postStockCount, and a posted one refuses a second import.
Stock overview
overview({ organizationId, limit?, expiryDays? }) reads the stock page in one call from the SQL function inventory_overview: levelCount, the levels at or below their reorder point (lowStockCount counts all of them, lowStock lists the emptiest limit, default 20), and the lots with stock that expire within expiryDays (default 30), soonest first. Quantities are text, in each variant's unit. The function runs as the caller, so row security decides which levels are counted, and it reads lots through expiring_lots, which checks the inventory.read permission. levels({ organizationId, variantIds?, locationId? }) calls inventory_levels and returns on hand, allocated, available, incoming, the reorder point and a status (in_stock, low or out) for those variants only, by the level primary key, so a page of products is one query. movements({ organizationId, variantId?, locationId?, binId?, lotId?, documentType?, documentId?, limit?, offset? }) calls list_inventory_movements and pages ledger movements of kind stock.%, newest first, with limit capped at 200. inventory_status_counts counts in-stock, low and out. Open purchase orders already add their remaining quantity to stock_levels.incoming.
const stock = await db.$blocks.inventory
.overview({ organizationId, limit: 10, expiryDays: 14 })
.orThrow();
const levels = await db.$blocks.inventory
.levels({ organizationId, variantIds: pageOfVariantIds })
.orThrow();
const history = await db.$blocks.inventory
.movements({ organizationId, variantId, limit: 20 })
.orThrow();Events
| Event | When |
|---|---|
stock.adjusted | adjustStock and countStock |
stock.reorder_point_reached | Available stock drops to the reorder point |
reservation.created, reservation.committed | reserve, commitReservation |
reservation.released | A release, with reason released or expired |
allocation.created, allocation.filled, allocation.released | allocate, a backorder filled, a release |
transfer.shipped, transfer.received, transfer.cancelled | A transfer step |
purchase_order.placed, purchase_order.received, purchase_order.cancelled | A purchase order step |
purchase_order.line_cancelled | cancelPurchaseOrderQuantity |
purchase_requisition.created, purchase_requisition.approved | requestPurchase, an approval |
inventory_receipt.created | A receipt of a purchase order |
stock.reorder_point_reached is a subject event on the product_variant
subject, so the watcher sink notifies
the variant's watchers. The catalog block
registers the subject.
Hooks
The SQL module calls before_stock_adjust, after_stock_adjust,
before_stock_reserve and after_stock_reserve when you define them (see
blocks). Their quantity argument is numeric. The TypeScript client takes hooks keyed
by method name.
Adopting existing tables
To run over tables you already have, map locations, levels and
reservations to yours;
movements live in the ledger block's tables. The stock items, bins, lots,
serials, buckets and allocations (items, bins, lots, serials,
buckets, allocations) are adoptable too. Transfers (transfers, transferLines) and purchase orders
(purchaseOrders, purchaseOrderLines) are optional: set them to null
and their functions are left out.
Not included
Sales orders, fulfilment and returns belong to the orders and shipments blocks. Inventory values stock at average cost only (no FIFO layers) and doesn't pick a location for an order.
Without the client
db.inventory is this client. Code that does not go through bsb.db() builds it with a transport and an organization id:
const inventory = createInventory({ transport });
const warehouse = await inventory
.saveLocation(organizationId, { code: "WH-AMS", name: "Amsterdam" })
.orThrow();Last updated on
Catalog
Products, options and variants, prices in bigint minor units per currency and price list, categories, collections, sales channels, translations, product media and a public storefront switch.
Warehouse
Pick waves and pick lists made from stock allocations, putaway and slotting suggestions, walking routes, and cycle count plans that hold large variances for review.