Deals
Deals on pipelines with amounts in minor units, a company and contacts, a deal team, line items, forecast calls with attainment, close-date slips, a next step, locking and batched edits that reject per change.
deals is the sales record: a deal for a company, with contacts, an owner and a team, an amount in minor units and a close date, moving through a pipeline from qualified to won or lost. It brings the fields a sales team works with every day: a motion (new logo, expansion, renewal), a priority, the rep's forecast call, the next step, risk flags and a lock for deals finance has countersigned.
Reading needs deals.read, creating and editing needs deals.write, and deleting someone else's deal needs deals.manage. Admins get every permission, and members get deals.read and deals.write.
better-supabase add dealsThe module needs tenant, access, subjects and pipelines. Installing it binds the deal type in the pipelines module with the categories open, won and lost, and a first pipeline of Qualified (20%), Discovery (35%), Proposal (55%), Negotiation (75%), Closed won and Closed lost. Set blocks.pipelines.on.deal to change the stages or add a rotting limit; your keys are merged over the defaults.
Installing deals and parties registers deal, company and person as subjects. Set the deal page on the entity:
export default defineConfig({
blocks: { contacts: {}, deals: { names: { deal: { url: "/deals/{id}" } } } },
});Create and edit
Server code calls the deals instance on db, in the caller's organization. With gen.hooks set, better-supabase gen writes the hooks:
export const { useList: useDeals } = defineDataHooks(
"deals",
(db: AppDb) => db.deals,
);import { createDeals } from "better-supabase/blocks/deals";
import { money } from "better-supabase/commerce";
const deal = await db.deals
.create(
organizationId,
{
name: "Growth plan, 60 seats",
closeOn: Temporal.PlainDate.from("2026-11-30"),
amount: money(4_800_000n, "EUR"),
company: { type: "company", id: acmeId },
motion: "new_logo",
},
[{ type: "person", id: adaId, role: "Champion", primary: true }],
)
.orThrow();"use client";
import { useDeals } from "@/lib/supabase/hooks";
const rows = useDeals({ limit: 50 });A deal needs a name and a close date. It gets a number per organization and an identifier such as DEAL-1, or the format of a deal entity in numbering. Its company and contacts are records in config.recordTypes (the parties types company and person by default, or set options.company and options.contact). Each must be in the organization and readable by the caller (DEAL_COMPANY_FORBIDDEN, DEAL_CONTACT_FORBIDDEN), so an app can point deals at its own customers table.
Amounts are Money values from commerce: a bigint of minor units with its ISO 4217 currency. The database functions send them as text, so they stay exact past 2^53. A deal created without a currency takes the currency of its amount. Every amount on a deal, its lines and its forecast target must be in the deal's currency: the client returns CURRENCY_MISMATCH before calling the database, an unknown code returns CURRENCY_INVALID, and an amount change in update in another currency is rejected with DEAL_CURRENCY_MISMATCH. Changing the currency field keeps the amounts and lines as they are, in the new currency.
update(changes) applies a batch of cell edits, { dealId, field, value }, each on its own. A change that fails is returned in rejected with its hint and reason, and the others stay applied, the shape a data grid's batched edit needs:
const { accepted, rejected } = await deals
.update({
changes: [
{ dealId, field: "stageId", value: proposalStageId },
{
dealId,
field: "closeOn",
value: Temporal.PlainDate.from("2026-12-15"),
},
{ dealId, field: "forecast", value: "commit" },
],
})
.orThrow();A change takes an optional expectedVersion, the updatedAt of the deal as you read it. When the deal changed since, the change is refused with the hint STALE_WRITE (a conflict error under strict, see stale writes). Every change of one batch compares to the deal as it was before the batch.
create takes an idempotencyKey when createDeals gets the idempotency option (createIdempotency(...)). A retry with the same key and input returns the first deal.
The rules the table enforces for every writer:
| Rule | Hint |
|---|---|
| A locked deal takes only its note | DEAL_LOCKED |
| The open date never moves | DEAL_OPENED_ON_FIXED |
| A closed deal is called by its stage, so its forecast doesn't change | DEAL_FORECAST_CLOSED |
A close date that moves later is a slip: slippedFrom keeps the first date, pushCount counts | none |
Motions and priorities come from options.motions and options.priorities | DEAL_MOTION_INVALID, DEAL_PRIORITY_INVALID |
Your own fields
Columns you add to line with alter table in your own schema files are fields of the block (details):, keyed by column
name with their SQL type: each line's fields writes them, and setLines takes them per line. A line table of yours
runs the same way; see line tables.
Columns you add to deals with alter table in your own schema files are fields of the block (details):,
keyed by column name with their SQL type. create writes them from fields, update takes them as cell edits by name, and every deal comes back with them under fields. 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 deals = createDeals({
transport,
fields: z.object({ region: z.enum(["emea", "amer", "apac"]) }),
});
await deals.create(organizationId, {
name: "Growth",
closeOn,
fields: { region: "emea" },
});
await deals.update({
changes: [{ dealId, field: "region", value: "apac" }],
strict: true,
});update returns the refused changes in rejected and leaves the others applied. With strict: true, the first refused change is the error instead, with its hint (such as DEAL_LOCKED) as the raised code.
Paging deals
page pages deals by keyset (ADR 1077), and get(id) reads one and returns a not_found error for an unknown id. list({ subject, limit }) stays as the read for the deals of one record. Sorts are createdAt (the default, newest first), closeOn, amount and name. pipelineId, stageId, outcome, ownerId, motion, priority, forecast, currency and companyId filter by a list of values, and q searches the name and the identifier. The facets are outcome, stageId, ownerId, priority, motion and forecast. The organization comes from organizationId or the block's tenant option.
const first = await deals
.page({
filters: { outcome: ["open"], ownerId: [userId] },
sort: { by: "closeOn", direction: "asc" },
q: "renewal",
limit: 50,
})
.orThrow();
const facets = await deals.facets({ filters: { outcome: ["open"] } }).orThrow();
const total = await deals.count({ filters: { stageId: [stageId] } }).orThrow();
const one = await deals.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.
Stages, winning and losing
A deal moves stage when stageId changes, through an edit or a board drag with rank (the deal subject groups the board by stage_id). The pipelines module checks the move and keeps the stage history. A won or lost stage sets outcome, which stamps closedAt and records deal.closed with the outcome. win(dealId, note) and lose(dealId, reason) move the deal to its pipeline's first won or lost stage, and reopen(dealId, stageId?) moves it back to an open stage.
moveStage({ dealId, stageId }) is update with one stageId change and strict, so a refused move comes back as the error and your update hooks see it.
Contacts, team and lines
setContacts replaces the contacts, with one primary. setMembers replaces the deal team; each member watches the deal and, with options.readAll: false, can see it. Without readAll (the default is true), a member sees only deals they own or are on, and deals.manage sees all.
setLines(dealId, lines) replaces the line items: a description, a quantity, a unit amount as Money, a discount and a tax rate in basis points, and an optional product reference. It returns the totals, and with amountSource: "line_items" the deal's amount follows the lines' subtotal. A locked deal's lines don't change.
Forecast and review
const call = await deals
.forecast(organizationId, {
since: Temporal.PlainDate.from("2026-10-01"),
until: Temporal.PlainDate.from("2026-12-31"),
currency: "EUR",
target: money(60_000_000n, "EUR"),
})
.orThrow();
// { won, commit, bestCase, pipeline, notCalled, omit, later, attainment, gap, owners }forecast sums one currency in a period: deals won in it, open deals closing in it by forecast category (notCalled when the rep has made no call), and later for open deals that close after it. attainment is won plus commit over the target, and owners splits the same sums per owner. health(pipelineId) lists the open deals with their days in stage, whether they are rotting, whether the close date slipped, whether there is no next step, and whether the next step is overdue. With the activities module installed, a planned activity on the deal counts as its next step.
On a record page
dealsBinding loads the deals that name a record as their company or as one of their contacts, newest first, through deals.list({ subject, limit }). Archived deals stay out. The organization comes from options.tenant: without it the call fails with TENANT_REQUIRED. The read runs as the caller, so it returns only the deals the caller can read, shows at most limit deals (default 50, up to 200) and goes stale on deal.* events. It has no writes, because a deal carries money and dates, which a Server Action can't carry.
archive({ dealId }) hides a deal and restore(dealId) brings it back; a restore records deal.restored.
Events
| Event | Data |
|---|---|
deal.created, deal.updated, deal.reopened, deal.archived, deal.restored, deal.deleted | organizationId, dealId, subjectType, subjectId, name, fields |
deal.closed | the same, with outcome, amount, currency and the lost reason |
With the notifications module installed, the owner and the team watch the deal, and winning or losing it notifies its watchers.
Hooks
The module calls before_deal_create(tenant, attrs jsonb), after_deal_create(deal uuid), before_deal_update(deal uuid, field text, value jsonb) and after_deal_update(deal uuid, field text). A before_ hook raises to refuse; in update, that refuses only its change.
Wire it to ReUI
The ReUI CRM Pipeline Workspace sends every gesture through one actions.write(writes) call with { dealId, field, value } writes: map it to update, with ReUI's title as name, closeDate as closeOn, forecast as forecast and nextAt and nextStep as they are, and show rejected reasons in its toast. Board lanes come from the pipeline's stages with their probability and rotting limit, the Forecast Call's lanes from forecast, and its slipped, rotting, no-next-step and overdue chips from health. The Deal Desk's line items map to setLines, and its Mark won and Mark lost buttons to win and lose.
Errors
| Hint | Cause |
|---|---|
DEAL_FORBIDDEN | the caller lacks deals.write |
DEAL_ATTRS_INVALID | a missing name or close date, or a field with a bad value |
DEAL_NOT_FOUND | no deal the caller can edit |
DEAL_FIELD_UNKNOWN | update names a field it doesn't write |
STALE_WRITE | the deal changed since expectedVersion was read |
DEAL_OUTCOME_INVALID | close as won or lost |
DEAL_STAGE_MISSING | the pipeline has no stage for that outcome |
DEAL_CHANGES_INVALID | changes isn't a list |
DEAL_CONTACTS_INVALID | contacts aren't a list, or name two primaries |
DEAL_MEMBERS_INVALID | members aren't a list |
LINES_RECORD_INVALID | no such deal, or it is locked |
LINES_INVALID | a line lacks a description, a positive quantity or an amount |
DEAL_CURRENCY_MISMATCH | an amount or existingAmount change isn't in the deal's currency |
CURRENCY_MISMATCH | an amount isn't in the record's currency; returned before any database call |
CURRENCY_INVALID | the currency isn't an ISO 4217 code |
LINES_CURRENCY | a line sent straight to SQL isn't in the record's currency |
Without the client
db.deals is this client. Code that does not go through bsb.db() builds it with a transport and an organization id:
import { createDeals } from "better-supabase/blocks/deals";
import { money } from "better-supabase/commerce";
const deals = createDeals({ transport });
const deal = await deals
.create(
organizationId,
{
name: "Growth plan, 60 seats",
closeOn: Temporal.PlainDate.from("2026-11-30"),
amount: money(4_800_000n, "EUR"),
company: { type: "company", id: acmeId },
motion: "new_logo",
},
[{ type: "person", id: adaId, role: "Champion", primary: true }],
)
.orThrow();Last updated on
Forecasts
Snapshot the deals forecast for a period, keep the deals behind each number, and compare two snapshots deal by deal.
Quotes
Quotes with line items, sections and optional lines, document discounts, tax-inclusive prices, deposits and tax per rate, published versions, a public link and a portal the customer answers through, expiry, and quotes made from deals.