Invoices
Invoices an organization sends its own customers, with drafts and lines, a gapless number on issue, payments and refunds, credit notes, void and write-off, overdue and aging per currency, and invoices from accepted quotes.
invoices is accounts receivable: the invoices an organization sends its own customers for work, licences or goods. It is not billing, which charges your organizations for your app through Stripe. An invoice starts as a draft with lines, gets its number when you issue it, collects payments until its balance is zero, and can be credited, voided or written off. With the quotes module installed, an accepted quote becomes a deposit invoice and a final invoice.
Reading needs invoices.read, creating, issuing, recording payments and credit notes needs invoices.write, and voiding and writing off needs invoices.manage; a key per action splits them further. Every write on a purchase bill needs invoices.purchase, paying a bill that doesn't match its purchase order needs invoices.override_match, approving a bill needs invoices.approve, and sending an e-invoice needs invoices.send. Admins get every permission, and members get invoices.read.
better-supabase add invoicesThe module needs tenant, permissions and subjects.
Server code calls the invoices instance on db, in the caller's organization. With gen.hooks set, better-supabase gen writes the hooks:
export const { useList: useInvoices } = defineDataHooks(
"invoices",
(db: AppDb) => db.invoices,
);import { createInvoices } from "better-supabase/blocks/invoices";
import { money } from "better-supabase/commerce";
const draft = await db.invoices
.create(
organizationId,
{ title: "October support", company: { type: "company", id: acmeId } },
[
{
description: "Support hours",
quantity: 12,
unitAmount: money(9_500n, "EUR"),
taxRateBps: 2100,
},
],
)
.orThrow();
const invoice = await db.invoices.issue({ invoiceId: draft.id }).orThrow(); // INV-1, due in 30 days
await db.invoices
.recordPayment(invoice.id, {
amount: money(137_940n, "EUR"),
reference: "bank-2026-10-21-1",
})
.orThrow();"use client";
import { useInvoices } from "@/lib/supabase/hooks";
const rows = useInvoices({ limit: 50 });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 lines come back with them under fields (untyped,
since fields validates the record's own columns). A line table of yours
runs the same way; see line tables.
Columns you add to invoices 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 the input by name, and every invoice 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 invoices = createInvoices({
transport,
fields: z.object({ region: z.enum(["emea", "amer", "apac"]) }),
});
await invoices.create(organizationId, {
title: "October",
fields: { region: "emea" },
});Change or delete a draft
update(invoiceId, patch) changes a draft's header: title, company, contact, termsDays, note, depositBps, pricesIncludeTax, discountBps, discountAmount and fields. A key left out keeps its value, null clears it, and the block's columns and the extra columns are written in one update, so a check across both holds. Changing pricesIncludeTax or the header discount counts the totals again. delete(invoiceId) deletes a draft with its lines and charges and returns true; an issued invoice keeps its number and is voided instead (INVOICE_NOT_DRAFT).
await db.invoices.update(draftId, {
title: "Website, phase 2",
termsDays: 14,
fields: { intro: "Thanks for your order." },
});
await db.invoices.delete(draftId);The SQL functions are update_invoice(invoice, attrs jsonb) and delete_invoice(invoice). They record invoice.updated and invoice.deleted.
An imported invoice without a title gets options.titleTemplate (default Invoice {number}, with draft for a number not yet given), and an imported opening balance gets options.openingTitleTemplate (default Opening balance {number}) as its title and line description. Set them in the tenant's language.
Archive and restore
An issued invoice cannot be deleted, so archive hides one of any status
without losing its number, lines or payments. It needs the opt-in
archivedAt column and the delete permission (invoices.delete), records
invoice.archived, and does nothing when the invoice is already archived.
restore clears the mark and records invoice.restored. Without the column
both fail with INVOICE_ARCHIVE_UNSUPPORTED.
await invoices.archive(invoiceId).orThrow();
await invoices.restore(invoiceId).orThrow();Issue and number
A draft has no number. issue(invoiceId, issuedOn?) gives it the next number of its kind (INV-1, credit notes CN-1, or the formats of invoice and credit_note entities in numbering), sets the issue date (today by default) and a due date termsDays later (options.termsDays, default 30), and freezes its lines. issue(invoiceId, issuedOn, { dueOn }) sets the due date itself, on or after the issue date (INVOICE_DUE_INVALID), and an invoice created with termsDays: null (over your own table with a nullable terms column) has no due date. The number is taken in the same transaction that issues the invoice, so an issue that fails takes none. Numbers are taken only on issue, so a voided draft leaves no gap. An issued invoice voided by mistake keeps its number.
The number belongs to the period of the issue date, so a numbering format with a year ({yyyy}-{n}) numbers an invoice issued on 31 December in that year's sequence, even when it is issued in January.
The invoices table keeps the identifier unique per organization, direction and kind, so sales invoices, purchase bills and credit notes are numbered apart. When numbering restarts each period, the number repeats (2025-1 and 2026-1) while the identifier does not, which is why the key is the identifier. There is no option to turn the key off: options.uniqueNumber was removed in 0.58, and the config refuses it. Before you apply the migration that adds the key, find numbers that repeat inside a kind with the query in the 0.57 to 0.58 guide. Over your own table the block adds the unique index on its identifier column, and a table without an identifier column uses the number column.
blocks: {
numbering: { options: { entities: { invoice: { period: "format", format: "{yyyy}-{n}" } } } },
}During an import run, issue_invoice and credit_invoice take a historical number (fixed_number), and credit_invoice takes the issue date (issued_on) of the credit note it then issues at once. Outside an import run a fixed number fails with NUMBER_FIXED_FORBIDDEN. A credit note copies the legal entity of its invoice, so it counts in that entity's credit note series. See numbering.
Payments, credits and balance
Amounts are Money values from commerce: lines, totals, payments, the paid, credited and outstanding sums and the aging buckets. The database functions send them as text, so they stay exact past 2^53. Every line, credit and payment must be in the invoice's currency: the client returns CURRENCY_MISMATCH before calling the database, and record_invoice_payment refuses a payment in another currency (INVOICE_CURRENCY_MISMATCH). An invoice created without a currency takes the currency of its lines.
The balance is the total minus credits minus payments. recordPayment takes an optional note kept with the payment, and each of an invoice's payments returns its note and recordedBy, the user who recorded it. It adds a payment (a negative amount is a refund, which can't exceed what was paid: INVOICE_REFUND_TOO_LARGE) and moves the invoice to partially_paid or paid. A reference, such as a bank transaction or a payment provider id, is unique per organization, so a webhook that delivers the same payment twice records it once.
Payments live on the ledger. Each invoice has a receivable account (code invoice:<id>) and each currency a cash account (invoices:cash:<currency>); a payment is a transaction of kind invoice.payment (or invoice.refund) that moves the amount from the receivable to cash, and its paymentId is the transaction id. reversePayment(paymentId, reason?) reverses a payment recorded by hand, such as a bounced transfer: it posts the opposite transaction (kind invoice.payment_reversal, pointing at the payment) and keeps the original, so the invoice is open again. A payment is reversed once (INVOICE_PAYMENT_REVERSED). A payment whose method is in options.providerPaymentMethods (default stripe and order) is refunded through its provider instead (INVOICE_PAYMENT_PROVIDER). Needs invoices.manage. The ledger client's holderAccounts({ type: "invoices", id }) reads an invoice's receivable account with its entries.
recomputeStatus(invoiceId) (recompute_invoice_status in SQL) derives an issued invoice's status, paidTotal and creditedTotal from its ledger payments, its imported allocations and its issued credit notes, the way the payment and credit functions do, including credited with options.creditedStatus. Call it after changing payments or credit notes outside the block's functions, instead of writing the status. The paid total never drops below the stored one, because an import's row settlement writes it without a ledger posting; reverse a payment to lower it. A draft, void or uncollectible invoice keeps its status (an uncollectible one settles with options.paymentsAfterWriteOff), but its totals are rewritten all the same. It records invoice.paid only when an invoice that was never paid (no paidAt) moves to paid; a move to credited, or from paid back to issued, records no block event (a state machine over the table still records status.changed). Needs invoices.manage, or invoices.purchase for a purchase invoice, and a session that may write.
payments(invoiceId) reads an invoice's payments, refunds and reversals, oldest first, with recordedBy on each, without loading the whole invoice. It needs permissions.read (list_invoice_payments) and returns INVOICE_NOT_FOUND to a caller who can't read the invoice.
credit(invoiceId, { lines? }) makes a draft credit note for the whole invoice, or for the given lines; issuing it reduces the original's balance and can settle it. A credit note can't exceed the invoice's total and charges less its earlier credits (INVOICE_CREDIT_TOO_LARGE), so a paid invoice can still be credited: issue the credit note, then record the refund as a negative payment. An issued credit note can't change.
void(invoiceId, reason) voids a draft, or an issued invoice without payments or credits. writeOff(invoiceId, reason?) marks an open invoice uncollectible; over your own table, columns.invoices.writeOffReason keeps the reason, and invoice.uncollected carries it. Both are written to the audit log.
A written-off invoice refuses payments (INVOICE_NOT_PAYABLE) unless you set options.paymentsAfterWriteOff: true. Then a payment that still arrives, such as a bank transfer or a provider payment started before the write-off, is booked on the ledger like any other. The invoice stays uncollectible while a balance is left and moves to paid once nothing is owed, which records invoice.paid. The write-off books the open balance as an expense when the accounting block is installed, and the write-off reason stays on the invoice.
blocks: {
invoices: { options: { paymentsAfterWriteOff: true } },
},issue(invoiceId, issuedOn, { actor }), recordPayment(invoiceId, { amount, actor }), void(invoiceId, reason, { actor }), writeOff(invoiceId, reason, { actor }), reversePayment(paymentId, reason, { actor }), charge(invoiceId, { amount, actor }) and removeCharge(chargeId, { actor }) take who acted, for the state machine's history of the status change they cause; a credit note's issue passes its actor to the status change of the invoice it settles. The void, write-off and reversal reasons are the history's reason, as is recordPayment's reason for the status change a payment or refund causes (recordPayment(invoiceId, { amount, reference, reason: "Payment refunded via Stripe" })), so a machine over the invoices table can write its own history (write: true). In SQL, those functions take a trailing actor jsonb, and an actor that isn't an object fails with INVOICE_ACTOR_INVALID.
| Status | Meaning |
|---|---|
draft | lines can change; no number yet |
issued | numbered and sent; nothing paid |
partially_paid | paid or credited in part |
paid | balance zero |
void | cancelled before anything was paid |
uncollectible | written off |
credited | fully credited (creditedStatus) |
The credited status
By default an invoice that credit notes fully cover becomes paid. With options.creditedStatus: true it becomes credited instead, whether it was unpaid or already paid (record the refund as a negative payment afterwards; it stays credited). An invoice is fully credited when its credit notes reach its total plus its charges; a smaller credit leaves it partially_paid or paid. credited is closed: the credit note records invoice.credited with the organization and invoice id, never invoice.paid (which is recorded only when an invoice moves to paid), and the invoice takes no charges. Voiding the credit note gives the credit back, and the invoice moves to the status its balance gives (issued, partially_paid or paid). Voiding an issued credit note gives its credit back with the option off too, and a state machine over the invoices table records the status.changed of the original invoice (for example paid back to issued). Credit notes voided before 0.73 are not restored retroactively; call recomputeStatus(invoiceId) on such an invoice.
blocks: {
invoices: { options: { creditedStatus: true } },
}The option is off by default, so a status column without a credited value keeps working. Turn it on once yours has one: the block's own table accepts it then, and an enum of yours needs alter type ... add value 'credited'. A state machine over the invoices table writes the history and the status.changed event; give it transitions from issued, partially_paid and paid to credited, and from credited back to those three, and treat credited as a closed state next to paid and void in your own filters.
Every invoice a read returns has balance and overdue (open and past its due date).
Charges
charge(invoiceId, { amount, description? }) adds an amount on top of an issued invoice's total, such as collection costs, statutory interest or a late fee, in the invoice's currency. Charges live in the invoice_charges table (tables.charges, which can be your own table or null), raise the balance and the aging, and come back as charges and chargedTotal on every read. A paid invoice with a new charge is partially_paid again until the charge is paid. Each charge records invoice.charged. removeCharge(chargeId) deletes a charge added by mistake from an issued invoice, settles the balance again and records invoice.charge_removed.
Your own charges table can carry columns the block doesn't know, such as a kind not null column. Add them to the charges table, then pass them as charge(invoiceId, { amount, fields: { kind: "collection" } }); reads return them under each charge's fields.
Line rates as percentages
Lines carry discountBps and taxRateBps in basis points (2100 is 21%). When your own line table keeps percentages, such as vat_rate numeric(5, 2), map the columns and set options.lineRates: "percent": the block writes taxRateBps / 100 and reads the column times 100, so the client still sees basis points. The option needs your own line table; quotes and deals take it too. When the tax rate is a percentage but the discount column keeps basis points, also set options.lineDiscountRates: "bps", so the discount is written and read unchanged.
Over your own line table, the block adds a unique index on the invoice and position, which setLines uses to update lines in place. If your app renumbers lines with one update, which that index refuses halfway, set options.linePositionKey: false: the block leaves the index out, and setLines updates the lines by position and inserts the rest.
The block also creates invoices_tenant_status_idx on the tenant, status and due date. When your schema already has an index that starts with those columns, set indexes: { skip: ["invoices_tenant_status_idx"] } so the module does not create it again. The name is the one in create index. A name the module does not create is an error.
Staff reads and portal reads
permissions.read is the key a member needs to read every invoice of the organization, and the block checks it through the authorization provider's SQL functions, so the provider has to mark it sqlComplete: true. When your read permission carries a row condition, such as a portal user who may read only their own customer's invoices, give the block a separate staff key (permissions: { read: "invoice.read_all" }) and let portal users in through guests: the read policy also admits a guest granted the invoice, and with a provider that answers portalSubjects, a portal party of the invoice's company or contact.
A key per action
write and manage cover several actions. Name a key per action in permissions to split them; an action without its own key checks write or manage as before, and delete checks update, then write.
| Key | Functions | Without it |
|---|---|---|
create | create_invoice, invoice_from_quote | write |
update | set_invoice_lines, update_invoice | write |
delete | delete_invoice | update |
issue | issue_invoice | write |
payment | record_invoice_payment | write |
settle | record_invoice_payment for the whole balance | payment |
credit | credit_invoice | write |
charge | create_invoice_charge, delete_invoice_charge | write |
void | void_invoice | manage |
writeOff | write_off_invoice | manage |
reverse | reverse_invoice_payment | manage |
Members who draft invoices but may not send them or book payments:
blocks: {
invoices: {
permissions: {
read: "invoice.read",
write: "invoice.update",
manage: "invoice.cancel",
issue: "invoice.send",
payment: "invoice.record_payment",
},
},
},The functions check the keys themselves, so a member without invoice.send can't issue through the API either.
settle is a second key that may pay an invoice in full but not in part, for a "mark paid" action next to a finer "record payment" one. record_invoice_payment accepts the caller with payment, or with settle when the amount is positive and equals the open balance, or the reference was already recorded, so markPaid and its retries work with either key:
permissions: {
payment: "invoice.record_payment",
settle: "invoice.mark_paid",
},A caller who can read the invoice but lacks an action's key gets INVOICE_FORBIDDEN (42501), so the app can say why. Reading counts the read key and the invoices table's own select policies, so a member who sees invoices through an app policy, such as one with row conditions the read key can't carry, gets the same answer. A caller who can't read it gets INVOICE_NOT_FOUND, which keeps the invoice's existence hidden.
Totals the app keeps
By default the block recounts an invoice's totals from its lines, rounding each line once, from each line's discountBps and taxRateBps and the header's pricing. It knows no fixed discount per line and no VAT regime that keeps the line rates but counts no VAT (reverse charge, exempt, a small-business scheme). When the app computes them itself, for those or for VAT per rate on the summed lines, set options.totals: "app". The block then installs no totals trigger, never writes subtotal, taxTotal or total, and reads what they hold for the balance, credits, events and aging. listTotal and discountTotal can map to null then; reads fill them from the subtotal and zero.
A customer, contact or quote as a foreign key
The company, contact and origin are a type and an id column each. Over your own table, map the type column to null and the id to your foreign key column, and the party has one fixed type: options.company for the company, options.contact for the contact and quote for the origin. The block writes the id cast to the column's type, refuses another type (INVOICE_COMPANY_UNSUPPORTED, INVOICE_CONTACT_UNSUPPORTED, INVOICE_ORIGIN_UNSUPPORTED), checks the record like a typed pair, and reads back company_type, contact_type and origin_type:
blocks: {
invoices: {
tables: { invoices: "public.invoices", lines: "public.invoice_lines", charges: "public.invoice_charges" },
columns: {
invoices: {
companyType: null, companyId: "customer_id",
contactType: null, contactId: "customer_contact_id",
originType: null, originId: "source_quote_id",
subtotal: "subtotal_excl_cents", taxTotal: "vat_total_cents", total: "total_incl_cents",
listTotal: null, discountTotal: null,
},
},
options: { company: "customer", contact: "customer_contact", totals: "app" },
},
}The customer and customer_contact types are subjects in config.recordTypes.
From a quote
const deposit = await invoices
.fromQuote(quoteId, { depositBps: 3000 })
.orThrow(); // 30%
const final = await invoices.fromQuote(quoteId).orThrow();The quote must be accepted (INVOICE_QUOTE_NOT_ACCEPTED). A deposit invoice has one line for that share of the quote's subtotal at the quote's average tax rate, or of its total when the quote's prices include tax. The final invoice copies the lines the customer accepted (required lines and the optional lines they selected), adds one Discount line per tax rate for the quote's document discount, and subtracts each deposit invoice already issued; it is made once per quote, so calling it again returns the same draft. It takes the quote's pricesIncludeTax, so its totals and tax match the accepted quote. An invoice that credit notes fully credited, or that the opt-in archivedAt column marks, no longer counts as the final invoice, so the next call makes a new one.
fromQuote(quoteId, { depositAmount }) makes a deposit invoice for a fixed amount, tax included, at most the quote's total; a share and an amount together answer INVOICE_DEPOSIT_INVALID. Both invoices copy the line extra columns (lineExtraColumns) and the header extra columns (extraColumns) the quote has under the same name, such as a unit, a line type or a VAT regime. A line's product goes along too, also when the quote's line table has only a product id column and the invoice's line table has no product type.
A line extra column value the invoice's column can't take, such as a pricing mode only quotes have, is left out, so the column's default applies. options.quoteLineValues maps quote values to invoice values first:
blocks: {
invoices: {
options: {
quoteLineValues: { pricing_mode: { subscription: "unit" } },
depositLine: { description: "Deposit {identifier}", fields: { line_type: "deposit" } },
},
},
}The final invoice takes each issued deposit off per tax rate of the deposit's lines: one line per deposit and rate, so a deposit with 21% and 9% lines gives two lines at those rates. A deposit whose pricesIncludeTax differs from the final invoice's is converted per rate, so the deduction is on the final invoice's basis. A deposit that credit notes fully credited, or that archivedAt marks, is not deducted. options.depositLine.description names these lines ({identifier} is the deposit invoice's, default Deposit {identifier}), and options.depositLine.fields sets line extra columns on every deposit line fromQuote writes, such as a not null line type. Pass depositDescription to translate the description per call:
const final = await invoices
.fromQuote(quoteId, { depositDescription: "Anzahlung {identifier}" })
.orThrow();These columns of the invoices table are opt-in: name them in columns.invoices to use them, and the block adds them to its own table. An app table made before them keeps working without them.
| Column | What it does |
|---|---|
archivedAt | a timestamp your app sets to archive an invoice; fromQuote skips an archived invoice |
depositAmount | holds a fixed deposit invoice's amount and marks it as a deposit; create and update take it |
discountBps | a percentage off the whole invoice, counted like a quote's document discount |
discountAmount | an amount off the whole invoice, after discountBps |
With discountBps (and discountAmount, when the quote has it), the final invoice keeps the quote's document discount on its header instead of Discount lines. While deposits are deducted and the block counts the totals, it keeps the lines: a header discount would take its share off the deductions too. With totals: "app", the header always gets it.
A deposit invoice is told from the final one by depositBps or depositAmount. options.depositKind marks it by the kind column instead: one of the values the invoice kind maps to, which fromQuote writes on a deposit invoice and finds the deposits to deduct by, with the link to the quote. The block treats it as an invoice everywhere else.
blocks: {
invoices: {
columns: { invoices: { depositBps: null, discountBps: "discount_bps", discountAmount: "discount_amount_cents" } },
options: { totals: "app", depositKind: "deposit" },
values: { invoices: { kind: { invoice: ["invoice", "deposit"] } } },
},
}const deposit = await invoices
.fromQuote(quoteId, { depositAmount: money(50_000n, "EUR") })
.orThrow();An invoice with pricesIncludeTax: true counts tax out of its unit amounts instead of adding it. create takes it, a credit note copies it, and invoice.pricesIncludeTax reads it. An invoices table of yours without the prices_include_tax column refuses it (INVOICE_PRICING_UNSUPPORTED).
Purchase bills
The same table keeps the bills an organization receives from its suppliers.
An invoice created with direction: "purchase" is a purchase bill: the
company or contact is the supplier, supplierReference keeps the
supplier's own invoice number, and purchaseOrderId links an
inventory purchase order. Every
write on a bill needs invoices.purchase instead of the sales keys, and
reading needs invoices.read.
const bill = await db.invoices
.create(
organizationId,
{
title: "Parts, October",
direction: "purchase",
company: { type: "company", id: supplierId },
supplierReference: "ACME-2026-1187",
purchaseOrderId: order.id,
dimensions: { project: "PRJ-12" },
},
[
{
description: "Bearings",
product: { type: "product_variant", id: variantId },
quantity: 60,
unitAmount: money(450n, "EUR"),
},
],
)
.orThrow();
await db.invoices.issue({ invoiceId: bill.id }).orThrow(); // books the bill: BILL-1
const match = await db.invoices.match(bill.id).orThrow();
// { status: "matched", lines: [{ variantId, quantity: "60", receivedQuantity: "60", ... }] }issue books a bill the way it numbers an invoice, from a sequence of its
own: BILL-1 and, for a credit note on a bill, BCN-1
(options.purchasePrefix and options.purchaseCreditPrefix). The unique
number index covers the direction, so a sales invoice and a bill can share a
number. aging(organizationId, currency, asOf, "purchase") sums what the
organization owes its suppliers.
The three-way match
match(billId) (purchase_bill_match in SQL) compares each product line of
a bill with its purchase order line and the received quantities in the
inventory receipts, and records invoice.match_checked. The worst line
decides the status:
| Status | When |
|---|---|
matched | every line is within the tolerance |
price_variance | a line's amount differs from quantity times the order's unit cost beyond the tolerance |
quantity_variance | the order's bills charge more of a variant than arrived |
not_received | nothing of a billed variant arrived yet |
not_applicable | the bill has no purchase order |
The tolerance is options.matchTolerance, { bps: 100, amount: 500 } by
default: a difference of 1 percent or 500 minor units, whichever is larger.
Recording a payment on a bill with a purchase order that doesn't match fails
with INVOICE_MATCH_FAILED, unless the caller holds invoices.override_match.
Credit limits
With the contacts block installed, issuing a sales
invoice adds its total to what the customer already owes in that currency and
compares the sum with the party's credit_limit. Over the limit, issue
fails with INVOICE_CREDIT_LIMIT_EXCEEDED unless the caller holds
orders.override_credit. The limit counts only in its own credit_currency.
A customer whose credit_block is soft is let through, and the overage comes
back as warnings in the result; none skips the check.
Party payments and credit
recordPartyPayment(organizationId, payment) records one payment from a
customer over several of its open sales invoices, such as a bank transfer
that settles three invoices at once. The party is the company or contact id
the invoices name. Each allocation is recorded as a payment of that invoice,
with the reference <reference>/<invoiceId>. What the allocations leave over
becomes the party's credit, kept on the ledger account
invoices:credit:<party>:<currency>.
const result = await db.invoices
.recordPartyPayment(organizationId, {
partyId: company.id,
amount: money(150_000n, "EUR"),
allocations: [
{ invoiceId: first.id, amount: money(100_000n, "EUR") },
{ invoiceId: second.id, amount: money(30_000n, "EUR") },
],
reference: "bank-2026-10-31-0042",
})
.orThrow();
result.credited; // 200.00 EUR, kept as creditThe reference is required and unique per organization, so recording the same
payment again adds nothing. An allocation can't be more than the invoice's
balance (INVOICE_ALLOCATION_TOO_LARGE); keep the rest as credit instead.
applyPartyCredit(partyId, invoiceId, amount) pays an open invoice from the
party's credit in the invoice's currency, and partyCredits(organizationId, partyId) reads what is left per currency. A credit payment shows in the
invoice's payments with method credit, and reversing it moves the amount
back to the credit. Both need the payment permission.
Dunning
Dunning levels set when an overdue invoice gets each reminder. A level has the days past the due date it is reached, the template key the reminder is rendered from, a fee in minor units of the invoice's currency, and whether it is the final reminder.
await db.invoices
.setDunningLevels(organizationId, [
{ daysAfterDue: 7, templateKey: "invoice-reminder" },
{ daysAfterDue: 21, templateKey: "invoice-second-reminder", fee: 1_500n },
{
daysAfterDue: 35,
templateKey: "invoice-final-notice",
fee: 4_000n,
final: true,
},
])
.orThrow();setDunningLevels replaces the organization's levels and needs
invoices.manage. The days rise from level to level and only the last level
can be final (INVOICE_DUNNING_LEVELS_INVALID). A fee needs the charges table
(INVOICE_DUNNING_FEE_UNSUPPORTED).
runDunning() runs as the service role. The manifest's dunning schedule
calls it every morning. It raises each open, overdue sales invoice to the
highest level it has reached, adds the level's fee as a charge,
notifies the invoice's creator when the
notifications block is installed, and records
invoice.dunning_escalated. An invoice skips the levels it passed while
paused, so it never gets two reminders in one run. Notifications reach
members only; send the reminder to the customer from an outbox sink on
invoice.dunning_escalated, which carries the level's templateKey.
pauseDunning(invoiceId, until, reason?) holds the reminders until a date,
such as during a dispute, and pauseDunning(invoiceId, null) resumes them. It
needs invoices.collect and records invoice.dunning_paused. Every invoice
read returns dunning: { level, at, pausedUntil }.
Dunning runs
runDunning() records each pass as a run. dunningRuns(organizationId, { limit })
lists them newest first, dunningRunItems(runId) returns the invoices a run
picked grouped by customer, and dunningHistory(invoiceId) lists what happened
to one invoice, oldest first. A level can carry a textKey for the reminder
wording next to its templateKey.
handOverToCollection(invoiceIds, agencyPartyId, { note }) hands up to 500
open sales invoices to a collection agency. It needs invoices.collect, sets
collection.status to handed_over, stops their dunning, records
invoice.collection_started and returns the ids. It fails with
INVOICE_HAND_OVER_INVALID, INVOICE_ALREADY_HANDED_OVER or
INVOICE_NOT_PAYABLE.
Discount matrix
With options.discountMatrix: true and the catalog block installed, set_invoice_lines prices each line that names a catalog variant through the discount matrix for the invoice's company (else its contact) 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. Values on the line win. The option is off by default.
Recurring invoices
A recurring invoice is a template schedule:
a template type whose apply creates and issues the invoice, applied at each
occurrence of a recurrence rule.
import { defineTemplateType } from "better-supabase/blocks/templates";
export const invoice = defineTemplateType<
{ readonly companyId: string; readonly termsDays: number },
{ readonly title: string; readonly lines: readonly LineInput[] }
>({
settings: InvoiceSettings,
body: InvoiceBody,
async apply({ settings, body, organizationId, key }) {
const created = await adminInvoices
.create(
organizationId,
{
title: body.title,
company: { type: "company", id: settings.companyId },
termsDays: settings.termsDays,
fields: { scheduleKey: key },
},
body.lines,
)
.orThrow();
await adminInvoices.issue(created.id).orThrow();
return { subject: { type: "invoices", id: created.id } };
},
});Keep the key in an extra column with a unique index, so a second worker that
claims the same occurrence fails on the insert instead of creating a second
invoice. The schedule then needs only the rule:
await templates.recurring
.upsert({
template: monthlyRetainer.id,
organizationId,
dtstart: Temporal.Instant.from("2026-11-01T08:00:00Z"),
tzid: "Europe/Amsterdam",
rrule: "FREQ=MONTHLY;BYMONTHDAY=1",
})
.orThrow();E-invoices
better-supabase/e-invoicing writes an issued
invoice or credit note as a UBL 2.1 document for Peppol and reads a received
one into a purchase bill.
Send through a format and a channel
sendEInvoice renders an issued invoice with an EInvoiceFormat, checks the
buyer with the channel's lookup, hands the document to an EInvoiceChannel
and logs the delivery as pending in e_invoice_deliveries. Both are
versioned ports (apiVersion: 1). peppolBis3Format is the Peppol BIS
Billing 3.0 format, and a channel package owns the access point credentials.
It needs invoices.send and a participant id on the buyer's company.
Drafts and void invoices come back as E_INVOICE_NOT_ISSUED, a buyer without
an id as E_INVOICE_NO_RECIPIENT, an unreachable buyer as
E_INVOICE_RECIPIENT_UNREACHABLE and an invoice already sent as
E_INVOICE_ALREADY_SENT unless you pass resend. A format or channel that
throws comes back as an error result.
await invoices.setEInvoiceEndpoint({
organizationId: orgId,
partyKind: "company",
partyId: companyId,
endpoint: { scheme: "0106", id: "12345678" },
});
const sent = await invoices
.sendEInvoice({
invoice: await invoices.issue({ invoiceId: draft.id }).orThrow(),
format: myPeppolFormat,
channel: myAccessPoint,
})
.orThrow();
// Later, on a schedule:
await invoices
.syncEInvoices({ organizationId: orgId, channel: myAccessPoint })
.orThrow();syncEInvoices moves pending deliveries to delivered or rejected, and
receiveEInvoices turns documents from the channel into purchase bills of the
company that owns the sender's participant id. Documents it can't match stay in
the log as unmatched. Each step records an invoice.e_invoice_sent,
invoice.e_invoice_delivered, invoice.e_invoice_rejected or
invoice.e_invoice_received event. The e-invoicing page
has the details.
In the books
With the accounting block installed, issuing an invoice or credit note books it in the sales journal (the receivable against revenue and tax per rate), each payment or refund books in the bank journal, and voiding an invoice reverses its entry, in the same transaction. Charges and write-offs aren't booked yet.
A purchase bill books in the purchase journal: the supplier's payable against
expense and deductible tax, with the bill's dimensions on the expense lines,
so project costing counts a bill with a project
dimension. A purchase line can carry its own dimensions ({ project: "PRJ-13" }),
which win over the bill's for the same key, so one bill can split its cost over
projects. Lines of one bill that share a dimension set share an expense line.
The invoice_lines table gains a dimensions column, also over your own
lines table; a sales line ignores it. With inventory installed, a product line of a bill with a purchase
order debits the payable the stock receipt already booked instead of an
expense, so received stock isn't counted twice. Paying a bill credits the bank
and debits the payable.
A party payment's credit books in the bank journal when it arrives: the bank against the party's receivable. Applying the credit to an invoice later books nothing, since the receivable was already credited.
Open items and allocation
openItems(organizationId, { partyId, asOf, side }) lists what a party owes
or is owed as of a date: open invoices and bills, plus payments and credits
that are not allocated yet as negative balances. openItemAgeing sums the
same items per party, currency and bucket (notDue, days1To30, days31To60,
days61To90, over90).
For today, both read the invoice_open_items table instead of replaying the
ledger. It holds one row per open invoice and one per party credit account with
an unallocated payment. Triggers on invoices, charges and ledger balances keep
it current, and an invoice issued with a future date shows from its issue date.
A past or future asOf replays invoices and ledger entries. An import calls
rebuild_open_items(tenant) once after the documents are in; only the service
role may call it.
open_items_drift(tenant) returns the rows where the table and the replay
differ (at most 100), import_integrity reports them as open_items_drift,
and doctor rule BS638 lists the organizations to rebuild. Set
blocks.invoices.tables.openItems to null to read the replay every time.
allocatePayment(organizationId, payment) spreads one payment or credit over
several documents of a party. An amount below the balance is a partial
payment, an amount above it stays on the party as credit, and an allocation
that arrives by the document's discount_due_on takes the early-payment
discount and posts it through accounting to invoices:discount:<sales|purchase>:<CUR>.
Sending the same reference again adds nothing. unallocatePayment reverses
every allocation of a reference and the documents reopen, discount included.
allocations lists them. The events are invoice.allocated,
invoice.unallocated and invoice.discount_applied.
await invoices.allocatePayment(organizationId, {
partyId,
side: "supplier",
amount: Money.of("980.00", "EUR"),
currency: "EUR",
receivedOn,
reference: "pay-2",
allocations: [{ invoiceId, amount: Money.of("980.00", "EUR") }],
});Purchase approval levels
setApprovalLevels(organizationId, levels, { legalEntityId }) sets the levels
by amount: a bill from minAmount up needs the approval of that level's
approverId, and each legal entity can have its own list. A person with
invoices.approve calls approvePurchaseInvoice(invoiceId) to sign the levels
they are the approver of, and approvalStatus(invoiceId) reports not_required,
pending or approved with the levels still open. A bill that waits for
approval is skipped by payment batches.
A list of bills reads where each stands in one call:
approvalStatuses(invoiceIds) (purchase_invoice_approval_statuses(invoice_ids))
returns a map from invoice id to the same approval approvalStatus returns. A
bill the caller cannot read has no entry.
const statuses = await invoices
.approvalStatuses(bills.map((bill) => bill.id))
.orThrow();
const waiting = bills.filter(
(bill) => statuses.get(bill.id)?.status === "pending",
);Repair stored totals
An invoice issued before its header total followed the payment-term credit
restriction keeps the old figures. recomputeTotals(organizationId, { invoiceIds?, dryRun? })
(recompute_invoice_totals(tenant, invoice_ids, dry_run)) recomputes the
header and tax lines of issued invoices through the tax computation and
reports each difference as old, new and the balance before and after. It
is a dry run unless you pass dryRun: false, writes only invoices that differ,
and a second run changes nothing. It never changes a number, an issue date or a
status. Needs invoices.manage.
const preview = await invoices.recomputeTotals(organizationId).orThrow();
await invoices.recomputeTotals(organizationId, { dryRun: false }).orThrow();Each correction is written to the audit log as invoice.totals_corrected
(a system correction, category billing). The event is sent to the outbox only
when options.correctionEvents is on. A posted accounting entry is never
changed: when an invoice is booked, its ledger reports posted,
entryNumber, the periodStatus and needsCorrectingEntry: true, also when
the period is closed, so the books are corrected with an entry of your own.
Aging
aging(organizationId, currency, asOf?, direction?) sums what is owed in one currency by days past due: not yet due, 1 to 30, 31 to 60, 61 to 90 and over 90, with the total outstanding and the number of overdue invoices. direction is sales by default; purchase sums the open bills.
Aging has no separate read to add: aging already returns the buckets for sales invoices and, with direction: "purchase", for payables, in one call per currency. accounting.trialBalance and the other reports cover the finance pages the same way.
On a record page
invoicesBinding loads the invoices that name a record as their company or contact, newest first, through invoices.list({ subject, limit }) with the subject as { type: "company", id } (or the renamed type). The organization comes from options.tenant: without it the call fails with TENANT_REQUIRED. The read needs the invoices read key, shows at most limit invoices (default 50, up to 200) and goes stale on invoice.* events. It has no writes, because issuing or paying an invoice takes dates and money, which a Server Action can't carry.
Events
| Event | Data |
|---|---|
invoice.created, invoice.updated, invoice.deleted, invoice.issued, invoice.paid, invoice.voided, invoice.uncollected | organizationId, invoiceId, subjectType, subjectId, identifier, and total, currency, dueOn, reason or balance |
invoice.payment_recorded | the same, with paymentId, amount and balance |
invoice.credited | the same, with creditNoteId and amount |
invoice.payment_reversed | the same, with paymentId, reversalId, amount, balance and reason |
invoice.charged, invoice.charge_removed | the same, with chargeId, amount and balance |
invoice.credit_applied | the same, with paymentId, partyId, amount and balance |
invoice.dunning_escalated | the same, with level, templateKey, fee, final, balance and dueOn |
invoice.dunning_paused | the same, with until and reason |
invoice.allocated, invoice.unallocated | the invoice, with reference, partyId, amount and balance |
invoice.discount_applied | the invoice, with reference, amount and balance |
invoice.approved | the invoice, with level and approvalStatus |
invoice.collection_started | the invoice, with agencyPartyId, balance and level |
invoice.totals_corrected | the invoice, with oldTotal, newTotal, oldTaxTotal, newTaxTotal and needsCorrectingEntry (sent only with options.correctionEvents) |
Send the customer's reminder from invoice.dunning_escalated with an outbox sink that renders its templateKey, or build your own sequence with a workflow that waits until the due date and checks the balance.
Hooks
The module calls before_invoice_issue(invoice uuid), after_invoice_issue(invoice uuid), before_invoice_payment(invoice uuid, amount bigint) and after_invoice_payment(invoice uuid, payment uuid), so an app can export an issued invoice to its accounting system or release an order once it is paid.
Errors
| Hint | Cause |
|---|---|
INVOICE_FORBIDDEN | the caller can read the invoice but lacks the action's key, such as payment, issue or writeOff |
NUMBER_FIXED_FORBIDDEN | a fixed number outside an import run |
INVOICE_ATTRS_INVALID | a missing title or a field with a bad value |
INVOICE_NOT_FOUND | no invoice the caller can read |
INVOICE_NOT_DRAFT | the invoice was already issued, so it no longer changes and isn't deleted |
INVOICE_ARCHIVE_UNSUPPORTED | archive or restore on an invoices table without the archivedAt column |
INVOICE_EMPTY | an invoice without lines can't be issued |
INVOICE_NOT_PAYABLE | only an issued invoice takes payments, or a written-off one with paymentsAfterWriteOff |
INVOICE_PAYMENT_INVALID | a payment needs an amount |
INVOICE_CURRENCY_MISMATCH | a payment isn't in the invoice's currency |
INVOICE_REFUND_TOO_LARGE | a refund is more than was paid |
INVOICE_NOT_CREDITABLE | only an issued invoice is credited |
INVOICE_CREDIT_TOO_LARGE | the credit is more than the total less earlier credits, or applied credit is more than the balance |
INVOICE_DUE_INVALID | the due date is before the issue date |
INVOICE_PAYMENT_NOT_FOUND | no such payment on an invoice the caller can manage |
INVOICE_PAYMENT_PROVIDER | the payment came from a payment provider and is refunded there |
INVOICE_PAYMENT_REVERSED | the payment is a reversal or is already reversed |
INVOICE_CHARGE_NOT_FOUND | no such charge on an invoice the caller can edit |
INVOICE_NOT_VOIDABLE | an invoice with payments or credits is credited instead |
INVOICE_NOT_OPEN | only an open invoice is written off |
INVOICE_QUOTE_NOT_ACCEPTED | the quote isn't accepted |
INVOICE_DEPOSIT_INVALID | a deposit is between 0 and 100 percent, or an amount up to the quote's total, not both |
INVOICE_DEPOSIT_UNSUPPORTED | the invoices table has no column for that deposit |
INVOICE_DISCOUNT_UNSUPPORTED | the invoices table has no column for a header discount |
INVOICE_ORIGIN_NOT_FOUND | no quote the caller can invoice |
INVOICE_NOT_CHARGEABLE | only an issued invoice takes charges |
INVOICE_CHARGE_INVALID | a charge has a positive amount |
INVOICE_COMPANY_UNSUPPORTED | the invoices table takes only the fixed company type |
INVOICE_MATCH_FAILED | a payment on a purchase bill that doesn't match its purchase order, without invoices.override_match |
INVOICE_NOT_PURCHASE_BILL | only a purchase bill is matched |
INVOICE_PURCHASE_ORDER_NOT_FOUND | no such purchase order in the bill's organization |
INVOICE_PURCHASE_ORDER_INVALID | only a purchase bill refers to a purchase order |
INVOICE_DIRECTION_UNSUPPORTED | the invoices table has no direction column for purchase bills |
INVOICE_CREDIT_LIMIT_EXCEEDED | issuing the sales invoice takes the customer over their credit limit |
INVOICE_DUNNING_RUN_NOT_FOUND | no such dunning run |
INVOICE_HAND_OVER_INVALID | no invoice ids, more than 500, or an agency that isn't a company or person |
INVOICE_ALREADY_HANDED_OVER | an invoice is already with a collection agency |
INVOICE_PARTY_INVALID | a party id is required and at most 150 characters |
INVOICE_PAYMENT_REFERENCE_REQUIRED | a party payment needs a reference, such as the bank transaction id |
INVOICE_ALLOCATIONS_INVALID | allocations are { invoiceId, amount } with a positive amount, one per invoice |
INVOICE_ALLOCATIONS_TOO_LARGE | the allocations add up to more than the payment |
INVOICE_ALLOCATION_TOO_LARGE | an allocation is more than the invoice's balance |
INVOICE_PARTY_MISMATCH | the invoice isn't this party's |
INVOICE_CREDIT_INSUFFICIENT | the party has less credit in the invoice's currency |
INVOICE_DUNNING_LEVELS_INVALID | at most 20 levels, with rising days and only the last one final |
INVOICE_DUNNING_FEE_UNSUPPORTED | a level has a fee and the module has no charges table |
INVOICE_DUNNING_PAUSE_INVALID | a pause ends today or later, and its reason is at most 2000 characters |
CURRENCY_MISMATCH | a line, credit or payment 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.invoices is this client. Code that does not go through bsb.db() builds it with a transport and an organization id:
import { createInvoices } from "better-supabase/blocks/invoices";
import { money } from "better-supabase/commerce";
const invoices = createInvoices({ transport });
const draft = await invoices
.create(
organizationId,
{ title: "October support", company: { type: "company", id: acmeId } },
[
{
description: "Support hours",
quantity: 12,
unitAmount: money(9_500n, "EUR"),
taxRateBps: 2100,
},
],
)
.orThrow();
const invoice = await invoices.issue({ invoiceId: draft.id }).orThrow(); // INV-1, due in 30 days
await invoices
.recordPayment(invoice.id, {
amount: money(137_940n, "EUR"),
reference: "bank-2026-10-21-1",
})
.orThrow();Line costs and billing parties
A line can carry discountAmount next to discountBps, a unitCost with a
costSource (catalog, average, manual or imported), a taxCodeId, a
locationId and a binId. A line without a product is free text, and the
same product can appear on several lines. billingParty says who pays a
line (customer, internal, own_warranty, supplier_warranty or
cost_account), with a billingPartyId or billingAccountId.
document_totals_by_billing_party(document) returns the totals and the cost per billing party.
Invoice several sources at once
invoiceFromSources builds invoices from delivered orders, delivered shipments and unbilled time for one party. The sources split into one draft invoice per billing party and currency, so a customer with an own_warranty line and a customer line gets two invoices. Totals and tax of the invoices add up to the sources, the tax code and payment terms resolve as for any invoice, and the legal entity of the first source is used.
Each invoice line keeps its origin in invoice_line_sources (the source, the order line and the quantity). A source is invoiced once: a repeat call returns it in skipped and writes nothing. An order line can be invoiced in parts with lines: [{ id, quantity }]; the quantity can't exceed what was delivered and not yet invoiced (INVOICE_SOURCE_QUANTITY). A void invoice releases its quantities. Only the selected order of a variant group is invoiced. The call is refused in import mode, because imported invoices come in through the invoice import.
const result = await bsb.invoices
.invoiceFromSources(
orgId,
{ type: "company", id: customerId },
[
{ type: "order", id: orderA, lines: [{ id: lineId, quantity: 2 }] },
{ type: "order", id: orderB },
{ type: "shipment", id: shipmentId },
{ type: "time", scope: { subject: { type: "project", id: projectId } } },
],
{ title: "October" },
)
.orThrow();
result.invoices; // [{ id, currency, total }]
result.skipped; // sources that were already invoicedsourcesReadyToInvoice(orgId, party?) lists what can be invoiced now: orders and shipments with a quantity left, and unbilled time. Time sources use the rate card of billable time, and an entry without a rate is left out. The SQL functions are invoice_from_sources and sources_ready_to_invoice.
| Hint | Cause |
|---|---|
INVOICE_SOURCE_INVALID | a malformed party, source list or option |
INVOICE_SOURCE_UNSUPPORTED | the layout has no shipments to invoice, or billable-time isn't installed |
INVOICE_SOURCE_NOT_FOUND | no such order or shipment in the organization |
INVOICE_SOURCE_NOT_READY | the order isn't confirmed or paid, or was invoiced at checkout, or the shipment isn't delivered |
INVOICE_SOURCE_QUANTITY | a line is invoiced for more than is delivered and not yet invoiced |
INVOICE_SOURCE_PARTY | an order was placed by another buyer than the party |
INVOICE_SOURCES_IMPORTING | the call ran in import mode |
Invoice helpers
createAndIssue({ organizationId, input, lines, issuedOn, dueOn }) creates a draft with its lines and issues it. markPaid({ invoice, method, reference }) records a payment for the invoice's whole balance; the reference defaults to paid:<id>, so retries are safe. issueAndSend({ invoiceId, format, channel }) issues the invoice, then sends it as an e-invoice, and returns { invoice, delivery }.
Write an adapter
A package for the EInvoiceFormat and EInvoiceChannel port starts from a tested template in Write an adapter. The port's contract is in Extension interfaces.
Paging invoices
page pages the invoices newest first and get(id) reads one with its lines and payments, or returns a not_found error (ADR 1077). list stays as a deprecated alias until 0.70; use filters: { subjectType, subjectId } for the invoices of one record. Sorts are createdAt, dueOn and total, filters are status, currency, kind, subjectType and subjectId, and q searches the number. The organization comes from organizationId or the block's tenant option.
const first = await invoices
.page({ filters: { status: ["issued"] }, sort: { by: "dueOn" }, limit: 25 })
.orThrow();
const forCompany = await invoices
.page({ filters: { subjectType: ["company"], subjectId: [companyId] } })
.orThrow();
const one = await invoices.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.
Last updated on
Promotions
Percentage, fixed and free-shipping promotions that apply automatically or by code, with usage limits, stacking rules and priorities, priced into orders carts and redeemed at checkout.
Reviews
Ratings and reviews of catalog products and other records, one per user and subject, verified against paid orders, moderated before or after publishing, with an aggregate a public storefront can read.