Skip to content

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.

23.3 KB
Raw Blame

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 Paid and Overdue are DERIVED in the salesInvoices/purchaseInvoices views from invoiceSettlement. There is no manual status change: Mark as Paid / Mark as Unpaid, their $invoiceId.status.tsx routes and update{Sales,Purchase}InvoiceStatus are gone, so in Carbon a payment (through invoiceSettlement) 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) set Paid or Partially Paid from the remote document (Xero: PAID gives Paid, and a bill with AmountPaid and AmountDue gives Partially Paid; QBO: Balance against TotalAmt), and the bill syncers also set datePaid. The salesInvoices / purchaseInvoices views show a base Paid as Paid with a zero balance, whatever the settlements say.
  • Due date — computeInvoiceDateDue anchors paymentTerm.daysDue by calculationMethod (Net / End of Month / Day of Month, clamped). A missing term falls back to DEFAULT_PAYMENT_TERM (Net 30); a term query failure throws so the caller aborts instead of persisting a stale dateDue. The date math is calculateDueDate (@carbon/utils).
  • Memo — ONE memo table, and direction (Credit/Debit) is orthogonal to party: all four combinations are legal (memoDirection carries both values; the table's only party constraint is customer-XOR-supplier). credit-memos.tsx / supplier-credits.tsx filter on the PARTY (getMemos({ party })) and offer direction as a separate filter; vendor-credits.tsx redirects old links. The readable id comes from the creditMemo or debitMemo sequence chosen by direction, not party.
  • Payment — THREE payee kinds. paymentValidator requires exactly one of customerId / supplierId / employeeId (mirroring the DB payment_party_check). An employeeId payment is a reimbursement payout: always Disbursement, never AR, never a refund. In replaceInvoiceSettlements the isReimbursement arm targets targetReimbursementId ONLY and refuses any discount, write-off, invoice/memo target, or cash-in direction; isRefund is !isReimbursement && cashIn !== isAR, so a three-way party can't be misread as a refund. totalAmount may be 0 — a payment can be a pure credit application.
  • invoiceSettlement — source is exactly one of paymentId/memoId; target exactly one of FOUR (targetSalesInvoiceId, targetPurchaseInvoiceId, targetMemoId, targetReimbursementId — the fourth added by 20260923231244, which widened invoiceSettlement_target_check). appliedAmount, discountAmount and writeOffAmount are company BASE currency; sourceAmount is the exact principal in the funding source's DOCUMENT currency (per the COMMENT ON COLUMN statements in 20260908021155_accounting_posting_corrections.sql) — getting that pair backwards is a live money bug. fxGainLossAmount is GENERATED (appliedAmount * (sourceExchangeRate - targetExchangeRate)); never write it.
  • Charge — renamed from cardTransaction by 20260922195151 (tables, enums, triggers, RLS, sequence, and the Card Transaction journal-source label). Ramp-fed and read-only in the ERP: list, drawer, void (charges{,.$id,.$id.void}.tsx). No chargeValidator and no create/edit route — post-charge is invoked by packages/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 — reimbursementUpdateValidator has no create counterpart, and check_reimbursement_draft_mutation refuses a non-Draft INSERT, a non-Draft DELETE, and any content change during the Draft→Posted flip. ReimbursementEditForm shows currencyCode and exchangeRate read-only on purpose: they are the source transaction's facts, a reimbursement has no *.exchange-rate route, and re-denominating an imported expense is not a workflow. linesBalanceHeader (invoicing.service.ts; EPSILON — matching the server function's requireLineSum, NOT its 0.01 journal tolerance) is the only pre-posting guard against posting an unbalanced reimbursement; postReimbursement and saveAndPostReimbursement both check it.
  • Party-contact gate — checkPartyContactRequirement (@carbon/lib/party-contact.server) runs in BOTH invoice post operations (postSalesInvoice, postPurchaseInvoice). Their own party read is companyId-scoped and fails CLOSED: an error or a missing row refuses the post, because the helper returns null for 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 in invoicing.service.ts (no-db-client-in-service): an operation passes ctx.asSystem.pg, a route getDatabaseClient() from ~/services/database.server. replaceInvoiceSettlements, applyCreditsToInvoices, upsertReimbursementLines and both update*InvoiceLineOrder take db: Kysely<KyselyDatabase>.
  • MUST re-assert Draft status inside every Kysely transaction with forUpdate() — Kysely bypasses RLS; replaceInvoiceSettlements and upsertReimbursementLines both do.
  • MUST write appliedAmount in base currency and sourceAmount in the source document's currency, converting with toBaseAmount / toDocumentAmount (@carbon/utils).
  • MUST recompute a balance or variance SERVER-side before acting on it — payReimbursement re-reads getOpenReimbursementsForEmployee; adjustReceivables / adjustPayables re-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 — invoiceSettlement is 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 salesInvoicePostValidator Stripe 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.direction from the party. MemoForm did exactly that and force-submitted it with <Hidden value> (which prefers value over defaultValue), 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 Paid or Overdue directly — they are view-derived from settlements.
  • Give an employee payment a discount, a write-off, an invoice/memo target, or a Receipt direction — replaceInvoiceSettlements throws on each.
  • Edit a posted document. isMemoLocked / isPaymentLocked / isReimbursementLocked are all "anything but Draft"; posting and voiding go through the post-sales-invoice, post-purchase-invoice, post-memo, post-payment, post-charge, post-reimbursement postings — 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.purchaseInvoiceLineId has no FK, so the payment row stays Invoiced and is never billed again. deleteDraftPurchaseInvoice / deleteDraftPurchaseInvoiceLine call deletePurchaseInvoiceReleasingLeases / 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 with deleteSalesInvoice(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 via get_next_sequence, mint the opportunity, copy party payment/shipping defaults. Use these, not a bare INSERT.
  • createSalesInvoiceFromSalesOrder / createSalesInvoiceFromShipment / createPurchaseInvoiceFromPurchaseOrder — all three call convertDocument (shared.service.ts, ported from the convert server function).
  • computeInvoiceDateDue / computeEarlyPaymentDiscounts — terms math (the due date itself is calculateDueDate / DEFAULT_PAYMENT_TERM from @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 — drive x+/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 by sequence, 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:

  • postSalesInvoice runs, in order: the party-contact gate, the sales-rule gate (blocked returns { violations, ruleNames } as data, which the route returns to useRuleViolations), the Stripe customer preflight, the Draft→Pending claim, then post-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 stamps sendError and returns warning.
  • postPurchaseInvoice claims 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 *Field operations require update: sales for both invoice kinds, as the properties panels' routes always did.

Related Modules

  • accounting — postings write journal/journalLine; accountDefault.employeeReimbursementsPayableAccount is the reimbursement control account; adjustReceivables / adjustPayables seed a Draft journal via saveJournalEntryWithLines.
  • 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 through hasAccountingCutover from ~/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 — getCompanyTimeZone and refuseUnlessOwned (shared.service.ts); incoterms/itemType/methodType from shared.models.

Rules References

  • .claude/rules/numeric-precision.md — the two storage scales, applyRate/round, toBaseAmount/toDocumentAmount, and why appliedAmount vs sourceAmount matters
  • .claude/rules/accounting-sync-handlers.md — how posted invoices, memos, payments, charges and reimbursements reach Xero / QuickBooks / Rillet
  • .claude/rules/ramp-integration.md — where charge and reimbursement rows come from
  • .claude/rules/conventions-forms.md — ValidatedForm + zod + route-action shape
  • .claude/rules/module-files.md — the post-* postings these routes call (building blocks in invoicing.service.ts)