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.

53.0 KB
Raw Blame

Purchasing Module

Purchase orders, supplier management, supplier quotes/interactions, RFQs, procurement planning, and lessee leases (ASC 842). Handles the full procure-to-receive lifecycle including supplier approval workflows, quote finalization, and conversion to purchase orders.

Key Domain Concepts

  • Purchase Order (PO) — document sent to a supplier. Statuses (purchaseOrderStatusType, purchasing.models.ts): Draft → Planned (from a planning suggestion) → Needs Approval → To Review → To Receive → To Receive and Invoice → To Invoice → Completed, plus Rejected and Closed. Close one manually with closePurchaseOrderAndApprovals (purchasing.server.ts).
  • PO Revision — purchaseOrder.revisionId counts amendments to a released order. Created ONLY when the header dropdown's "Create PO Revision" action posts createRevision=true; a plain Reopen never bumps. The write is reopenPurchaseOrderAsRevision (Kysely, purchasing.service.ts): a compare-and-swap that sets revisionId = revisionId + 1 in SQL with the eligibility conditions (locked status + non-null orderDate) in the WHERE clause, so concurrent requests can't collide and an ineligible order matches 0 rows. canCreatePurchaseOrderRevision (purchasing.models.ts) is the matching pure predicate used to gate the menu item — keep the two in sync. Unlike quotes, a PO revision is in-place: no new row, receipts/invoices stay attached. Displayed as PO000123-1 when > 0 via getPurchaseOrderDisplayId (@carbon/documents/utils) on the PDF, email, filenames, and UI; the two-tone in-app rendering uses <RevisionSuffix> (~/components).
  • Supplier Interaction — umbrella entity linking a supplier quote to RFQs, POs, and documents. A supplier quote always lives under an interaction.
  • Supplier Quote — vendor-side pricing with line-level price breaks (supplierQuoteLinePrice). Can be finalized (finalizeSupplierQuote) and converted to POs via convertDocument (shared.service.ts, ported from the convert server function).
  • RFQ (Request for Quotation) — solicits pricing from multiple suppliers. Links to supplier quotes via purchasingRfqToSupplierQuote. Statuses managed by updatePurchasingRFQStatus.
  • Conversion Factor — when a supplier's UoM differs from stocking UoM, conversionFactor on purchaseOrderLine scales quantities at receipt: inventoryQty = purchaseQty × conversionFactor. See .claude/rules/purchasing-conversion-factors.md.
  • Purchasing Planning — MRP-driven planned orders surfaced via getPurchasingPlanning (calls the get_purchasing_planning_grid RPC, which wraps get_purchasing_planning with the planning-horizon fence, first negative week, latest order date and the database-side action filters). Planning actions on PO lines are applied by applyPlanningActions (purchasing.server.ts; the route is x+/purchasing+/planning.update.tsx) through applyPurchasingPlanningActions(db, …) — set-based, one Kysely transaction for the whole batch: the claim, one UPDATE … FROM (VALUES …) for the dates, one for the quantities (tax pair restated via taxPairForQuantity), one DELETE for the cancels (a Draft / Planned PO and nothing received or invoiced, in the statement), and the un-claim of refused rows (planning-action-claims.ts, shared with production). The drawer's inline edit of one line is updatePlanningPurchaseOrderLine, through updatePurchaseOrderLineSchedule (one Kysely UPDATE with the same Draft / Planned guard, returns updated). Planning changes a PO only while isPurchaseOrderEditableFromPlanning (Draft / Planned — not in approval, not sent). Ordering suggestions raises one PO per supplier per week (planningPurchaseOrderWeek + findPlanningPurchaseOrder, purchasing.models.ts), so each week's PO is finalized on its own and the later weeks stay editable from planning. An Increase / Decrease writes quantityReceived + the suggested quantity still to come (MRP reads a line's quantityToReceive), so a reopened, partly received line keeps its receipts. A row's ⋯ (expanded action lines and the drawer's Open Orders) carries the order's own commands from usePurchaseOrderPlanningCommands (ui/Planning/): Reopen / Reopen as Revision on a PO planning cannot change, posting status=Planned (+ createRevision) to the PO status route — Planned, NOT Draft, because Draft is not MRP supply (openPurchaseOrderLines) and a Draft PO's lines would be suggested again as a new order — and Finalize on a Draft / Planned PO, through PurchaseOrderFinalizeModal (now takes a purchaseOrderId prop) with its order + default CC from api+/purchasing.purchase-order.$id.finalize.ts.
  • Planning approval bypass — purchaseOrder.createdFromPlanning (migration 20261006214907) is set by planning's Order (orderPlannedPurchases) on the POs it creates (and restored on planning POs it adds lines to). upsertPurchaseOrderLine / deletePurchaseOrderLine clear it BEFORE writing (clearPlanningOrigin), so any manual line change — PO page, API, MCP, kanban — sends the PO back through approval; planning's Apply and drawer edits (Kysely) never touch it. finalizePurchaseOrderAndNotify (purchasing.server.ts) skips isApprovalRequired when the flag is set AND companySettings.skipApprovalForPlanningPurchaseOrders (default true, Settings → Planning → Purchase Order Approval) — failing closed on a read error.
  • Approval signature — approveRequest (@carbon/ee/approvals.server) copies the approver's user.signaturePath to approvalRequest.decisionSignaturePath, so a later change of signature never changes an approved PO. With companySettings.requirePurchaseOrderApprovalSignature (Settings → Purchasing) it refuses a PO approval from an approver with none (code: "signature-required", a validation error from decidePurchaseOrderApproval); the PO page loader's approvalNeedsSignature opens ApprovalSignatureModal instead of the decision modal. The PDF's Approval block prints it (getPurchaseOrderApproval(…, { withSignature: true })).
  • Lease — equipment or property the company leases FROM a supplier (the company is the lessee): a right-of-use asset and a lease liability on the books, payment rows the daily job turns into Draft purchase invoices, and a monthly schedule the lease run posts. See "Leases (sub-area)".
  • Reopen — reopenPurchaseOrder (purchasing.server.ts) moves a PO to Draft OR Planned (PURCHASE_ORDER_REOPEN_STATUSES): purchasing_delete from a locked status, pending approvals cancelled (from Needs Approval only by the requester or an approver), and an optional revision bump — reopenPurchaseOrderAsRevision takes the target status, canCreatePurchaseOrderRevision accepts either. A reopen to Planned skips the MRP run when the PO already was supply (Planned / To Receive / To Receive and Invoice).

Safety

Always

  • MUST scope all queries by companyId — purchasing data is multi-tenant.
  • MUST use convertDocument (shared.service.ts) for supplier-quote → PO conversion — never hand-roll inserts.
  • MUST preserve conversionFactor on PO lines when editing — it drives receipt quantity math.
  • MUST use finalizePurchaseOrder / finalizeSupplierQuote for finalization — they enforce business rules.

Ask First

  • Changing PO status (approval/finalization workflows have business rules).
  • Deleting suppliers or POs that may have linked receipts or invoices.

Never

  • Bypass the approval workflow by directly setting status to To Receive.
  • Delete receipt lines that have already been posted to inventory.
  • Directly INSERT into purchaseOrder — MUST use insertPurchaseOrder / updatePurchaseOrder.

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/purchasing

Key Data Model

Table / View Purpose
purchaseOrder / purchaseOrders (view) PO header: supplier, status, dates, location; view adds receivableQuantity/receivedQuantity aggregates (drives the list's Received progress bar and the derived "Partially Received" header chip — display-only, not a status enum value)
purchaseOrderLine Line items: item, quantity, price, conversionFactor, jobId
purchaseOrderDelivery / purchaseOrderPayment PO delivery and payment terms
supplier / suppliers (view) Vendor master: name, type, status, tax info
supplierContact / supplierLocation Supplier address book
supplierProcess Which manufacturing processes a supplier offers
supplierInteraction Container for a supplier quote exchange
supplierQuote / supplierQuoteLine / supplierQuoteLinePrice Vendor pricing at quantity breaks
purchasingRfq / purchasingRfqLine / purchasingRfqSupplier RFQ header, lines, and invited suppliers
terms Payment/delivery terms reference data
purchaseReturnOrder / purchaseReturnOrderLine / purchaseReturnOrders (view) Supplier returns: authorize → ship (via shipments, source "Purchase Return Order") → credit. Statuses Draft → Confirmed → Partially Shipped → Shipped → Completed/Cancelled; supplierReference carries the supplier's own RMA number; line quantities/prices are ALWAYS inventory-UOM (converted once at authoring)
purchaseReturnOrderLineTrackedEntity / purchaseReturnOrderCreditLine Entities to send back (picked from that supplier's Available or Rejected stock — rejected units are what a return usually sends back) — the create posting (shipmentFromPurchaseReturnOrder) stamps these onto the shipment's tracked entities (attributes ->> Shipment/Shipment Line/Shipment Line Index, so each serial lands in its own box) so the batch/serial flows through; post-shipment splits a batch when the returned quantity is less than the entity's (mirrors the Sales Order path, buildBatchSplitRecords). Per-line credit breakdown behind the AP memo (memo.purchaseReturnOrderId, reason account = GRNI). The memo is a Debit memo (DR- sequence): direction alone picks the control side, so Credit would INCREASE AP and re-debit GRNI — a vendor return must DR AP / CR GRNI

Key Service Functions

  • getPurchaseOrder / getPurchaseOrders / getPurchaseOrderLines — read POs
  • submitPurchaseOrderForApproval(db, …) — Needs Approval, the order date when it has none, and the approval request unless one is pending, inside the caller's transaction (the status update locks the order first)
  • setPurchaseOrderStatus(db, …) / cancelPendingApprovals(db, …) — the Kysely status write and approval-request cancel that reopenPurchaseOrder, closePurchaseOrderAndApprovals and deletePurchaseOrders run in ONE transaction, so a status change or delete that fails leaves the requests Pending
  • A line's receivedComplete / invoicedComplete are only ever SET by receipt and invoice posting (stored || …), and the header status is derived from them. So every write that changes an existing line's purchaseQuantity — upsertPurchaseOrderLine, updatePurchaseOrderLineSchedule, the planning Increase / Decrease in applyPurchasingPlanningActions — restates both through getCompletionAfterQuantityChange (@carbon/utils short-close.ts; a line still short-closed stays closed), computed against the current row: the two Kysely paths lock it FOR UPDATE in the write's transaction, and upsertPurchaseOrderLine (Supabase client) is a compare-and-swap on the columns the flags came from, retried when a receipt or invoice lands in between. Without it a PO invoiced for 10, reopened and raised to 20 went straight to Completed on receipt with 10 never invoiced
  • shortClosePurchaseOrderLine — Kysely transaction; sets a line's receivedComplete ("Stop/Resume Receiving") and recomputes the header status. Open-PO supply queries (get_inventory_quantities, openPurchaseOrderLines, get_job_quantity_on_hand) exclude receivedComplete lines, so short-closed remainders stop counting as incoming stock
  • convertSupplierQuoteToOrder — calls convertDocument (shared.service.ts, ported from the convert server function)
  • duplicatePurchaseOrder — copies a PO with new sequence
  • finalizePurchaseOrder / finalizeSupplierQuote — lock documents for processing. finalizeSupplierQuote and finalizePurchasingRfq are ported from the server functions of the same names (ctx, input, permission create: purchasing); the operations run them through invokePosting, and their live tests are apps/erp/test/database/purchasing-finalize.test.ts
  • sendSupplierQuote — sends quote to supplier
  • getPurchasingPlanning — MRP-driven planned order view (RPC get_purchasing_planning_grid)
  • applyPurchasingPlanningActions(db, { companyId, userId, actions }) — one Kysely transaction for a batch of planning actions on PO lines: the claim (Open → Actioned, returning each action's suggested quantity and date, which are what gets written), one UPDATE … FROM (VALUES …) for dates and one for quantities (taxPairForQuantity restates the tax pair), one DELETE for Cancels (Draft / Planned PO, nothing received or invoiced), then the refused claims are released. Returns { applied, alreadyApplied, refused, failed }
  • updatePurchaseOrderLineSchedule(client, db, args) — planning's single-line write (the order drawer's inline edit): requiredDate or purchaseQuantity on a line of a Draft / Planned PO, the guard inside the UPDATE; returns { updated, error }
  • Supplier approval — the $supplierId loader reads getDocumentApprovalState; $supplierId.approval.tsx calls requestSupplierApproval / deactivateSupplier / decideSupplierApproval, which use openApprovalRequests / decideApprovalRequest (@carbon/ee/approvals/document.server)
  • getPurchasingRFQ / getPurchasingRFQs / upsertPurchasingRFQ — RFQ management
  • getSupplierQuotesForComparison — side-by-side quote comparison
  • getDefaultAttachmentsForPO — default document attachments for PO creation
  • getPurchaseReturnOrders / insertPurchaseReturnOrder / upsertPurchaseReturnOrderLine — supplier-return CRUD; confirmPurchaseReturnOrder (Kysely row-locked caps: receiptLine received → PO line received×factor → invoice line×factor), cancelPurchaseReturnOrder / shortClosePurchaseReturnOrderLine (the header status follows the lines through getPurchaseReturnOrderStatus, @carbon/utils; there is no complete function)
  • getReturnableLinesForSupplier (posted receipt lines minus already-authorized) — thin wrapper over the get_returnable_receipt_lines RPC, which does the received − authorized > 0 filter, the search (receipt #, PO #, item readable id, item name), recency ordering, and limit/offset paging in SQL and returns totalCount on each row. Scales to thousands of receipt lines; the "Add lines from receipt" modal (ReturnableReceiptLinesModal) shows the 5 most recent and searches for the rest. / getReturnableEntitiesForSupplier (Available or Rejected entities whose attributes ->> Receipt resolves to a posted receipt from the supplier) / getReturnableEntitiesForReceiptLine (Available or Rejected entities from ONE receipt line, via attributes ->> Receipt Line) — the $id.new action uses it to auto-select the single entity when a tracked line is added from a specific receipt, persisting it at creation so it flows onto the shipment
  • createPurchaseReturnOrderCredit (Kysely, shipped-minus-credited cap) / getCreditableQuantitiesForPurchaseReturn / createReplacementPurchaseOrder (linked-PO-line / supplierPart pricing)
  • createSupplierInteractionDocumentUploadUrl / createSupplierInteractionLineDocumentUploadUrl — MCP file upload (step 1): presigned URLs for supplier-interaction (supplier-interaction/{interactionId}) and interaction-line documents; pair with documents_insertUploadedDocument. See .claude/rules/mcp-tools-reference.md → "File uploads"

Operations (purchasing.server.ts)

Each is a defineServiceFn const in purchasing.server.ts. The route calls it as api.purchasing.<name>(input); the API and MCP publish the ones tagged @mcp as purchasing_<name>. It holds every check the route made. Routes validate the request, call one, and answer with respond(request, result).redirect(…) (a flash) or the result.

  • Line dates — every PO line keeps its own requiredDate (requested), promisedDate and receivedDate (delivery; receipt posting also sets it), mapped to the order's receiptRequestedDate / receiptPromisedDate / deliveryDate by purchaseOrderLineDateOfOrderDate (purchasing.models.ts). A new line starts on the order's requested and promised dates (upsertPurchaseOrderLine fills them when absent; both line forms default them). A changed order date is copied by cascadePurchaseOrderDateToLines (purchasing.service.ts) to every line whose date is empty or still the order's previous one, in the transaction that writes the delivery row; a line given its own date keeps it, and received-complete lines keep their requested and promised dates. An order whose date is not changing moves no line, so saving the Shipping card fills no empty line. The delivery date is when the goods arrived (receipt posting sets the order's), so it reaches only lines with something received (quantityReceived > 0). Receipt posting also overwrites a line's receivedDate with the posting day on every receipt, so a hand-corrected delivery date lasts until the line's next receipt. Pinned by apps/erp/test/database/purchase-order-line-dates.test.ts. A saved line's dates save one at a time (updatePurchaseOrderLineDate), outside the line form's submit: the requested date is fixed once the order is released, the promised date once the line is received complete or the order fully received, and the delivery date stays correctable. The line page edits them in the form's Dates section (PurchaseOrderLineDateFields); the order summary edits each line's promised date in place (PurchaseOrderLinePromisedDate). The line details route drops the date fields from its update, because updatePurchaseOrderLineRestatingCompletion sanitizes a missing field to null.
  • Purchase orders — updatePurchaseOrder (the details form: header columns only, never status, refused on a finalized order), updatePurchaseOrders (one field of the properties panel, refused on a released order except deliveryDate, and receiptPromisedDate until the order is fully received: isPurchaseOrderPromisedDateEditable. A new requested, promised or delivery date also moves the order's lines — see Line dates), updatePurchaseOrderDelivery (the Shipping card, $orderId.delivery.tsx; refused on a released order; cascades its three dates the same way), updatePurchaseOrderLineDate (one date of one line, $orderId.$lineId.date.tsx; purchaseOrderLineDateRefusal), deletePurchaseOrders (Draft / Planned, or Needs Approval by its requester — purchaseOrderDeleteRefusal in purchasing.models.ts; cancels the pending approvals in the delete's transaction), finalizePurchaseOrderAndNotify (party contact and supplier approval rules, the approval rule or the planning bypass, then prices, the PDF document and the email; the email attaches the new PDF, the supplier interaction's files without the PDFs stored for its orders (withoutStoredPurchaseOrderPdfs: every order converted from one supplier quote shares the folder) and the default attachments, and the PO page's Finalize list shows the same files; an order that needs approval is never released: submitPurchaseOrderForApproval sets Needs Approval and opens the request in one transaction, and the approvers are notified after it commits), decidePurchaseOrderApproval, reopenPurchaseOrder (Draft / Planned, optionally as a revision; delete permission from a released status), closePurchaseOrderAndApprovals. The status route takes only Draft, Planned and Closed.
  • Return orders — updateReturnOrders, confirmReturnOrder (stores the PDF; a failed PDF is a warning), cancelReturnOrder, reopenReturnOrder, addReturnOrderLine (Draft only), updateReturnOrderLine (post-confirm locks: lockedReturnLineField).
  • RFQs — createPurchasingRfq, updatePurchasingRfqs, cancelPurchasingRfq (cancels the linked supplier quotes), finalizePurchasingRfqAndNotify (service.finalizePurchasingRfq, ported from finalize-purchasing-rfq, then the emails: the RFQ and line documents, and each line item's original CAD file from getItemModelFiles — attached in line order while the total stays under PO_EMAIL_ATTACHMENT_LIMIT_MB (splitRfqModelAttachments), the rest signed for 7 days and listed as links in the body; a model with no known size goes as a link, one whose attachment cannot be signed falls back to a link, and one with no link either is named in the body). The RFQ PDF (file+/purchasing-rfq+/$id[.]pdf.tsx, template type purchasingRfq, the header's PDF action at any status) is a letter for suppliers who quote in their own format: letterhead, date, reference and due date, what the quotation should include, the delivery address and the buyer to send it to (the RFQ's assignee, else its author), a ruled table of each line's quantity breaks in its purchase unit, then the notes and a sign-off (the notes block) and the terms on their own page. It has no price cells; the share page is where a supplier enters prices. Both share pages (share+/purchasing-rfq.$id.tsx, share+/supplier-quote.$id.tsx) show the line's purchase unit (else inventory unit) beside each quantity.
  • Supplier quotes — updateSupplierQuotes, finalizeSupplierQuoteWithLink, sendSupplierQuoteToSupplier; submitDigitalSupplierQuote / declineDigitalSupplierQuote / updateDigitalSupplierQuoteLineNotes / recordSupplierQuoteLinkVisit (system only, not published: the supplier's share link runs them through shareLinkContext, ~/modules/service-context.server; submit refuses a line that is not the quote's).
  • Suppliers — requestSupplierApproval, deactivateSupplier, decideSupplierApproval.
  • Planning — orderPlannedPurchases (suggestions to Planned POs, one per supplier per week), updatePlanningPurchaseOrderLine, applyPlanningActions, dismissPurchasingPlanningActions, reopenPurchasingPlanningActions, assignPurchasingPlanningActions. The route answers { success, message }, the shape usePlanningActions (production module, shared with production planning) reads.
  • Leases — see Leases.

The PO, return order and RFQ PDFs render in purchasing.pdf.tsx (renderPurchaseOrderPdf, renderPurchaseReturnOrderPdf, renderPurchasingRfqPdf) from a client, so the file+ routes and the operations that store them render one document. Email links use ERP_URL (~/utils/path), not the request's host. Import other modules' code from the file that defines it (*.service.ts, *.models.ts); modules have no barrel.

Key Exports

import { getPurchaseOrder, insertPurchaseOrder, getSuppliers } from "~/modules/purchasing/purchasing.service";
import { purchaseOrderValidator, supplierValidator } from "~/modules/purchasing/purchasing.models";

Leases (sub-area)

Lessee leases under ASC 842: the company leases one or more assets from a supplier. Spec .ai/specs/2026-10-11-lessee-leases.md (multi-asset: its Addendum, A1–A8). Each leased asset is a leaseLine, a separate lease component (842-10-15-28) with its own payment, classification inputs, classification, measurement, payment rows and schedule; the lease keeps the term, the payment frequency and timing, the escalation and the rate, as a rental agreement keeps them on its header. Lives inside this module: validators in purchasing.models.ts (leaseValidator, leaseLineValidator, leasePaymentValidator, leaseClassificationValidator, leaseModifyValidator (a lines repeatable, one payment per active asset), leaseTerminateValidator, leasePurchaseValidator, the enum arrays leaseStatuses … leasePaymentTypes), reads, Draft writes and the Kysely wrappers in the "Leases" section of purchasing.service.ts, the service functions in purchasing.server.ts, UI in ui/Leases/, routes x+/purchasing+/leases.tsx (list, nav entry "Leases" in the Agreements group of usePurchasingSubmodules) and x+/lease+/ (new and $id.setup.* — the Draft setup wizard, see below —, update (one lease term at a time: any term of a Draft; once started only the name, notes, owner and notice date, leaseDetailFields), $id.lines.new (Add Asset), $id.$lineId.update (one asset cell), $id.$lineId.delete, $id.payments.* (new, create: purchasing; $id.payments.$paymentId.update, one grid cell; $id.payments.$paymentId.delete, delete: purchasing; regenerate), the $id shell with $id.details and the asset page $id.$lineId.details for a lease past Draft, and the action routes $id.activate, $id.$lineId.classification, $id.invoice, $id.modify, $id.$lineId.terminate, $id.$lineId.purchase, $id.status (intent cancel, an Active lease only), $id.delete). Lifecycle math is pure in packages/utils/src/lease-math.ts (@carbon/utils: generateLeasePayments, paymentMonthIndex, presentValueOfPayments, classifyLesseeLease (the lessor's five tests via classifyLessorLease, plus the short-term election, tested on the dates with isTermWithinTwelveMonths), buildLesseeSchedule, remeasureLease, addMonths, leaseMonthsAt / leaseTermMonths (lease months counted with the clamped addMonths, so a lease from the 31st agrees with its rows), leaseMonthEnds, leaseMonthShare (a short last month's share by days, buildLesseeSchedule's lastMonthShare)), pinned by lease-math.test.ts. The month arithmetic (addMonths, leaseMonthsAt, leaseMonthShare, paymentMonthIndex, scheduleMonthOfPayment) lives in @carbon/database/lease-months and is re-exported, so the accounting cutover's open items count payments the way the schedule pays them; the discount rate and factor are shared with lessor-lease.ts (monthlyRate, discountFactor). Schema: 20261011163133_lessee-lease-enums.sql, 20261011163211_lessee-leases.sql, 20261011192448_lessee-leases-rls.sql, 20261011202305_lease-invoice-line-type.sql, 20261012015739_lease-lines.sql (+ 20261012015905_lease-lines-rls.sql).

Table / View Purpose
lease / leases (view) Header (sequence LSE): supplier, location, assignee (the owner who gets the digest and reminders), optional name (pages fall back to the supplier and the number) and description (Notes), commencementDate / endDate (NULL = open-ended, 20261012033330_lease-open-ended.sql) / noticeDate / invoiceFromDate, paymentFrequency Monthly / Quarterly / Annual, paymentTiming Advance / Arrears, annualEscalationPercent (CHECK > −100), discountRate (annual %, CHECK ≥ 0), commencementJournalId, noticeRemindedFor / endRemindedFor. Status leaseStatus: Draft → Active → Expired / Terminated / Purchased (the last asset's end), or Cancelled. The view (20261012191455_lease-guards-and-constraints.sql, one lateral aggregate over the assets) adds supplierName, assetCount, paymentAmount (the assets' sum) and classification (the one the assets share, else Mixed) — over the Active assets of a Draft, Active or Cancelled lease, over all assets of an ended one —, nextDueDate (first Pending payment; NULL for a Draft or Cancelled lease) and currentLiability (per Active asset, the closing liability of its last leaseScheduleLine with postedAt, else its initialLiability; 0 for a Draft or Cancelled lease)
leaseLine One leased asset (id('lsln'), sortOrder): description, serialNumber, locationId (else the lease's), paymentAmount (CHECK ≥ 0), the classification inputs (fairValue, economicLifeMonths, ownershipTransfers, specializedAsset, purchaseOptionAmount, purchaseOptionReasonablyCertain; CHECK fairValue > 0, economicLifeMonths > 0, purchaseOptionAmount ≥ 0, and an amount when reasonably certain), status leaseLineStatus Active / Terminated / Purchased / Expired, the stored result (lesseeClassification, classificationInputs JSON, classificationOverride + required classificationOverrideReason), the measurement (initialLiability, initialRouAsset, rouAssetCost) and fixedAssetId (after a purchase; FK, set null)
leasePayment Payment rows of one asset (leaseLineId NOT NULL; paymentType Rent / Purchase Option / Termination Penalty, period, dueDate, amount, status Pending / Invoiced / Skipped, purchaseInvoiceLineId, voidedPurchaseInvoiceId). Unique (companyId, leaseLineId, dueDate, paymentType). Read by the PV, the schedule and the invoice job. purchaseInvoiceLineId has NO foreign key; CHECK leasePayment_invoiced_check: status = 'Invoiced' iff it is set, and the AFTER DELETE trigger purchaseInvoiceLine_release_lease_payment returns the row to Pending when its invoice line is deleted
leaseScheduleLine One asset's effective-interest schedule (leaseLineId NOT NULL; unique (companyId, leaseLineId, periodDate)), one row per lease month (periodDate = the month's last day): opening / closing liability, payment, interest, principal, leaseCost, rouAmortization, closingRouAsset; journalId / postedAt stamped when the lease run posts it (postedAt alone for a month in an opening balance); the lease page reads posted state from postedAt (isScheduleLinePosted) and "run-posted" from journalId, never from the run rows, which need accounting_view
leaseEvent Modification / Termination / Purchase audit trail, ONE row per asset (leaseLineId NOT NULL; a Modify writes one per active asset, all naming its journal): effective date, liability and ROU before / after, gainLoss, classification before / after, fixedAssetId (FK, set null), journalId
purchaseInvoiceLine.leaseId / leasePaymentId The Lease invoice line (see invoicing AGENTS). CHECK purchaseInvoiceLine_lease_check: invoiceLineType = 'Lease' iff leaseId is set
revenueRecognitionSchedule.leaseId / leaseScheduleLineId The two run rows each schedule line spawns (type Interest and Amortization), which the lease run posts (see accounting AGENTS). CHECK revenueRecognitionSchedule_lease_pairing_check: both or neither

leasePayment, leaseScheduleLine and leaseEvent reference their asset by (leaseLineId, leaseId, companyId) (unique on leaseLine), so a row always names an asset of its own lease.

RLS on the five lease tables: purchasing_view to read; lease, leaseLine and leasePayment take purchasing_* writes (company("purchasing", { read: "purchasing_view" }) in packages/database/src/authz/manifest.ts), while leaseScheduleLine and leaseEvent have no API write policy — only post-lease and the lease run write them, through Kysely (20261012183637_lease-derived-tables-read-only.sql). The purchasing_* policies are narrowed by the lease_api_write_guard triggers (20261012191455_lease-guards-and-constraints.sql, pinned by supabase/tests/lease-api-guards.test.sql): for an API role (anon / authenticated) a lease, its assets and its payment rows are writable only while the lease is Draft — except a started lease's name, description, assignee, noticeDate and customFields — and the lease's status / commencementJournalId and an asset's classification, measurement, status and fixedAssetId never change. The service role (the classification route) and Kysely (the postings) are not guarded; a write the database makes itself (a cascade, the invoice-line release) runs at trigger depth > 1 and passes. The audit log entity lease covers lease + leaseLine + leasePayment (audit.config.ts).

  • Draft — the setup wizard. A Draft is set up in the same wizard as contracts and rental agreements (~/components/Setup: SetupFrame, SetupSteps, SetupBody / SetupSection, SetupFooter, TermForm, useCellSave), steps leaseSetupSteps = Details → Assets → Payments → Accounting → Review (ui/Leases/LeaseSetupSteps.tsx, path.to.leaseSetup(id, step)). new.tsx renders step 1 (LeaseDetailsForm: Lessor — supplier, site, contact and the lease's Location —, Term — commencement and a Duration copied from the AR contract: leaseDurations 12 / 24 / 36 / 48 / 60 months, open, custom + End Date; leaseEndDate turns it into the end date in leaseTermColumns (through resolveLeaseDates), leaseDurationOf reads it back —, More Details — owner, Notes (description), custom fields; the name, payment terms and rate ride along as hidden fields) and creates the Draft (insertLease, leaseId from the lease sequence, discountRate from companySettings.leaseIncrementalBorrowingRate — a failed settings read is logged and sends the user back to the list rather than default the rate to 0), then redirects to setup/assets. $id.setup (the index) opens the Assets step. $id.setup.tsx is the shell (refuses a non-Draft; Back / Next footer, Next disabled on Assets with no asset and on Payments with no row; Review's footer has Save as Draft and Activate, gated by leaseActivationGaps — no asset, an asset with no row, a foreign currency — mirroring activateBlocker). $id.setup.details saves the details with updateDraftLease, which cuts every asset's rows again in the same transaction when a term they are cut from changed (leasePaymentTermFields); an invoice-from date still equal to the commencement follows a new one (resolveLeaseDates, shared with update.tsx). Assets (LeaseAssetsGrid, copied from the rental agreement's RentalUnitsGrid): Add Asset ($id.lines.new, create: purchasing: description, serial, payment), cells for description, serial number, location and payment ($id.$lineId.update) — both through saveDraftLeaseLine, which writes the asset and, when it is new or a field its rows are cut from changed (leaseLinePaymentFields: payment, purchase option), cuts that asset's rows in the same transaction, Remove Asset ($id.$lineId.delete, delete: purchasing; its rows cascade). Payments (LeasePaymentTerms + LeasePaymentsGrid): the frequency, timing and escalation save on their own through update.tsx (useLeaseTermSave), and a change cuts every asset's rows again in the same transaction (updateDraftLease). Every cut — regenerateLeasePayments, updateDraftLease, saveDraftLeaseLine (purchasing.service.ts), the daily job's open-ended roll and Modify — goes through ONE cutter, cutLeasePaymentRows (apps/erp/app/modules/shared/shared.service.ts): each asset's rows from generateLeasePayments at the asset's own payment (escalation on each anniversary of the commencement, a short last period prorated by days, a Purchase Option row on endDate only when reasonably certain; a row due before invoiceFromDate is Skipped, paid outside Carbon; no row of 0). An asset with no payment has no rows. The grid (an Asset column when there are several) edits a row's period, due date and amount cell by cell ($id.payments.$paymentId.update, upsertLeasePayment); "Add Payment" (asset chosen in LeasePaymentForm) and "Regenerate from Terms" stay. Accounting (LeaseAccounting): LeaseClassificationPreview live for every asset (cards count the assets per treatment; the five tests read "N of M assets"; a table per asset with its PV and "Override" → $id.$lineId.classification, update: accounting, Draft only, Operating or Finance with a reason, or intent=remove to clear it so the tests decide again; both audit-logged), the lease's discount rate, and the asset inputs grid (fair value, economic life, purchase option and the three switches, each through $id.$lineId.update). Review: LeaseSummary, the gaps linked to their step (a Skipped payment of a capitalized asset that no opening balance holds is named by asset and due date, linked to Details for Invoice From — skippedPaymentBlockers, against the opening date the $id loader reads with leaseOpeningAsOf, the read-only mirror of activation's resolveAccountingPeriod), LeaseCommencementPreview (ROU / liability per asset). Opening a Draft ($id._index, $id.details, $id.$lineId.details) sends anyone with update: purchasing to its setup (draftLeaseSetupPath, step Assets); a viewer sees the page. insertLease and updateDraftLease write only the picked leaseTermColumns; saveDraftLeaseLine only the picked leaseLineColumns (never status, classification or measurement); updateLeaseDetails only leaseDetailFields. deleteLeaseLine, upsertLeasePayment and deleteLeasePayment refuse a lease that is not Draft (LEASE_NOT_DRAFT); upsertLeasePayment matches the row's own lease and asset and sets Pending / Skipped from invoiceFromDate; every delete reports a row it did not find. The lease dates are real YYYY-MM-DD dates (leaseValidator, leasePaymentValidator, the Modify / Terminate / Purchase validators).
  • Open-ended leases (spec Addendum A10) — endDate NULL. Every asset is Short-Term: activate posts nothing and writes no schedule, and refuses with OPEN_ENDED_NEEDS_EXPEDIENT (both fixes named; OpenEndedExpedientNotice links them on the Accounting and Review steps and in the Activate dialog, leaseActivationGaps gap openEndedWithoutExpedient) while companySettings.leaseShortTermExpedient is off. Payment rows are whole periods through openEndedLeaseHorizon (the start of the period after today's): the Draft setup cuts the first, and create-lease-invoices (rollOpenEndedLeasePayments, every Active open-ended lease, per active asset only after its last Rent row — cutLeasePaymentRows with after) cuts the next before drafting. No purchase option row; Modify and Purchase refuse; Terminate sets the end date; it never expires.
  • Lifecycle — postLeaseAction (apps/erp/app/modules/purchasing/purchasing.service.ts, ported from the post-lease server function, permission update: purchasing, payload { type, leaseId, … } (payloadValidator, same file); Terminate and Purchase add leaseLineId, Modify a lines list of { leaseLineId, paymentAmount }). Each action is ONE Kysely transaction that locks the lease first (lockLease, then readLines). Every action that posts needs the lessee account defaults plus the asset gain / loss on disposal defaults (LESSEE_ACCOUNTS_REQUIRED). All lessee journals are sourceType 'Lease', lines documentType 'Lease' + documentId = the lease + documentLineReference = the asset, with Supplier and the asset's Location dimensions (postLesseeJournal, purchasing.service.ts, which takes each asset's lines): Provisional before the accounting cutover, Posted after it. The journal-line builders are pure, in purchasing.service.ts (pinned by apps/erp/test/database/post-lease/lessee.test.ts).
    • activate: refuses a non-Draft lease, a lease with no asset, an asset with no payment row, a currency other than the base currency, and a Skipped payment of a capitalized asset due on or after the commencement that no opening balance holds (skippedPaymentBlocker: nothing would ever relieve it from the liability; Invoice From is only for payments made before the opening balance). measureAsset classifies each asset (classifyLesseeLease with companySettings.leaseShortTermExpedient and the shared thresholds; an override wins) and measures its liability at the PV of its rows. A Short-Term asset posts nothing and has no schedule. The others share ONE Lease Commencement LSE… journal (Dr Right-of-Use Assets / Cr Lease Liabilities at each asset's PV), and writeSchedules writes each asset's lease months plus their Interest and Amortization run rows (scheduleRowAccounts: Operating books both rows' debit to Operating Lease Expense; Finance to Interest Expense – Leases and Amortization – Right-of-Use Assets). ROU amortization runs over what is left of the economic life when ownership transfers or the purchase option is reasonably certain, else the months the schedule covers (amortizationMonths). updateLineMeasurements writes every asset's result in one statement.
    • Commenced before the cutover — when commencementDate < companySettings.accountingCutoverDate, activate posts Lease Opening Balance LSE… instead, dated the cutover (or the first open period after it): per asset, Dr ROU at cost, Cr accumulated amortization and the carrying liability its schedule reaches on that date (balancesBefore), the difference to retainedEarningsAccount (openingBalanceLines). Schedule lines before the date are written with postedAt and their run rows Posted with no journal, and the Pending payments the schedule pays in those months are set Skipped (they are in the opening balance). That is decided by the schedule month a payment is paid in (isPaidBeforeOpening / lesseeScheduleMonthOf, @carbon/utils), not its due date: an Advance payment due inside the as-of month is still in the carrying liability and is invoiced.
    • cancel: undoes an activation and nothing else. A Draft is refused (deleting is $id.delete, delete: purchasing). An Active lease is Cancelled only while every asset is Active, it has no leaseEvent (no Modify, Terminate or Purchase), no Invoiced payment, no run holding its rows (heldByRun) and no run-posted row; its commencement or opening journal is voided with a negated VOID <description> copy dated today (voidLeaseJournal, through the shared insertNegatedJournal in shared.service.ts), refused when it predates the cutover, and the schedule is deleted.
    • modify / terminate / purchase share prepare over the assets acted on: an Active lease and active assets, a date on a lease-month boundary (leaseMonthStarting) that does not fall inside a payment period (straddledPeriod: Modify on the first day of a period, Terminate / Purchase on the last), every run row before it Posted, no Posted row on or after it (a lease run or an opening balance already put that month in the GL), no run holding a later row, no Invoiced or Skipped payment due on or after it. Terminate and Purchase refuse a date before the commencement. Modify (the lease) updates the term, rate, frequency and escalation and cuts each active asset's remaining payments again (cutLeasePaymentRows with from): from the COMMENCEMENT, keeping the rows from the effective date, so the escalation steps up on the commencement's anniversaries and a lease from the 29th–31st keeps its months; the payment entered is the one at the effective date (an asset not named keeps the rate it pays then), the asset stores the commencement payment it implies, and a period the new frequency started before the date is cut to its days from there. The schedule after the date is the commencement's months too. It remeasures each capitalized asset (remeasureLease; a decrease beyond the ROU is a gain), reassesses Operating / Finance (an override still wins), posts one Lease Modification LSE… with lines per asset, and writes one event per asset. A Short-Term asset cannot be extended past 12 months. Terminate (one asset) deletes that asset's Pending rows after the date and its Purchase Option row — adding back to the carrying liability an option the schedule counted as paid (deleteEndedPayments) — adds a Termination Penalty row, posts Lease Termination LSE… <asset> (gain / loss to assetGainOnDisposalAccount / assetLossOnDisposalAccount) and sets the asset Terminated. Purchase (one asset; refused for Short-Term, and with neither a purchaseOptionAmount nor ownershipTransfers — an asset whose ownership transfers with no option is taken on the end date at price 0; a price that leaves the asset a negative cost is a 400) reuses an option row already Invoiced on or before the date when the price matches (refused otherwise), else replaces the option row with one at the price (the same add-back), posts Lease Purchase LSE… <asset>, inserts an Active fixedAsset at the asset's location with its serial number, and sets the asset Purchased + fixedAssetId. When no active asset is left, endAsset gives the lease the last asset's status and end date.
  • Invoicing — createLeaseInvoices (purchasing.service.ts, ported from the create-lease-invoices server function) ({ asOf, leaseId? }, update: purchasing + create: invoicing): per lease that is Active, Expired, Terminated or Purchased with a Pending row due on or before asOf, ONE Draft purchaseInvoice per due date with one Lease line per row, described with the asset (leasePaymentDescription) at the asset's location, the rows stamped Invoiced + purchaseInvoiceLineId. Each lease is its own transaction; a failure is returned in failures, never thrown. Called daily by the Inngest recurring-billing job and by "Invoice Now" ($id.invoice.tsx → generateLeaseInvoicesNow). The drafts stay Draft: the buyer adds the supplier's invoice number and posts. Drafting and posting bill the same statuses (BILLABLE_LEASE_STATUSES, @carbon/utils lease-math.ts). Posting reads the classification of the payment row's asset: a capitalized asset's line debits Lease Liabilities with the NOMINAL payment only (quantity × base unit price), which must equal the row's amount in base currency, and its tax, line shipping and share of the header freight go to Operating Lease Expense; a Short-Term asset's line debits Operating Lease Expense in full; a line with no payment row is a variable charge to Variable Lease Expense. A Lease line of a Draft or Cancelled lease is refused, and so is a row billed by another invoice line (its purchaseInvoiceLineId is not this line). VOID returns the rows to Pending and stamps voidedPurchaseInvoiceId.
  • Deleting an invoice releases its rows — deletePurchaseInvoiceReleasingLeases / deletePurchaseInvoiceLineReleasingLeases (purchasing.service.ts) delete a Draft purchase invoice (or one line), checked under a row lock, and return the billed rows to Pending in the same transaction (releaseLeasePayments, which stamps who did it; the purchaseInvoiceLine_release_lease_payment trigger releases a row on any delete of its line as the backstop). The invoicing service functions deleteDraftPurchaseInvoice / deleteDraftPurchaseInvoiceLine call them. No plain purchase invoice delete is published: the building block deletePurchaseInvoiceLine checks no status, and a released row of a posted invoice would be billed twice.
  • Reminders and expiry — the same daily job notifies the owner (assignee ?? createdBy) and the company's invoiceNotificationGroup once per date (LeaseCriticalDate, packages/jobs/src/invoicing/lease-reminders.ts dueLeaseReminders + stampLeaseReminders, which stamps the date reminded and skips a date that moved since) when noticeDate or endDate is within companySettings.leaseReminderDays, and expires (expireLeases) every Active lease past its endDate with every run row Posted, no Pending payment and no active asset whose last schedule line still carries an ROU asset (one the lessee will own ends with a Purchase); its active assets expire with it.
  • The lease page — copied from the rental agreement's. The explorer (LeaseExplorer) lists the assets, one row each with the fixed asset's item thumbnail and its status (no row menu); a row opens the asset's page $id.$lineId.details (path.to.leaseLine): LeaseAssetSummary (serial, location, payment, initial and current liability, fixed asset; Terminate, and Exercise Purchase Option — or Take Ownership for an asset whose ownership transfers with no option, leasePurchaseOffer), then that asset's LeasePayments, LeaseSchedule and LeaseEvents. The actions and their modals live in useLeaseAssetActions, as the rental's in useRentalLineActions. The lease number in the header opens $id.details: LeaseSummary (the view's asset count and payment, over the active assets; liability and net ROU from leaseAssetBalances, the same helper as the asset page), LeasePayments and LeaseEvents for every asset (an Asset column). The header (LeaseHeader; a Draft activates from its setup) has Modify, Cancel (disabled unless canCancelLease: every asset Active, no leaseEvent, nothing Invoiced, no run-posted month), a Journals menu, and Invoice Now for any lease but a Draft or Cancelled one — a Purchase Invoices menu whenever the lease has invoices, as the rental header turns Deliver into a Shipments menu. LeaseProperties keeps the name, owner, notice date and notes editable once started (through update.tsx); every other term is read only. Every decision the screens make mirrors post-lease and lives in ui/Leases/utils.ts (pinned by utils.test.ts): the activation gaps (incl. skippedPayment, skippedPaymentBlockers, with LeasePolicy.openingAsOf when the loader supplies it), the Modify payment pre-fill (leaseModifyPaymentAt: the rate the asset pays at the effective date) and remeasurement (leaseModifyPreview, rows cut from the commencement), the short-term 12-month limit, and the Purchase refusals (leasePurchaseRefusal). Their arithmetic — carrying amounts (lesseeCarryingAt), the purchase-option add-back (endedPaymentsAddBack), measureLesseeAsset, remainingLeasePayments, the opening-balance split (isPaidBeforeOpening) and the journal legs (lessee*Legs) — is in @carbon/utils lease-math.ts, which postLeaseAction (purchasing.service.ts) posts from. The Accounting step's classification table has Override and, on an overridden asset, Remove Override (posts intent=remove to $id.$lineId.classification). Amounts render with ~/components/Money (shared with RentalMoney).

Key lease service functions

  • getLeases / getLease (the leases view) / getLeaseLines / getLeasePayments / getLeaseSchedule (schedule lines + their run rows) / getLeaseEvents / getLeaseRelatedDocuments (purchase invoices with a Lease line, and journals with documentType 'Lease') — the lists are paged past PostgREST's 1,000-row cap (fetchAllRecords / fetchAllByIds)
  • insertLease / deleteLease / deleteLeaseLine / upsertLeasePayment / deleteLeasePayment (Draft only), updateLeaseDetails (name, notes, owner, notice date — any status). Every one is an MCP tool; nothing an MCP caller can reach writes a term or an asset without cutting the rows, because those writes are Kysely-only
  • updateDraftLease(db, { leaseId, companyId, userId, terms, customFields? }) / saveDraftLeaseLine(db, { leaseId, leaseLineId?, companyId, userId, line }) / regenerateLeasePayments(db, { leaseId, leaseLineId?, companyId, userId }) — one Kysely transaction each that locks the Draft, writes, and cuts the rows (cutLeasePaymentRows); generateLeaseInvoicesNow(db, { companyId, userId, asOf, leaseId }) / deletePurchaseInvoiceReleasingLeases / deletePurchaseInvoiceLineReleasingLeases (purchasing.service.ts)
  • Pure, in purchasing.models.ts: leaseTermColumns / leaseLineColumns (the columns a write may set), resolveLeaseDates (end date from a duration; invoice-from follows the commencement), leasePaymentTermFields / leaseLinePaymentFields (what the rows are cut from), leaseDetailFields / leaseDetailsValidator (what stays editable once started)
  • Lifecycle: activateLease / cancelLease / modifyLease and terminateLeaseLine / purchaseLeaseLine (purchasing.server.ts), each one service.postLease(ctx, { type, leaseId, … }), which checks the lease is the company's and runs postLeaseAction through invokePosting; overrideLeaseLineClassification / removeLeaseLineClassificationOverride write the override (update: accounting)

Leases safety

  • Never write lease.status, leaseLine.status, the classification, the measurement columns, leaseScheduleLine or the lease's revenueRecognitionSchedule rows from app code. Every lifecycle change goes through post-lease.
  • Delete a purchase invoice (or a line) that may carry Lease lines with the *ReleasingLeases functions. leasePayment.purchaseInvoiceLineId has no FK; the purchaseInvoiceLine_release_lease_payment trigger returns the row to Pending on any delete, but the functions also check the invoice is Draft.
  • Terms, assets and payment rows are editable only while Draft; a term or an asset is written together with its cut rows (updateDraftLease / saveDraftLeaseLine), never on its own. Once started only leaseDetailFields change (the database refuses the rest for an API role). Change an Active lease with Modify (or Terminate / Purchase one asset), never by editing its rows.
  • A purchaseInvoiceLine.leasePaymentId is set only by create-lease-invoices; upsertPurchaseInvoiceLine drops it on create and never rewrites it on update.

Related Modules

  • inventory — receipts consume PO lines; purchaseOrderLine.quantityReceived updated on receipt
  • items — purchaseOrderLine.itemId → item master; supplier parts pricing in items module (supplierPart)
  • production — jobs link to PO lines via jobId for outside operations and purchased materials
  • accounting — purchase invoices tie to POs; posting groups drive GL entries
  • sales — supplier quotes can originate from sales RFQ workflows

Rules References

  • .claude/rules/purchasing-conversion-factors.md — UoM conversion on PO lines (factor math, gotchas)
  • .claude/rules/method-material-sourcing.md — how method materials determine sourcing type (Buy/Make/Pull)
  • .claude/rules/conventions-services.md — service function shape and naming