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.
Sales Module
Quotes (with cost rollup and pricing), sales orders, sales RFQs, customer management, opportunity tracking, pricing rules/overrides, the customer portal, rental agreements for the fleet (see Rentals below), and AR contracts for services billed on a schedule (see Contracts below). Full quote-to-order-to-fulfillment lifecycle.
Key Domain Concepts
- Opportunity — deal container linking RFQs, quotes, and sales orders for one customer engagement.
- Quote — detailed cost estimate with line items, each having a make method (BOM + routing) and quantity-break pricing. Statuses: Draft → Pending → Sent → Ordered / Lost / Cancelled.
- Quote Revision —
quote.revisionId. Unlike a PO (amended in place), a quote revision is a newquoterow created bycopyQuote→getMethod(production.service.ts, ported from theget-methodserver function) (quoteToQuote,asRevision: true), keeping the samequoteIdwithrevisionId = max + 1, sharing the sourceopportunityId. Each revision gets its ownexternalLinkrow, whosedocumentIdis revision-qualified (Q000001-1) becauseexternalLinkis UNIQUE on(documentId, documentType, companyId)— an unqualified id collides with the original's link.deleteQuotedoes not remove the link row, so that insert usesonConflict … doUpdateSetto reuse the orphan a deleted revision left behind. Displayed asQ000001-1when > 0 viagetQuoteDisplayId(@carbon/documents/utils) on the PDF, email, share page, and filenames; two-tone in-app rendering uses<RevisionSuffix>(~/components). - Quote Line Pricing — per-quantity-break pricing. PK is
(quoteLineId, quantity)— noidcolumn.discountPercentis a fraction 0–1 (not 0–100). Generated columns compute net/converted prices. Lead time can be PREDICTED from the shop schedule rather than typed: the calendar-clock button on the Lead Time row opensQuoteLeadTimeModal, which POSTs$quoteId.$lineId.lead-time.tsx→runQuoteLeadTimeWhatIf(@carbon/planning) and applies one constraint's value to every break at once. The write goes through the grid'sonUpdateLeadTimes(quoteLinePrice.leadTime, one state update for every break — never a loop overonUpdatePrice, which snapshots state per call; a failed row is rolled back and the modal stays open) — no new persistence, soresolvePreservedQuoteLinePriceFieldsis untouched. - Price trace — how a price was reached (base → overrides → rules → final), a snapshot stored WITH the price because rules are edited in place:
quoteLinePrice.priceTraceper quantity break,salesOrderLine.priceTraceper order line (copied from the quote byconvert). Typed (manual) prices storenull. The calculator icon opens it in a modal; on a quote linegetQuoteLinePriceTracesalso returns today'scurrentTrace, andrepriceQuoteLineFromRulesstores it. See.claude/rules/quote-discount-system.md. - Pricing Rules — company-scoped Discount/Markup/Configuration rules. Discounts are non-stacking (highest-priority wins); Markups stack and compound in priority order. A Configuration rule targets exactly ONE configurable item (
itemIdin the form →itemIds: [id], amount 0, no item group —normalizePricingRuleinsales.service.ts) and carriesconfigurationPrices(JSONB{ key, value, amount, label? }[]— list option /"true"for a boolean /null= per unit of a numeric value;labelis the parameter's label at save time, used by the price trace; validated bypricingRuleConfigurationPriceValidatorinsales.utils.ts, which stays out of thesales.modelsimport graph so the engine tests can load it).toMatchedRuleparses a rule row for the engine;applyPriceRules(sales.utils.ts) adds those signed surcharges to the starting price before the discount, given the line'sconfiguration. An override withapplyRulesOnTop = falsestill takes them (configurationOnly) — they price the options, not the part. Every other rule type storesconfigurationPricesas null. - Line configuration —
quoteLine.configurationandsalesOrderLine.configuration(keyed byconfigurationParameter.key;convertDocument(shared.service.ts, ported from theconvertserver function) copies it quote → order). Jobs made for an order line useresolveJobConfiguration(sales.utils.ts): the order line's configuration, else the quote line's; when the order line was configured differently from its quote the job is built withitemToJob+ that configuration instead of copying the quote's method (an unset value — absent, null or blank — compares equal). A configured Make to Order quote line is priced from the part's unit sale price (not the cost rollup) when it has one, so it matches the order line —configuredQuoteBasePrice; a row with markups someone chose stays cost-plus. The sales order line form keeps its configurator inuseItemConfiguration+ItemConfigureButton(~/components/Configurator/ItemConfigurator), which loads parameters throughgetConfigurationParametersand ignores a stale load for an item no longer selected. - Price Overrides — price overrides with quantity breaks via
customerItemPriceOverride/customerItemPriceOverrideBreak, scoped to one customer, one customer type, or every customer (both ids null). Precedence: customer > customer-type > all-customers > base price. An all-customers override must be asked for:upsertCustomerItemPriceOverriderefuses a write with no scope unlessallCustomers: true(priceOverrideScopeError,sales.utils.ts, also the form validator's refine) — an omitted field once turned one quote's price into every customer's list price. Price List (resolvePriceList) takescustomerId,customerTypeIdorallCustomers(?scope=all, the picker's All Customers) and lists the scope's own overrides plus the ones it inherits (priceListOverrideScopes): a customer also sees its type's and the all-customers rows, tagged byoverrideSource. Override trace steps carryoverrideId, whichPriceTraceModallinks to the override. - Sales Order — confirmed order from a quote. Lines carry
methodType(Make to Order, Make to Stock, etc.) that determines production handling. - Sales RFQ — inbound request from a customer, convertible to a quote via
convertDocument(shared.service.ts, ported from theconvertserver function). - Rental Agreement — rents serialized fleet units (fixed assets) to a customer; billed in persisted periods, invoiced as
Rentallines on Draft sales invoices. See "Rentals (sub-area)". - Contract — bills a customer for Service items under an agreement: One-time and Recurring lines, an invoice schedule and a monthly revenue plan both editable while Draft (set up through a five-step wizard), amendments, cancellation with a credit memo, renewal. Drafted as
Servicelines (list price +discountPercent) on Draft sales invoices that post to Deferred Revenue / Contract Assets; the recognition run recognizes the plan. See "Contracts (sub-area)".
Safety
Always
- MUST use
convertQuoteToOrder/convertSalesRfqToQuotefor lifecycle conversions — they callconvertDocument(shared.service.ts, ported from theconvertserver function). - MUST use
resolvePrice+applyPriceRulesfor price calculation — never compute prices ad hoc. - MUST store
discountPercentas a fraction (0.10, not 10) — all downstream math assumes 0–1. - MUST scope customer queries by
companyId— customers are company-scoped.
Ask First
- Closing sales orders —
setSalesOrderStatuswithClosed(throughupdateSalesOrderStatus, which also clears the assignee); Closed is terminal for the order. - Deleting quotes linked to an opportunity — may orphan related orders.
- Modifying pricing rules — affects all future
resolvePricecalls.
Never
- Bypass
convertDocument(shared.service.ts) for quote→order or RFQ→quote conversions. - Delete
quoteLinePricerows when rewriting a line's pricing — go throughupsertQuoteLinePrices, which delete-and-reinserts inside one transaction and carries over any user-entered field (discountPercent,leadTime,shippingCost,categoryMarkups,priceSource) you omit (explicit-wins, omit-preserves viaresolvePreservedQuoteLinePriceFields). Deleting rows for a quantity break the line no longer offers is different and required: seereconcileQuantityBreaks(sales.utils.ts) and its use inupdateQuoteLine. Orphaned rows render as selectable options on the customer share page. - Store
discountPercentas a whole number (e.g., 10 instead of 0.10).
Validation Commands
# The app's package name is "erp" — there is no "@carbon/erp" workspace.
pnpm exec turbo run typecheck --filter=erp
# apps/erp has no `test` script; run vitest from the app directory.
cd apps/erp && pnpm exec vitest run app/modules/sales
Key Data Model
| Table / View | Purpose |
|---|---|
opportunity |
Deal container linking quotes and sales orders |
quote / quoteLine / quoteLinePrice |
Quote with cost rollup and quantity-break pricing |
quoteMakeMethod / quoteMaterial / quoteOperation |
Quote-level BOM and routing |
salesOrder / salesOrderLine |
Confirmed orders with fulfillment tracking |
salesRfq / salesRfqLine |
Inbound customer RFQs |
customer / customerContact / customerLocation |
Customer master data |
customerStatus / customerType |
Customer categorization |
pricingRule |
Company-scoped discount/markup rules |
customerItemPriceOverride / customerItemPriceOverrideBreak |
Customer-specific price overrides with quantity breaks |
noQuoteReason |
Why a quote line was declined |
salesReturnOrder / salesReturnOrderLine / salesReturnOrders (view) |
Customer RMAs: non-posting authorization document; receipt-driven statuses (Draft → Confirmed → Partially Received → Received → Completed/Cancelled); lines link optionally to SO/shipment/invoice lines with a disposition + closedComplete short-close |
salesReturnOrderLineTrackedEntity / salesReturnOrderCreditLine |
Legacy expected-serials junction (no longer written — "which serial is it" lives entirely on the receipt; existing rows still honored by disposition) ; per-line credit breakdown behind the header-level AR memo (memo.salesReturnOrderId) |
returnReason |
Why goods came back (company-defined, seeded; inventoryValueZero re-enters stock at zero value). Shared with purchasing's supplier returns |
Key Service Functions
importQuotes(sales.service.ts) — app-side bulk CSV quote importer (modesquote/quoteLine/quoteWithLines); reusesinsertQuote/upsertQuoteLine/upsertQuoteLinePricesso quote side effects are preserved. Called byimportCsvFile(modules/shared/shared.server.ts, theroutes/x+/shared+/import.$tableId.tsxaction); config inmodules/shared/imports.models.ts. Create-only idempotency viaexternalIntegrationMapping(integrationcsv).convertQuoteToOrder/convertSalesRfqToQuote— lifecycle conversions viaconvertDocument(shared.service.ts, ported from theconvertserver function)copyQuoteLine/copyQuote— duplication viagetMethod(production.service.ts, ported from theget-methodserver function)applyPriceRules— applies matched discount/markup rules to a starting priceresolvePrice— full price resolution: base → overrides → rules → finalresolvePriceList— batch price list for a customer/type with quantity previewupdateSalesOrderStatus/cancelSalesOrder/finalizeQuote— status transitions; the operationssetSalesOrderStatusandfinalizeAndSendQuote(sales.server.ts) call themgetQuote/getQuoteLinePrices/getQuoteMaterialsByLine/getQuoteOperationsByLine— quote reads;getQuoteLinesandgetQuoteLinePricesByQuoteIdare insales.utils.ts(components call them)getSalesOrder(s)/getSalesOrderLines/getExternalSalesOrderLines— order readsgetOpenSalesOrderLinesForItem— sales order lines a job can link to (open orders, matching item);isSalesOrderClosed/OPEN_SALES_ORDER_STATUSESgate eligibilitygetCustomer(s)/getCustomerContacts/getCustomerLocations— customer readsgetPricingRules/createPricingRule/duplicatePricingRule— rule managementgetOpportunity/getOpportunityDocuments— deal trackinggetSalesReturnOrders/insertSalesReturnOrder/upsertSalesReturnOrderLine— RMA CRUD;confirmSalesReturnOrder(Kysely, row-locked reversible-quantity caps, THROWS),cancelSalesReturnOrder(guarded),shortCloseSalesReturnOrderLinegetReturnableLinesForCustomer(posted shipment lines minus already-authorized) — RMA line picker;getShippedTrackedEntitiesForCustomer— receipt-side serial/batch candidates (entities of the item currently with the customer via posted shipments)createSalesReturnOrderCredit(Kysely, row-locked creditable cap, THROWS) /getCreditableQuantities/createReplacementSalesOrder(resolvePrice-priced draft SO)setSalesReturnOrderLineDisposition— Use As Is releases returned entities; Scrap/Rework escalate to a quality Issue via the line's issue routecreateOpportunityDocumentUploadUrl/createOpportunityLineDocumentUploadUrl— MCP file upload (step 1): presigned URLs for opportunity (opportunity/{opportunityId}) and opportunity-line documents; pair withdocuments_insertUploadedDocument. See.claude/rules/mcp-tools-reference.md→ "File uploads"
Operations (sales.server.ts)
Every route action that writes calls one defineServiceFn operation through
carbon(request) (api.sales.setQuoteStatus(input)); the API and MCP publish
the ones tagged @mcp as sales_<name>:
- RFQs:
createSalesRfq,updateSalesRfqField,setSalesRfqStatus,convertSalesRfq,attachSalesRfqFile,mapSalesRfqLines - Quotes:
updateQuoteDetails,setQuoteStatus,updateQuoteField,finalizeAndSendQuote,convertQuote,attachQuoteFile;createQuoteLine/updateQuoteLine/configureQuoteLine/copyItemMethodToQuoteLine/copyQuoteLineMethod;createQuoteMaterial/updateQuoteMaterial/deleteQuoteMaterialAndReprice/deleteQuoteMaterialsAndReprice(unpublished, Delete Selected: many rows, one reprice) /copyItemMethodToQuoteMaterial;createQuoteOperation/updateQuoteOperation/deleteQuoteOperationAndReprice/deleteQuoteOperationsAndReprice(unpublished, Delete Selected: operations of one line, one reprice);acceptDigitalQuote/rejectDigitalQuote(system only: the public share link runs them throughshareLinkContext,~/modules/service-context.server) - Orders:
updateSalesOrderDetails,setSalesOrderStatus,updateSalesOrderField,confirmSalesOrder;createSalesOrderLine/updateSalesOrderLine/shipSalesOrderLine - Return orders:
updateSalesReturnOrderField,confirmReturnOrder;createReturnOrderLine/updateReturnOrderLine/escalateReturnOrderLine - Contracts:
createContract,updateContractTerms,setContractTerm,setContractType,setContractInvoiceAutomation,confirmContract,previewContractAmendment,amendContract,previewContractCancellation,cancelContract,revertContractCancellation - Rental agreements:
createRentalAgreement,setRentalAgreementTerm,setRentalInvoiceAutomation,activateRentalAgreement,setRentalAgreementStatus;deliverRentalUnit/returnRentalUnit/releaseRentalUnit/classifyRentalUnit/sellRentalUnit
How they behave:
- A status past a document's finalize / confirm gate (
setQuoteStatus,setSalesOrderStatus, or a status inupdateQuoteDetails/updateSalesOrderDetails) is refused when the document breaks an error-severity sales rule (advancingStatusRefusal). - A sales-rule gate (
salesDocumentGatefor a whole document,salesLineGatefor one line) returns{ violations, ruleNames }as the result's data when it blocks, and the route returns that data touseRuleViolations. The caller sendsacknowledged: trueto let warnings through; errors always block. - A failure after the main write (pricing a new quote line, a quote email, an
RMA PDF, a rental's first unit) keeps the write and returns
warning. - A permission the data asks for (invoicing, when a confirmed contract's mode
posts or a cancellation drafts a credit memo) is checked inside the
operation with
ctx.can. - The quote, order and RMA PDFs render from
sales.pdf.tsxwith the caller's client; thefile+routes call the same renderers.
Key Exports
import { resolvePrice, getCustomer } from "~/modules/sales/sales.service";
import { applyPriceRules } from "~/modules/sales/sales.utils";
Sales Rules (sub-area)
Configurable if-condition-then-error/warn rules evaluated when an item is added to a sales document (quote line, sales order line, sales invoice line) — e.g. "if item type is X and the customer's ship-to country is Y → block". Lives inside this module: validators in sales.models.ts, UI in ui/SalesRules/; the admin CRUD is the family-parametrized implementation in shared.service.ts (see "Service functions" below). There is no modules/sales-rules directory — a rule feature is not its own domain.
Distinct from storage rules (~/modules/inventory, warehouse/MES surfaces) and configurator rules (configurationRule, x+/part+/$itemId.rule*.tsx) — storage and sales rules now share ONE table, enforcementRule, discriminated by family ('storage' | 'sales'); the configurator's configurationRule is unrelated. Every read/write in this module MUST filter family = 'sales'.
- Rule —
enforcementRulerow (family = 'sales'):conditionAstJSONB ({kind: all|any|none, conditions:[{field,op,value}]}),severity(errorblocks;warnrequires acknowledgment),messagewith{token}interpolation,surfaces(enforcementRuleSurfaceenum; the sales-legal subsetquoteLine|salesOrderLine|salesInvoiceLineis enforced by theenforcementRule_sales_surfacesCHECK), item scoping viafilteredItemTypes/filteredItemGroupIds/filteredItemMatchAll(empty = all items) or explicitenforcementRuleItemAssignmentpins (shared with the storage family — always resolve pins against a family-filtered rule set, never a PostgREST embed). - Shared engine — the AST compiler/evaluator lives in
@carbon/utils(rules.ts+field-registry.ts, with the zod AST mirror inrules-schema.ts):compileSalesRuleWithCache,evaluateRules,SALES_RULE_SURFACES,getFieldsForSalesRuleSurfaces,SALES_RULE_FIELD_REGISTRY(customer type/status/country + synthesizedcustomer.customFields.*). Countries are alpha-2 codes. - Evaluator —
@carbon/ee/rules.serverevaluateSalesRuleLines(service-role client; plan-gated onSALES_RULES). Missing ship-to → the engine's required-field semantics emit "Customer location is required" at the rule's severity. - Fail loud, never silently permissive. A failed rule load, item load, or ship-to resolution THROWS. Each of those returns "nothing to enforce" if swallowed, which turns a compliance control off with no signal.
- Drop-ship ship-to —
resolveSalesOrderShipToreturns the shipment'scustomerLocationId, never the header's, whendropShipmentis set. If the drop-ship location is missing it returns null rather than falling back: the header is a DIFFERENT address, so a fallback would clear a country rule that should have blocked. - Invoice ship-to — a sales invoice's customer ship-to is
salesInvoiceShipment.customerLocationId(migration20261006221401_sales-invoice-discount-and-ship-to.sql;invoiceCustomerLocationIdis the bill-to; thelocationIdcolumns are Carbon's own warehouses). Authored on the invoice's Shipping card ("Ship To", scoped to the invoice's customer;update.tsxclears it on a customer change);convertcopies the order's delivery location (drop-ship location whendropShipment, else the header'scustomerLocationId),create-contract-invoicescopiesshipToCustomerLocationId,create-rental-invoicesthe agreement's Rental Site. An order-derived line (salesInvoiceLine.salesOrderId) resolves throughresolveSalesOrderShipTo; a standalone line resolves throughresolveSalesInvoiceShipTo(document gate, line create/edit, API gate) and, with no ship-to set, passes null and fails closed via required-field semantics. NEVER substitute the bill-to — pinned bypackages/ee/src/rules/sales/invoice-shipto.test.ts. ThesalesInvoiceLocationsview'sshipment*address columns join this column (same migration; they joined the warehouselocationIdbefore and were always null), feeding the PDF Ship To block and the Stripe shipping address. - One modal — enforcement actions return
{ violations, ruleNames }; forms submit viauseRuleViolationsand render the sharedRuleViolationModal(@carbon/ee/rules). Do not add a second violation UI. - Acknowledgment log —
enforcementRuleAcknowledgment(append-only): one row per deduped violation on blocked attempts and acknowledged overrides.
Sales Rules safety
- MUST evaluate with the service role client, in the operation after its permission gate (
salesDocumentGate/salesLineGateinsales.service.ts) — the check must see full truth regardless of the acting user's read permissions. - MUST gate write routes with
requireFeature({ feature: "SALES_RULES" })(key inpackages/ee/src/plan.ts) — community-blocked, not merely Cloud-paywalled. The ee write functions also embedrequireEntitlement("SALES_RULES")as the un-strippable lock. - The shared rule-builder components (
RuleBuilder,SurfacesField,MessageWithTokens,SeveritySelect,ItemFilterSelector) live in~/modules/inventory/ui/StorageRules/and are imported by deep path. Keep any parameterization additive (defaults preserve storage behavior), and keep the dependency a one-way deep import fromsalesinto the inventory UI folder (never throughinventory/ui/index.ts) to avoid a cycle. The shared zod AST schema lives in@carbon/utilsfor the same reason. - Never widen the
enforcementRule_sales_surfacesCHECK to admit storage surfaces — that CHECK is what replaced the old per-family enum typing. - Never duplicate
isBlocked/dedupeViolations/the violation modal — import from@carbon/ee/rules(.server).
| Table | Purpose |
|---|---|
enforcementRule (family='sales') |
Rule definitions (house PK ("id","companyId"); RLS writes sales_* for sales-family rows) |
enforcementRuleItemAssignment |
Explicit per-item pins, PK (itemId, ruleId) — SHARED with storage rules |
enforcementRuleAcknowledgment |
Append-only override/block evidence (INSERT via sales_create) |
Service functions: the admin CRUD is NOT in sales.service.ts. The read helpers (getEnforcementRules / getEnforcementRule / getEnforcementRuleAssignmentCounts) share one parametrized implementation in shared.service.ts, called with "sales" as the family. The entitlement-gated WRITES (upsertEnforcementRule / deleteEnforcementRule) moved to @carbon/ee/rules.server (packages/ee/src/rules/service.server.ts) — they embed requireEntitlement("SALES_RULES"). Cross-app READ queries getActiveSalesRulesForItems / getSalesRuleAssignmentsForItem / getSalesRulesList are imported from @carbon/ee/rules DIRECTLY at the call site; the gated writes assignSalesRule / unassignSalesRule are imported from @carbon/ee/rules.server at the call site too. Routes: x+/sales+/sales-rules* (list/new/edit/delete/assign/unassign), sidebar entry in useSalesSubmodules, per-item "Sales rules" card on x+/part+/$itemId.inventory.tsx. Enforcement: the quote, sales-order, and sales-invoice line create + edit actions, plus document gates (quote finalize/convert, RFQ convert, order confirm, shipment post, invoice post — the invoice-post gate runs in postSalesInvoice (invoicing/invoicing.server.ts) BEFORE the optimistic Pending write). Every blocked or acknowledged outcome (line checks and document gates) is recorded through recordSalesRuleOutcome in sales.service.ts — one enforcementRuleAcknowledgment row per violation plus the sales-rule-violation notification; the RFQ-convert gate is the one exception (the table's documentType CHECK has no salesRfq; the minted quote re-records downstream).
Rentals (sub-area)
Rental of serialized fleet units (fixed assets with an itemId), each line's accounting treatment (lessorClassification) set at activation: Rental or Sale (ASC 842 operating / sales-type lease; the enum's third value Financing, a direct financing lease, has no input). UI heading "Accounting treatment". Lives inside this module: validators in sales.models.ts, services and Kysely wrappers in the "Rental agreements (spec §3)" section of sales.service.ts, service functions in sales.server.ts, UI in ui/Rentals/, routes x+/sales+/rental-agreements.tsx (list, nav entry "Rental Agreements" in the Agreements group of useSalesSubmodules) and x+/rental-agreement+/ (new = setup step 1; $id.setup + $id.setup.{details,units,billing,accounting,review} = the wizard (see Setup wizard below); $id is the sales-order-style shell — RentalAgreementHeader top bar (beside RentalStatus, an Active agreement shows RentalEquipmentStatusBadge: To Deliver / Partially Delivered / On Rent / Partially Returned / Returned, derived from the line statuses by the pure rentalEquipmentStatus in sales.utils.ts (Sold counts as back; pinned by sales.utils.test.ts); on an Active agreement, for update: sales + create: inventory, Deliver / Return POST the agreement to shipment+/new / receipt+/new, which open the agreement's Draft rental document or create one; once the agreement has a document the button becomes a Shipments / Receipts dropdown with New Shipment / New Receipt and the agreement's documents, read by getRentalAgreementRelatedDocuments) + ResizablePanels with RentalAgreementExplorer (one row per unit, Add Unit while Draft), the center <Outlet /> and RentalAgreementProperties (every term, editable while Draft and read-only after; each field saves through x+/rental-agreement+/update.tsx → setRentalAgreementTerm, which re-reads the agreement, swaps the one field in and runs the whole rentalAgreementValidator + updateRentalAgreement on the merged terms, so a cross-field rule such as "reasonably certain needs an end date" still holds; a customer change clears the site and contact); $id.details renders RentalAgreementSummary (sales-order-style: units as line items with rates, status, the Posted shipment and receipt that moved each unit (rentalLineDocuments in sales.utils.ts) — no per-unit actions, delivery and return start from the header — then billed / unbilled / monthly rent / deposit / next due), the Accounting Treatment preview while Draft, Charges, Billing Periods and Deposits; $id.$lineId.details is the unit's page: RentalAgreementLineSummary (status, Delivered / Returned with their documents, Deliver / Return / Release unit / Sell to Customer / Remove Unit), RentalAgreementLineForm as a card, and that unit's charges and periods). Unit lifecycle actions live in one hook, useRentalLineActions, and share one rule set: Deliver and Return submit straight to the per-unit shortcut routes $lineId.deliver / $lineId.return (see Deliver and return below), which redirect into the document. The others open as page state (confirms, RentalAgreementReleaseForm, the charge form, the add-unit form) posting through fetchers to action-only routes (lines.new, charges.new, $lineId.release, $lineId.sell, …), which redirect to requestReferrer(request) so acting from a unit's page stays there — except Close / Cancel ($id.status, Cancel deletes Pending lines) and line delete, which go to /details. Schema: 20261006220301_fleet-rental-lease-enums.sql (incl. journalEntrySourceType 'Lease'), 20261006220501_rental-agreements.sql (tables incl. customerItemRentalRate and rentalLeaseScheduleLine), 20261006221101_rental-invoice-automation.sql; the delivery and return documents 20261008155050_rental-documents-enums.sql + 20261008155056_rental-documents.sql (spec .ai/specs/2026-10-07-rental-shipments-and-receipts.md). Spec §3–§4 of .ai/specs/implemented/2026-09-22-revenue-recognition-rentals-and-contracts.md Part I; the plan's execution notes (Tasks 36–54) record where the build deviated.
| Table / View | Purpose |
|---|---|
itemRentalRate |
Day / week / month rate ladder per item AND currency (unique (companyId, itemId, currencyCode), CHECK ≥ 1 tier). Edited on the part Sales tab ("Rental Rates" card, serial-tracked parts, base currency only) |
customerItemRentalRate |
A ladder agreed with ONE customer or ONE customer type (num_nonnulls(customerId, customerTypeId) = 1) for an item and currency, optional validFrom / validTo (inclusive, gated on the agreement's startDate), notes. Partial unique indexes: one row per (customer, item, currency) and per (type, item, currency). Migration 20261006220501_rental-agreements.sql; RLS company("sales", { read: "sales_view" }). Edited on the part Sales tab ("Customer Rental Rates" card, CustomerRentalRates + CustomerRentalRateForm in modules/items/ui/Item/, routes x+/part+/$itemId.sales.rental-rates.{new,$rateId,delete.$rateId}.tsx). A separate table from customerItemPriceOverride on purpose: a rental price is a rate per frequency with no quantity breaks, and pricing rules (percent / fixed on one unit price, quantity ranges) do not apply to rentals |
rentalAgreement / rentalAgreements (view) |
Header, readable rentalAgreementId (sequence RA, drawn by createRentalAgreement). status Draft / Active / Closed / Cancelled; billingCycle Calendar Month / Monthly / 28 Days (the Billing card shows Monthly + 28 Days, and an "Align to calendar periods" box under Monthly stores Calendar Month when ticked, Monthly when not — the contract Billing card's pattern; Properties reads "Monthly (calendar)" for Calendar Month); billingTiming Advance / Arrears; taxPercent (0–1 fraction, the rent lines' tax); depositAmount; lease-classification inputs discountRate (annual %, prefilled in new.tsx from companySettings.leaseDefaultDiscountRate), ownershipTransfers, specializedAsset, purchaseOptionAmount, purchaseOptionReasonablyCertain (the validator refuses it without endDate). View adds customerName, lineCount, onRentCount, nextDueOn, unbilledAmount |
rentalAgreementLine |
One fleet unit (fixedAssetId, quantity CHECK = 1). status Pending / On Rent / Returned / Sold (no Cancelled). rateUnit (Day / Week / Month, NOT NULL — the "Rate Frequency") and rate (NOT NULL, ≥ 0) = the unit's ONE rate, what billing and classification read. The line form starts rate from getDefaultRentalRates for the chosen frequency (customer → customer type → item, per frequency, effective on startDate) and re-starts it when the unit's item or the frequency changes; the value is the user's to overwrite. upsertRentalAgreementLine fills an omitted rate the same way (API / the fleet Rent action) and refuses RENTAL_LINE_NO_RATE when nothing is on file, deliveredAt + meterOut (written by a posted rental shipment), returnedAt + meterIn + returnNotes (written by a posted rental receipt; Release unit writes returnedAt only). Lease: inputs fairValue, economicLifeMonths, guaranteedResidualValue, unguaranteedResidualValue; set at activation lessorClassification (Rental / Sale; null on a Draft line; Financing has no input), classificationInputs (JSON ClassificationInputs from lessor-lease in @carbon/utils), initialNetInvestment / sellingProfit / commencementJournalId (Sale only); classificationOverride + classificationOverrideReason (the override route, Draft only). Partial unique index rentalAgreementLine_asset_live_idx: one live (Pending / On Rent) line per asset |
rentalAgreementCharge |
Variable charges per line (chargeType from enum rentalInvoiceLineType, default Charge — set server-side only: upsertRentalAgreementCharge always writes Charge, insertRentalPurchaseOptionCharge writes Purchase Option), chargeDate, amount, taxPercent, invoiceSeparately (default false; a Charge with it set is drafted on the held charges invoice instead of the rent invoice — ignored on a Purchase Option, which is always separate), salesInvoiceLineId stamp when billed, voidedSalesInvoiceId (set by VOID; makes the re-bill a held draft; sticky across a deleted draft, overwritten by a later VOID) |
rentalBillingPeriod |
Persisted periods per line: periodStart/End, days, rateUnitApplied, amount, isAdjustment, dueOn, status Pending / Invoiced, salesInvoiceLineId, memoId (an isAdjustment row is billed by a credit memo, never an invoice line — CHECK rentalBillingPeriod_memo_check; FK ON DELETE RESTRICT, so a Draft rental credit is deleted only through deleteRentalCreditMemoReleasingPeriods), voidedSalesInvoiceId (set by VOID; makes the re-bill a held draft; sticky across a deleted draft, overwritten by a later VOID). Unique (companyId, rentalAgreementLineId, periodStart, isAdjustment) |
rentalLeaseScheduleLine |
Effective-interest schedule of a Sale line, one row per payment (periodDate = its billing period's end, openingNetInvestment, paymentAmount, interestAmount, principalAmount, closingNetInvestment), written at activation; journalId / postedAt stamped by postRevenueRecognitionRun when a lease run posts its Interest row (a line that earns no interest has no row and stays unstamped; earnsInterest, lessor-lease in @carbon/utils). Unique (companyId, rentalAgreementLineId, periodDate); revenueRecognitionSchedule.rentalLeaseScheduleLineId points at it |
RLS on all seven: sales_view to read, sales_create/update/delete to write — each a company("sales", { read: "sales_view" }) rule in packages/database/src/authz/manifest.ts, shipped by 20261006221501_revenue-recognition-rentals-contracts-rls.sql (the schedule is written only by service-role posting paths).
- Billing math —
packages/utils/src/rental-periods.ts(pure,@carbon/utils). Every amount is billed, sorateCharge,calendarMonthCharge,periodChargeandgenerateRentalBillingPeriodstakedecimals(the agreement currency'sdecimalPlaces, read fromcurrencybypost-rental-agreementandcreate-rental-invoices,useCurrencyDecimalsin the ERP) and round to it — a part month, an early-return credit and a rate carrying the storage scale;leasePaymentTerms(lessor-lease) values a sales-type unit on the same rounded payment.rateCharge(whole units of the frequency × rate — Month = 28 days),periodCharge(a Monthly unit on a Calendar Month agreement iscalendarMonthCharge, month rate × days ÷ days in month; on a Monthly agreement it ismonthlyCharge, month rate × days ÷ days in its anniversary period, so a whole period is the rate; every other frequency / cycle israteCharge, so a Daily unit bills the days and a Weekly unit the whole weeks of a calendar month),defaultRentalRates(a unit's starting rate per frequency),billingHorizon(Calendar Month: end of next month / Monthly: today + 1 month / 28 Days: today + 28; activation cuts to it throughactivationBillingThroughinsales.service.ts, capped atendDatefor aSaleline),generateRentalBillingPeriods(cuts from the AGREEMENT start date, never delivery; fixed term cut in full; open-ended rolls one period pastthrough; holdover keeps billing pastendDate(Rentalonly — aSaleline never gets a period pastendDate); a return re-cuts the Pending period, and an Advance-billed period past the return gets one negativeisAdjustmentrow = billed − charge(days used) priced by the line's own frequency and rate, never positive). Pinned bypackages/utils/src/rental-periods.test.ts. - Lifecycle —
postRentalAgreement(apps/erp/app/modules/sales/sales.service.ts, ported from thepost-rental-agreementserver function;activate/release/close/cancel,postRentalAgreementPermissionupdate: "sales"). The service functionsactivateRentalAgreement,setRentalAgreementStatusandreleaseRentalUnit(sales.server.ts) run it throughinvokePosting. Its validators and pure blockers (unpricedUnitError, …) are insales.service.ts. Activate: Draft only, refuses a unit at rate 0 (unpricedUnitError), refuses a non-base currency ("Rental agreements in a foreign currency are not supported yet"), checks every unit via thefleetAssetsview (Available, or Reserved by this same agreement; asset Active / Fully Depreciated; not In Maintenance), bills each line at its ownrateUnit+rate(activation reads no rate card), classifies every line (below), cuts periods tobillingHorizon(today)(aSaleline only up toendDate), leaves undelivered lines Pending. No journal for aRentalline; aSaleline books its commencement. Release (rentalAgreementLineId,returnedAt): ends aPendingunit that never left the yard throughreturnRentalUnitwith no location, so its billing stops at the release date (an Advance period gets the early-return adjustment), the line goes Returned andfixedAsset.locationIdis unchanged; refused for a date after company today ("The release date cannot be in the future"), a line that is not Pending, aSaleline ("UNIT is treated as a sale; return it on a rental receipt instead" — plan decision P1; the UI hides Release unit for it) and a unit on an open (Draft / Pending) rental shipment or receipt ("UNIT is on shipment SHP…; remove it there before releasing the unit"). Close: refused FIRST while a Draft or Pending rental shipment or receipt of the agreement still has a line (openRentalDocumentBlocker: "Shipment SHP… is still open; post or delete it before closing the agreement"), then needs every line Returned/Sold, no Pending period, no unbilled charge. Cancel: Draft, or Active with no commencedSaleline and nothing On Rent/Sold/invoiced/recognized — DELETES the Pending lines (frees the units) and their Pending periods.fixed-asset+/$fixedAssetId.out-of-service.tsxlikewise readsgetOnRentLineForAssetwith the service role (an accountant may lacksales_view). - Deliver and return — a unit leaves on a rental shipment and comes back on a rental receipt: ordinary
shipment/receiptdocuments withsourceDocument'Rental Agreement'(sourceDocumentId= the agreement), one unit pershipmentFixedAssetLine/receiptFixedAssetLinerow throughrentalAgreementLineId(see inventory AGENTS). Thecreateposting builds them with typesshipmentFromRentalAgreement/receiptFromRentalAgreement({ rentalAgreementId, rentalAgreementLineId? }, Active agreement only, location = the agreement's,postingDateleft null because a setpostingDatereads as posted). Without a line id, a shipment holds everyPendingunit not on another open rental shipment, ticked; a receipt holds everyOn Rentunit ticked and everyPendingunit unticked (spec Q8: ticking a Pending unit returns it, and its billing stops at the return date). With a line id, the unit is added ticked to the agreement's Draft (or ticked when it sits there unticked), else a one-unit Draft is created. Refusals: "No units to deliver" / "No units to return", "The unit is already on an open shipment" / "… receipt". Partial unique indexesshipment_oneOpenDraftPerRentalAgreement_idx/receipt_oneOpenDraftPerRentalAgreement_idxallow one Draft of each per agreement.post-shipmentandpost-receiptown the'Rental Agreement'source (postShipment/postReceiptininventory.service.ts) and take an optionalpostingDate(YYYY-MM-DD; the post modal's Delivered on / Returned on, default company today; a future date is refused; other sources ignore it). Posting a shipment locks the agreement and the ticked lines, refuses a line that is not Pending or a unit out of service (the message names the unit), setsOn Rent+deliveredAt+meterOutand writes aRental DeliverytrackedActivity; noitemLedger,costLedgeror journal, for aRentaland aSaleline alike. Its void is allowed while every unit is still On Rent and noAccrualrow of its lines is Posted or claimed by a Draft run: the lines go back to Pending withdeliveredAt/meterOutcleared, and their unclaimed PlannedAccrualrows are deleted. Posting a receipt runsreturnRentalUnitfor each ticked line (Pending or On Rent), sets the unit'sfixedAsset.locationIdto the receipt's location (for aSaleline returned to Fleet, the new asset) and writes aRental Returnactivity for aRentalline. A rental receipt is never voided ("A rental return cannot be voided. Correct the unit by hand."). Posting either needsupdate: inventory. - Per-unit shortcuts —
$id.$lineId.deliver.tsx/$id.$lineId.return.tsx(update: sales+create: inventory) invokecreatewith the line id and redirect into the shipment or receipt, so a counter pickup is the shortcut, then Post.shipment+/new/receipt+/newtake the'Rental Agreement'source from the header buttons and redirect to the agreement's Draft when one exists. The inventory$id.detailsactions refuse a change of source on a rental document. - The return body —
returnRentalUnit(sales.service.ts, with the helpers it shares with activation), called bypost-receiptand byrelease. The caller locks the agreement and checks it is Active. It refuses areturnedAtafter company today (futureReturnError: "The return date cannot be in the future"), re-cuts aRentalline's periods (aSaleline's billing is its term and is left alone), setsfixedAsset.outOfServiceSince/ReasonwhentakeOutOfServiceis set, and runsreturnResidualfor aSaleline, which needsresidualDestinationand is refused beforeendDate(below). Its optionallocationIdis where aSaleline's residual lands: a rental receipt passes its own location (spec Q7), so the stock adjustment, or the new fleet asset and itsCapitalizationtransfer, are at the receipt's location; the'Lease'journal's Location dimension keeps the agreement's location (plan decision P4). Without it (release), the agreement's location. - Invoice generation and automation —
createRentalInvoices(sales.service.ts, ported from thecreate-rental-invoicesserver function, live testapps/erp/test/database/create-rental-invoices.test.ts;{ asOf, rentalAgreementId? }, permissionsupdate: sales+create: invoicing; an agreement that throws is returned infailures, never stops the others): per Active agreement, first rolls every liveRental(or unclassified) line's periods tobillingHorizon(asOf)— aSaleline never rolls a holdover period, its whole term was cut at activation — then drafts DraftsalesInvoices with aRentalline per due non-adjustment period (dueOn <= asOf) and per charge dated<= asOf, stampingsalesInvoiceLineId. Due early-return adjustments (isAdjustment) never go on an invoice — a negative line could net it below zero, which no payment can apply and no refund can pay out: they go on ONE Draft credit memo per agreement (insertRentalCreditMemo:memo.rentalAgreementId,creditMemosequence, amount = Σ credits at currency decimals,reference= the readable agreement id, notes = the "Early return credit — N days used" descriptions), stampedmemoId+Invoiced, returned increditMemos; it stays Draft in every automation mode and a person posts it (post-memo, below). The Invoice action redirects to the memo when nothing else was drafted. The agreement's effective invoice automation (rentalAgreement.invoiceAutomation ?? companySettings.invoiceAutomation, view columnrentalAgreements.effectiveInvoiceAutomation;Draft Only/Post/Post and Email/Post and Send via Stripe) decides the split:Draft Onlydrafts ONE combined invoice and automates nothing; otherwise the rent and everyChargego on one rent invoice (a charge alone, unheld, when no rent is due) and charges markedinvoiceSeparatelyplus everyPurchase Optiongo on a separate charges invoice (planRentalInvoices,@carbon/utils); holds are stamped onsalesInvoice.automationHoldReason— the charges invoice always, a rent invoice with an early-return credit, and a re-bill of a voided invoice (wins over the credit; checked across every line of the rent invoice, charges included). Called by the Inngestrecurring-billingjob (cron0 5 * * *,userId "system"), which then posts, files the invoice PDF on (attachPostedInvoicePdf, every posting mode), and emails or sends via Stripe, every unheld non-Draft-Only draft it created — read back from the database (findInvoicesToAutomate), so drafts from a failed or retried attempt are automated too (packages/jobs/src/invoicing/automate-invoice.ts) and sends each agreement owner (salesPersonId ?? createdBy) a "Recurring invoicing" digest; and by "Invoice" ($id.invoice.tsx→generateRentalInvoicesNow, needsupdate: salesANDcreate: invoicing) and Sell to Customer, which firecarbon/invoice.automatefor the same invoices. The per-agreement override isupdateRentalAgreementInvoiceAutomation(setRentalInvoiceAutomation, intentinvoiceAutomationonrental-agreement+/update.tsx; Draft/Active only;Post and Emailrefused without a contact email,RENTAL_INVOICE_EMAIL_NO_CONTACT). Spec:.ai/specs/implemented/2026-09-22-revenue-recognition-rentals-and-contracts.mdPart II. - Rental credit memos —
post-memobooks a memo withrentalAgreementIdthroughloadRentalCredit+ the pureplanRentalCredit(apps/erp/app/modules/invoicing/invoicing.service.ts, tested): the memo is apportioned over its adjustment periods (distributeRoundingResidual; a mismatch with an edited amount is refused), each period planned by the invoice path's ownplanRentalLine/rentalScheduleRows, so the legs replacing the memo's reason leg are Dr Deferred Revenue up to the period's Planned Deferral rows and Dr Rental Income for the rest (Cr AR), and the negative Deferral rows carryrevenueRecognitionSchedule.memoId. Once posted it is applied to invoices from a payment (credits) or refunded like any credit memo. Void (post-memoindex.ts) is refused once a run holds or has posted one of its rows; otherwise it reverses the journal, deletes its Planned rows and returns its periods to Pending. A Draft one is deleted bydeleteRentalCreditMemoReleasingPeriods(sales.service.ts, called bydeleteDraftMemo), which returns the periods to Pending. The Billing Periods card links an adjustment to its memo; the memo's Documents panel links the agreement (getSettlementRelatedItemsrentalAgreementId). - Invoice deletion —
deleteSalesInvoiceReleasingRentals/deleteSalesInvoiceLineReleasingRentals(sales.service.ts) delete andreleaseRecurringInvoiceStampsin ONE Kysely transaction (the stamps have no FK). It releases rental periods and charges AND contract schedule rows (customerContractInvoiceLine.salesInvoiceLineId; a planned invoice returns toPlannedonce none of its rows is stamped). The line variant takes the route'sinvoiceIdand, underFOR UPDATE, refuses a line of another invoice or of a non-Draft invoice (releasing a posted line's stamps would bill its period again). The MCP toolsinvoicing_deleteSalesInvoice/invoicing_deleteSalesInvoiceLinestill call the plain service functions and leave stamps behind (open follow-up). - The
Rentalinvoice line —salesInvoiceLineTypevalueRental, no item; columnsrentalAgreementId,rentalAgreementLineId,rentalBillingPeriodId,rentalAgreementChargeId,rentalLineType(enumrentalInvoiceLineType: Rent / Charge / Purchase Option), CHECKsalesInvoiceLine_rental_check. Rendered read-only bySalesInvoiceLineForm;salesInvoiceLineValidatoraccepts but never offers it. Posting (postSalesInvoice, decisions ininvoicing.service.ts, pinned byapps/erp/test/database/post-sales-invoice/rental-posting.test.ts): Rent → Cr Contract Assets for unbilled accruals, rest Cr Deferred Revenue + Deferral schedule rows; negative Rent (an early-return credit on an invoice drafted before credits became memos; new ones are credit memos, above) → Dr Deferred Revenue (negative Deferral rows) / Dr Rental Income for the recognized part; Charge → Cr Rental Income; on aSaleline Rent and Purchase Option → Cr Net Investment in Leases (no schedule rows, no accrual consumption; a negative Rent line is refused) and Charge → Cr Rental Income; Purchase Option on aRentalline → refused ("Purchase option billing requires a line treated as a sale"). ASaleline's Purchase Option line also posts the NI settlement (below). Posting a Purchase Option line flips its agreement line toSold(only aSalelineOn Rent, in the posting transaction, regardless of accounting); VOID returns a still-Soldline toOn Rent. Revenue legs carrydocumentType 'Rental Agreement'. - Rental rows post in the lease run — every
revenueRecognitionSchedulerow of a rental agreement (rentDeferralrows frompost-sales-invoiceandpost-memo,Accrualrows fromsynthesizeRentalAccruals, aSaleline'sInterestrows) carriesrentalAgreementLineId, so the Lease run claims it (runTypeFilter,@carbon/database/run-type) and posts it assourceType 'Lease Run'; the revenue recognition run never sees it. Accounting → Closing → Leases lists them; close task "Post lease journals".20261011163211_lessee-leases.sqlreleased these rows from Draft revenue runs (Posted runs keep theirs) and20261011192957_lease-run-sync-policy.sqlgave each accounting integration'sLease Runthe sync setting itsRevenue Recognitionhad. The rental refusals name it: "A draft lease run holds accrued rent for UNIT; delete the run before voiding the shipment", "A posted run holds accrued rent for UNIT; the shipment cannot be voided", "A draft lease run includes this lease's interest; post or delete the run before returning the unit", "This rental credit is already part of a lease run; reverse or delete the run before voiding it". See accounting AGENTS → Run types. - Deposits —
payment.rentalAgreementId/payment.salesOrderId(at most one). The Deposits card listsgetRentalAgreementDeposits; "Record Deposit" links topayments/new?customerId&rentalAgreementId&amount. Posting is inpost-payment(see accounting AGENTS, Payments). - Lease classification — pure math in
packages/utils/src/lessor-lease.ts(@carbon/utils):presentValue(pvRent,pvPaymentsincl. a reasonably certain option + guaranteed residual,pvResidual,netInvestment),classifyLessorLease(tests a–e; any true ⇒Sale;termMonthsnull ⇒ alwaysRental),buildLessorSchedule(last line closes on option + residuals),wholeMonthsInTerm,leasePaymentTerms(Calendar Month and Monthly: the month rate over whole months — Monthly counts them as billing cuts them,leaseMonthsThrough— a Daily or Weekly unit at its average month over a 365-day year; 28 Days: the unit's 28-day charge over whole 28-day periods at annual × 28/365),salesTypeRequirementError(also refuses a Daily / Weekly unit treated as a sale on a Calendar Month or Monthly agreement: its invoices would not match a level payment, and — giventoday— an agreement starting before the activation month: commencement posts on the activation day while interest is dated from the start),netInvestmentExceedsFairValue(a WARNING, shown on the unit's Accounting treatment panel and inRentalCommencementPreview: payments + residual discounted at the entered rate are worth more than the fair value, i.e. the rate is below the rate implicit in the lease),classifyRentalLine(the storedClassificationInputsrecord). Thresholds fromcompanySettings.leaseMajorPartThresholdPercent/leaseSubstantiallyAllThresholdPercent. The Draft preview (sales.utils.ts:leaseTermMonths,draftLeasePaymentTerms,previewLeaseClassification,readLeaseClassification,leaseCommencementPreview) calls the same functions; UIui/Rentals/RentalLeaseClassification.tsx(LeaseClassificationPanelon the line form, headed "Accounting treatment" with Rental / Sale cards and the ASC 842 names as secondary text (Financing has no input and is not shown),LeaseClassificationOverrideModal,RentalCommencementPreviewin the Activate confirmation — the$id.tsxloader reads the units' cost and accumulated depreciation with the user's client, sofixedAssetRLS hides them from a user without accounting view and the preview shows only the NI / revenue legs). Override route$id.$lineId.classification.tsx→classifyRentalUnit:update: accounting, Draft only, reason required, reads and writes with the service role (an accountant may lack sales RLS), best-effort audit entry (entityType "rentalAgreement",tableName "rentalAgreementLine", reason as aclassificationOverrideReasondiff entry). - Sales-type commencement / end of term —
postRentalAgreement(its pure decisions are insales.service.ts, pinned byapps/erp/test/database/post-rental-agreement/lessor.test.ts). Activation, perSaleline (salesTypeRequirementError,lessor-leasein@carbon/utils: needsendDate,fairValue> 0, and WHOLE billing periods — Calendar Month starts on the 1st and ends on a month end, Monthly ends the day beforestart + n monthson any start day, 28 Days is a multiple of 28 days — so the rent billed equals payment × periods the NI was valued on; messages read "UNIT is treated as a sale, which …";RentalCommencementPreviewshows the same message in the Activate confirmation): assetDisposedbySale+fixedAssetDisposal(saleProceedsNI,netBookValueAtDisposalC,gainLossselling profit); a'Lease'journal, Provisional before the accounting cutover (Dr NI, Dr COGS C − PVres, Dr class accumulated depreciation / Cr Lease Revenue PVpay, Cr class asset at cost); tracked entityConsumedwithRental Agreement+Customerattributes and aLease Commencementactivity;rentalLeaseScheduleLinerows and PlannedInterestrecognition rows (Dr NI / Cr lease interest income), which refuse when their account defaults are empty (a schedule row has no stand-in). Fleet units only (activation already refuses an asset-less line). Return of aSaleline (on a rental receipt;residualDestinationFleet / Inventory, not beforeendDate, not in the future, not while a Draft run holds its Interest rows dated after the return): closing NI =netInvestmentAt— theclosingNetInvestmentof the last schedule line dated on or beforereturnedAt(the closing target at/afterendDate;initialNetInvestmentwhen there are no lines); Fleet → newfixedAssetin the class named "Rental Fleet" (else the class the unit left) at that cost + a PostedCapitalizationfixedAssetTransfer; Inventory →bookAdjustment+1 at that unit cost;'Lease'journal Dr asset / inventory, Cr NI; only unposted Interest rows and schedule lines dated AFTER the return are deleted — those on or before it stay and post through lease runs, bringing NI to zero. Sell to Customer ($id.$lineId.sell.tsx→sellRentalUnit,create: [sales, invoicing]+update: sales): an Active agreement'sSalelineOn RentwithpurchaseOptionAmount, once per line, not beforeendDate(early exercise is an early termination — a manual journal) — inserts aPurchase Optioncharge dated company today through the server-onlyinsertRentalPurchaseOptionCharge(sales.service.ts) and callsgenerateRentalInvoicesNow; the invoice's posting marks the line Sold and settles the line's remaining NI against the schedule's closing balance (purchaseOptionSettlementininvoicing.service.ts: shortfall DrcostOfGoodsSoldAccount/ Cr NI, excess Dr NI / CrleaseRevenueAccount, same journal line reference so VOID reverses it; each default required only when its leg is). On a rental receipt,ReceiptRentalLineItemshows the Return To radios for aSaleline (saved toreceiptFixedAssetLine.residualDestination),ReceiptPostModalblocks a tickedSaleline without one, and the post re-reads the classification. - Fleet —
fleetAssetsderives Reserved (live Pending line) and On Rent (a commencedSaleunit reads Sold: its asset is Disposed); the fleet table's Rent row action (Available units) opensnewRentalAgreement?fixedAssetId=.post-asset-transferreturnrefuses a unit on a live line. A posted rental receipt moves the unit'sfixedAsset.locationIdto the receipt's location; a release does not move it.
Building blocks (sales.service.ts): getRentalAgreements / getRentalAgreement / insertRentalAgreement / updateRentalAgreement / deleteRentalAgreement, getRentalAgreementLines / getRentalAgreementLine / upsertRentalAgreementLine / insertRentalAgreementLines (the wizard's Add Units; not an MCP tool) / deleteRentalAgreementLine, getRentalAgreementCharges / upsertRentalAgreementCharge / deleteRentalAgreementCharge, (their service functions in sales.server.ts are the published tools — createRentalAgreementLine / updateRentalAgreementLine over the line upsert, createRentalAgreementCharge / updateRentalAgreementCharge over the charge upsert; insertRentalAgreement and updateRentalAgreement sit under createRentalAgreement / setRentalAgreementTerm — so the building blocks carry their own guards: updateRentalAgreement and line upsert/delete only while the agreement is Draft, a line never moves agreements and its fleet unit is read under the line's company; a charge insert only on a Draft/Active agreement's line and always as charge type Charge — rentalAgreementChargeValidator has no chargeType; a charge update only while unbilled; refusals are PostgrestError-shaped RENTAL_* codes; every writer picks its fields explicitly rather than spreading the payload, so status, lifecycle timestamps, the rate snapshot, the classification columns, a charge's chargeType and its billing stamp cannot be set through them), getRentalBillingPeriods, getRentableFleetAssets (fleetStatus = 'Available'), getItemRentalRate (takes the currency) / upsertItemRentalRate / deleteItemRentalRate, getDefaultRentalRates (in sales.utils.ts; batch over itemIds, one query per table, keyed by item → per frequency { rate, source } with source Customer / Customer Type / Item; used by the line upsert for an omitted rate, the line form on unit change, and the $id.$lineId.details loader while Draft for the "where did this rate come from" hint and frequency changes), getCustomerItemRentalRates / getCustomerItemRentalRate / upsertCustomerItemRentalRate / deleteCustomerItemRentalRate, getRentalAgreementDeposits, getRentalAgreementRelatedDocuments (the agreement's rental shipments and receipts with their asset lines, for the header dropdowns and rentalLineDocuments). Validators: rentalAgreementValidator, rentalAgreementLineValidator, rentalAgreementLinesAddValidator, rentalAgreementChargeValidator, rentalAgreementReleaseValidator (rentalAgreementLineId + returnedAt), rentalAgreementLineClassificationValidator, itemRentalRateValidator, customerItemRentalRateValidator, const arrays lessorClassificationOverrides, rentalResidualDestinations, rentalAgreementStatuses, rentalAgreementLineStatuses, rentalBillingCycles, rentalBillingTimings, rentalRateUnits, rentalInvoiceLineTypes.
- Setup wizard — creating an agreement is five routed steps, built on the same
~/components/Setuppieces as the contract wizard (rentalAgreementSetupStepsinRentalSetupSteps.tsx: details → units → billing → accounting → review;path.to.rentalAgreementSetup(id, step)).new.tsxis step 1 (RentalAgreementDetailsForm: customer, rental site, contact, shipping location, Open-ended / Fixed Term choice cards with the end date, sales person defaulted to the current user, currency, notes; the terms later steps own are carried as hidden fields) and redirects tosetup/units— also when the fleet register's Rent action pre-adds a unit.$id.setup.tsx(layout,update: sales) redirects a non-Draft to$id.detailsand rendersSetupFrame+SetupFooter(unit count and, when every unit is Monthly, the monthly rent; Back / Next, Next disabled on Units until there is a unit; on Review "Save as Draft" (→ list) and "Activate", which opens the sameConfirm+RentalCommencementPreviewas the header).$id.setup._indexredirects to units;setup.detailsre-saves step 1 throughupdateRentalAgreement(a currency change re-reads the exchange rate). Steps: Units =RentalUnitsGrid(Rate Frequency and Rate cells →$lineId.update, which merges one field into the line and runsrentalAgreementLineValidator+upsertRentalAgreementLine, a new frequency restarting the rate fromgetDefaultRentalRates, else 0; "Add Units" →lines.add→insertRentalAgreementLines, several Available fleet units at their rate on file for one frequency, 0 when none — not an MCP tool; Remove Unit →$lineId.delete, which now returns to the referrer unless it was the removed unit's page); Billing =RentalAgreementBilling(billing cycle and timing as choice cards, payment terms, deposit, tax percent, invoicing mode — each saved alone throughupdate.tsxviauseRentalTermSave); Accounting =RentalAgreementAccounting(LeaseClassificationPreviewfrom the saved terms; with an end date the discount rate, purchase option and the three switches, plus a unit-inputs grid — fair value, economic life, residuals — through$lineId.update); Review =RentalAgreementSummary, the blockers linked to their step (no units; a unit at rate 0 —postRentalAgreementactivate refuses it,unpricedUnitErrorinsales.service.ts, and the wizard footer and header disable Activate) andRentalCommencementPreview. The Add Units modal and the no-units state carry an info alert: a serial number missing from the list must first be capitalized (part Inventory tab → Storage Units → Capitalize as Fixed Asset). Opening a Draft lands in the wizard:$id._indexand the$id.detailsloader redirect anyone withupdate: sales(draftRentalAgreementSetupPath,sales.service.ts), so the list and every action that falls back to the agreement page continue setup; a viewer without it gets the page, whose header has "Continue Setup". A successful Activate from the wizard redirects to$id.detailsrather than back into it.
Rentals safety
- Never write
rentalBillingPeriod/ line status transitions from app code; no app code writes a line status. Activate / release / close / cancel go throughpost-rental-agreement, delivery and return throughpost-shipment/post-receipt(source'Rental Agreement'). - Never delete a sales invoice (or line) that may carry Rental lines with a plain delete — use the
*ReleasingRentalsservice functions (sales.service.ts). - Terms and units are editable only while Draft; the line details route refuses a unit change after activation.
- Delivery (a posted rental shipment) puts the unit on rent (it starts accruals); billing periods run from the agreement's start date and cycle, whatever the delivery date.
- A
Saleline (sales-type lease) is derecognized at ACTIVATION, not delivery. Never unwind it from app code: early termination is a manual journal (return beforeendDateand cancel both refuse "Ending a rental treated as a sale early is a manual journal"). - A stored classification is final once Active; thresholds changed in settings apply only to later activations.
Contracts (sub-area)
AR contracts (spec .ai/specs/implemented/2026-09-22-revenue-recognition-rentals-and-contracts.md Part III; plans .ai/plans/implemented/2026-09-22-revenue-recognition-rentals-and-contracts.md Part III and .ai/plans/implemented/2026-09-22-revenue-recognition-rentals-and-contracts.md Part IV — Phase B revenue + the setup wizard): a customer is billed for Service items on a planned invoice schedule, and each line's revenue is recognized from a stored monthly plan. Lives inside this module: validators in sales.models.ts (contract block), services and the Kysely / posting wrappers in the "Customer contracts" section of sales.service.ts, service functions in sales.server.ts, UI in ui/Contracts/, routes x+/sales+/contracts.tsx (list, titled "Service Contracts"; nav "Service Contracts" in the Agreements group of useSalesSubmodules, before Rental Agreements) and x+/contract+/ (new = setup step 1; $id.setup + $id.setup.{details,products,invoicing,revenue,review} = the wizard (below); update (properties); $id shell = ContractHeader + ContractExplorer + Outlet + ContractProperties, or the bare Outlet when a $id.setup route matches; $id.details renders Summary, Invoices, Revenue, Amendments; lines.new, lines.add (several Service items at once), $lineId.details, $lineId.update (one grid cell), $lineId.delete, delete, schedule, revenue, amend, cancel, revert-cancellation, confirm, invoice), plus x+/sales-order+/$orderId.contract.tsx (Create Contract).
| Table / View | Purpose |
|---|---|
customerContract / customerContracts (view) |
Header, readable customerContractId (sequence CON, drawn in new.tsx). status Draft / Active / Ended; contractType (New Sales / Existing / Expansion / Reactivation / Contraction); billingFrequency Week / Month / Quarter / Year; billingAlignment Anniversary / Calendar; billingTiming Advance / Arrears; startDate / endDate (NULL = open-ended; CHECK endDate >= startDate - 1, where startDate - 1 is a contract cancelled back to nothing) / termMonths; renewal Renew / End + renewalUplift; firstInvoiceDate; billedThrough; recognizeRevenueFrom (revenue months before its month are Recognized Externally); invoiceAutomation (NULL = company default); projectId; salesOrderId; shipToCustomerLocationId (FK customerLocation; new.tsx defaults it from Customer → Shipping when the customer ships to itself; a customer change on a Draft — setup step 1 ($id.setup.details.tsx) or the properties panel (update.tsx) — replaces it, the bill-to, invoice contact and address and payment terms with the new customer's defaults through contractCustomerChange (sales.service.ts), clearing any the new customer lacks; copied onto each drafted invoice's salesInvoiceShipment.customerLocationId); stamps confirmedAt/By, cancelledAt + cancellationReason, endedAt. View adds customerName, effectiveInvoiceAutomation, lineCount, contractValue (Σ every schedule row incl. memo credits), invoicedToDate, recognizedToDate (Σ Recognized revenue rows), nextInvoiceDate |
customerContractLine |
revenueType One-time / Recurring (enum contractRevenueType, UI label "Revenue Type"); Service itemId; quantity, rate, rateUnit (Day–Year; CHECK: set iff Recurring); discountPercent + discountEndsOn, taxPercent (0–1 fractions); startDate / endDate (NULL = runs to the contract end); revenueMethod Daily / Even Period, goLiveDate, revenueStartDate / revenueEndDate (plan the revenue rows); amendmentId / amendsLineId; salesOrderLineId (unique); projectId (overrides the header's) |
customerContractAmendment |
amendmentDate (effective, after snapping), effect Change Date / Next Period, contractType, reason; previousState JSONB { contractEndDate, renewal, lineEndDates }, written ONLY by a cancellation so it can be reverted. Confirm writes "Discount ends" amendments, renewal writes "Renewal" (Existing, Next Period), cancel writes Cancellation: <reason> (Contraction) |
customerContractInvoice |
A planned invoice: invoiceDate, status Planned / Invoiced / Billed Externally, isEdited, salesInvoiceId stamp (no FK) |
customerContractInvoiceLine |
A schedule row: customerContractLineId, periodStart / periodEnd, units, unitPrice (the LIST price per line unit — the migration comment "net of discount" is wrong), amount (negative for an adjustment), isAdjustment, stamps salesInvoiceLineId / voidedSalesInvoiceId / memoId. customerContractInvoiceId is NULL only for a cancellation credit (CHECK: invoice or memo) |
customerContractRevenue |
The revenue plan: one row per (line, calendar month), UNIQUE (companyId, customerContractLineId, periodStart); periodStart = the 1st, periodEnd = the month's last day; amount in contract currency (negative for a catch-up); status contractRevenueStatus Planned / Recognized / Recognized Externally. Cascades with its contract and line |
customerContractLedgerEntry |
The movement ledger: one row per movement of a line's position, entryType contractLedgerEntryType Opening / Invoice / Recognition / Credit Memo / Void, postingDate, source refs salesInvoiceLineId / memoId / revenueRecognitionScheduleId (FK ON DELETE CASCADE — a recalculated Draft run drops both) / customerContractRevenueId, journalId, signed deferredAmount / deferredBase / assetAmount / assetBase; updatedBy / updatedAt (20261006221301_contracts.sql). A line's position = Σ its rows |
Provenance on existing tables: salesInvoice.customerContractId, salesInvoiceLine.customerContractId / customerContractLineId / customerContractInvoiceLineId / projectId, memo.customerContractId (all FK, ON DELETE SET NULL); revenueRecognitionSchedule.customerContractLineId / customerContractRevenueId (FK, ON DELETE SET NULL on that column) / contractAmount (the row in contract currency). These FKs push a bare salesInvoice(...) embed from salesInvoiceLine over TypeScript's instantiation depth (TS2589): name the FK, salesInvoice!salesInvoiceLine_invoiceId_fkey(...). RLS on all seven tables: company("sales", { read: "sales_view" }) in authz/manifest.ts, shipped by 20261006221501_revenue-recognition-rentals-contracts-rls.sql (tables 20261006221301_contracts.sql, enums 20261006221201_contract-enums.sql, which also adds journalLineDocumentType Contract).
- Schedule math — pure,
@carbon/database/contract-schedule(packages/database/src/contract-schedule.ts, re-exported from@carbon/utils; in@carbon/databaseso the demo-dataset tier can plan a schedule).billingGrid(Anniversary anchors onstartDate, Calendar on the Monday / 1st of month / quarter / 1 Jan; period k is always added FROM the anchor, so a 31 Jan anchor clamps to 28 Feb and returns to 31 Mar; first period clipped to the start, last to the end).periodUnitscounts whole months from the period start, then the remaining days as a fraction of the next month (15 Mar–14 Apr = 1);wholePeriodUnitsmakes a whole unclipped month-based period exact (Month at a Year rate = 1/12). A Weekly grid at a Month / Quarter / Year rate prices every row withaverageDayUnitsinstead — days at the yearly average day (rate × 12 ÷ 365 for a Month rate) — so every whole week is the same amount and a 365-day year is exactly 12 months (periodUnitsmade a week 7/28, 7/30 or 7/31 of a month).rowPricing:unitPrice = round(rate × units),amount = round(quantity × unitPrice × (1 − discountPercent)).planInvoiceSchedule: One-time = one row on the first grid due date on or after its start; Recurring = one row per grid period, due on its first (Advance) or last (Arrears) day vianextInvoiceDate(a mid-period row lands on the NEXT regular invoice date); an invoice dated beforefirstInvoiceDatemoves to it; a row ending on or beforebilledThroughisBilled Externally.horizon: fixed term →endDate; open-ended → the end of the period after today's.validateScheduleEditis the conservation check (residual per line = computed − Σ non-adjustment rows).reconcileContractSchedule= reconcile, never rewrite: billed rows untouched; ONE adjustment per already-Invoiced recurring row whose line now ends earlier (−billed × daysAfter ÷ daysBilled); Planned invoices from the change date deleted and re-planned; split installments re-cut as a group. AlsoamendmentEffectiveDate,recurringValuePerPeriod,suggestAmendmentType(up Expansion, down Contraction, equal Existing),suggestContractType(Reactivation when every non-Draft contract of the customer Ended, else New Sales),currentPeriodEnd,renewedEndDate,invoiceLinePricing. Pinned bycontract-schedule.test.ts. - Persist on first edit — an unedited Draft has NO schedule rows: the
$idloader plans them live. The first schedule edit (or Confirm) writes them (isEdited = trueon touched invoices). The page names live rows by POSITION —planned:<invoiceDate>for an invoice,planned:<invoiceDate>:<lineId>:<periodStart>[:adjustment]for a row — andedit-scheduleresolves them after writing (fix56fa0f7b8e, pinned bycontract-lifecycle.test.ts). A line edited after a schedule edit leaves per-line residuals; the invoice grid shows them and offers Reset Schedule. The revenue plan follows the same model: an unedited Draft has nocustomerContractRevenuerows (the loader plans them live,revenueIsStored: false), and the firstedit-revenue(or Confirm) writes them. Revenue rows are addressed by (line, month), so they need no position refs. - Revenue plan — pure,
@carbon/database/contract-revenue-schedule(re-exported by@carbon/utilscontract-revenue.ts, which keepscontractPositionPreview;revenue-schedule.tsmoved to@carbon/databasetoo,@carbon/utilsre-exports it).planRevenueSchedule: a line's revenue total = Σ its invoice-schedule rows (adjustments and memo credits included), spread overlineRevenueDates(go-live ?? revenue start ?? start → revenue end ?? end) byrevenuePreview— Daily =spreadStraightLine; Even Period = equal per full calendar month, a partial month prorated by its days, residual placed bydistributeRoundingResidual; no end → one row in the start month (an open-ended Recurring line runs to its last scheduledperiodEnd). Months beforerecognizeRevenueFrom's month areRecognized Externally.validateRevenueEditis the conservation rule: residual per line = billed − Σ revenue rows.reconcileRevenueSchedule= reconcile, never rewrite (one line from a date):Recognized/Recognized Externallyrows andPlannedrows before the date's month are kept; the other months take the new plan; whatever keeps the line off the new plan's total (a recognized month now worth less) lands on the first non-kept month on or after the date, as a catch-up row when the plan has none. Pinned bycontract-revenue-schedule.test.ts. Writers insales.service.ts(shared bypostCustomerContractandcreateContractInvoices):billedTotals,plannedRevenue,materializeRevenue,ensureRevenue(writes the plan for an Active contract that has none — one confirmed before Phase B),reconcileRevenue(also keeps an in-flight Planned month — one arevenueRecognitionSchedulerow references, held by a Draft run — and never deletes it),changedRevenueLines(only lines whose revenue dates, method, billed total or last billed period changed are reconciled),writeOpeningEntries. - Position — pure,
@carbon/database/contract-position. Position = invoiced − recognized, per line, in contract currency AND base: Deferred Revenue holds max(N, 0), Contract Assets max(−N, 0). Every movement goes throughapplyContractMovement({ position, amount, rate, counterpart }): a raising amount (an invoice) clears Contract Assets first, then adds to Deferred Revenue; a lowering amount (a recognition, a credit, a VOID) releases Deferred Revenue first, then adds to Contract Assets. Base is carried at a weighted-average rate per pool (drawing takes the pool's carried base, adding takes the movement's rate); against areceivablethe difference to the receivable's base is realized FX (fxBase), againstrevenueit is 0. AlsopositionFromEntries,normalizePosition(the reclass that brings a negative pool back),movementCredits. Pinned bycontract-position.test.ts. Ledger I/O inapps/erp/app/modules/shared/shared.service.ts:loadContractPositions(one grouped read) andlockContractPositions— ONE transaction advisory lockcontract-position:<companyId>that every writer takes (invoice posting and its VOID,post-memo,synthesizeContractRevenue). Confirm writes Opening entries without it. - Lifecycle —
postCustomerContract(apps/erp/app/modules/sales/sales.service.ts, ported from thepost-customer-contractserver function,update: sales; every action locks the headerFOR UPDATE; it runs as the signed-in user (invokePostingwith the caller's client and{ as: postCustomerContractPermission }, inrunContractAction):confirmContract/amendContract/cancelContract/revertContractCancellationand the two previews throughpostContract,$id.scheduleand$id.revenuethroughrunContractAction(sales.service.ts)):confirm(Draft; ≥ 1 line, Service items, a rate unit on Recurring lines; materializes an unedited schedule or refuses an edited one that no longer conserves; underPost and Send via Striperefuses unless the bill-to customer has astripe-connectcustomer mapping — the confirm modal links one first throughStripeCustomerPanelby customer (/api/stripe-connect/customer/by-customer/:customerId) andlinkStripeCustomerForBillinginconfirmContract; turns eachdiscountEndsOninto a "Discount ends" amendment + full-price copy; a stored revenue plan must conserve before that (refuseRevenueResiduals, details{ revenueResiduals }), the plan is written when none is stored or reconciled for the lines a discount end split, then checked again; thenwriteOpeningEntries(D8: per line, ΣBilled Externallyrows − ΣRecognized Externallyrevenue, applied to an empty position at the contract'sexchangeRate,postingDate= start, no journal — the customer's opening journal carries it); status Active),edit-schedule(Draft, Planned invoices only;move/split/merge/moveLine, plus the invoice grid'ssetAmount(one invoice × line cell becomes ONE non-adjustment row of the amount, units rescaled like a split; 0 deletes the cell's rows and an emptied invoice),addInvoice(date + per-line amounts, ≥ 1 above 0; added to a Planned invoice already on that date) anddelete(the invoice and its rows; each line shows a residual)),reset-schedule,edit-revenue(Draft; the first edit writes the live plan through thehorizon;setAmount(line ×YYYY-MM-01month upsert, 0 deletes),addMonth(amounts add to what the month holds),deleteMonth(every line's row),reset(delete all rows → live again); a month beforerecognizeRevenueFromis writtenRecognized Externally),amend(Active;change/add/end; One-time lines change as a whole and refuse once invoiced; a Recurring copy (amendment or discount-end split) keeps a go-live / revenue start only when it falls after the cutover and a revenue end only on or after it (carriedRevenueDates), andsetLineEndDatesclamps an ended line'srevenueEndDateto its new end —cancelrecords what it clamped inpreviousState.lineRevenueEndDatesfor the revert;preview: trueruns the whole amendment and rolls back viaPreviewRollback; reconciles revenue from the effective date),cancel(Active; ends lines past the end date,renewal = End, removes later Planned invoices; withcreditUnusedTimedrafts one Draft creditmemowithcustomerContractIdcarrying the adjustment rows, else the adjustments are dropped; an end date before the start sets Ended at once; reconciles revenue from the end date, so a month already recognized past it gets a negative catch-up row; also previewable),revert-cancellation(Active, on or before the cancelled end date, memo still Draft; restores frompreviousState; reconciles revenue from the cancelled end date). Percent inputs are points ÷ 100. - Invoice generation —
createContractInvoices(sales.service.ts, ported from thecreate-contract-invoicesserver function; jobs call it as thecreate-contract-invoicesposting) ({ asOf, customerContractId? },update: sales+create: invoicing; one transaction per contract, failures returned infailures): renew (renewal = RenewandendDate <= asOf, one term at a time; with an uplift every continuing Recurring line is ended and copied atround(rate × (1 + uplift)); revenue reconciled from the new term's first day), roll an open-ended schedule to the horizon (append only; revenue reconciled from the first appended period), both afterensureRevenue; draft every Planned invoice dated<= asOfas one DraftsalesInvoice(with an opportunity,customerContractId,customerReference= PO number, location = the origin order's shipment location else the oldest location), then set Ended whenendDate < asOfand nothing is Planned. Each row becomes aninvoiceLineType 'Service'line: description "NAME · Nov 1, 2026–Nov 30, 2026";invoiceLinePricinggives the contract line's quantity, LISTunitPriceanddiscountPercent(the sales invoice line discount), or quantity 1 at the row amount with "N% off" in the description for a split installment or an adjustment; service dates = the billing period (One-time:lineRevenueDates, NULL with no end, so it posts straight to revenue);projectId = line.projectId ?? contract.projectId. Stamps the planned invoiceInvoicedand each row'ssalesInvoiceLineId(idempotent). ERP wrappergenerateContractInvoicesNow(sales.service.ts) runs it throughinvokePostingOrThrowas the system; its caller, the routex+/contract+/$id.invoice.tsx, checks permissions. - Automation and holds — the contract is the second source of the shared recurring-invoicing layer (
packages/jobsrecurring-billing, after the rental step, sameasOf;invoice-automate). Effective modecustomerContracts.effectiveInvoiceAutomation, includingPost and Send via Stripe(sendPostedInvoiceViaStripe→@carbon/stripe/send-sales-invoice.server). Holds fromcontractInvoiceHold(@carbon/utilscontract-invoice-plan.ts): "Re-billing INV…, which was voided" (any row withvoidedSalesInvoiceId, wins) or "Includes a credit for a contract change" (a negative adjustment row); Draft Only never holds. The shared holds (sales rules, required contact, posting failure) apply as for rentals.updateContractInvoiceAutomationrefuses Post and Email without an invoice contact email. - Posting (Phase B; for every company — the journals are Provisional before the accounting cutover, see accounting AGENTS):
- Invoice —
post-sales-invoicetakes a line withcustomerContractLineIdout of the Service deferral path:planContractInvoiceLine(invoicing.service.ts) applies the line's revenue (salesRevenueBase × rate, contract currency) to the line's position against the receivable and replaces the Sales leg with two revenue legs — Cr Contract Assets up to the asset pool, the rest Cr Deferred Revenue (a negative line: Dr Deferred Revenue first, then Contract Assets) — plus reclass lines for the pools' carried base and the realized FX difference (realizedExchangeGain/LossAccount, required only when it is non-zero). No schedule rows. Legs carrydocumentType 'Contract'/documentId= the contract; the line'sprojectIdis the Project dimension on revenue-side legs only (AR, tax, shipping carry none). Deferred Revenue, Contract Assets and Sales must be mapped active leaves. OneInvoiceledger entry per line, on the posting journal. Positions are read before the transaction and re-read under the lock; a moved position refuses ("A contract line's revenue position changed while this invoice was posting; post it again"). - VOID — each
Invoiceentry is negated exactly (entry typeVoid, on the VOID journal, whose reversal of the original legs includesdocumentType 'Contract'lines); when the negation drives a pool below zero (the run already recognized part of what the invoice deferred),normalizePositionreclasses it to the other pool with one Deferred Revenue / Contract Assets pair on the same journal. The schedule rows still go back to Planned withvoidedSalesInvoiceId(re-drafted held). - Credit memo —
post-memo(planContractCredit): the memo-borne adjustment rows are summed per line and applied as a lowering movement against the receivable — Dr Deferred Revenue up to the deferred pool, the rest Dr Contract Assets, any part no credited line covers Dr Sales, and realized FX for the remainder; oneCredit Memoentry per line. It no longer touchesrevenueRecognitionSchedule. Voiding it is still refused ("A contract cancellation credit cannot be voided"). - Recognition —
synthesizeContractRevenue(proposeRevenueRecognitionRun(accounting.service.ts, ported from thepropose-revenue-recognition-runserver function), the revenue recognition run's synthesizer inrunRowSynthesizers) turns each Planned non-zero revenue month starting on or before the run's period end, of a non-Draft contract (Ended included — a cancellation's catch-up rows), with no schedule row yet, into a Deferral row (Dr Deferred Revenue / Cr Sales) for what the deferred pool covers and an Accrual row (Dr Contract Assets / Cr Sales) for the rest, atget_exchange_rate(…, periodEnd), oneRecognitionentry per row.postRevenueRecognitionRunposts them withdocumentType 'Contract'and Customer / Item / Project dimensions, flips the months toRecognized, stamps the entries'journalId, and refuses (RunOutOfDateError) while a due contract month is unsynthesized. See accounting AGENTS → Contract revenue. - Contract invoices posted before Phase B keep their Service Deferral rows (no restatement).
- Invoice —
- Create from a sales order —
createContractFromSalesOrder(sales.service.ts, Kysely): eligible lines are Service, notinvoicedComplete, nothing invoiced; refuses a Cancelled / Closed order. Terms from the order andsalesOrderPayment(bill-to, payment term);contractTypealways suggested; lines copy quantity, the document-currency price (convertedUnitPrice) as rate, tax (no discount). The modal (SalesOrderToContractModal) defaults the term from the eligible lines' service dates throughcontractTermFromServicePeriods(sales.models.ts): the earliest start and the latest end, as a month preset when the end is exactly N months on, else a custom end date; with no dated line it starts today for 12 months. Sets the chosen order linesinvoicedComplete = true(soconvertskips them and the rollup counts them) and recomputes the order status.deleteContractReleasingSalesOrderLines/deleteContractLineReleasingSalesOrderLinehand the lines back (reset only wherequantityInvoiced < saleQuantity) and recompute. - Invoice deletion —
releaseRecurringInvoiceStamps(see Rentals → Invoice deletion) un-stamps contract rows too; a planned invoice returns to Planned once none of its rows is stamped.voidedSalesInvoiceIdis left alone. - Setup wizard — creating a contract is five routed steps (
contractSetupStepsinContractSetupSteps.tsx: details → products → invoicing → revenue → review;path.to.contractSetup(id, step)).new.tsxis step 1:createContractinserts the Draft (bill-to, contact, invoice address, payment term and ship-to default fromcontractInvoicingDefaults,sales.service.ts) and redirects tosetup/products; every later step edits that Draft through the real endpoints, so Next only navigates.$id.setup.tsx(layout,update: sales) redirects a non-Draft to$id.detailsand renders the sharedSetupFrame(heading +ContractSetupSteps) +SetupFooter(contract total = ΣlineTotals, Back / Next; on Review "Save as Draft" and "Confirm", disabled until there are lines and every invoice and revenue residual is zero; Confirm opensContractConfirmModal). Opening a Draft lands in the wizard:$id._indexand the$id.detailsloader redirect anyone withupdate: salestosetup/products(draftContractSetupPath,sales.service.ts), so the list, invoice / memo links, Create Contract and every action that falls back to the contract page all continue setup; a viewer without it gets the page. "Save as Draft" goes to the contracts list. A successful Confirm redirects straight to$id.details(never the referrer), and the$idshell'sshouldRevalidatealways reloads when a navigation enters or leavessetup/— a redirect chain (wizard → contract page) drops the submission, so the shell would otherwise keep showing the Draft.$id.setup._indexredirects to products;setup.detailsre-saves step 1 (a new customer brings its own invoicing defaults). Steps: Products =ContractProductsGrid(cells →$lineId.update; "Add Products" →lines.add, which inserts each Service item as a Recurring line at rate 0 per the contract's billing frequency viainsertContractLines); Invoicing =ContractBillTo(bill-to, invoice contact and address, ship-to, payment terms, frequency, first invoice, timing, calendar alignment, invoicing mode, Billed Through) +ContractInvoiceGrid; Revenue =ContractRecognitionGrid(method, go-live, revenue dates per line) +ContractRevenueGrid+ContractRevenueMigration(Recognize Revenue From); Review =ContractSummary+ every residual linked to its step. The header's "Continue Setup" reopens a Draft's wizard. The frame, steps, sections, footer,TermFormand the grid helpers (setupGridHeight,rowMenuColumn,useCellSave) live in~/components/Setup, shared with the rental agreement wizard. - Amend modal (
ContractAmendModal) — the same grid over LOCAL state: rows are the open lines plus lines it adds ("Add Services", a multi-select like the wizard's), cell edits update state (localSave), and the changes post as one amendment. An existing line's Revenue Type and Per are read-only; End Line / Keep Line / Remove Line are the row menu; a Change column badges New / Changed / Ends. The grid's wrapper stops Enter from submitting the form. The sharedTable's key handling skips only an overlay that does NOT contain the table, so a grid inside a dialog still navigates. - Grids — the shared
TablewitheditableComponents(EditableNumber, the new~/components/EditableEditableDate); rows = invoices / months, columns = contract lines (contractGrid.tsx), footer = what each line has left to invoice / recognize (the loader'sresiduals/revenueResiduals, never recomputed in the browser). A cell postsquiet=truetoschedule/revenue/$lineId.updateand gets{ error }back instead of a redirect + flash. "Add Invoice" / "Add Month" openContractAmountsModal(amounts default to each line's residual); "Delete Invoice" / "Delete Month" are the row menu; "Reset Schedule" / "Reset Revenue" discard the edits. The contract page's Invoices and Revenue cards render the same grids while Draft and read-only views otherwise (ContractInvoiceshas no schedule-edit UI left —move/split/merge/moveLineremain posting intents, used by the invoice grid's date cell formove). A confirmed contract's Revenue card shows the STORED plan read-only (ContractRevenuePlan: month × line, a month status fromCUSTOMER_CONTRACT_REVENUE_STATUS_COLOR_MAP, "Partly Recognized" when its non-zero rows disagree, recognized-to-date footer) and a position fromcontractPositionPreviewfed only non-Planned invoices (+ memo credits) and Recognized / Recognized Externally months; with no stored rows (confirmed before Phase B) it falls back torevenuePreview. It never reads the ledger. Loader additions onContractRouteData:lineTotals,revenueRows(stored, or planned live),revenueIsStored,revenueResiduals.
Service functions (sales.server.ts, MCP tools with prefix sales_): the reads getContracts, getContract, getContractLines, getContractLine, getContractInvoiceSchedule ({ invoices, credits }, credits = memo rows), getContractAmendments, getCustomerContractStatuses (@mcp read), and createContractLine / updateContractLine (over the building block upsertContractLine). insertContract, updateContract (Draft only), updateContractType and updateContractNotes are building blocks in sales.service.ts under the contract service functions above. Never tools: insertContractLines (the wizard's Add Products; Draft only, Service items only) and updateContractInvoiceAutomation (under setContractInvoiceAutomation, which enforces create: invoicing for a posting mode on a live contract and refuses Stripe mode without Stripe Connect). Guards return PostgREST-shaped refusals (contractRefusal): CONTRACT_NOT_DRAFT ("Only a Draft contract can be edited — use Amend", "Lines can only be added or changed / removed … on a Draft contract — use Amend"), CONTRACT_LINE_WRONG_CONTRACT, CONTRACT_LINE_NOT_SERVICE, CONTRACT_INVOICE_EMAIL_NO_CONTACT. Writers pick fields explicitly; status, the lifecycle stamps and salesOrderId are never written by them.
Contracts safety
- Never write
customerContract.status, schedule rows, revenue rows, ledger entries or amendments from app code — Confirm / schedule and revenue edits / Amend / Cancel / Revert go throughpost-customer-contract, drafting / renewal / ending throughcreate-contract-invoices, ledger movements through posting and the recognition run. - Never rewrite a
Recognizedrevenue month or a month a Draft run holds — reconcile (reconcileRevenue), which books the difference on a later Planned month. - Every writer of a contract position takes
lockContractPositionsand computes fromloadContractPositions; never derive a movement's accounts outsideapplyContractMovement. - Terms and lines are editable only while Draft; on an Active contract only
contractType,invoiceAutomationandnoteschange directly. - Never delete a sales invoice or line that may carry contract rows with a plain delete — use the
*ReleasingRentalsfunctions (they release contract stamps too). The MCPinvoicing_deleteSalesInvoice*tools still use the plain deletes (open follow-up). - A page that shows live-planned rows must send
planned:position refs, never invented ids. discountEndsOnis acted on only at Confirm; an amendment or renewal copy keeps the date but never splits again.
Related Modules
- production — sales order lines create jobs for Make to Order items
- items — quote lines reference items; methods copied from item make methods
- purchasing — outside operations on quotes create PO lines
- inventory — shipments fulfill sales order lines
- accounting — sales invoices tie to orders;
getExchangeRateresolves document exchange rates (per-company: base=1, override, else global market store). Rental rent is accrued / released and sales-type lease interest posted by the lease run, and contract revenue months recognized by the revenue recognition run; the fleet (fleetAssets) and the Net Investment in Leases report (getLeaseNetInvestment) are accounting's - invoicing — Rental invoice lines, and customer deposits on
payment.rentalAgreementId/salesOrderId; contract invoices and the cancellation credit memo (memo.customerContractId) - people —
getEmployeeJobused for assignee lookups
Rules References
.claude/rules/quote-discount-system.md— pricing architecture, discount vs markup, price trace.claude/rules/customer-supplier-database-schema.md— customer/supplier data model.claude/rules/fixed-asset-lifecycle.md— the fleet the rental agreements rent (Reserved / On Rent statuses)