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.

94.9 KB
Raw Blame

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 new quote row created by copyQuote → getMethod (production.service.ts, ported from the get-method server function) (quoteToQuote, asRevision: true), keeping the same quoteId with revisionId = max + 1, sharing the source opportunityId. Each revision gets its own externalLink row, whose documentId is revision-qualified (Q000001-1) because externalLink is UNIQUE on (documentId, documentType, companyId) — an unqualified id collides with the original's link. deleteQuote does not remove the link row, so that insert uses onConflict … doUpdateSet to reuse the orphan a deleted revision left behind. Displayed as Q000001-1 when > 0 via getQuoteDisplayId (@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) — no id column. discountPercent is 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 opens QuoteLeadTimeModal, 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's onUpdateLeadTimes (quoteLinePrice.leadTime, one state update for every break — never a loop over onUpdatePrice, which snapshots state per call; a failed row is rolled back and the modal stays open) — no new persistence, so resolvePreservedQuoteLinePriceFields is 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.priceTrace per quantity break, salesOrderLine.priceTrace per order line (copied from the quote by convert). Typed (manual) prices store null. The calculator icon opens it in a modal; on a quote line getQuoteLinePriceTraces also returns today's currentTrace, and repriceQuoteLineFromRules stores 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 (itemId in the form → itemIds: [id], amount 0, no item group — normalizePricingRule in sales.service.ts) and carries configurationPrices (JSONB { key, value, amount, label? }[] — list option / "true" for a boolean / null = per unit of a numeric value; label is the parameter's label at save time, used by the price trace; validated by pricingRuleConfigurationPriceValidator in sales.utils.ts, which stays out of the sales.models import graph so the engine tests can load it). toMatchedRule parses a rule row for the engine; applyPriceRules (sales.utils.ts) adds those signed surcharges to the starting price before the discount, given the line's configuration. An override with applyRulesOnTop = false still takes them (configurationOnly) — they price the options, not the part. Every other rule type stores configurationPrices as null.
  • Line configuration — quoteLine.configuration and salesOrderLine.configuration (keyed by configurationParameter.key; convertDocument (shared.service.ts, ported from the convert server function) copies it quote → order). Jobs made for an order line use resolveJobConfiguration (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 with itemToJob + 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 in useItemConfiguration + ItemConfigureButton (~/components/Configurator/ItemConfigurator), which loads parameters through getConfigurationParameters and 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: upsertCustomerItemPriceOverride refuses a write with no scope unless allCustomers: 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) takes customerId, customerTypeId or allCustomers (?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 by overrideSource. Override trace steps carry overrideId, which PriceTraceModal links 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 the convert server function).
  • Rental Agreement — rents serialized fleet units (fixed assets) to a customer; billed in persisted periods, invoiced as Rental lines 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 Service lines (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 / convertSalesRfqToQuote for lifecycle conversions — they call convertDocument (shared.service.ts, ported from the convert server function).
  • MUST use resolvePrice + applyPriceRules for price calculation — never compute prices ad hoc.
  • MUST store discountPercent as 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 — setSalesOrderStatus with Closed (through updateSalesOrderStatus, 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 resolvePrice calls.

Never

  • Bypass convertDocument (shared.service.ts) for quote→order or RFQ→quote conversions.
  • Delete quoteLinePrice rows when rewriting a line's pricing — go through upsertQuoteLinePrices, 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 via resolvePreservedQuoteLinePriceFields). Deleting rows for a quantity break the line no longer offers is different and required: see reconcileQuantityBreaks (sales.utils.ts) and its use in updateQuoteLine. Orphaned rows render as selectable options on the customer share page.
  • Store discountPercent as 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 (modes quote / quoteLine / quoteWithLines); reuses insertQuote / upsertQuoteLine / upsertQuoteLinePrices so quote side effects are preserved. Called by importCsvFile (modules/shared/shared.server.ts, the routes/x+/shared+/import.$tableId.tsx action); config in modules/shared/imports.models.ts. Create-only idempotency via externalIntegrationMapping (integration csv).
  • convertQuoteToOrder / convertSalesRfqToQuote — lifecycle conversions via convertDocument (shared.service.ts, ported from the convert server function)
  • copyQuoteLine / copyQuote — duplication via getMethod (production.service.ts, ported from the get-method server function)
  • applyPriceRules — applies matched discount/markup rules to a starting price
  • resolvePrice — full price resolution: base → overrides → rules → final
  • resolvePriceList — batch price list for a customer/type with quantity preview
  • updateSalesOrderStatus / cancelSalesOrder / finalizeQuote — status transitions; the operations setSalesOrderStatus and finalizeAndSendQuote (sales.server.ts) call them
  • getQuote / getQuoteLinePrices / getQuoteMaterialsByLine / getQuoteOperationsByLine — quote reads; getQuoteLines and getQuoteLinePricesByQuoteId are in sales.utils.ts (components call them)
  • getSalesOrder(s) / getSalesOrderLines / getExternalSalesOrderLines — order reads
  • getOpenSalesOrderLinesForItem — sales order lines a job can link to (open orders, matching item); isSalesOrderClosed / OPEN_SALES_ORDER_STATUSES gate eligibility
  • getCustomer(s) / getCustomerContacts / getCustomerLocations — customer reads
  • getPricingRules / createPricingRule / duplicatePricingRule — rule management
  • getOpportunity / getOpportunityDocuments — deal tracking
  • getSalesReturnOrders / insertSalesReturnOrder / upsertSalesReturnOrderLine — RMA CRUD; confirmSalesReturnOrder (Kysely, row-locked reversible-quantity caps, THROWS), cancelSalesReturnOrder (guarded), shortCloseSalesReturnOrderLine
  • getReturnableLinesForCustomer (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 route
  • createOpportunityDocumentUploadUrl / createOpportunityLineDocumentUploadUrl — MCP file upload (step 1): presigned URLs for opportunity (opportunity/{opportunityId}) and opportunity-line documents; pair with documents_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 through shareLinkContext, ~/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 in updateQuoteDetails / updateSalesOrderDetails) is refused when the document breaks an error-severity sales rule (advancingStatusRefusal).
  • A sales-rule gate (salesDocumentGate for a whole document, salesLineGate for one line) returns { violations, ruleNames } as the result's data when it blocks, and the route returns that data to useRuleViolations. The caller sends acknowledged: true to 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.tsx with the caller's client; the file+ 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 — enforcementRule row (family = 'sales'): conditionAst JSONB ({kind: all|any|none, conditions:[{field,op,value}]}), severity (error blocks; warn requires acknowledgment), message with {token} interpolation, surfaces (enforcementRuleSurface enum; the sales-legal subset quoteLine | salesOrderLine | salesInvoiceLine is enforced by the enforcementRule_sales_surfaces CHECK), item scoping via filteredItemTypes/filteredItemGroupIds/filteredItemMatchAll (empty = all items) or explicit enforcementRuleItemAssignment pins (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 in rules-schema.ts): compileSalesRuleWithCache, evaluateRules, SALES_RULE_SURFACES, getFieldsForSalesRuleSurfaces, SALES_RULE_FIELD_REGISTRY (customer type/status/country + synthesized customer.customFields.*). Countries are alpha-2 codes.
  • Evaluator — @carbon/ee/rules.server evaluateSalesRuleLines (service-role client; plan-gated on SALES_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 — resolveSalesOrderShipTo returns the shipment's customerLocationId, never the header's, when dropShipment is 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 (migration 20261006221401_sales-invoice-discount-and-ship-to.sql; invoiceCustomerLocationId is the bill-to; the locationId columns are Carbon's own warehouses). Authored on the invoice's Shipping card ("Ship To", scoped to the invoice's customer; update.tsx clears it on a customer change); convert copies the order's delivery location (drop-ship location when dropShipment, else the header's customerLocationId), create-contract-invoices copies shipToCustomerLocationId, create-rental-invoices the agreement's Rental Site. An order-derived line (salesInvoiceLine.salesOrderId) resolves through resolveSalesOrderShipTo; a standalone line resolves through resolveSalesInvoiceShipTo (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 by packages/ee/src/rules/sales/invoice-shipto.test.ts. The salesInvoiceLocations view's shipment* address columns join this column (same migration; they joined the warehouse locationId before and were always null), feeding the PDF Ship To block and the Stripe shipping address.
  • One modal — enforcement actions return { violations, ruleNames }; forms submit via useRuleViolations and render the shared RuleViolationModal (@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 / salesLineGate in sales.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 in packages/ee/src/plan.ts) — community-blocked, not merely Cloud-paywalled. The ee write functions also embed requireEntitlement("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 from sales into the inventory UI folder (never through inventory/ui/index.ts) to avoid a cycle. The shared zod AST schema lives in @carbon/utils for the same reason.
  • Never widen the enforcementRule_sales_surfaces CHECK 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, so rateCharge, calendarMonthCharge, periodCharge and generateRentalBillingPeriods take decimals (the agreement currency's decimalPlaces, read from currency by post-rental-agreement and create-rental-invoices, useCurrencyDecimals in 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 is calendarMonthCharge, month rate × days ÷ days in month; on a Monthly agreement it is monthlyCharge, month rate × days ÷ days in its anniversary period, so a whole period is the rate; every other frequency / cycle is rateCharge, 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 through activationBillingThrough in sales.service.ts, capped at endDate for a Sale line), generateRentalBillingPeriods (cuts from the AGREEMENT start date, never delivery; fixed term cut in full; open-ended rolls one period past through; holdover keeps billing past endDate (Rental only — a Sale line never gets a period past endDate); a return re-cuts the Pending period, and an Advance-billed period past the return gets one negative isAdjustment row = billed − charge(days used) priced by the line's own frequency and rate, never positive). Pinned by packages/utils/src/rental-periods.test.ts.
  • Lifecycle — postRentalAgreement (apps/erp/app/modules/sales/sales.service.ts, ported from the post-rental-agreement server function; activate / release / close / cancel, postRentalAgreementPermission update: "sales"). The service functions activateRentalAgreement, setRentalAgreementStatus and releaseRentalUnit (sales.server.ts) run it through invokePosting. Its validators and pure blockers (unpricedUnitError, …) are in sales.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 the fleetAssets view (Available, or Reserved by this same agreement; asset Active / Fully Depreciated; not In Maintenance), bills each line at its own rateUnit + rate (activation reads no rate card), classifies every line (below), cuts periods to billingHorizon(today) (a Sale line only up to endDate), leaves undelivered lines Pending. No journal for a Rental line; a Sale line books its commencement. Release (rentalAgreementLineId, returnedAt): ends a Pending unit that never left the yard through returnRentalUnit with no location, so its billing stops at the release date (an Advance period gets the early-return adjustment), the line goes Returned and fixedAsset.locationId is unchanged; refused for a date after company today ("The release date cannot be in the future"), a line that is not Pending, a Sale line ("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 commenced Sale line and nothing On Rent/Sold/invoiced/recognized — DELETES the Pending lines (frees the units) and their Pending periods. fixed-asset+/$fixedAssetId.out-of-service.tsx likewise reads getOnRentLineForAsset with the service role (an accountant may lack sales_view).
  • Deliver and return — a unit leaves on a rental shipment and comes back on a rental receipt: ordinary shipment / receipt documents with sourceDocument 'Rental Agreement' (sourceDocumentId = the agreement), one unit per shipmentFixedAssetLine / receiptFixedAssetLine row through rentalAgreementLineId (see inventory AGENTS). The create posting builds them with types shipmentFromRentalAgreement / receiptFromRentalAgreement ({ rentalAgreementId, rentalAgreementLineId? }, Active agreement only, location = the agreement's, postingDate left null because a set postingDate reads as posted). Without a line id, a shipment holds every Pending unit not on another open rental shipment, ticked; a receipt holds every On Rent unit ticked and every Pending unit 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 indexes shipment_oneOpenDraftPerRentalAgreement_idx / receipt_oneOpenDraftPerRentalAgreement_idx allow one Draft of each per agreement. post-shipment and post-receipt own the 'Rental Agreement' source (postShipment / postReceipt in inventory.service.ts) and take an optional postingDate (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), sets On Rent + deliveredAt + meterOut and writes a Rental Delivery trackedActivity; no itemLedger, costLedger or journal, for a Rental and a Sale line alike. Its void is allowed while every unit is still On Rent and no Accrual row of its lines is Posted or claimed by a Draft run: the lines go back to Pending with deliveredAt / meterOut cleared, and their unclaimed Planned Accrual rows are deleted. Posting a receipt runs returnRentalUnit for each ticked line (Pending or On Rent), sets the unit's fixedAsset.locationId to the receipt's location (for a Sale line returned to Fleet, the new asset) and writes a Rental Return activity for a Rental line. A rental receipt is never voided ("A rental return cannot be voided. Correct the unit by hand."). Posting either needs update: inventory.
  • Per-unit shortcuts — $id.$lineId.deliver.tsx / $id.$lineId.return.tsx (update: sales + create: inventory) invoke create with the line id and redirect into the shipment or receipt, so a counter pickup is the shortcut, then Post. shipment+/new / receipt+/new take the 'Rental Agreement' source from the header buttons and redirect to the agreement's Draft when one exists. The inventory $id.details actions refuse a change of source on a rental document.
  • The return body — returnRentalUnit (sales.service.ts, with the helpers it shares with activation), called by post-receipt and by release. The caller locks the agreement and checks it is Active. It refuses a returnedAt after company today (futureReturnError: "The return date cannot be in the future"), re-cuts a Rental line's periods (a Sale line's billing is its term and is left alone), sets fixedAsset.outOfServiceSince/Reason when takeOutOfService is set, and runs returnResidual for a Sale line, which needs residualDestination and is refused before endDate (below). Its optional locationId is where a Sale line's residual lands: a rental receipt passes its own location (spec Q7), so the stock adjustment, or the new fleet asset and its Capitalization transfer, 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 the create-rental-invoices server function, live test apps/erp/test/database/create-rental-invoices.test.ts; { asOf, rentalAgreementId? }, permissions update: sales + create: invoicing; an agreement that throws is returned in failures, never stops the others): per Active agreement, first rolls every live Rental (or unclassified) line's periods to billingHorizon(asOf) — a Sale line never rolls a holdover period, its whole term was cut at activation — then drafts Draft salesInvoices with a Rental line per due non-adjustment period (dueOn <= asOf) and per charge dated <= asOf, stamping salesInvoiceLineId. 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, creditMemo sequence, amount = Σ credits at currency decimals, reference = the readable agreement id, notes = the "Early return credit — N days used" descriptions), stamped memoId + Invoiced, returned in creditMemos; 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 column rentalAgreements.effectiveInvoiceAutomation; Draft Only / Post / Post and Email / Post and Send via Stripe) decides the split: Draft Only drafts ONE combined invoice and automates nothing; otherwise the rent and every Charge go on one rent invoice (a charge alone, unheld, when no rent is due) and charges marked invoiceSeparately plus every Purchase Option go on a separate charges invoice (planRentalInvoices, @carbon/utils); holds are stamped on salesInvoice.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 Inngest recurring-billing job (cron 0 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, needs update: sales AND create: invoicing) and Sell to Customer, which fire carbon/invoice.automate for the same invoices. The per-agreement override is updateRentalAgreementInvoiceAutomation (setRentalInvoiceAutomation, intent invoiceAutomation on rental-agreement+/update.tsx; Draft/Active only; Post and Email refused without a contact email, RENTAL_INVOICE_EMAIL_NO_CONTACT). Spec: .ai/specs/implemented/2026-09-22-revenue-recognition-rentals-and-contracts.md Part II.
  • Rental credit memos — post-memo books a memo with rentalAgreementId through loadRentalCredit + the pure planRentalCredit (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 own planRentalLine / 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 carry revenueRecognitionSchedule.memoId. Once posted it is applied to invoices from a payment (credits) or refunded like any credit memo. Void (post-memo index.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 by deleteRentalCreditMemoReleasingPeriods (sales.service.ts, called by deleteDraftMemo), which returns the periods to Pending. The Billing Periods card links an adjustment to its memo; the memo's Documents panel links the agreement (getSettlementRelatedItems rentalAgreementId).
  • Invoice deletion — deleteSalesInvoiceReleasingRentals / deleteSalesInvoiceLineReleasingRentals (sales.service.ts) delete and releaseRecurringInvoiceStamps in ONE Kysely transaction (the stamps have no FK). It releases rental periods and charges AND contract schedule rows (customerContractInvoiceLine.salesInvoiceLineId; a planned invoice returns to Planned once none of its rows is stamped). The line variant takes the route's invoiceId and, under FOR 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 tools invoicing_deleteSalesInvoice / invoicing_deleteSalesInvoiceLine still call the plain service functions and leave stamps behind (open follow-up).
  • The Rental invoice line — salesInvoiceLineType value Rental, no item; columns rentalAgreementId, rentalAgreementLineId, rentalBillingPeriodId, rentalAgreementChargeId, rentalLineType (enum rentalInvoiceLineType: Rent / Charge / Purchase Option), CHECK salesInvoiceLine_rental_check. Rendered read-only by SalesInvoiceLineForm; salesInvoiceLineValidator accepts but never offers it. Posting (postSalesInvoice, decisions in invoicing.service.ts, pinned by apps/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 a Sale line 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 a Rental line → refused ("Purchase option billing requires a line treated as a sale"). A Sale line's Purchase Option line also posts the NI settlement (below). Posting a Purchase Option line flips its agreement line to Sold (only a Sale line On Rent, in the posting transaction, regardless of accounting); VOID returns a still-Sold line to On Rent. Revenue legs carry documentType 'Rental Agreement'.
  • Rental rows post in the lease run — every revenueRecognitionSchedule row of a rental agreement (rent Deferral rows from post-sales-invoice and post-memo, Accrual rows from synthesizeRentalAccruals, a Sale line's Interest rows) carries rentalAgreementLineId, so the Lease run claims it (runTypeFilter, @carbon/database/run-type) and posts it as sourceType 'Lease Run'; the revenue recognition run never sees it. Accounting → Closing → Leases lists them; close task "Post lease journals". 20261011163211_lessee-leases.sql released these rows from Draft revenue runs (Posted runs keep theirs) and 20261011192957_lease-run-sync-policy.sql gave each accounting integration's Lease Run the sync setting its Revenue Recognition had. 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 lists getRentalAgreementDeposits; "Record Deposit" links to payments/new?customerId&rentalAgreementId&amount. Posting is in post-payment (see accounting AGENTS, Payments).
  • Lease classification — pure math in packages/utils/src/lessor-lease.ts (@carbon/utils): presentValue (pvRent, pvPayments incl. a reasonably certain option + guaranteed residual, pvResidual, netInvestment), classifyLessorLease (tests a–e; any true ⇒ Sale; termMonths null ⇒ always Rental), 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 — given today — 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 in RentalCommencementPreview: 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 stored ClassificationInputs record). Thresholds from companySettings.leaseMajorPartThresholdPercent / leaseSubstantiallyAllThresholdPercent. The Draft preview (sales.utils.ts: leaseTermMonths, draftLeasePaymentTerms, previewLeaseClassification, readLeaseClassification, leaseCommencementPreview) calls the same functions; UI ui/Rentals/RentalLeaseClassification.tsx (LeaseClassificationPanel on 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, RentalCommencementPreview in the Activate confirmation — the $id.tsx loader reads the units' cost and accumulated depreciation with the user's client, so fixedAsset RLS 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 a classificationOverrideReason diff entry).
  • Sales-type commencement / end of term — postRentalAgreement (its pure decisions are in sales.service.ts, pinned by apps/erp/test/database/post-rental-agreement/lessor.test.ts). Activation, per Sale line (salesTypeRequirementError, lessor-lease in @carbon/utils: needs endDate, fairValue > 0, and WHOLE billing periods — Calendar Month starts on the 1st and ends on a month end, Monthly ends the day before start + n months on 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 …"; RentalCommencementPreview shows the same message in the Activate confirmation): asset Disposed by Sale + fixedAssetDisposal (saleProceeds NI, netBookValueAtDisposal C, gainLoss selling 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 entity Consumed with Rental Agreement + Customer attributes and a Lease Commencement activity; rentalLeaseScheduleLine rows and Planned Interest recognition 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 a Sale line (on a rental receipt; residualDestination Fleet / Inventory, not before endDate, not in the future, not while a Draft run holds its Interest rows dated after the return): closing NI = netInvestmentAt — the closingNetInvestment of the last schedule line dated on or before returnedAt (the closing target at/after endDate; initialNetInvestment when there are no lines); Fleet → new fixedAsset in the class named "Rental Fleet" (else the class the unit left) at that cost + a Posted Capitalization fixedAssetTransfer; 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's Sale line On Rent with purchaseOptionAmount, once per line, not before endDate (early exercise is an early termination — a manual journal) — inserts a Purchase Option charge dated company today through the server-only insertRentalPurchaseOptionCharge (sales.service.ts) and calls generateRentalInvoicesNow; the invoice's posting marks the line Sold and settles the line's remaining NI against the schedule's closing balance (purchaseOptionSettlement in invoicing.service.ts: shortfall Dr costOfGoodsSoldAccount / Cr NI, excess Dr NI / Cr leaseRevenueAccount, same journal line reference so VOID reverses it; each default required only when its leg is). On a rental receipt, ReceiptRentalLineItem shows the Return To radios for a Sale line (saved to receiptFixedAssetLine.residualDestination), ReceiptPostModal blocks a ticked Sale line without one, and the post re-reads the classification.
  • Fleet — fleetAssets derives Reserved (live Pending line) and On Rent (a commenced Sale unit reads Sold: its asset is Disposed); the fleet table's Rent row action (Available units) opens newRentalAgreement?fixedAssetId=. post-asset-transfer return refuses a unit on a live line. A posted rental receipt moves the unit's fixedAsset.locationId to 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/Setup pieces as the contract wizard (rentalAgreementSetupSteps in RentalSetupSteps.tsx: details → units → billing → accounting → review; path.to.rentalAgreementSetup(id, step)). new.tsx is 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 to setup/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.details and renders SetupFrame + 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 same Confirm + RentalCommencementPreview as the header). $id.setup._index redirects to units; setup.details re-saves step 1 through updateRentalAgreement (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 runs rentalAgreementLineValidator + upsertRentalAgreementLine, a new frequency restarting the rate from getDefaultRentalRates, 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 through update.tsx via useRentalTermSave); Accounting = RentalAgreementAccounting (LeaseClassificationPreview from 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 — postRentalAgreement activate refuses it, unpricedUnitError in sales.service.ts, and the wizard footer and header disable Activate) and RentalCommencementPreview. 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._index and the $id.details loader redirect anyone with update: 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.details rather 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 through post-rental-agreement, delivery and return through post-shipment / post-receipt (source 'Rental Agreement').
  • Never delete a sales invoice (or line) that may carry Rental lines with a plain delete — use the *ReleasingRentals service 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 Sale line (sales-type lease) is derecognized at ACTIVATION, not delivery. Never unwind it from app code: early termination is a manual journal (return before endDate and 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/database so the demo-dataset tier can plan a schedule). billingGrid (Anniversary anchors on startDate, 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). periodUnits counts whole months from the period start, then the remaining days as a fraction of the next month (15 Mar–14 Apr = 1); wholePeriodUnits makes 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 with averageDayUnits instead — 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 (periodUnits made 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 via nextInvoiceDate (a mid-period row lands on the NEXT regular invoice date); an invoice dated before firstInvoiceDate moves to it; a row ending on or before billedThrough is Billed Externally. horizon: fixed term → endDate; open-ended → the end of the period after today's. validateScheduleEdit is 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. Also amendmentEffectiveDate, 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 by contract-schedule.test.ts.
  • Persist on first edit — an unedited Draft has NO schedule rows: the $id loader plans them live. The first schedule edit (or Confirm) writes them (isEdited = true on touched invoices). The page names live rows by POSITION — planned:<invoiceDate> for an invoice, planned:<invoiceDate>:<lineId>:<periodStart>[:adjustment] for a row — and edit-schedule resolves them after writing (fix 56fa0f7b8e, pinned by contract-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 no customerContractRevenue rows (the loader plans them live, revenueIsStored: false), and the first edit-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/utils contract-revenue.ts, which keeps contractPositionPreview; revenue-schedule.ts moved to @carbon/database too, @carbon/utils re-exports it). planRevenueSchedule: a line's revenue total = Σ its invoice-schedule rows (adjustments and memo credits included), spread over lineRevenueDates (go-live ?? revenue start ?? start → revenue end ?? end) by revenuePreview — Daily = spreadStraightLine; Even Period = equal per full calendar month, a partial month prorated by its days, residual placed by distributeRoundingResidual; no end → one row in the start month (an open-ended Recurring line runs to its last scheduled periodEnd). Months before recognizeRevenueFrom's month are Recognized Externally. validateRevenueEdit is the conservation rule: residual per line = billed − Σ revenue rows. reconcileRevenueSchedule = reconcile, never rewrite (one line from a date): Recognized / Recognized Externally rows and Planned rows 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 by contract-revenue-schedule.test.ts. Writers in sales.service.ts (shared by postCustomerContract and createContractInvoices): 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 a revenueRecognitionSchedule row 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 through applyContractMovement({ 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 a receivable the difference to the receivable's base is realized FX (fxBase), against revenue it is 0. Also positionFromEntries, normalizePosition (the reclass that brings a negative pool back), movementCredits. Pinned by contract-position.test.ts. Ledger I/O in apps/erp/app/modules/shared/shared.service.ts: loadContractPositions (one grouped read) and lockContractPositions — ONE transaction advisory lock contract-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 the post-customer-contract server function, update: sales; every action locks the header FOR UPDATE; it runs as the signed-in user (invokePosting with the caller's client and { as: postCustomerContractPermission }, in runContractAction): confirmContract / amendContract / cancelContract / revertContractCancellation and the two previews through postContract, $id.schedule and $id.revenue through runContractAction (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; under Post and Send via Stripe refuses unless the bill-to customer has a stripe-connect customer mapping — the confirm modal links one first through StripeCustomerPanel by customer (/api/stripe-connect/customer/by-customer/:customerId) and linkStripeCustomerForBilling in confirmContract; turns each discountEndsOn into 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; then writeOpeningEntries (D8: per line, Σ Billed Externally rows − Σ Recognized Externally revenue, applied to an empty position at the contract's exchangeRate, 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's setAmount (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) and delete (the invoice and its rows; each line shows a residual)), reset-schedule, edit-revenue (Draft; the first edit writes the live plan through the horizon; setAmount (line × YYYY-MM-01 month upsert, 0 deletes), addMonth (amounts add to what the month holds), deleteMonth (every line's row), reset (delete all rows → live again); a month before recognizeRevenueFrom is written Recognized 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), and setLineEndDates clamps an ended line's revenueEndDate to its new end — cancel records what it clamped in previousState.lineRevenueEndDates for the revert; preview: true runs the whole amendment and rolls back via PreviewRollback; reconciles revenue from the effective date), cancel (Active; ends lines past the end date, renewal = End, removes later Planned invoices; with creditUnusedTime drafts one Draft credit memo with customerContractId carrying 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 from previousState; reconciles revenue from the cancelled end date). Percent inputs are points ÷ 100.
  • Invoice generation — createContractInvoices (sales.service.ts, ported from the create-contract-invoices server function; jobs call it as the create-contract-invoices posting) ({ asOf, customerContractId? }, update: sales + create: invoicing; one transaction per contract, failures returned in failures): renew (renewal = Renew and endDate <= asOf, one term at a time; with an uplift every continuing Recurring line is ended and copied at round(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 after ensureRevenue; draft every Planned invoice dated <= asOf as one Draft salesInvoice (with an opportunity, customerContractId, customerReference = PO number, location = the origin order's shipment location else the oldest location), then set Ended when endDate < asOf and nothing is Planned. Each row becomes an invoiceLineType 'Service' line: description "NAME · Nov 1, 2026–Nov 30, 2026"; invoiceLinePricing gives the contract line's quantity, LIST unitPrice and discountPercent (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 invoice Invoiced and each row's salesInvoiceLineId (idempotent). ERP wrapper generateContractInvoicesNow (sales.service.ts) runs it through invokePostingOrThrow as the system; its caller, the route x+/contract+/$id.invoice.tsx, checks permissions.
  • Automation and holds — the contract is the second source of the shared recurring-invoicing layer (packages/jobs recurring-billing, after the rental step, same asOf; invoice-automate). Effective mode customerContracts.effectiveInvoiceAutomation, including Post and Send via Stripe (sendPostedInvoiceViaStripe → @carbon/stripe/send-sales-invoice.server). Holds from contractInvoiceHold (@carbon/utils contract-invoice-plan.ts): "Re-billing INV…, which was voided" (any row with voidedSalesInvoiceId, 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. updateContractInvoiceAutomation refuses 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-invoice takes a line with customerContractLineId out 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 carry documentType 'Contract' / documentId = the contract; the line's projectId is the Project dimension on revenue-side legs only (AR, tax, shipping carry none). Deferred Revenue, Contract Assets and Sales must be mapped active leaves. One Invoice ledger 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 Invoice entry is negated exactly (entry type Void, on the VOID journal, whose reversal of the original legs includes documentType 'Contract' lines); when the negation drives a pool below zero (the run already recognized part of what the invoice deferred), normalizePosition reclasses it to the other pool with one Deferred Revenue / Contract Assets pair on the same journal. The schedule rows still go back to Planned with voidedSalesInvoiceId (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; one Credit Memo entry per line. It no longer touches revenueRecognitionSchedule. Voiding it is still refused ("A contract cancellation credit cannot be voided").
    • Recognition — synthesizeContractRevenue (proposeRevenueRecognitionRun (accounting.service.ts, ported from the propose-revenue-recognition-run server function), the revenue recognition run's synthesizer in runRowSynthesizers) 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, at get_exchange_rate(…, periodEnd), one Recognition entry per row. postRevenueRecognitionRun posts them with documentType 'Contract' and Customer / Item / Project dimensions, flips the months to Recognized, 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).
  • Create from a sales order — createContractFromSalesOrder (sales.service.ts, Kysely): eligible lines are Service, not invoicedComplete, nothing invoiced; refuses a Cancelled / Closed order. Terms from the order and salesOrderPayment (bill-to, payment term); contractType always 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 through contractTermFromServicePeriods (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 lines invoicedComplete = true (so convert skips them and the rollup counts them) and recomputes the order status. deleteContractReleasingSalesOrderLines / deleteContractLineReleasingSalesOrderLine hand the lines back (reset only where quantityInvoiced < 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. voidedSalesInvoiceId is left alone.
  • Setup wizard — creating a contract is five routed steps (contractSetupSteps in ContractSetupSteps.tsx: details → products → invoicing → revenue → review; path.to.contractSetup(id, step)). new.tsx is step 1: createContract inserts the Draft (bill-to, contact, invoice address, payment term and ship-to default from contractInvoicingDefaults, sales.service.ts) and redirects to setup/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.details and renders the shared SetupFrame (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 opens ContractConfirmModal). Opening a Draft lands in the wizard: $id._index and the $id.details loader redirect anyone with update: sales to setup/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 $id shell's shouldRevalidate always reloads when a navigation enters or leaves setup/ — a redirect chain (wizard → contract page) drops the submission, so the shell would otherwise keep showing the Draft. $id.setup._index redirects to products; setup.details re-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 via insertContractLines); 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, TermForm and 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 shared Table's key handling skips only an overlay that does NOT contain the table, so a grid inside a dialog still navigates.
  • Grids — the shared Table with editableComponents (EditableNumber, the new ~/components/Editable EditableDate); rows = invoices / months, columns = contract lines (contractGrid.tsx), footer = what each line has left to invoice / recognize (the loader's residuals / revenueResiduals, never recomputed in the browser). A cell posts quiet=true to schedule / revenue / $lineId.update and gets { error } back instead of a redirect + flash. "Add Invoice" / "Add Month" open ContractAmountsModal (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 (ContractInvoices has no schedule-edit UI left — move / split / merge / moveLine remain posting intents, used by the invoice grid's date cell for move). A confirmed contract's Revenue card shows the STORED plan read-only (ContractRevenuePlan: month × line, a month status from CUSTOMER_CONTRACT_REVENUE_STATUS_COLOR_MAP, "Partly Recognized" when its non-zero rows disagree, recognized-to-date footer) and a position from contractPositionPreview fed only non-Planned invoices (+ memo credits) and Recognized / Recognized Externally months; with no stored rows (confirmed before Phase B) it falls back to revenuePreview. It never reads the ledger. Loader additions on ContractRouteData: 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 through post-customer-contract, drafting / renewal / ending through create-contract-invoices, ledger movements through posting and the recognition run.
  • Never rewrite a Recognized revenue 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 lockContractPositions and computes from loadContractPositions; never derive a movement's accounts outside applyContractMovement.
  • Terms and lines are editable only while Draft; on an Active contract only contractType, invoiceAutomation and notes change directly.
  • Never delete a sales invoice or line that may carry contract rows with a plain delete — use the *ReleasingRentals functions (they release contract stamps too). The MCP invoicing_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.
  • discountEndsOn is 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; getExchangeRate resolves 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 — getEmployeeJob used 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)