Pipelines
Tenant-editable pipelines for any record type, with ordered stages whose categories map to open, success or failure, a stage history with time in stage, board totals per currency, and a status the stage sets through the state machine.
pipelines puts any record your app registers in config.recordTypes on a pipeline the organization edits: deals, quotes, job applications, tickets, tasks. Each organization can keep several pipelines per record type, each with its own stages, and every stage has a category your config declares. A category maps to one of three fixed outcomes, open, success or failure, so reports and policies read the outcome and never a stage name.
The module writes a history row every time a record changes stage, keeps the time it entered its current stage, totals each board column per currency, and can set a status column from the stage category, so won on a deal still runs through the state machine.
Reading pipelines and boards needs pipelines.read, and creating, renaming, reordering or archiving pipelines and stages needs pipelines.manage. Admins get both and members get pipelines.read. Moving a record is an update of its own table, so your table's policies decide who may move it.
better-supabase add pipelinesThe module needs tenant, permissions and subjects.
Bind a record type
Register the record in config.recordTypes, add a stage_id and a pipeline_id column (both uuid) to its table, and bind it in the module's options. categories is required: it names the categories stages of this type can have and maps each to an outcome. stages is the template the first pipeline of an organization starts with.
recordTypes: {
deal: {
table: "public.deals",
idType: "uuid",
rank: { column: "rank", group: "stage_id" },
},
},
blocks: {
pipelines: {
on: {
deal: {
categories: { open: "open", won: "success", lost: "failure" },
enteredAt: "stage_entered_at",
amount: "amount",
currency: "currency",
probability: "probability",
owner: "owner_id",
status: { column: "outcome", values: { open: "open", won: "won", lost: "lost" } },
stages: [
{ key: "qualified", name: "Qualified", category: "open", probability: 20 },
{ key: "proposal", name: "Proposal", category: "open", probability: 55 },
{ key: "won", name: "Closed won", category: "won", probability: 100 },
{ key: "lost", name: "Closed lost", category: "lost", probability: 0 },
],
},
},
},
},| Key | Meaning |
|---|---|
categories | Each category of this type and its outcome: open, success or failure. At least one is open |
stage | The stage column, stage_id by default |
pipeline | The pipeline column, pipeline_id by default |
enteredAt | A timestamptz column the module sets whenever the stage changes |
amount | A bigint column of minor units the board totals. Needs currency, a char(3) column |
probability | A record's own win probability (0 to 100), which overrides the stage's in weighted totals |
owner | A user id column. The owner watches the record and board can filter by it |
scope | A column whose value picks one pipeline per scope, such as job_id for a pipeline per job |
status | A status column and the value each category sets in it, and follow to move the stage when the status is written |
stages | The first pipeline's stages: key, name, category and probability. Without it, one stage per category |
An insert without a pipeline lands in the organization's default pipeline for the type and scope, created from stages the first time. An insert without a stage lands in the first open stage. The first pipeline an admin creates for a type and scope becomes its default.
Manage pipelines and stages
Server code calls the pipelines instance on db, in the caller's organization. With gen.hooks set, better-supabase gen writes the hooks:
export const { useList: usePipelines } = defineDataHooks(
"pipelines",
(db: AppDb) => db.pipelines,
);import { createPipelines } from "better-supabase/blocks/pipelines";
const renewals = await db.pipelines
.upsert(organizationId, {
subjectType: "deal",
key: "renewals",
name: "Renewals",
})
.orThrow();
await db.pipelines
.saveStage(renewals.id, {
key: "due",
name: "Renewal due",
category: "open",
probability: 70,
rottingAfterDays: 14,
wipLimit: 25,
})
.orThrow();
const [deals] = await db.pipelines.list(organizationId, "deal").orThrow();"use client";
import { usePipelines } from "@/lib/supabase/hooks";
const rows = usePipelines({ limit: 50 });saveStage adds a stage at the end, or changes one when you pass its id. Its category must be one the type declares (PIPELINE_CATEGORY_UNKNOWN), and a stage that holds records keeps its outcome (PIPELINE_STAGE_IN_USE), so a won stage never turns open under its deals. reorderStage(stageId, { previous, next }) moves a stage between two rank keys. archive refuses a pipeline that still holds records, and a pipeline keeps at least one open stage (PIPELINE_LAST_OPEN_STAGE).
restore(pipelineId) and restoreStage(stageId) bring an archived pipeline or stage back (the stage's pipeline must be active; a restored pipeline is not the default again) and record pipeline.restored or pipeline_stage.restored. archiveStage({ stageId, moveTo }) archives a stage. Pass moveTo, another active stage of the same pipeline, and the records in the stage move there in the same call, even where the allowed stage changes would not permit that pair (the allowed changes guide a person, they do not restrict an administrator who removes a lane). Without moveTo, a stage that holds records is refused (PIPELINE_STAGE_IN_USE). A moveTo that is the stage itself, archived or in another pipeline raises PIPELINE_STAGE_REPLACEMENT_INVALID.
A stage takes an optional icon, a name your app maps to its own icon set, next to its color. Both appear on the stage and on the board columns.
Starter stages per brand
When one app serves several brands, give the pipelines block the table and column that hold an organization's brand and a brands map on the binding. An organization of that brand starts with its own stage names; every other organization starts with the binding's stages.
blocks: {
pipelines: {
options: { brand: { table: "public.organizations", column: "brand" } },
on: {
ticket: {
categories: { open: "open", done: "success" },
stages: [
{ key: "open", name: "Open", category: "open" },
{ key: "done", name: "Done", category: "done" },
],
brands: {
acme: {
stages: [
{ key: "open", name: "Inbox", category: "open" },
{ key: "done", name: "Shipped", category: "done" },
],
},
},
},
},
},
}The brand is read when the organization's pipeline is first created, so changing the column later does not rename existing stages. A binding with brands creates its pipeline on first use instead of through pipelines.seeds.
Without transitions, a record moves from any stage to any other. setTransitions(pipelineId, [{ from, to }]) limits the moves to the pairs you list, and an empty list allows every move again (PIPELINE_TRANSITION_INVALID for any other move).
Paging pipelines
page pages the organization's pipelines by keyset (ADR 1077), and get(id) reads one and returns a not_found error for an unknown id. list stays as a deprecated alias until 0.70. Sorts are rank (the default), name and key. subjectType, key and scopeId filter by a list of values, q searches the name and the key, and subjectType is the one facet. The organization comes from organizationId.
const first = await pipelines
.page({ organizationId, filters: { subjectType: ["deal"] }, limit: 50 })
.orThrow();
const facets = await pipelines.facets({ organizationId }).orThrow();
const total = await pipelines.count({ organizationId }).orThrow();
const one = await pipelines.get(first.items[0].id).orThrow();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.
Move records
A record changes stage when its stage column changes. An update from your app, a bulk action or a board drag all go through the same trigger, which refuses a stage of another pipeline, an archived stage, or a stage of another organization (PIPELINE_STAGE_INVALID), checks the transitions, closes the previous history row and opens a new one.
On a board, move the card with rank and the stage id as the group, so the rank key and the stage change in one update:
import { createRank } from "better-supabase/blocks/rank";
const rank = createRank({ transport });
await rank
.move("deal", dealId, {
previous: aboveId,
next: belowId,
group: proposalStageId,
})
.orThrow();With status set, a stage in a mapped category also writes the status column in a separate update, so a state machine on that column checks the change and records status.changed. Moving a deal to Closed won sets outcome to won, and moving it back to an open stage sets open again.
The binding can work the other way too. With status.follow: true, a write to the status column that doesn't come from a stage change moves the record to the first active stage, in rank order, of its pipeline whose category maps to the new status. A status no category maps to leaves the stage alone, and a mapped status the pipeline has no active stage for fails with PIPELINE_STAGE_INVALID. Code that still writes the status column directly then keeps the stage, its history and the time in stage right:
pipelines: {
on: {
task: {
categories: { todo: "open", doing: "open", done: "success" },
status: {
column: "status",
values: { todo: "todo", doing: "doing", done: "done" },
follow: true,
},
stages: [
{ key: "todo", name: "To do", category: "todo" },
{ key: "doing", name: "Doing", category: "doing" },
{ key: "done", name: "Done", category: "done" },
],
},
},
},The stage change the follow writes sets the status it already has, so the two never loop. An insert that sets the status and no stage lands on the first active stage whose category maps to that status, so the inserted status stays; without a match it starts on the first open stage as before.
Board, stats and health
const columns = await pipelines
.board("deal", pipelineId, { owner: userId })
.orThrow();
// [{ stageId, name, outcome, count, overLimit, totals: [{ currency, amount, weighted }] }]
const stats = await pipelines
.stats(pipelineId, { since: quarterStart, until: quarterEnd })
.orThrow();
// { won, lost, winRate, stages: [{ stageId, entered, averageSeconds }] }
const stuck = (await pipelines.health(pipelineId).orThrow()).filter(
(row) => row.rotting,
);board returns every active stage in order with the number of records the caller can see and, per currency, the total amount and the amount weighted by probability (the record's own, else the stage's). amount and weighted are Money values from commerce, sent as text so they stay exact past 2^53, and currencies are never added together. A currency that isn't an ISO 4217 code makes board fail, so keep the currency column to ISO codes. overLimit is true when a stage holds more records than its WIP limit. All three reads run as the caller, so the record table's policies decide what they count.
stats reads the stage history in a time window: how many records entered each stage, how long the ones that left stayed on average, and the win rate (records that entered a success stage over those that entered a success or failure stage). health lists the open records with the time they entered their stage, their days in stage and whether they sit longer than the stage's rottingAfterDays.
Watching
With the notifications module installed, the owner column's user watches the record at the participating level when the record is created or reassigned, and a level the user already chose stays. Every stage change notifies the record's watchers with a pipeline.stage_changed notification. Anyone else watches a record with the notifications client's subscribe({ subject: { type: "deal", id } }).
Events
| Event | When | Data |
|---|---|---|
pipeline.stage_changed | a record moved to another stage | organizationId, subjectType, subjectId, pipelineId, fromStageId, toStageId, category, outcome |
pipeline.created, pipeline.updated, pipeline.archived | an admin changed a pipeline | organizationId, pipelineId, subjectType, key |
pipeline_stage.created, pipeline_stage.updated, pipeline_stage.archived | an admin changed a stage | organizationId, pipelineId, stageId, key, category |
pipeline.stage_changed carries the record as its subject, so the activity feed shows it on the record's timeline. Pipeline and stage changes are written to the audit log as configuration changes.
Your own fields
Columns you add to pipelines with alter table in your own schema files are fields of the block (details). upsert writes them from fields,
and upsert and list 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"."pipelines" add column "team" text;const client = createPipelines({
transport,
fields: v.object({ team: v.optional(v.string()) }),
});
await client.upsert(organizationId, {
subjectType: "deal",
key: "enterprise",
name: "Enterprise",
fields: { team: "sales-emea" },
});Hooks
The module calls before_pipeline_save, after_pipeline_save, before_pipeline_stage_save and after_pipeline_stage_save around admin changes, and before_pipeline_stage_change(subject_type text, subject_id text, from_stage uuid, to_stage uuid) and after_pipeline_stage_change(subject_type text, subject_id text, to_stage uuid) inside the trigger. A before_ hook raises to refuse the move. The TypeScript client takes hooks for its methods (see extending blocks).
Wire it to ReUI
The ReUI Kanban commits a finished drag through onValueCommit(value, meta). Call rank.move with the card's new neighbours in meta.overContainer and the column's stage id as the group, and restore meta.previousValue when the result is an error. Read the column headers from board, and the count and totals of each column from its entry.
Errors
| Hint | Cause |
|---|---|
PIPELINE_FORBIDDEN | the caller lacks pipelines.manage |
PIPELINE_SUBJECT_UNKNOWN | the subject type has no binding in on |
PIPELINE_NOT_FOUND | no such pipeline |
PIPELINE_KEY_TAKEN | another pipeline of the type and scope has the key |
PIPELINE_IN_USE | records are still in the pipeline |
PIPELINE_CATEGORY_UNKNOWN | the type declares no such category |
PIPELINE_STAGE_NOT_FOUND | no such stage in the pipeline |
PIPELINE_STAGE_KEY_TAKEN | another stage of the pipeline has the key |
PIPELINE_STAGE_IN_USE | records are in the stage, so it can't be archived or change its outcome |
PIPELINE_LAST_OPEN_STAGE | archiving it would leave the pipeline without an open stage |
PIPELINE_STAGE_INVALID | the stage isn't an active stage of the record's pipeline |
PIPELINE_TRANSITION_INVALID | the pipeline's transitions don't allow the move |
PIPELINE_TRANSITIONS_INVALID | a transition names a stage of another pipeline |
PIPELINE_RANK_INVALID | not a rank key |
Without the client
db.pipelines is this client. Code that does not go through bsb.db() builds it with a transport and an organization id:
import { createPipelines } from "better-supabase/blocks/pipelines";
const pipelines = createPipelines({ transport });
const renewals = await pipelines
.upsert(organizationId, {
subjectType: "deal",
key: "renewals",
name: "Renewals",
})
.orThrow();
await pipelines
.saveStage(renewals.id, {
key: "due",
name: "Renewal due",
category: "open",
probability: 70,
rottingAfterDays: 14,
wipLimit: 25,
})
.orThrow();
const [deals] = await pipelines.list(organizationId, "deal").orThrow();Declared defaults
A binding without scope has one pipeline per organization, and the block
declares it as a default: seed_pipelines_defaults(organization, variant) adds
the default pipeline of each such record type with the stages of its template.
default_pipeline() stays the function a record's trigger calls. It returns the
type's pipeline, applying the declared defaults first when the organization has
none, so a new organization needs no setup. A binding with a scope (applications
per job, cases per kind) has a pipeline per scope value, which exists only once a
record names it, so default_pipeline() still creates that one on first use.
A binding can name a variant, a set of stage templates a preset refers to. The
deals block uses b2b-sales and the hiring block recruiting. Seeding a variant
adds the pipelines of its bindings plus those without a variant; seeding none adds
all of them. Your own on entries take variant as well.
blocks: {
pipelines: {
on: {
ticket: { categories: { open: "open", done: "success" }, variant: "support" },
},
},
},recruiting is declared but seeds no rows yet, because applications are scoped
by job.
Declare stages as rows
Stages can be pipeline_stage rows in supabase/rows/pipelines.sql, with the record type as the
subject (deal@acme for one brand). The value holds key, name, category, probability,
color and icon; the outcome follows from the category the binding names. When rows exist for a
subject, the seed inserts them in place of the config stages, and the rank follows position.
better-supabase db rows writes the data migration, and better-supabase codemod declared-rows
moves the stages you already have.
Default and ensure
default({ organizationId, subjectType, scopeId }) returns the pipeline marked as default for the subject type (and scope), or undefined. ensure({ organizationId, subjectType, key, name, stages }) returns the pipeline with that key, or creates it and its stages in order when it is missing. Calling it again changes nothing.
Board lanes on the client
createBoardController holds the lanes of a board and moves a card at once, then saves the move. Pass the starting lanes (from the board's read set) and move, a server action that transitions the record:
import { createBoardController } from "better-supabase/blocks/pipelines";
const board = createBoardController({
lanes: [
{ id: "new", cards: [{ id: "1" }, { id: "2" }] },
{ id: "won", cards: [] },
],
move: ({ cardId, to }) => transitionDeal({ id: cardId, to }),
});
await board.actions.move("1", "won", 0); // false when the save failedA failed save puts the card back and sets error; saving counts the moves in flight. After a reload, setLanes replaces the lanes with the server's. A move onto the card's own place, or of an unknown card or lane, returns false without calling move.
Last updated on
Assets and locations
A location hierarchy (site, building, unit) and an asset registry with tags, status, coordinates and assignment to members or records. Optional PostGIS stores points and areas as geography; booking resources and work items can name an asset.
Option sets
Tenant-editable items for a field such as priority or severity, with a label, color, icon and level per item, replacement when an item is removed, and starter items per brand.