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.
catalog stores what an organization sells. A product has options (size,
colour), and each variant picks one value per option and carries its own SKU.
Prices live per variant, currency and optional price list, as bigint minor
units next to an ISO 4217 code, so an amount never passes through a float.
Categories form a tree, and collections are either a ranked list of products
or a saved filter.
better-supabase add catalogimport { createCatalog } from "better-supabase/blocks/catalog";
import { money } from "better-supabase/commerce";Permissions
Every write checks catalog.manage in the product's organization, and the
read policies check catalog.read. The owner role holds *. Give the roles
that work on the catalog these keys:
roles: {
admin: ["catalog.*", "members.*"],
merchandiser: ["catalog.read", "catalog.manage"],
member: ["catalog.read"],
},The service role passes every check, for imports and sync jobs.
blocks.catalog.permissions.create, update and purge name separate keys
for creating, changing and purging products and variants (statuses, archive,
restore and options count as changes; purge falls back to manage). categoryCreate, categoryUpdate and
categoryDelete do the same for upsert_category (a new or an existing
category), move_category and delete_category. Without them those writes
check manage, and prices, product categories, collections and channels
always do.
catalog: {
permissions: {
manage: "product.update",
categoryCreate: "category.create",
categoryUpdate: "category.update",
categoryDelete: "category.delete",
},
}Products
Server code calls the catalog instance on db, in the caller's organization. With gen.hooks set, better-supabase gen writes the hooks:
export const { useList: useCatalog } = defineDataHooks(
"catalog",
(db: AppDb) => db.catalog,
);const shirt = await db.catalog
.createProduct(organizationId, { title: "Linen Shirt", kind: "physical" })
.orThrow();
// { id, slug: "linen-shirt", status: "draft" }
await db.catalog.setProductStatus(shirt.id, "active").orThrow();"use client";
import { useCatalog } from "@/lib/supabase/hooks";
const rows = useCatalog({ limit: 50 });The slug comes from the title when you leave it out, and it is unique per
organization (CATALOG_SLUG_TAKEN). kind is physical, digital or
service. A unique index of your own on the products, variants or categories
table, such as one on a barcode, keeps its own error: the block reports
CATALOG_SLUG_TAKEN or CATALOG_SKU_TAKEN only for an index on the slug or
SKU column, and raises any other unique violation unchanged with its
constraint name.
A new row never writes null into a column the call leaves out: the
description of a product or category, and the SKU, title, barcode and weight of
a variant take your column's default instead, so a title text not null default '' column works for a variant without a title.
A product starts as draft. The built-in transitions are draft to active or
archived, active to draft or archived, and archived back to draft; anything
else fails with CATALOG_TRANSITION_INVALID. When a
state machine is declared on the products
table's status column, the machine owns the transitions instead, so you can
add a review state.
Over your own products table with other statuses, map the block's three
through values.products.status. An app with active, discontinued and
archived and no draft maps { draft: null, archived: ["archived", "discontinued"] }: setProductStatus(id, "archived") writes archived, also
over a discontinued product, which reads as archived;
setProductStatus(id, "discontinued") writes that app value; and a move to
draft is refused. Without a draft status, an archived product goes back to
active.
Options and variants
const size = await catalog
.saveOption({
productId: shirt.id,
input: { name: "Size", values: ["S", "M", "L"] },
})
.orThrow();
await catalog
.createVariant({
productId: shirt.id,
input: {
sku: "SHIRT-LINEN-S",
optionValues: [size.values[0].id],
weightGrams: 220,
},
})
.orThrow();A variant names exactly one value of every option of its product
(CATALOG_VARIANT_OPTIONS), and two variants can't pick the same values
(CATALOG_VARIANT_DUPLICATE). SKUs are unique per organization
(CATALOG_SKU_TAKEN). A product without options has one variant.
A product with variants can gain an option: each existing variant gets the
option's first value, so the default variant of a product without options
becomes its first combination. Without a variant values table that is refused
(CATALOG_OPTION_HAS_VARIANTS). Variants keep a rank key, and
reorderVariant(id, { previous, next }) computes a new one with
rankBetween. reorderOptions(productId, optionIds) puts
the product's options in the given order; the list names each option once
(CATALOG_OPTION_ORDER_INVALID).
A value saveOption leaves out is removed with the variants that use it. A
variant something still references is archived instead: a foreign key of yours
that refuses the delete, stock movements in inventory,
or your own check in options.variantInUse, a function (variant uuid) returns boolean. Archiving sets the mapped columns.variants.status to its archived
value (through values.variants.status) and drops the variant's option values;
without a status column such a variant refuses the change
(CATALOG_OPTION_VALUE_IN_USE). Removing variants needs the update permission,
not purge. An archived variant doesn't block a new one with the same values.
Archive, restore and purge
archiveProduct(id) moves a product to its archived status and
restoreProduct(id) puts it back to active (or draft when the app has a
draft status). Both go through setProductStatus, so there is no new column:
the archive is the status, and each call records product.archived or
product.restored next to product.status_changed. Restoring a product that
is not archived changes nothing. archiveVariant(id) and restoreVariant(id)
do the same for a variant when columns.variants.status is mapped; without it
they refuse with CATALOG_VARIANT_STATUS_UNSUPPORTED.
An archived product leaves the storefront and the channelProducts list unless
you pass archived: true, which lists only archived products. An archived
variant can't be added to a cart (the orders block refuses it) and leaves the
storefront. Search and the subject registry hide a row by its deletedAt, not
by its status, so an archived product stays findable by staff. purgeProduct(id)
and purgeVariant(id) replace deleteProduct and deleteVariant: they delete
the row for good, record product.purged or product_variant.purged and need
permissions.purge, falling back to catalog.manage (ADRs 1048 and 1049).
catalog: {
columns: { variants: { status: "status" } },
options: { variantInUse: "public.product_variant_in_use" },
}Variant status
With columns.variants.status mapped, setVariantStatus(variantId, status)
(set_variant_status) moves a variant to active, archived or another label
values.variants.status names, with the update permission. It returns the
new and the previous label. Archived variants (every app value
values.variants.status.archived lists) don't count as live, so setOptions
and createVariant add a new variant for their combination. A variant that
goes live again needs one value of every option (CATALOG_VARIANT_OPTIONS) and
a combination no live variant has (CATALOG_VARIANT_DUPLICATE). Without a
status column the function refuses (CATALOG_VARIANT_STATUS_UNSUPPORTED).
catalog: {
columns: { variants: { status: "status" } },
values: { variants: { status: { discontinued: "discontinued" } } },
}
await catalog.setVariantStatus({ variantId, status: "discontinued" }).orThrow();The whole matrix at once
setOptions(productId, options, { titleSeparator? }) (set_product_options)
replaces a product's options and makes its variants the full matrix of their
values, in one transaction. Options are matched by name and kept in the order
given; a missing one is removed, and a new one is added with its first value
on every existing variant. Every combination ends up with exactly one live
variant:
- a variant whose values are still a combination keeps its id, SKU and prices;
- variants that become the same combination keep the first by rank, and the others go, like a removed value's variants (archived when something still references them, as above);
- a missing combination gets a new variant, with a SKU made from the product
slug and the values when the SKU column is
not null, and none otherwise.
With a title column, every variant's title becomes its values joined by
titleSeparator (" / " by default; null leaves titles alone). The matrix
is capped at options.maxVariants combinations (100 by default,
CATALOG_VARIANT_LIMIT), checked before anything changes. It needs the update
permission, and the create permission when it adds variants, and returns the
options with their values and the live variants with their optionValueIds.
const matrix = await catalog
.setOptions({
productId: shirt.id,
options: [
{ name: "Size", values: ["S", "M", "L"] },
{ name: "Colour", values: ["Sand", "Navy"] },
],
})
.orThrow();
// matrix.variants.length === 6updateVariant changes only what it names: a SKU, option values or a flag
left out keeps its value, and null clears sku, title, barcode or
weightGrams (upsert_variant takes clear). Clearing a SKU needs a nullable
SKU column. updateProduct patches the same way: title, slug,
description and kind left out keep their value, description: null clears
the description and slug: null derives it from the title again. The block's
columns, the price settings and the extra columns change in one update, so a
check across kind and an extra column holds when a product changes kind.
trackInventory and allowBackorder are read by the
inventory block when it is installed.
When your variants have no tracking column, map columns.variants.trackInventory
to null and keep the flag on the product (columns.products.trackInventory):
inventory and orders read the product's flag, and upsert_variant refuses a
per-variant one (CATALOG_TRACK_INVENTORY_UNSUPPORTED).
Integer positions
Options, option values, variants, categories and collection products are
ordered by base-62 rank keys. When your rank columns are whole-number
positions, set options.rankType: "integer": a new row goes one after the
last. reorderVariant, moveCategory and addToCollection then take
{ position }, or { previous, next } with whole-number neighbors, which picks
the number halfway between them or one past an end. Two neighbors with no
whole number between them return RANK_KEY_INVALID; pass a position and
renumber the rest yourself. A position with text ranks returns the same error.
blockConfig passes rankType to the client.
await catalog
.moveCategory({ categoryId, parentId, rank: { position: 3 } })
.orThrow();Prices
await catalog
.setPrice({
variantId,
input: { amount: money(4900n, "EUR"), compareAt: money(5900n, "EUR") },
})
.orThrow();
const price = await catalog
.variantPrice({ variantId, currency: "EUR" })
.orThrow();
// { id, variantId, amount: { amount: 4900n, currency: "EUR" }, compareAt, priceListId: null }Amounts travel as strings and come back as bigint, so values beyond
Number.MAX_SAFE_INTEGER stay exact. The database checks the currency against
the pinned ISO 4217 list (CATALOG_CURRENCY_INVALID) and refuses a
compare-at amount that isn't above the price.
A price can belong to a price list (for a customer group or a market) and can
have a validity window. Two prices for the same variant, currency and list
can't overlap in time (CATALOG_PRICE_OVERLAP). variantPrice returns the
list price when you pass priceListId and one is valid, and the base price
otherwise; asOf resolves a price at another instant.
Every change to an amount emits catalog.price_changed with the previous
amount, when outbox is installed.
Prices on the variant
When your variants hold their own price, map tables.prices to null, and
columns.variants.price to the variant's price column. A variant without a
price falls back to columns.products.price, and the price is in the
product's currency (columns.products.currency). updateProduct with
price: null clears the product's price. setPrice writes the
variant's column and refuses another currency, a compare-at amount, a price
list or a validity window; deletePrice(variantId) clears the variant's own
price; variantPrice returns the variant's or the product's price, and a
price's id is its variant's.
catalog: {
tables: { products: "public.products", variants: "public.product_variants", prices: null },
columns: {
products: { price: "default_selling_price_cents", currency: "currency", trackInventory: "track_inventory" },
variants: { price: "selling_price_cents", trackInventory: null, rank: "position" },
},
options: { rankType: "integer" },
}createProduct and updateProduct then take the product's own price (a
Money, which sets both the price and the currency column) and
trackInventory when variants map trackInventory to null. A field you
leave out keeps the column's value.
Variant and category columns of your own
Columns you add to the variants and categories tables the block doesn't know, such as a
manufacturer part number, a purchase cost, a default flag or a category icon.
createVariant, updateVariant and saveCategory take them as fields,
write them, and return them under fields:
alter table "better_supabase"."your_table" add column "manufacturer_part_number" text;
alter table "better_supabase"."your_table" add column "purchase_price_cents" bigint;
alter table "better_supabase"."your_table" add column "is_default" boolean not null default false;
alter table "better_supabase"."your_table" add column "icon" text not null default 'Package01Icon';Categories and collections
Categories form a tree per organization. moveCategory refuses a move under
its own descendant (CATALOG_CATEGORY_CYCLE), and a category with children
can't be deleted (CATALOG_CATEGORY_HAS_CHILDREN).
setProductCategories(productId, ids) replaces a product's categories.
A manual collection is a ranked list: addToCollection appends a product, or
places it between two neighbours. A rule collection stores a filter tree, the
same FilterQuery the list query reads, so the app
renders it with the filter UI it already has:
await catalog
.saveCollection({
organizationId,
input: {
title: "Digital",
kind: "rule",
rule: {
id: "root",
type: "group",
combinator: "and",
rules: [
{
id: "kind",
type: "rule",
path: ["kind"],
operator: "is",
value: "digital",
},
],
},
},
})
.orThrow();Channels
A channel is a place the catalog sells through: a web shop, a marketplace or a point of sale. Each one has a key, a currency and an optional price list, and lists the products it sells:
const web = await catalog
.saveChannel({
organizationId,
input: {
key: "web-de",
name: "Web shop Germany",
currency: "EUR",
priceListId: retailListId,
},
})
.orThrow();
await catalog
.listOnChannel({ channelId: web.id, productIds: [shirt.id] })
.orThrow();
const listed = await catalog
.channelProducts({ channelId: web.id, locale: "de", limit: 50 })
.orThrow();
// [{ id, slug, status, kind, locale: "de", title, description, listedAt }]
const price = await catalog
.channelPrice({ channelId: web.id, variantId })
.orThrow();The key is lower-case letters, digits and hyphens, unique per organization
(CATALOG_CHANNEL_KEY_INVALID, CATALOG_CHANNEL_TAKEN). listOnChannel and
unlistFromChannel resolve to how many listings they added or removed, and
a product that isn't in the channel's organization fails with
CATALOG_PRODUCT_NOT_FOUND. channelProducts returns the listed products in
slug order, 100 per page by default and at most 500, with cursor for the
next page.
channelPrice resolves the variant's price in the channel's currency through
variantPrice, so a channel with a price list gets the list price when one is
valid and the base price otherwise. A channel without a currency returns
null. Deleting a channel removes its listings, and deleting a price list
clears it on the channels that used it.
Identifiers and relations
A variant carries the codes other parties know it by: its EAN, a supplier's
code, a manufacturer's code. saveProductIdentifier stores one on a variant
(the variant's barcode column stays as it is), and findVariantsByIdentifier
looks a code up:
await catalog
.saveProductIdentifier({
organizationId,
input: { variantId, type: "ean", value: "4006381333931" },
})
.orThrow();
await catalog
.saveProductIdentifier({
organizationId,
input: {
variantId,
type: "supplier",
value: "GV-100",
partyId: supplierId,
},
})
.orThrow();
const matches = await catalog
.findVariantsByIdentifier({
organizationId,
value: "GV-100",
type: "supplier",
})
.orThrow();
// [{ identifierId, variantId, productId, sku, type, value, partyId }]type is ean, supplier, manufacturer or other
(CATALOG_IDENTIFIER_TYPE_INVALID). An EAN has 8, 12, 13 or 14 digits, and
every value is 1 to 100 characters (CATALOG_IDENTIFIER_INVALID). A variant
stores a code once per type and party, so a repeated call returns
created: false. partyId is the supplier or manufacturer the code belongs
to; it isn't a foreign key, so the contacts block stays optional.
saveProductRelation links two variants. The relation points from the variant
that has the alternative or accessory, or that is superseded, to the other
one:
await catalog
.saveProductRelation({
organizationId,
input: {
fromVariantId: oldValve,
toVariantId: newValve,
kind: "superseded_by",
},
})
.orThrow();
await catalog.variantRelations({ variantId: oldValve }).orThrow();
// [{ kind: "superseded_by", direction: "outgoing", variantId, sku }]
await catalog.variantRelations({ variantId: newValve }).orThrow();
// [{ kind: "superseded_by", direction: "incoming", variantId, sku }]
const current = await catalog.replacementVariant(oldValve).orThrow();kind is alternative, superseded_by or accessory
(CATALOG_RELATION_KIND_INVALID). Each relation is stored once in the
direction you save it, and variantRelations reports it as outgoing for the
from variant and incoming for the to variant, so an alternative shows on
both sides. A variant can't relate to itself (CATALOG_RELATION_INVALID), and
a superseded_by link that would close a loop is refused with
CATALOG_RELATION_CYCLE. replacementVariant follows the superseded_by
chain to its end and returns the variant itself when nothing replaces it.
Variants of another organization fail with CATALOG_VARIANT_NOT_FOUND.
Supplier items
A supplier item is what a supplier sells under its own code. It lives next to the catalog until the first time you use it, so you can load a whole price list without creating a product for every row:
const item = await catalog
.saveSupplierItem({
organizationId,
input: {
supplierId,
code: "GV-100",
description: "Gate valve, brass",
price: 123450n, // minor units of the currency
currency: "EUR",
unit: "pcs",
keywords: "acme valves",
},
})
.orThrow();
const found = await catalog
.searchSupplierItems({ organizationId, query: "brass gate", supplierId })
.orThrow();
const promoted = await catalog
.promoteSupplierItem({ itemId: item.id, sku: "VALVE-100" })
.orThrow();
// { productId, variantId, created: true }A supplier has each code once (CATALOG_SUPPLIER_ITEM_TAKEN). price is a
whole number of minor units and currency an ISO 4217 code
(CATALOG_CURRENCY_INVALID). The description, the code and the keywords feed
a full-text index: searchSupplierItems matches words in them and the start
of a code, best matches first, 25 by default and 200 at most.
promoteSupplierItem creates a product and a variant from the item on first
use. The title is the description (or the code), the SKU is the one you pass
or the supplier's code, and the supplier's code is stored as a supplier
identifier of the new variant. The item keeps a link to the variant, so a
second call returns the same ids with created: false. A SKU another variant
already has fails with CATALOG_SKU_TAKEN; the call never links an item to
an existing variant silently. It emits product.created and
product_variant.created, and it needs the catalog.manage permission.
Column mappings per supplier
Every supplier names its price list columns differently.
setSupplierItemMapping stores which source column fills which field, and
mapSupplierRow turns one source row into supplier item fields:
await catalog
.setSupplierItemMapping({
organizationId,
supplierId,
input: {
columns: {
code: "Artikel",
description: "Omschrijving",
price: "Prijs",
keywords: ["Merk", "Groep"],
},
defaults: { currency: "EUR", unit: "pcs" },
},
})
.orThrow();
const fields = await catalog
.mapSupplierRow({
organizationId,
supplierId,
row: {
Artikel: "GV-100",
Omschrijving: "Gate valve",
Prijs: "1.234,50",
Merk: "Acme",
Groep: "valves",
},
})
.orThrow();
// { code: "GV-100", description: "Gate valve", price: 123450n,
// currency: "EUR", unit: "pcs", keywords: "Acme valves" }A mapping needs a code column and fills only code, description, price,
currency, unit and keywords (CATALOG_SUPPLIER_MAPPING_INVALID).
keywords can list several columns. defaults holds the currency and unit
for rows that carry none. The source price is a decimal number in major units.
When it has both separators, the last one is the decimal separator; a lone
comma is a decimal separator too. It is converted to minor units with the
currency's decimals (CATALOG_SUPPLIER_PRICE_INVALID for a value that is not
a number). A supplier without a mapping fails with
CATALOG_SUPPLIER_MAPPING_NOT_FOUND.
Importing price lists and codes
The catalog contributes two import targets,
so a price list or a list of codes loads through defineImport by external key:
| Entity | data |
|---|---|
supplier_item | supplierId, then row (mapped through the supplier's mapping) or the fields code, description, price, currency, unit, keywords |
product_identifier | sku or variantId, type, value, partyId |
Fields named next to a row win over the mapped ones, and price is in minor
units. A new key for a code the supplier already has updates that supplier
item instead of failing, so a re-import with new keys is safe. The target
doesn't resolve external keys itself: resolve the supplier or variant ids
first with imports.resolve.
Trade code
setVariantTradeCode sets the variant's Combined Nomenclature (CN) code, the
4 to 10 digit number customs and Intrastat reporting use. Spaces are dropped,
so 8481 80 99 is stored as 84818099, and null clears it
(CATALOG_TRADE_CODE_INVALID). The weight stays in the existing
weightGrams of saveVariant.
await catalog
.setVariantTradeCode({ variantId, tradeCode: "8481 80 99" })
.orThrow();Discount groups and the matrix
A customer group and a product group are the two axes of a price matrix. saveDiscountGroup creates a group of kind customer or product with a code that is unique per kind. setPartyDiscountGroup puts a customer in one customer group, and setVariantDiscountGroup puts a variant in one product group. Passing null removes the membership. A group that a rule uses can't be deleted (CATALOG_DISCOUNT_GROUP_IN_USE).
const dealers = await db.catalog
.saveDiscountGroup({
organizationId: orgId,
input: { kind: "customer", code: "DEALER", name: "Dealers" },
})
.orThrow();
const pumps = await db.catalog
.saveDiscountGroup({
organizationId: orgId,
input: { kind: "product", code: "PUMPS", name: "Pumps" },
})
.orThrow();
await db.catalog
.setPartyDiscountGroup({
organizationId: orgId,
partyId: companyId,
groupId: dealers.id,
})
.orThrow();
await db.catalog
.setVariantDiscountGroup({ variantId, groupId: pumps.id })
.orThrow();
await db.catalog
.saveDiscountRule({
organizationId: orgId,
input: {
customerGroupId: dealers.id,
productGroupId: pumps.id,
minQuantity: 10,
discountBps: 2500,
},
})
.orThrow();A rule leaves a group out to apply to every customer or every product. It can carry a validity window (validFrom, validTo, inclusive), a minQuantity, a discountBps from 0 to 10000 and a fixed unit price with its currency (fixedPrice in minor units). A bad value fails with CATALOG_DISCOUNT_RULE_INVALID.
resolveLineDiscount(orgId, partyId, variantId, quantity, { on, currency }) returns the rule that prices a line: { discountBps, fixedPrice, currency, ruleId }. Among the rules whose window holds on the date and whose minQuantity the quantity reaches, the most specific one wins (both groups, then the customer group alone, then the product group alone, then neither). Equally specific rules fall to the highest quantity break, then the latest validFrom. A fixed price in another currency than currency is skipped. With no match, the result is discountBps: 0 and a null ruleId.
Pricing document lines with the matrix
options.discountMatrix: true on quotes, orders and invoices prices lines that name a catalog variant through the matrix, for the document's customer (the company, else the contact, of a quote or invoice, and attrs.customerId of an order) on the day the lines are set. A line without a discountBps takes the rule's discount, and a line without a unitAmount takes the rule's fixed price before the catalog price. A value on the line always wins. The option is off by default, so existing documents price as before, and it needs the catalog block.
Importing groups and rules
The catalog contributes discount_group, discount_rule and party_discount_group import targets. A group takes { kind, code, name, parties? }, where parties lists party ids to put in a customer group. A rule takes customerGroup and productGroup as group codes (or customerGroupId and productGroupId), validFrom, validTo, minQuantity, discountBps, fixedPrice and currency. party_discount_group takes { party, groupId? } or { party, groupCode? }. An empty group removes the party. Import the groups first. Quote and invoice line setters pass the party id as text when discountMatrix is on.
Locales and translations
The locales option lists the languages the catalog is written in, as
language tags. The first one is the default, and its text stays on the
product and variant themselves:
blocks: { catalog: { options: { locales: ["en", "de", "pt-BR"] } } },await catalog
.setProductTranslation({
productId: shirt.id,
locale: "de",
translation: { title: "Leinenhemd", description: "Aus reinem Leinen." },
})
.orThrow();
await catalog
.setVariantTranslation({ variantId, locale: "de", title: "Klein" })
.orThrow();
const text = await catalog
.productText({ productId: shirt.id, locale: "de-AT" })
.orThrow();
// { id, slug, locale: "de", title: "Leinenhemd", description, variants: [{ id, sku, title }] }A read takes any locale and resolves it to a configured one: the locale
itself, then its language (de-AT reads de), then the default. A field the
translation leaves empty falls back to the default text, so a partial
translation still reads as a whole product. A translation for a locale that
isn't configured fails with CATALOG_LOCALE_INVALID, and one for the default
locale fails with CATALOG_LOCALE_DEFAULT; update the product instead.
Setting every field to null removes the translation. The default is
["en"], and a locale list with a tag twice is refused when the SQL renders.
Options, option values, categories and collections are not translated yet.
Product media
With attachments installed, a product keeps an ordered list of images and other files, each with alt text per locale and an optional variant it shows:
const file = await attachments
.put({
subject: { type: "product", id: shirt.id },
attachment: {
name: "front.jpg",
mimeType: "image/jpeg",
size: image.byteLength,
},
file: image,
})
.orThrow();
const media = await catalog
.addProductMedia({
productId: shirt.id,
attachmentId: file.id,
input: { alt: { en: "Linen shirt, front", de: "Leinenhemd, vorne" } },
})
.orThrow();
// { id, position: 0 }
await catalog
.reorderProductMedia({ productId: shirt.id, mediaIds: [media.id, otherId] })
.orThrow();
const gallery = await catalog
.productMedia({ productId: shirt.id, locale: "de" })
.orThrow();
// [{ id, attachmentId, variantId, position, alt: "Leinenhemd, vorne", altByLocale }]The attachment must belong to the product or one of its variants
(CATALOG_MEDIA_ATTACHMENT_NOT_FOUND), and a file appears in a product's
media once (CATALOG_MEDIA_TAKEN). Alt text keys are configured locales
with 1 to 1000 characters (CATALOG_MEDIA_ALT_INVALID). reorderProductMedia
takes every media item of the product once (CATALOG_MEDIA_ORDER_INVALID),
and removeProductMedia closes the gap it leaves. Deleting the attachment
removes its media item. updateProductMedia changes the variant and the alt
text.
Storefront
Set the storefront option to public to let anyone read the published
catalog of an organization:
blocks: { catalog: { options: { storefront: "public" } } },With it, anon can read the active products of organizations that called
publishStorefront(organizationId, true), their variants, options,
categories and collections, and their base prices (prices without a price
list). Price lists stay private. The default, private, adds no anon
policies.
The storefront also reads active channels and their listings, translations
and product media. channelProducts, channelPrice, productText and
productMedia are granted to anon, and they return only what these
policies allow. A media row names its attachment; the file itself stays
behind the attachments block's own policies.
Subjects
Installing the block registers products (product) and variants
(product_variant) as subjects, so comments, tags, attachments and search
work on them. A product links to /products/{slug} unless you set its page:
blocks: {
catalog: { entities: { product: { url: "/admin/products/{id}" } } },
},Events
| Event | When |
|---|---|
product.created, product.updated | createProduct, updateProduct |
product.status_changed | A status transition, with from and to |
product.archived, product.restored, product.purged | archiveProduct, restoreProduct, purgeProduct |
product_variant.created, product_variant.updated | A variant change |
product_variant.archived, product_variant.restored, product_variant.purged | archiveVariant, restoreVariant, purgeVariant |
catalog.price_changed | A price's amount changes |
storefront.published, storefront.unpublished | publishStorefront |
Hooks
The SQL module calls before_product_save, after_product_save,
before_variant_save, after_variant_save, before_price_set and
after_price_set when you define them (see blocks).
The TypeScript client takes hooks keyed by method name.
Adopting existing tables
To run over tables you already have, map products, variants and prices
to yours. Every other table is optional: set it to null and the functions that need it are
left out. Columns such as description, barcode, compareAt or
validFrom can also be null.
The tables added in version 3 (channels, channelProducts,
productTranslations, variantTranslations and media) and in version 5
(identifiers, relations, supplierItems and supplierItemMappings) run
over a table of yours only when tables maps them. The tradeCode column of
variants is optional: map it to null and setVariantTradeCode is left
out. Unmapped, the module creates its own, so
a table of yours under one of those default names is an error until you map
it.
Not included
Product import from CSV goes through the imports block with a mapping you write. Rule collections are not evaluated in SQL; the app runs the stored filter through its list query. Price lists don't know who belongs to a customer group yet, so only base prices are public.
Your own fields
Columns you add to products with alter table in your own schema files are fields of the block (details):,
keyed by column name with their SQL type. Pass createCatalog a Standard Schema
for them as fields: createProduct, updateProduct take them next to the block's own keys and
validate them (a bad value is a validation error), and the saved product return them
parsed. A column the module already uses is refused. See
your own fields.
const client = createCatalog({
transport,
fields: z.object({ priority: z.number().int().positive().nullable() }),
});Without the client
db.catalog is this client. Code that does not go through bsb.db() builds it with a transport and an organization id:
const catalog = createCatalog({ transport });
const shirt = await catalog
.createProduct({
organizationId,
input: { title: "Linen Shirt", kind: "physical" },
})
.orThrow();
// { id, slug: "linen-shirt", status: "draft" }
await catalog
.setProductStatus({ productId: shirt.id, status: "active" })
.orThrow();Simple products
createSimpleProduct({ organizationId, title, price, sku, slug, description, publish }) creates a product with one variant and its price, and sets it to active when publish is true. It returns { product, variant, price }.
Last updated on
Entitlements
Stripe entitlements per tenant in the access token, in RLS, and fresh again after a plan change.
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.