Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.
Invoicing Module
Five document families plus the AR/AP subledger: sales invoices, purchase invoices, memos (credit/debit), payments (AR receipts, AP disbursements, employee reimbursement payouts), charges (card transactions), and reimbursements — with settlement/ application, aging, tie-out, and the receivables/payables workbenches on top.
One of the largest modules in the app: one invoicing.service.ts and one
invoicing.models.ts, per the one-service-per-module rule. There is no barrel: import from
the file that defines a thing. invoicing.server.ts holds the module's operations (see
Operations below). invoicing.service.ts is server-only and holds the building blocks,
including the deposit and payment-seeding helpers the payment loaders read
(getDepositDocuments, seedPaymentApplications) and Stripe Connect customer resolution
(resolveStripeCustomer, with the pure stripe-customer.mapper.ts).
invoicing.reports.ts is pure calendar/aggregation math (previousPeriod, aggregateSpend)
with no route consumer yet — only its own test. ui/SalesInvoice/ has no index.ts and is NOT
in ui/index.ts; x+/sales-invoice+/ deep-imports it. Every other ui/ folder (Charge,
Dashboard, Memo, Payment, PurchaseInvoice, Reimbursement, Workbench) is barrel-exported.
Key Domain Concepts
- Invoice status —
salesInvoiceStatusType/purchaseInvoiceStatusType;is{Sales,Purchase}InvoiceLocked= not Draft.Partially PaidandOverdueare DERIVED in thesalesInvoices/purchaseInvoicesviews frominvoiceSettlement. There is no manual status change: Mark as Paid / Mark as Unpaid, their$invoiceId.status.tsxroutes andupdate{Sales,Purchase}InvoiceStatusare gone, so in Carbon a payment (throughinvoiceSettlement) is the only way an invoice becomes paid. An accounting-provider pull still writes the base status: the Xero and QuickBooks Online invoice and bill syncers (packages/ee/src/accounting/providers/{xero,quickbooks-online}/entities/{invoice,bill}.ts,upsertLocal) setPaidorPartially Paidfrom the remote document (Xero:PAIDgivesPaid, and a bill withAmountPaidandAmountDuegivesPartially Paid; QBO:BalanceagainstTotalAmt), and the bill syncers also setdatePaid. ThesalesInvoices/purchaseInvoicesviews show a basePaidasPaidwith a zerobalance, whatever the settlements say. - Due date —
computeInvoiceDateDueanchorspaymentTerm.daysDuebycalculationMethod(Net/End of Month/Day of Month, clamped). A missing term falls back toDEFAULT_PAYMENT_TERM(Net 30); a term query failure throws so the caller aborts instead of persisting a staledateDue. The date math iscalculateDueDate(@carbon/utils). - Memo — ONE
memotable, anddirection(Credit/Debit) is orthogonal to party: all four combinations are legal (memoDirectioncarries both values; the table's only party constraint is customer-XOR-supplier).credit-memos.tsx/supplier-credits.tsxfilter on the PARTY (getMemos({ party })) and offer direction as a separate filter;vendor-credits.tsxredirects old links. The readable id comes from thecreditMemoordebitMemosequence chosen by direction, not party. - Payment — THREE payee kinds.
paymentValidatorrequires exactly one ofcustomerId/supplierId/employeeId(mirroring the DBpayment_party_check). AnemployeeIdpayment is a reimbursement payout: alwaysDisbursement, never AR, never a refund. InreplaceInvoiceSettlementstheisReimbursementarm targetstargetReimbursementIdONLY and refuses any discount, write-off, invoice/memo target, or cash-in direction;isRefundis!isReimbursement && cashIn !== isAR, so a three-way party can't be misread as a refund.totalAmountmay be 0 — a payment can be a pure credit application. invoiceSettlement— source is exactly one ofpaymentId/memoId; target exactly one of FOUR (targetSalesInvoiceId,targetPurchaseInvoiceId,targetMemoId,targetReimbursementId— the fourth added by20260923231244, which widenedinvoiceSettlement_target_check).appliedAmount,discountAmountandwriteOffAmountare company BASE currency;sourceAmountis the exact principal in the funding source's DOCUMENT currency (per theCOMMENT ON COLUMNstatements in20260908021155_accounting_posting_corrections.sql) — getting that pair backwards is a live money bug.fxGainLossAmountis GENERATED (appliedAmount * (sourceExchangeRate - targetExchangeRate)); never write it.- Charge — renamed from
cardTransactionby20260922195151(tables, enums, triggers, RLS, sequence, and theCard Transactionjournal-source label). Ramp-fed and read-only in the ERP: list, drawer, void (charges{,.$id,.$id.void}.tsx). NochargeValidatorand no create/edit route —post-chargeis invoked bypackages/jobs/.../integrations/ramp-sync-card.ts; only the void goes through the ERP. The nav entry is NOT gated on a spend integration being connected. - Reimbursement — first-class as of
20260923231244:reimbursement/reimbursementLine/reimbursementLineDimension, Draft → Posted → Voided. Imported from a spend tool, never hand-created —reimbursementUpdateValidatorhas no create counterpart, andcheck_reimbursement_draft_mutationrefuses a non-Draft INSERT, a non-Draft DELETE, and any content change during the Draft→Posted flip.ReimbursementEditFormshowscurrencyCodeandexchangeRateread-only on purpose: they are the source transaction's facts, a reimbursement has no*.exchange-rateroute, and re-denominating an imported expense is not a workflow.linesBalanceHeader(invoicing.service.ts; EPSILON — matching the server function'srequireLineSum, NOT its 0.01 journal tolerance) is the only pre-posting guard against posting an unbalanced reimbursement;postReimbursementandsaveAndPostReimbursementboth check it. - Party-contact gate —
checkPartyContactRequirement(@carbon/lib/party-contact.server) runs in BOTH invoice post operations (postSalesInvoice,postPurchaseInvoice). Their own party read iscompanyId-scoped and fails CLOSED: an error or a missing row refuses the post, because the helper returnsnullfor a party with no id — so an unchecked read was the gate's own bypass. The helper's own internal reads fail OPEN, per-read, and log every degradation.
Safety
Always
- MUST pass the Kysely client in as
db, never build it ininvoicing.service.ts(no-db-client-in-service): an operation passesctx.asSystem.pg, a routegetDatabaseClient()from~/services/database.server.replaceInvoiceSettlements,applyCreditsToInvoices,upsertReimbursementLinesand bothupdate*InvoiceLineOrdertakedb: Kysely<KyselyDatabase>. - MUST re-assert Draft status inside every Kysely transaction with
forUpdate()— Kysely bypasses RLS;replaceInvoiceSettlementsandupsertReimbursementLinesboth do. - MUST write
appliedAmountin base currency andsourceAmountin the source document's currency, converting withtoBaseAmount/toDocumentAmount(@carbon/utils). - MUST recompute a balance or variance SERVER-side before acting on it —
payReimbursementre-readsgetOpenReimbursementsForEmployee;adjustReceivables/adjustPayablesre-run the tie-out instead of trusting the form. - MUST resolve currency decimals from data (
getPaymentCurrencyConfiguration→requireCurrencyDecimals), never a literal scale.
Ask First
- Changing the settlement columns or their XOR checks —
invoiceSettlementis the only ledger of what has been paid, and the aging/tie-out RPCs read it directly. - Adding a create path for a charge or a reimbursement — both are import-only by design and the DB draft-mutation triggers enforce it.
- Relaxing either invoice-post party-contact gate, or the
salesInvoicePostValidatorStripe refinements — they are what make the customer-confirmation step structurally mandatory before a customer is created on a merchant's Stripe account.
Never
- Derive
memo.directionfrom the party.MemoFormdid exactly that and force-submitted it with<Hidden value>(which prefersvalueoverdefaultValue), overwriting the stored direction on every save and making customer-Debit / supplier-Credit memos unauthorable.invoicing.models.test.ts→describe("memoValidator")pins the contract. - Set
Partially PaidorOverduedirectly — they are view-derived from settlements. - Give an employee payment a discount, a write-off, an invoice/memo target, or a Receipt
direction —
replaceInvoiceSettlementsthrows on each. - Edit a posted document.
isMemoLocked/isPaymentLocked/isReimbursementLockedare all "anything but Draft"; posting and voiding go through thepost-sales-invoice,post-purchase-invoice,post-memo,post-payment,post-charge,post-reimbursementpostings — never a direct status write. - Delete a purchase invoice, or one of its lines, with a plain delete when it may carry Lease
lines:
leasePayment.purchaseInvoiceLineIdhas no FK, so the payment row stays Invoiced and is never billed again.deleteDraftPurchaseInvoice/deleteDraftPurchaseInvoiceLinecalldeletePurchaseInvoiceReleasingLeases/deletePurchaseInvoiceLineReleasingLeases(~/modules/purchasing/purchasing.service), which return the rows to Pending in the same transaction; no plain delete is published. The sales invoice deletes work the same way withdeleteSalesInvoice(Line)ReleasingRentals(~/modules/sales/sales.service).
Validation Commands
pnpm --filter erp exec vitest run app/modules/invoicing # scoped: 9 files / 166 tests
pnpm exec turbo run typecheck --filter=erp
pnpm --filter erp test # the whole app's vitest suite
Key Data Model
| Table / View | Purpose |
|---|---|
salesInvoice / salesInvoices (view) |
AR header; view derives balance, invoiceTotal, Partially Paid/Overdue, paymentTermName. Invoice automation columns: automationHoldReason (a Draft a person must review before automation posts it), sentAt / sentTo / sendError (the post operation stamps sentAt when the email is QUEUED, or sentTo: "Stripe" once the Stripe send succeeds, and sendError when anything after the post — the PDF, the contact, the email or the Stripe send — fails; the automation stamps when it is SENT, and a sent stamp that fails to write becomes a sendError rather than a clean send). The header shows "Emailed", or "Sent via Stripe" when sentTo is Stripe. The view's needsReview = held Draft, or posted with sendError and no sentAt — the Sales Invoices list shows an orange "Needs Review" badge beside the status (tooltip: the hold reason or send error) and filters on the hidden needsReview column (?filter=needsReview:eq:true, the link the digest notification uses). There is no sidebar entry for it. A posted invoice that failed to send has a Send action (sendSalesInvoice, fires carbon/invoice.automate with resend: true: the job sends through Stripe when the invoice's source mode is Post and Send via Stripe, otherwise by email — including a manually posted invoice with no recurring source). The posted PDF is stored under {companyId}/opportunity/{opportunityId}/, or {companyId}/sales-invoice/{invoiceId}/ when the invoice has no opportunity; it is rendered by @carbon/lib/sales-invoice-document.server (shared with the PDF route and the automation job) |
salesInvoiceLine / salesInvoiceLines / salesInvoiceLocations (views) |
AR lines (salesInvoiceLineType includes Fixed Asset). Line discount (migration 20261006221401): discountPercent is a FRACTION 0–1 (CHECK, default 0) with generated netUnitPrice / convertedNetUnitPrice; it discounts the merchandise (quantity × unitPrice) only — add-ons and shipping never — and tax is charged on the discounted merchandise. unitPrice stays the LIST price. Every amount path applies it: the salesInvoices view totals, calculateSalesPostingAmounts (@carbon/database, sales-posting-amounts.ts), the PDF / email (@carbon/documents utils/sales-invoice.ts), SalesInvoiceSummary, Stripe (toStripeInvoiceLines) and the accounting providers (sales-document-components.ts). The form field "Discount (%)" posts percent POINTS; createSalesInvoiceLine / updateSalesInvoiceLine divide by 100 (salesInvoiceLineValidator accepts 0–100), for the API too. upsertSalesInvoiceLine writes the value as given and is not published. Contract provenance: customerContractId / customerContractLineId / customerContractInvoiceLineId and projectId (written as the Project dimension on the line's revenue legs); salesInvoice.customerContractId and memo.customerContractId likewise. With these FKs, inferring a bare salesInvoice(...) embed from salesInvoiceLine exceeds TypeScript's instantiation depth (TS2589): name the FK, salesInvoice!salesInvoiceLine_invoiceId_fkey(...) |
salesInvoiceShipment |
Per-invoice shipping method/term/cost + incoterm, and the customer ship-to customerLocationId ("Ship To" on SalesInvoiceShipmentForm; copied from the order / contract / rental agreement when one drafts the invoice; sales rules evaluate standalone lines against it, never the bill-to — see sales AGENTS.md "Invoice ship-to") |
purchaseInvoice / purchaseInvoices (view) |
AP header; view derives balance, orderTotal, the derived statuses |
purchaseInvoiceLine / purchaseInvoiceLines (view) |
AP lines (invoiceLineType, enum payableLineType, includes G/L Account and Lease). A Lease line (migrations 20261011163133 / 20261011202305) has no item, account or asset: leaseId names the lessee lease (CHECK purchaseInvoiceLine_lease_check: type Lease iff leaseId set) and leasePaymentId the leasePayment row it bills when createLeaseInvoices (purchasing.service.ts, ported from the create-lease-invoices server function) drafted it (one line per leased asset's row, described with the asset; upsertPurchaseInvoiceLine never takes leasePaymentId from a caller). The view adds leaseReadableId / leaseName. purchaseInvoiceLineValidator requires leaseId and a description on a Lease line; PurchaseInvoiceLineForm has a Lease tab listing the supplier's Active / Expired / Terminated / Purchased leases, and locks the lease and amount of a drafted line. Posting (postPurchaseInvoice; the account and checks in resolveLeasePostingLine, shared with the cutover's legacy backfill; the lines in kind: "lease"; all in invoicing.service.ts): by the classification of the row's asset (leaseLine), a capitalized (Operating / Finance) asset's line debits leaseLiabilityAccount with its NOMINAL amount (nominalBaseCost, quantity × base unit price), which must equal the row's amount (equals), and its tax, line shipping and share of the header freight to operatingLeaseExpenseAccount; a Short-Term asset's line debits operatingLeaseExpenseAccount in full; a line without a payment row debits variableLeaseExpenseAccount in full; AP is credited the whole total. Refused for a lease that is not billable (BILLABLE_LEASE_STATUSES: a Draft or Cancelled lease), a payment row of another lease, a row whose purchaseInvoiceLineId is not this line (billed by another line), or with a project. VOID returns the billed rows to Pending and stamps voidedPurchaseInvoiceId. See purchasing AGENTS → Leases |
purchaseInvoiceDelivery |
AP delivery terms |
memo |
Credit/debit memos; customer XOR supplier, direction orthogonal to party |
payment |
Receipts, disbursements, employee payouts (three-way payment_party_check) |
invoiceSettlement |
Applications: one source × one of four targets; base-currency reliefs + generated fxGainLossAmount |
charge / chargeLine |
Card charges (chargeType: Charge/Credit/Payment/Cashback/Repayment) |
reimbursement / reimbursementLine / reimbursementLineDimension |
Employee expense payable, coding lines, dimension tags |
paymentTerm, currency, company |
Due-date, decimals, and base-currency resolution |
RPCs: get_ar_aging, get_ap_aging, get_ar_tie_out, get_ap_tie_out,
get_ar_open_by_customer, get_ap_open_by_supplier, get_next_sequence.
Validators → routes
| Validator | Used by |
|---|---|
salesInvoiceValidator |
x+/sales-invoice+/{new,$invoiceId.details}.tsx |
salesInvoiceLineValidator / salesInvoiceShipmentValidator |
$invoiceId.new, $invoiceId.$lineId.details, $invoiceId.shipment |
salesInvoicePostValidator (+ stripeCustomerActions) |
x+/sales-invoice+/$invoiceId.post.tsx |
purchaseInvoiceValidator |
x+/purchase-invoice+/{new,$invoiceId.details}.tsx |
purchaseInvoiceLineValidator / purchaseInvoiceDeliveryValidator |
$invoiceId.new, $invoiceId.$lineId.details, $invoiceId.delivery |
memoValidator |
x+/credits+/{new,$memoId}.tsx |
paymentValidator |
x+/payments+/{new,$paymentId}.tsx |
invoiceSettlementValidator (+ invoiceSettlementBase for .omit()) |
x+/payments+/$paymentId.applications.set.tsx |
reimbursementUpdateValidator / reimbursementLinesValidator |
x+/reimbursements+/$reimbursementId.edit.tsx |
reimbursementPaymentValidator |
$reimbursementId.pay.tsx — 1:1 with Rillet's POST /reimbursements/{id}/payments |
Charges have no validator; x+/{sales,purchase}-invoice+/update.tsx are bulk-field routes
guarded by requireUnlockedBulk, not validators.
Key Service Functions
insertSalesInvoice/insertPurchaseInvoice— allocate the sequence viaget_next_sequence, mint theopportunity, copy party payment/shipping defaults. Use these, not a bare INSERT.createSalesInvoiceFromSalesOrder/createSalesInvoiceFromShipment/createPurchaseInvoiceFromPurchaseOrder— all three callconvertDocument(shared.service.ts, ported from theconvertserver function).computeInvoiceDateDue/computeEarlyPaymentDiscounts— terms math (the due date itself iscalculateDueDate/DEFAULT_PAYMENT_TERMfrom@carbon/utils, shared with invoice posting); discounts batch-load their terms in one query, never per invoice.replaceInvoiceSettlements(Kysely) — replace-all for a Draft payment's applications; owns the AR / AP / refund / reimbursement arm rules and the balance ceilings.applyCreditsToInvoices(Kysely) — additive memo-sourced settlements, GL-neutral (the memos already posted their own journals); v1 requires equal source and target rates.getAvailableCreditsForParty/getCompanyHasOpenCredits/getStagedCreditsForPayment/getAvailableOnAccountCredit(Sources)— the credits half of the payment composer.getInvoiceSettlementsForInvoice/getMemoApplications— application history, fully paged.getOpenSalesInvoicesForCustomer/getOpenPurchaseInvoicesForSupplier/getOpenReimbursementsForEmployee— payable targets, one per payee kind.getArAging/getApAging/getArTieOut/getApTieOut/getArOpenByCustomer/getApOpenBySupplier— drivex+/reports+/{ar,ap}-aging.tsx,x+/invoicing+/{receivables,payables}.tsx(ARAPWorkbench) and_index.tsx(InvoicingDashboard).updateReimbursement(Draft-scoped UPDATE) /upsertReimbursementLines(Kysely, delete-then-reinsert; bind dimensions bysequence, never by returned row order) /getPaymentCurrencyConfiguration(base currency +currency.decimalPlaces; throws when the currency is not configured for the company group).
Operations (invoicing.server.ts)
Every route action that composes writes calls one defineServiceFn operation through
carbon(request) (api.invoicing.postSalesInvoice(input)); the API and MCP publish the ones
tagged @mcp (all below except the two *Field updates) as invoicing_<name>:
- Sales invoices:
updateSalesInvoiceField,postSalesInvoice,voidSalesInvoice,sendSalesInvoice,deleteDraftSalesInvoice;createSalesInvoiceLine/updateSalesInvoiceLine/deleteDraftSalesInvoiceLine - Purchase invoices:
createPurchaseInvoice,updatePurchaseInvoiceField,postPurchaseInvoice,voidPurchaseInvoice,deleteDraftPurchaseInvoice,mapPurchaseInvoiceLines;deleteDraftPurchaseInvoiceLine - Payments:
createPayment,postPayment,voidPayment - Memos:
postMemo,voidMemo,deleteDraftMemo - Charges:
voidCharge adjustReceivables,adjustPayables(create: accounting)- Reimbursements:
saveReimbursement,saveAndPostReimbursement,postReimbursement,voidReimbursement,payReimbursement
How they behave:
postSalesInvoiceruns, in order: the party-contact gate, the sales-rule gate (blocked returns{ violations, ruleNames }as data, which the route returns touseRuleViolations), the Stripe customer preflight, the Draft→Pending claim, thenpost-sales-invoice. A failed post puts the claim back to Draft. After the post, the PDF, the email or the Stripe send never undo it: a failure stampssendErrorand returnswarning.postPurchaseInvoiceclaims Draft or Pending, posts, then updates purchase prices when the company does so on invoice post. A failed post or price update sets the invoice back to Draft (after the post has committed, for the price update: a known gap).- The posting and voiding operations return the posting's own refusal message.
- A failure after the main write (seeding a payment's applications, applying or posting a
reimbursement payout, the lines of an adjusting entry) keeps the write and returns
warning. - The
*Fieldoperations requireupdate: salesfor both invoice kinds, as the properties panels' routes always did.
Related Modules
- accounting — postings write
journal/journalLine;accountDefault.employeeReimbursementsPayableAccountis the reimbursement control account;adjustReceivables/adjustPayablesseed a Draft journal viasaveJournalEntryWithLines. - sales / purchasing — invoices convert from sales orders, shipments and POs; sales
rules gate the sales-invoice post;
getCustomerPayment/getCustomerShipping(and the supplier equivalents) seed invoice headers. - settings —
getNextSequence,getCompanySettings(accountingCutoverDate, read throughhasAccountingCutoverfrom~/modules/accounting/accounting.utils: before the cutover the receivables / payables workbenches and the invoicing dashboard skip the GL tie-out, and the adjust operations refuse),party-contact(a re-export of@carbon/lib/party-contact; the post gate reads@carbon/lib/party-contact.server). - shared —
getCompanyTimeZoneandrefuseUnlessOwned(shared.service.ts);incoterms/itemType/methodTypefromshared.models.
Rules References
.claude/rules/numeric-precision.md— the two storage scales,applyRate/round,toBaseAmount/toDocumentAmount, and whyappliedAmountvssourceAmountmatters.claude/rules/accounting-sync-handlers.md— how posted invoices, memos, payments, charges and reimbursements reach Xero / QuickBooks / Rillet.claude/rules/ramp-integration.md— wherechargeandreimbursementrows come from.claude/rules/conventions-forms.md—ValidatedForm+ zod + route-action shape.claude/rules/module-files.md— thepost-*postings these routes call (building blocks ininvoicing.service.ts)