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.
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 withclosePurchaseOrderAndApprovals(purchasing.server.ts). - PO Revision —
purchaseOrder.revisionIdcounts amendments to a released order. Created ONLY when the header dropdown's "Create PO Revision" action postscreateRevision=true; a plain Reopen never bumps. The write isreopenPurchaseOrderAsRevision(Kysely,purchasing.service.ts): a compare-and-swap that setsrevisionId = revisionId + 1in SQL with the eligibility conditions (locked status + non-nullorderDate) 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 asPO000123-1when > 0 viagetPurchaseOrderDisplayId(@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 viaconvertDocument(shared.service.ts, ported from theconvertserver function). - RFQ (Request for Quotation) — solicits pricing from multiple suppliers. Links to supplier quotes via
purchasingRfqToSupplierQuote. Statuses managed byupdatePurchasingRFQStatus. - Conversion Factor — when a supplier's UoM differs from stocking UoM,
conversionFactoronpurchaseOrderLinescales quantities at receipt:inventoryQty = purchaseQty × conversionFactor. See.claude/rules/purchasing-conversion-factors.md. - Purchasing Planning — MRP-driven planned orders surfaced via
getPurchasingPlanning(calls theget_purchasing_planning_gridRPC, which wrapsget_purchasing_planningwith the planning-horizon fence, first negative week, latest order date and the database-side action filters). Planning actions on PO lines are applied byapplyPlanningActions(purchasing.server.ts; the route isx+/purchasing+/planning.update.tsx) throughapplyPurchasingPlanningActions(db, …)— set-based, one Kysely transaction for the whole batch: the claim, oneUPDATE … FROM (VALUES …)for the dates, one for the quantities (tax pair restated viataxPairForQuantity), oneDELETEfor 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 isupdatePlanningPurchaseOrderLine, throughupdatePurchaseOrderLineSchedule(one Kysely UPDATE with the same Draft / Planned guard, returnsupdated). Planning changes a PO only whileisPurchaseOrderEditableFromPlanning(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 writesquantityReceived+ the suggested quantity still to come (MRP reads a line'squantityToReceive), 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 fromusePurchaseOrderPlanningCommands(ui/Planning/): Reopen / Reopen as Revision on a PO planning cannot change, postingstatus=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, throughPurchaseOrderFinalizeModal(now takes apurchaseOrderIdprop) with its order + default CC fromapi+/purchasing.purchase-order.$id.finalize.ts. - Planning approval bypass —
purchaseOrder.createdFromPlanning(migration20261006214907) is set by planning's Order (orderPlannedPurchases) on the POs it creates (and restored on planning POs it adds lines to).upsertPurchaseOrderLine/deletePurchaseOrderLineclear 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) skipsisApprovalRequiredwhen the flag is set ANDcompanySettings.skipApprovalForPlanningPurchaseOrders(default true, Settings → Planning → Purchase Order Approval) — failing closed on a read error. - Approval signature —
approveRequest(@carbon/ee/approvals.server) copies the approver'suser.signaturePathtoapprovalRequest.decisionSignaturePath, so a later change of signature never changes an approved PO. WithcompanySettings.requirePurchaseOrderApprovalSignature(Settings → Purchasing) it refuses a PO approval from an approver with none (code: "signature-required", avalidationerror fromdecidePurchaseOrderApproval); the PO page loader'sapprovalNeedsSignatureopensApprovalSignatureModalinstead 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_deletefrom a locked status, pending approvals cancelled (from Needs Approval only by the requester or an approver), and an optional revision bump —reopenPurchaseOrderAsRevisiontakes the target status,canCreatePurchaseOrderRevisionaccepts 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
conversionFactoron PO lines when editing — it drives receipt quantity math. - MUST use
finalizePurchaseOrder/finalizeSupplierQuotefor 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 useinsertPurchaseOrder/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 POssubmitPurchaseOrderForApproval(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 thatreopenPurchaseOrder,closePurchaseOrderAndApprovalsanddeletePurchaseOrdersrun in ONE transaction, so a status change or delete that fails leaves the requests Pending- A line's
receivedComplete/invoicedCompleteare 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'spurchaseQuantity—upsertPurchaseOrderLine,updatePurchaseOrderLineSchedule, the planning Increase / Decrease inapplyPurchasingPlanningActions— restates both throughgetCompletionAfterQuantityChange(@carbon/utilsshort-close.ts; a line still short-closed stays closed), computed against the current row: the two Kysely paths lock itFOR UPDATEin the write's transaction, andupsertPurchaseOrderLine(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'sreceivedComplete("Stop/Resume Receiving") and recomputes the header status. Open-PO supply queries (get_inventory_quantities,openPurchaseOrderLines,get_job_quantity_on_hand) excludereceivedCompletelines, so short-closed remainders stop counting as incoming stockconvertSupplierQuoteToOrder— callsconvertDocument(shared.service.ts, ported from theconvertserver function)duplicatePurchaseOrder— copies a PO with new sequencefinalizePurchaseOrder/finalizeSupplierQuote— lock documents for processing.finalizeSupplierQuoteandfinalizePurchasingRfqare ported from the server functions of the same names (ctx, input, permissioncreate: purchasing); the operations run them throughinvokePosting, and their live tests areapps/erp/test/database/purchasing-finalize.test.tssendSupplierQuote— sends quote to suppliergetPurchasingPlanning— MRP-driven planned order view (RPCget_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), oneUPDATE … FROM (VALUES …)for dates and one for quantities (taxPairForQuantityrestates the tax pair), oneDELETEfor 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):requiredDateorpurchaseQuantityon a line of a Draft / Planned PO, the guard inside the UPDATE; returns{ updated, error }- Supplier approval — the
$supplierIdloader readsgetDocumentApprovalState;$supplierId.approval.tsxcallsrequestSupplierApproval/deactivateSupplier/decideSupplierApproval, which useopenApprovalRequests/decideApprovalRequest(@carbon/ee/approvals/document.server) getPurchasingRFQ/getPurchasingRFQs/upsertPurchasingRFQ— RFQ managementgetSupplierQuotesForComparison— side-by-side quote comparisongetDefaultAttachmentsForPO— default document attachments for PO creationgetPurchaseReturnOrders/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 throughgetPurchaseReturnOrderStatus,@carbon/utils; there is no complete function)getReturnableLinesForSupplier(posted receipt lines minus already-authorized) — thin wrapper over theget_returnable_receipt_linesRPC, which does thereceived − authorized > 0filter, the search (receipt #, PO #, item readable id, item name), recency ordering, and limit/offset paging in SQL and returnstotalCounton 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 whoseattributes ->> Receiptresolves to a posted receipt from the supplier) /getReturnableEntitiesForReceiptLine(Available or Rejected entities from ONE receipt line, viaattributes ->> Receipt Line) — the$id.newaction 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 shipmentcreatePurchaseReturnOrderCredit(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 withdocuments_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),promisedDateandreceivedDate(delivery; receipt posting also sets it), mapped to the order'sreceiptRequestedDate/receiptPromisedDate/deliveryDatebypurchaseOrderLineDateOfOrderDate(purchasing.models.ts). A new line starts on the order's requested and promised dates (upsertPurchaseOrderLinefills them when absent; both line forms default them). A changed order date is copied bycascadePurchaseOrderDateToLines(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'sreceivedDatewith the posting day on every receipt, so a hand-corrected delivery date lasts until the line's next receipt. Pinned byapps/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, becauseupdatePurchaseOrderLineRestatingCompletionsanitizes a missing field to null. - Purchase orders —
updatePurchaseOrder(the details form: header columns only, neverstatus, refused on a finalized order),updatePurchaseOrders(one field of the properties panel, refused on a released order exceptdeliveryDate, andreceiptPromisedDateuntil 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 —purchaseOrderDeleteRefusalinpurchasing.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:submitPurchaseOrderForApprovalsets 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;deletepermission 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 awarning),cancelReturnOrder,reopenReturnOrder,addReturnOrderLine(Draft only),updateReturnOrderLine(post-confirm locks:lockedReturnLineField). - RFQs —
createPurchasingRfq,updatePurchasingRfqs,cancelPurchasingRfq(cancels the linked supplier quotes),finalizePurchasingRfqAndNotify(service.finalizePurchasingRfq, ported fromfinalize-purchasing-rfq, then the emails: the RFQ and line documents, and each line item's original CAD file fromgetItemModelFiles— attached in line order while the total stays underPO_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 typepurchasingRfq, 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 throughshareLinkContext,~/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 shapeusePlanningActions(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), stepsleaseSetupSteps= Details → Assets → Payments → Accounting → Review (ui/Leases/LeaseSetupSteps.tsx,path.to.leaseSetup(id, step)).new.tsxrenders step 1 (LeaseDetailsForm: Lessor — supplier, site, contact and the lease's Location —, Term — commencement and a Duration copied from the AR contract:leaseDurations12 / 24 / 36 / 48 / 60 months,open,custom+ End Date;leaseEndDateturns it into the end date inleaseTermColumns(throughresolveLeaseDates),leaseDurationOfreads 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,leaseIdfrom theleasesequence,discountRatefromcompanySettings.leaseIncrementalBorrowingRate— a failed settings read is logged and sends the user back to the list rather than default the rate to 0), then redirects tosetup/assets.$id.setup(the index) opens the Assets step.$id.setup.tsxis 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 byleaseActivationGaps— no asset, an asset with no row, a foreign currency — mirroringactivateBlocker).$id.setup.detailssaves the details withupdateDraftLease, 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 withupdate.tsx). Assets (LeaseAssetsGrid, copied from the rental agreement'sRentalUnitsGrid): Add Asset ($id.lines.new,create: purchasing: description, serial, payment), cells for description, serial number, location and payment ($id.$lineId.update) — both throughsaveDraftLeaseLine, 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 throughupdate.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 fromgenerateLeasePaymentsat the asset's own payment (escalation on each anniversary of the commencement, a short last period prorated by days, a Purchase Option row onendDateonly when reasonably certain; a row due beforeinvoiceFromDateisSkipped, 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 inLeasePaymentForm) and "Regenerate from Terms" stay. Accounting (LeaseAccounting):LeaseClassificationPreviewlive 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, orintent=removeto 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$idloader reads withleaseOpeningAsOf, the read-only mirror of activation'sresolveAccountingPeriod),LeaseCommencementPreview(ROU / liability per asset). Opening a Draft ($id._index,$id.details,$id.$lineId.details) sends anyone withupdate: purchasingto its setup (draftLeaseSetupPath, step Assets); a viewer sees the page.insertLeaseandupdateDraftLeasewrite only the pickedleaseTermColumns;saveDraftLeaseLineonly the pickedleaseLineColumns(never status, classification or measurement);updateLeaseDetailsonlyleaseDetailFields.deleteLeaseLine,upsertLeasePaymentanddeleteLeasePaymentrefuse a lease that is not Draft (LEASE_NOT_DRAFT);upsertLeasePaymentmatches the row's own lease and asset and sets Pending / Skipped frominvoiceFromDate; every delete reports a row it did not find. The lease dates are realYYYY-MM-DDdates (leaseValidator,leasePaymentValidator, the Modify / Terminate / Purchase validators). - Open-ended leases (spec Addendum A10) —
endDateNULL. Every asset is Short-Term:activateposts nothing and writes no schedule, and refuses withOPEN_ENDED_NEEDS_EXPEDIENT(both fixes named;OpenEndedExpedientNoticelinks them on the Accounting and Review steps and in the Activate dialog,leaseActivationGapsgapopenEndedWithoutExpedient) whilecompanySettings.leaseShortTermExpedientis off. Payment rows are whole periods throughopenEndedLeaseHorizon(the start of the period after today's): the Draft setup cuts the first, andcreate-lease-invoices(rollOpenEndedLeasePayments, every Active open-ended lease, per active asset only after its last Rent row —cutLeasePaymentRowswithafter) 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 thepost-leaseserver function, permissionupdate: purchasing, payload{ type, leaseId, … }(payloadValidator, same file); Terminate and Purchase addleaseLineId, Modify alineslist of{ leaseLineId, paymentAmount }). Each action is ONE Kysely transaction that locks the lease first (lockLease, thenreadLines). Every action that posts needs the lessee account defaults plus the asset gain / loss on disposal defaults (LESSEE_ACCOUNTS_REQUIRED). All lessee journals aresourceType 'Lease', linesdocumentType '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, inpurchasing.service.ts(pinned byapps/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 aSkippedpayment 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).measureAssetclassifies each asset (classifyLesseeLeasewithcompanySettings.leaseShortTermExpedientand 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 ONELease Commencement LSE…journal (Dr Right-of-Use Assets / Cr Lease Liabilities at each asset's PV), andwriteScheduleswrites each asset's lease months plus theirInterestandAmortizationrun 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).updateLineMeasurementswrites every asset's result in one statement.- Commenced before the cutover — when
commencementDate<companySettings.accountingCutoverDate,activatepostsLease 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 toretainedEarningsAccount(openingBalanceLines). Schedule lines before the date are written withpostedAtand their run rowsPostedwith no journal, and the Pending payments the schedule pays in those months are setSkipped(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 noleaseEvent(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 negatedVOID <description>copy dated today (voidLeaseJournal, through the sharedinsertNegatedJournalinshared.service.ts), refused when it predates the cutover, and the schedule is deleted.modify/terminate/purchaseshareprepareover 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 (cutLeasePaymentRowswithfrom): 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 oneLease 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 aTermination Penaltyrow, postsLease Termination LSE… <asset>(gain / loss toassetGainOnDisposalAccount/assetLossOnDisposalAccount) and sets the assetTerminated. Purchase (one asset; refused for Short-Term, and with neither apurchaseOptionAmountnorownershipTransfers— 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), postsLease Purchase LSE… <asset>, inserts an ActivefixedAssetat the asset's location with its serial number, and sets the assetPurchased+fixedAssetId. When no active asset is left,endAssetgives the lease the last asset's status and end date.
- Invoicing —
createLeaseInvoices(purchasing.service.ts, ported from thecreate-lease-invoicesserver function) ({ asOf, leaseId? },update: purchasing+create: invoicing): per lease that is Active, Expired, Terminated or Purchased with a Pending row due on or beforeasOf, ONE DraftpurchaseInvoiceper due date with oneLeaseline per row, described with the asset (leasePaymentDescription) at the asset's location, the rows stampedInvoiced+purchaseInvoiceLineId. Each lease is its own transaction; a failure is returned infailures, never thrown. Called daily by the Inngestrecurring-billingjob 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/utilslease-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 (itspurchaseInvoiceLineIdis not this line). VOID returns the rows to Pending and stampsvoidedPurchaseInvoiceId. - 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; thepurchaseInvoiceLine_release_lease_paymenttrigger releases a row on any delete of its line as the backstop). The invoicing service functionsdeleteDraftPurchaseInvoice/deleteDraftPurchaseInvoiceLinecall them. No plain purchase invoice delete is published: the building blockdeletePurchaseInvoiceLinechecks 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'sinvoiceNotificationGrouponce per date (LeaseCriticalDate,packages/jobs/src/invoicing/lease-reminders.tsdueLeaseReminders+stampLeaseReminders, which stamps the date reminded and skips a date that moved since) whennoticeDateorendDateis withincompanySettings.leaseReminderDays, and expires (expireLeases) every Active lease past itsendDatewith 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'sLeasePayments,LeaseScheduleandLeaseEvents. The actions and their modals live inuseLeaseAssetActions, as the rental's inuseRentalLineActions. 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 fromleaseAssetBalances, the same helper as the asset page),LeasePaymentsandLeaseEventsfor every asset (an Asset column). The header (LeaseHeader; a Draft activates from its setup) has Modify, Cancel (disabled unlesscanCancelLease: every asset Active, noleaseEvent, 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.LeasePropertieskeeps the name, owner, notice date and notes editable once started (throughupdate.tsx); every other term is read only. Every decision the screens make mirrorspost-leaseand lives inui/Leases/utils.ts(pinned byutils.test.ts): the activation gaps (incl.skippedPayment,skippedPaymentBlockers, withLeasePolicy.openingAsOfwhen 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/utilslease-math.ts, whichpostLeaseAction(purchasing.service.ts) posts from. The Accounting step's classification table has Override and, on an overridden asset, Remove Override (postsintent=removeto$id.$lineId.classification). Amounts render with~/components/Money(shared withRentalMoney).
Key lease service functions
getLeases/getLease(theleasesview) /getLeaseLines/getLeasePayments/getLeaseSchedule(schedule lines + their run rows) /getLeaseEvents/getLeaseRelatedDocuments(purchase invoices with a Lease line, and journals withdocumentType '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-onlyupdateDraftLease(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/modifyLeaseandterminateLeaseLine/purchaseLeaseLine(purchasing.server.ts), each oneservice.postLease(ctx, { type, leaseId, … }), which checks the lease is the company's and runspostLeaseActionthroughinvokePosting;overrideLeaseLineClassification/removeLeaseLineClassificationOverridewrite the override (update: accounting)
Leases safety
- Never write
lease.status,leaseLine.status, the classification, the measurement columns,leaseScheduleLineor the lease'srevenueRecognitionSchedulerows from app code. Every lifecycle change goes throughpost-lease. - Delete a purchase invoice (or a line) that may carry Lease lines with the
*ReleasingLeasesfunctions.leasePayment.purchaseInvoiceLineIdhas no FK; thepurchaseInvoiceLine_release_lease_paymenttrigger 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 onlyleaseDetailFieldschange (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.leasePaymentIdis set only bycreate-lease-invoices;upsertPurchaseInvoiceLinedrops it on create and never rewrites it on update.
Related Modules
- inventory — receipts consume PO lines;
purchaseOrderLine.quantityReceivedupdated on receipt - items —
purchaseOrderLine.itemId→ item master; supplier parts pricing in items module (supplierPart) - production — jobs link to PO lines via
jobIdfor 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