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.
Lease Accounting (ASC 842 / IFRS 16) — Lessee + Lessor Subledger
Status: in-progress Author: Claude (readiness program, GAP-2) Date: 2026-07-04 Tracking issue: crbnos/carbon#1056 Readiness finding: GAP-2 (
.ai/specs/2026-07-03-public-company-readiness.md) Scope note (2026-09-22): the LESSOR slice (operating income, sales-type commencement, net-investment schedule, interest income) is superseded by.ai/specs/implemented/2026-09-22-revenue-recognition-rentals-and-contracts.mdPart I (rental agreements); this spec keeps lessee accounting, modifications/remeasurements, disclosures and the IFRS 16 delta. EnumlessorClassificationis shared. Scope note (2026-10-12): the LESSEE slice (lease master, classification, ROU asset and lease liability, effective-interest schedules, modifications, termination and purchase, the monthly lease journals, the "Post lease journals" close task, and the disclosure report) is superseded by.ai/specs/2026-10-11-lessee-leases.md(lessee leases in purchasing, posted by the lease run). This spec now keeps only the IFRS 16 delta.
TLDR
Carbon has zero lease accounting code (verified 2026-07-04: grep -ri lease across migrations and modules/accounting yields only false positives — "release", the Romania ISO code ROU). This spec builds a lease subledger beside fixed assets in the accounting module: a lease master with payment structures, IBR, and term options; PV computation producing an ROU asset + lease liability with effective-interest schedules; ASC 842 operating/finance classification with the correct expense pattern per class; short-term and low-value practical expedients; modifications and remeasurements that re-spread schedules from the effective date; lessor accounting (operating / sales-type / direct financing) with full schema, operating-lessor income posting in v1, and net-investment interest posting in v1 (commencement derecognition JE is system-drafted, user-posted — see Lessor section); monthly lease journals generated by a scheduled Inngest run and posted as accounting-source entries under the period matrix; a "Post lease journals" close-checklist task with an auto-check on due unposted schedule lines; disclosure data (maturity analysis, weighted-average term and discount rate, cash paid); and IFRS 16 single-model treatment as an adjustment-book delta consuming the multi-book generator framework (.ai/specs/2026-07-04-multi-book.md, parallel spec on this branch).
Problem Statement
ASC 842 / IFRS 16 put essentially all leases on the balance sheet. A public-company (or audit-ready) manufacturer with facility, equipment, and vehicle leases must produce, per period and per book: ROU asset and lease liability balances tied to effective-interest schedules, the correct expense pattern (single straight-line lease cost for ASC 842 operating leases; interest + amortization for finance leases and all IFRS 16 leases), remeasured schedules after modifications, and the ASC 842-20-50 / IFRS 16 ¶51+ disclosure package (maturity analysis by year, weighted-average remaining term and discount rate, cash paid for leases). Carbon has none of this; the interim path (FinQuery-style JE upload via GAP-E1) leaves no subledger tying to the GL. Manufacturers also lease out equipment (lessor side) — the ambitious scope Brad approved 2026-07-04 includes lessor classification and posting, not just lessee.
Research Basis
.ai/research/public-company-compliance.md— "842/IFRS 16: ROU/liability amortization schedules per book, maturity analysis"; leases named as ERP-native at mid-market (NetSuite Fixed Assets Lease Accounting precedent); IFRS 16 vs ASC 842 named as the canonical case where "the same lease produces different P&L per book"..ai/rules/fixed-asset-lifecycle.md+20260524143826/27migrations — the sibling subledger whose patterns this spec copies: class table with NOT NULL account FKs, Draft→Posted run batches, application-level calculation (no DB functions),journalEntrySourceTypeadditions..ai/specs/2026-07-02-period-closing.md— persisted close checklist (periodCloseTaskDefinition/periodCloseTask); later features "register their own definitions when they ship". This spec registers one..ai/specs/2026-07-04-multi-book.md(parallel agent, same branch) — adjustment-book generator framework; the IFRS 16 delta here is a registered generator, not a fork of the poster.
Proposed Solution
1. Lease master
One lease table covers both roles (role: Lessee | Lessor) — counterparty is supplierId (lessee) or customerId (lessor). Core fields: readable leaseId (sequence lease), leaseClassId (GL mapping + defaults), commencement date, non-cancellable end date, renewal/termination/purchase options (own table, each with a "reasonably certain" flag that extends the accounting term), IBR (discountRate, annual %, converted to periodic at computation), payment frequency (Monthly/Quarterly/Annual), timing (Advance/Arrears), currency, initial direct costs, incentives received, prepaid rent — all feeding ROU = liability + IDC + prepaid − incentives. Classification inputs live on the lease: underlying-asset fair value, remaining economic life (months), ownership-transfer and specialized-asset flags, residual value guaranteed. Status: Draft → Active (activation computes schedule v1 and posts/drafts the commencement JE) → Terminated/Expired.
Payment structure, not a flat amount: leasePaymentTerm rows (date range, amount per period, optional escalation % per annum) generate the dated fixed cashflows; in-substance-fixed payments are entered as fixed. Variable payments (usage/sales-based, and index-linked changes) are never in the liability — leaseVariablePayment rows are recorded as incurred and expensed by the monthly run (ASC 842: index-linked payments stay measured at the commencement index; rate changes hit variable expense. IFRS 16 remeasures on index change — handled as a remeasurement event, see §4, and flagged as IFRS-book-relevant).
2. PV computation, schedules, classification
buildLeaseSchedule() (in accounting.utils.ts, beside buildDepreciationLines()) discounts the fixed cashflows at the periodic IBR and emits one leaseScheduleLine per period carrying both expense patterns so later books/reclassifications never recompute: openingLiability, paymentAmount, interestAmount, principalAmount, closingLiability, rouAmortizationFinance (straight-line ROU/term), leaseCostOperating (total cost/term), rouAmortizationOperating (plug = operating cost − interest). The last line absorbs rounding so the liability closes to exactly 0.
Classification (ASC 842-10-25-2) is computed at activation and stored with its inputs: (a) ownership transfers; (b) purchase option reasonably certain; (c) term ≥ major part of remaining economic life (policy threshold, default 75%); (d) PV of payments + guaranteed residual ≥ substantially all of fair value (default 90%); (e) specialized asset. Any test true ⇒ Finance, else Operating. Thresholds live on companySettings; a manual override with required reason is allowed and audit-logged.
Practical expedients: isShortTerm (term ≤ 12 months, no reasonably-certain purchase option — policy election on companySettings, default on) and isLowValue (IFRS-only election, threshold default $5,000) bypass capitalization entirely: no liability/ROU, straight-line expense line in the monthly run, and separate disclosure buckets for cash paid.
Worked example (acceptance baseline). 36-month lease, $10,000/month in arrears, 6% annual IBR (0.5%/month): initial liability = 10,000 × (1 − 1.005⁻³⁶)/0.005 = $328,710.16 = initial ROU (no IDC/incentives). Month 1: interest $1,643.55, principal $8,356.45, closing liability $320,353.71. Finance pattern month 1: interest $1,643.55 + ROU amortization $9,130.84 (= 328,710.16/36) = $10,774.39 expense. Operating pattern month 1: single lease cost $10,000.00, ROU amortization plug $8,356.45.
3. Journal patterns (lessee)
| Event | Finance | Operating |
|---|---|---|
| Commencement | Dr ROU asset / Cr Lease liability (+ Cr Cash for IDC, Dr for incentives) | same |
| Monthly — payment | Dr Lease liability (principal) + Dr Interest expense / Cr AP‑lease clearing | Dr Operating lease expense (leaseCostOperating) / Cr AP‑lease clearing (payment); Dr Lease liability (principal) / Cr Accumulated ROU amortization (plug) |
| Monthly — amortization | Dr ROU amortization expense / Cr Accumulated ROU amortization (SL) | (in the plug above — single expense line preserved) |
| Variable / short-term / low-value | Dr Variable (or Short-term) lease expense / Cr AP‑lease clearing | same |
The credit leg posts to a lease clearing account relieved by the existing AP invoice/payment flow (leases are invoiced by real suppliers); companies not entering supplier invoices for rent can map clearing = cash. journalEntrySourceType gains 'Lease' (precedent: 'Asset Depreciation').
4. Modifications and remeasurements
leaseEvent records every reassessment with reason (Term Change, Payment Change, Index Change (IFRS), Option Reassessment, Partial Termination, Full Termination), effective date, revised inputs, and the liability before/after. Processing: schedule lines from the effective period forward are superseded (scheduleVersion bump; old lines kept, flagged), the liability is re-PV'd at the revised IBR when required (term/option changes) or the original rate (index changes under IFRS), and ROU is adjusted by the liability delta. Partial termination reduces ROU proportionately and posts a gain/loss; full termination derecognizes both and posts gain/loss. Modifications that add an ROU at market rate for an additional asset are a new lease (per both standards) — the UI offers "create linked lease". Posted history is never mutated — remeasurement affects only unposted future lines plus one adjustment JE at the effective date (period-close-safe by construction).
5. Lessor accounting (the ambitious part)
Same lease table, role = 'Lessor', own classification enum (Operating / Sales-Type / Direct Financing) using the mirrored ASC 842-10-25-2/-3 tests (sales-type: any lessee-finance criterion; direct financing: PV + third-party residual guarantee ≥ substantially all + collection probable).
- Operating lessor — full posting in v1. Underlying asset stays on
fixedAssetand depreciates normally (existing runs; the lease linksfixedAssetId). Monthly run posts straight-line lease income: Dr Lease receivable (clearing → AR invoice) / Cr Lease income; uneven cash vs straight-line income accrues to a straight-line rent receivable/liability account on the class. - Sales-type / direct financing — schema + schedules + interest posting in v1; commencement derecognition system-drafted, user-posted. The schedule engine reuses
leaseScheduleLinewith lessor semantics (openingLiability≡ opening net investment;interestAmount≡ interest income; residual accretes via a final unguaranteed-residual row). The monthly interest-income accrual posts automatically in v1 (same poster, Dr Net investment / Cr Interest income; Dr Lease clearing / Cr Net investment for cash). The commencement JE (derecognize inventory/asset at carrying amount, recognize net investment, selling profit/COGS for sales-type) is generated as a Draft journal proposal the user reviews and posts, because automated derecognition must integrate with item costing/inventory relief that GAP-3 (standard cost, revaluation) has not landed yet — auto-posting a COGS relief against an unfinished costing layer would corrupt inventory valuation. This is a schema-now/auto-post-later cut on one JE only; everything downstream (net-investment schedule, interest income, receipts) posts automatically in v1.
6. Monthly run + close checklist
An Inngest cron (packages/jobs, monthly, per company — pattern GAP-4.1 will reuse for depreciation) creates a Draft leaseRun (leaseRunId readable, periodEnd, status Draft|Posted — mirrors depreciationRun) with one leaseRunLine per due item: unposted leaseScheduleLines with period ≤ periodEnd, variable payments, short-term/low-value expense lines, operating-lessor income. postLeaseRun() (in accounting.server.ts, beside postDepreciationRun()) posts per lease with getOrCreateAccountingPeriod(..., source: "accounting"), stamps journalId on lines, and marks schedule lines Posted. Manual "create run now" button exists (depreciation-run parity).
Close checklist registration: seed a periodCloseTaskDefinition — name "Post lease journals", type Auto, autoCheckKey: 'unposted-lease-schedules', severity Warning (parity with "Post depreciation runs"), ordered directly after it. The evaluator flags any Active lease with unposted schedule lines (or an unposted Draft leaseRun) dated in the period.
7. IFRS 16 delta via adjustment book
Key insight: ASC 842 operating leases are already capitalized — the IFRS 16 difference is expense pattern only, no balance-sheet reclass. The multi-book spec's generator framework gets a registered ifrs16-lease generator that, for each posted operating-lease period, emits into the IFRS adjustment book: Dr Interest expense (interestAmount) + Dr ROU amortization expense (rouAmortizationFinance) / Cr Operating lease expense (leaseCostOperating), net P&L delta = the front-loading difference. Zero recomputation — both patterns are persisted on every schedule line (§2). Finance leases and lessor leases generate no delta. IFRS-only remeasurements (index changes, low-value threshold differences) post book-specific leaseEvent adjustments through the same generator. If multi-book ships later than leases, the generator registers then; nothing here blocks on it.
8. Disclosures
Service-computed, no new posting: maturity analysis (undiscounted remaining fixed payments by each of the next 5 fiscal years + thereafter, less imputed interest, reconciling to the liability — lessor mirror for net investment), weighted-average remaining lease term and weighted-average discount rate (liability-weighted, split operating/finance), cash paid (operating-lease operating cash, finance principal = financing, finance interest = operating, plus short-term/variable buckets), ROU by class. Rendered on a Leases report route with CSV export (table-csv-export pattern).
Design Decisions
| Decision | Choice | Rationale |
|---|---|---|
| GL account mapping | leaseClass table (Real Estate / Equipment / Vehicles seeded), NOT accountDefault columns |
fixedAssetClass precedent is exact: per-class NOT NULL account FKs, seeded classes, class-level defaults. Leases need ~11 accounts × per-class variation (real-estate ROU vs equipment ROU); accountDefault is one row per company and already wide — 11 more columns there loses per-class mapping and violates the sibling subledger's pattern. |
One lease table for both roles |
role column + role-specific nullable columns + CHECK constraints, two classification enums |
Shared 80% (payments, term, IBR, schedules, events, runs); separate tables would duplicate the schedule/event/run machinery. CHECKs keep role integrity (lessee ⇒ supplierId, lessor ⇒ customerId). |
| Schedule stores both expense patterns | rouAmortizationFinance, leaseCostOperating, rouAmortizationOperating on every line |
Makes the IFRS 16 generator a pure reader; reclassification-on-modification re-spreads without recomputing history; costs 3 numeric columns. |
| Remeasurement model | Versioned schedule (supersede future lines), never mutate posted lines | Posted-journal immutability (period-closing MW-1 fold-in) makes in-place edits impossible anyway; versions give the auditor the before/after. |
| Lessor sales-type commencement JE | System-drafted, user-posted in v1; auto-post after GAP-3 costing lands | Auto derecognition needs inventory relief at correct carrying cost; standard costing is dead schema today (GAP-3). One manual-review JE vs corrupting inventory valuation. Interest schedules + posting are fully automatic in v1. |
| Monthly posting vehicle | leaseRun/leaseRunLine Draft→Posted batch, Inngest-proposed |
depreciationRun precedent; approvable batch matches MW-2 approval direction; scheduled proposal fixes the "entirely manual" gotcha fixed assets still have. |
| Source type | Single 'Lease' journalEntrySourceType value |
Terminations/modifications are distinguishable via the lease/event FK on the run line; enum values are irreversible, add sparingly. |
| Multi-tenancy (heuristic 1) | Every new table: companyId, composite PK ("id","companyId"), id('prefix') defaults, audit columns, customFields on master tables |
House convention; child FKs reference composites (tax-spec precedent). |
| Service shape (heuristic 2) | All functions in accounting.service.ts / models in accounting.models.ts; Kysely transactions in accounting.server.ts (postLeaseRun, activateLease, processLeaseEvent); calc in accounting.utils.ts; (client, companyId, ...) → {data, error} |
Leases live beside fixed assets in the accounting module — one service file per module, no new module. |
| RLS (heuristic 3) | Four standard policies per table: SELECT get_companies_with_employee_role() (or _permission('accounting_view') matching fixed-asset tables), writes get_companies_with_employee_permission('accounting_*') |
AR/AP-payments migration pattern (20260630093809). |
| Permissions (heuristic 4) | Routes view/create/update/delete: "accounting"; posting update: "accounting" |
Fixed-asset and depreciation-run route precedent exactly. |
| Forms (heuristic 5) | ValidatedForm + zod (leaseValidator, leaseClassValidator, leasePaymentTermValidator, leaseEventValidator, leaseRunValidator); Drawer overlays for detail |
House convention. |
| Module layout (heuristic 6) | modules/accounting/ui/Leases/; routes x+/lease+/ + x+/lease-run+/ + list pages under x+/accounting+/ |
Mirrors FixedAssets/ + fixed-asset+/ + depreciation-run+/. |
| Backward compatibility (heuristic 7) | Purely additive: new tables, one enum value, companySettings/checklist-seed additions; no existing surface changes |
No frozen surface touched; companies without leases see one new nav item and one auto-passing close task. |
Data Model Changes
One migration pair (enums + tables, fixed-asset pattern) plus a checklist-seed migration.
-- 1) Enum additions (separate migration, fixed-asset precedent)
ALTER TYPE "journalEntrySourceType" ADD VALUE IF NOT EXISTS 'Lease';
CREATE TYPE "leaseRole" AS ENUM ('Lessee', 'Lessor');
CREATE TYPE "leaseStatus" AS ENUM ('Draft', 'Active', 'Terminated', 'Expired');
CREATE TYPE "lesseeClassification" AS ENUM ('Operating', 'Finance');
CREATE TYPE "lessorClassification" AS ENUM ('Operating', 'Sales-Type', 'Direct Financing');
CREATE TYPE "leasePaymentFrequency" AS ENUM ('Monthly', 'Quarterly', 'Annual');
CREATE TYPE "leasePaymentTiming" AS ENUM ('Advance', 'Arrears');
CREATE TYPE "leaseEventType" AS ENUM ('Term Change', 'Payment Change', 'Index Change',
'Option Reassessment', 'Partial Termination', 'Full Termination');
CREATE TYPE "leaseOptionType" AS ENUM ('Renewal', 'Termination', 'Purchase');
-- 2) Policy elections
ALTER TABLE "companySettings"
ADD COLUMN "leaseShortTermExpedientEnabled" BOOLEAN NOT NULL DEFAULT TRUE,
ADD COLUMN "leaseLowValueExpedientEnabled" BOOLEAN NOT NULL DEFAULT FALSE, -- IFRS books only
ADD COLUMN "leaseLowValueThreshold" NUMERIC NOT NULL DEFAULT 5000,
ADD COLUMN "leaseMajorPartThresholdPercent" NUMERIC(5,2) NOT NULL DEFAULT 75,
ADD COLUMN "leaseSubstantiallyAllThresholdPercent" NUMERIC(5,2) NOT NULL DEFAULT 90;
-- 3) leaseClass — GL mapping (fixedAssetClass pattern; seeded Real Estate / Equipment / Vehicles)
CREATE TABLE "leaseClass" (
"id" TEXT NOT NULL DEFAULT id('lcls'),
"companyId" TEXT NOT NULL,
"name" TEXT NOT NULL,
"description" TEXT,
-- lessee accounts (NOT NULL — class is unusable without them)
"rouAssetAccountId" TEXT NOT NULL REFERENCES "account"("id"),
"accumulatedRouAmortizationAccountId" TEXT NOT NULL REFERENCES "account"("id"),
"leaseLiabilityAccountId" TEXT NOT NULL REFERENCES "account"("id"),
"interestExpenseAccountId" TEXT NOT NULL REFERENCES "account"("id"),
"rouAmortizationExpenseAccountId" TEXT NOT NULL REFERENCES "account"("id"),
"operatingLeaseExpenseAccountId" TEXT NOT NULL REFERENCES "account"("id"),
"variableLeaseExpenseAccountId" TEXT NOT NULL REFERENCES "account"("id"),
"leaseClearingAccountId" TEXT NOT NULL REFERENCES "account"("id"),
-- lessor accounts (nullable — required only when a lessor lease uses the class; CHECK at activation)
"leaseIncomeAccountId" TEXT REFERENCES "account"("id"),
"netInvestmentAccountId" TEXT REFERENCES "account"("id"),
"interestIncomeAccountId" TEXT REFERENCES "account"("id"),
"straightLineRentAccountId" TEXT REFERENCES "account"("id"),
"createdBy" TEXT NOT NULL REFERENCES "user"("id"),
"createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
"updatedBy" TEXT REFERENCES "user"("id"),
"updatedAt" TIMESTAMP WITH TIME ZONE,
"customFields" JSONB,
CONSTRAINT "leaseClass_pkey" PRIMARY KEY ("id", "companyId"),
CONSTRAINT "leaseClass_companyId_fkey" FOREIGN KEY ("companyId")
REFERENCES "company"("id") ON DELETE CASCADE ON UPDATE CASCADE
);
-- 4) lease — master (both roles)
CREATE TABLE "lease" (
"id" TEXT NOT NULL DEFAULT id('lse'),
"companyId" TEXT NOT NULL,
"leaseId" TEXT NOT NULL, -- readable, from sequence
"leaseClassId" TEXT NOT NULL,
"role" "leaseRole" NOT NULL DEFAULT 'Lessee',
"status" "leaseStatus" NOT NULL DEFAULT 'Draft',
"name" TEXT NOT NULL,
"supplierId" TEXT, -- lessee role
"customerId" TEXT, -- lessor role
"fixedAssetId" TEXT, -- lessor underlying asset / lessee finance-to-own link
"locationId" TEXT,
"commencementDate" DATE NOT NULL,
"endDate" DATE NOT NULL, -- non-cancellable; options extend accounting term
"discountRate" NUMERIC(8,5) NOT NULL, -- annual IBR % (or rate implicit, lessor)
"paymentFrequency" "leasePaymentFrequency" NOT NULL DEFAULT 'Monthly',
"paymentTiming" "leasePaymentTiming" NOT NULL DEFAULT 'Arrears',
"currencyCode" TEXT NOT NULL,
"initialDirectCosts" NUMERIC NOT NULL DEFAULT 0,
"incentivesReceived" NUMERIC NOT NULL DEFAULT 0,
"prepaidAmount" NUMERIC NOT NULL DEFAULT 0,
-- classification inputs + result
"fairValue" NUMERIC,
"economicLifeMonths" INTEGER,
"ownershipTransfers" BOOLEAN NOT NULL DEFAULT FALSE,
"specializedAsset" BOOLEAN NOT NULL DEFAULT FALSE,
"residualGuaranteed" NUMERIC NOT NULL DEFAULT 0,
"unguaranteedResidual" NUMERIC NOT NULL DEFAULT 0, -- lessor
"lesseeClassification" "lesseeClassification",
"lessorClassification" "lessorClassification",
"classificationOverride" BOOLEAN NOT NULL DEFAULT FALSE,
"classificationOverrideReason" TEXT,
"isShortTerm" BOOLEAN NOT NULL DEFAULT FALSE,
"isLowValue" BOOLEAN NOT NULL DEFAULT FALSE,
-- computed at activation
"initialLiability" NUMERIC, -- lessor: initial net investment
"initialRouAsset" NUMERIC,
"terminationDate" DATE,
"terminationGainLoss" NUMERIC,
"createdBy" TEXT NOT NULL REFERENCES "user"("id"),
"createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
"updatedBy" TEXT REFERENCES "user"("id"),
"updatedAt" TIMESTAMP WITH TIME ZONE,
"customFields" JSONB,
CONSTRAINT "lease_pkey" PRIMARY KEY ("id", "companyId"),
CONSTRAINT "lease_companyId_fkey" FOREIGN KEY ("companyId")
REFERENCES "company"("id") ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT "lease_leaseClass_fkey" FOREIGN KEY ("leaseClassId", "companyId")
REFERENCES "leaseClass"("id", "companyId"),
CONSTRAINT "lease_role_counterparty_check" CHECK (
("role" = 'Lessee' AND "customerId" IS NULL) OR
("role" = 'Lessor' AND "supplierId" IS NULL)
),
CONSTRAINT "lease_leaseId_unique" UNIQUE ("leaseId", "companyId")
);
-- 5) Payment structure + options + variable actuals
CREATE TABLE "leasePaymentTerm" ( -- fixed payments, escalations
"id" TEXT NOT NULL DEFAULT id('lpt'),
"companyId" TEXT NOT NULL,
"leaseId" TEXT NOT NULL, -- FK lease(id, companyId)
"startDate" DATE NOT NULL,
"endDate" DATE NOT NULL,
"amountPerPeriod" NUMERIC NOT NULL,
"annualEscalationPercent" NUMERIC(5,2) NOT NULL DEFAULT 0,
-- audit columns, composite PK, FK, RLS as above
CONSTRAINT "leasePaymentTerm_pkey" PRIMARY KEY ("id", "companyId")
);
CREATE TABLE "leaseOption" ( -- renewal/termination/purchase options
"id" TEXT NOT NULL DEFAULT id('lop'),
"companyId" TEXT NOT NULL,
"leaseId" TEXT NOT NULL,
"optionType" "leaseOptionType" NOT NULL,
"exerciseDate" DATE NOT NULL,
"extensionMonths" INTEGER, -- renewal
"optionAmount" NUMERIC, -- purchase price / termination penalty
"reasonablyCertain" BOOLEAN NOT NULL DEFAULT FALSE, -- true ⇒ in accounting term/liability
CONSTRAINT "leaseOption_pkey" PRIMARY KEY ("id", "companyId")
);
CREATE TABLE "leaseVariablePayment" ( -- expensed as incurred, picked up by the run
"id" TEXT NOT NULL DEFAULT id('lvp'),
"companyId" TEXT NOT NULL,
"leaseId" TEXT NOT NULL,
"paymentDate" DATE NOT NULL,
"amount" NUMERIC NOT NULL,
"description" TEXT,
"leaseRunLineId" TEXT, -- set when posted
CONSTRAINT "leaseVariablePayment_pkey" PRIMARY KEY ("id", "companyId")
);
-- 6) Effective-interest schedule (both roles; lessor: liability columns = net investment)
CREATE TABLE "leaseScheduleLine" (
"id" TEXT NOT NULL DEFAULT id('lsl'),
"companyId" TEXT NOT NULL,
"leaseId" TEXT NOT NULL,
"scheduleVersion" INTEGER NOT NULL DEFAULT 1,
"superseded" BOOLEAN NOT NULL DEFAULT FALSE, -- true when a later version replaces this unposted line
"periodDate" DATE NOT NULL, -- period end
"openingLiability" NUMERIC NOT NULL, -- lessor: opening net investment
"paymentAmount" NUMERIC NOT NULL,
"interestAmount" NUMERIC NOT NULL, -- lessor: interest income
"principalAmount" NUMERIC NOT NULL,
"closingLiability" NUMERIC NOT NULL,
"rouAmortizationFinance" NUMERIC NOT NULL, -- SL ROU/term (also the IFRS-book pattern)
"leaseCostOperating" NUMERIC NOT NULL, -- total cost / term
"rouAmortizationOperating" NUMERIC NOT NULL, -- plug = leaseCostOperating − interest
"postedAt" TIMESTAMP WITH TIME ZONE,
"journalId" TEXT,
CONSTRAINT "leaseScheduleLine_pkey" PRIMARY KEY ("id", "companyId"),
CONSTRAINT "leaseScheduleLine_unique" UNIQUE ("leaseId", "companyId", "scheduleVersion", "periodDate")
);
-- 7) Remeasurement / modification events
CREATE TABLE "leaseEvent" (
"id" TEXT NOT NULL DEFAULT id('lev'),
"companyId" TEXT NOT NULL,
"leaseId" TEXT NOT NULL,
"eventType" "leaseEventType" NOT NULL,
"effectiveDate" DATE NOT NULL,
"revisedDiscountRate" NUMERIC(8,5), -- NULL ⇒ original rate retained (index changes)
"liabilityBefore" NUMERIC NOT NULL,
"liabilityAfter" NUMERIC NOT NULL,
"rouAdjustment" NUMERIC NOT NULL,
"gainLoss" NUMERIC, -- partial/full termination
"newScheduleVersion" INTEGER NOT NULL,
"notes" TEXT,
"journalId" TEXT, -- the adjustment JE
CONSTRAINT "leaseEvent_pkey" PRIMARY KEY ("id", "companyId")
);
-- 8) Monthly run batch (depreciationRun pattern)
CREATE TABLE "leaseRun" (
"id" TEXT NOT NULL DEFAULT id('lrun'),
"companyId" TEXT NOT NULL,
"leaseRunId" TEXT NOT NULL, -- readable
"periodEnd" DATE NOT NULL,
"status" TEXT NOT NULL DEFAULT 'Draft' CHECK ("status" IN ('Draft', 'Posted')),
"postedAt" TIMESTAMP WITH TIME ZONE,
"postedBy" TEXT REFERENCES "user"("id"),
CONSTRAINT "leaseRun_pkey" PRIMARY KEY ("id", "companyId")
);
CREATE TABLE "leaseRunLine" ( -- one per lease per component
"id" TEXT NOT NULL DEFAULT id('lrl'),
"companyId" TEXT NOT NULL,
"leaseRunId" TEXT NOT NULL,
"leaseId" TEXT NOT NULL,
"leaseScheduleLineId" TEXT, -- NULL for variable/short-term/low-value expense lines
"lineType" TEXT NOT NULL CHECK ("lineType" IN
('Schedule', 'Variable', 'Short-Term', 'Low-Value', 'Lessor Income', 'Lessor Interest')),
"amount" NUMERIC NOT NULL,
"journalId" TEXT,
CONSTRAINT "leaseRunLine_pkey" PRIMARY KEY ("id", "companyId")
);
-- RLS: all tables — 4 policies each, e.g.
ALTER TABLE "lease" ENABLE ROW LEVEL SECURITY;
CREATE POLICY "lease_SELECT" ON "lease" FOR SELECT USING (
"companyId" = ANY ((SELECT get_companies_with_employee_permission('accounting_view'))::text[]));
-- INSERT/UPDATE/DELETE with accounting_create / accounting_update / accounting_delete
-- 9) Seeds: 'lease' + 'leaseRun' sequences; GL accounts per company group
-- (ROU Asset, Accumulated ROU Amortization, Lease Liability, ROU Amortization Expense,
-- Operating/Variable Lease Expense, Lease Clearing, Lease Income, Net Investment in Leases,
-- Interest Income — numbers assigned at implementation to fit the seeded chart, fixed-asset
-- seed pattern 20260525084319); 3 leaseClass rows per company; periodCloseTaskDefinition
-- 'Post lease journals' (Auto, autoCheckKey 'unposted-lease-schedules', Warning, after depreciation task)
API / Service Changes
// accounting.service.ts — CRUD + queries (client-first, {data, error})
get/insert/update/deleteLease, getLeases(filters), getLeaseClass(es) + CRUD,
getLeasePaymentTerms/Options/VariablePayments + CRUD (Draft-only mutation),
getLeaseSchedule(leaseId, { version? }), getLeaseEvents(leaseId),
getLeaseRun(s), getLeaseRunLines,
getLeaseMaturityAnalysis(companyId, asOfDate) // disclosure §8
getLeaseWeightedAverages(companyId, asOfDate)
getLeaseCashPaidSummary(companyId, periodRange)
// accounting.server.ts — Kysely transactions
activateLease() // classify, PV, schedule v1, commencement JE (lessee auto; lessor sales-type → Draft JE)
processLeaseEvent() // remeasure: supersede future lines, new version, adjustment JE, gain/loss
postLeaseRun() // per-lease journals, source 'Lease', getOrCreateAccountingPeriod(source: "accounting")
// accounting.utils.ts
buildLeaseSchedule(), classifyLease(), presentValue(), expandPaymentTerms()
// accounting.models.ts — validators + enum arrays (leaseRoles, lesseeClassifications, …)
// packages/jobs — inngest cron 'lease-run-proposal' (monthly per company): insert Draft leaseRun + lines
// close checklist — evaluator 'unposted-lease-schedules' added to getPeriodCloseReadiness auto-check registry
// multi-book (parallel spec) — register generator 'ifrs16-lease' reading posted schedule lines (§7)
Routes (fixed-asset layout): x+/accounting+/leases*, lease-classes*, lease-runs* (lists/new); x+/lease+/$leaseId.{tsx,activate,modify,terminate,delete}; x+/lease-run+/$leaseRunId.{tsx,post,delete}; x+/accounting+/lease-disclosures.tsx.
UI Changes
- Leases table + New Lease form (role, class, counterparty, dates, IBR, expedient flags); detail Drawer with tabs: Payments (terms + options + variable), Schedule (versioned, posted badges), Classification (test results + override), Events, Disclosures snapshot.
- Activate flow shows computed classification, initial liability/ROU, and the commencement JE preview before confirm; Modify/Terminate flows capture the event and preview the re-spread + adjustment JE.
- Lease runs: list + Draft run detail (lines grouped by lease), Post button — depreciation-run parity.
- Lease classes settings page (asset-classes parity). Disclosures report page with maturity table, weighted averages, cash-paid summary, CSV export.
- Flash messages on all transitions; close drawer shows the new task automatically via the checklist substrate.
Acceptance Criteria
- Grep baseline:
lease*tables, services, and routes exist;journalEntrySourceTypecontains'Lease'. - Numeric example: a Lessee lease, 36 months, $10,000/month in Arrears, 6% IBR → activation computes initial liability = initial ROU = $328,710.16 (±$0.01); schedule v1 has 36 lines; line 1 = interest $1,643.55 / principal $8,356.45 / closing $320,353.71; line 36 closes to exactly $0.00 (rounding absorbed on the final line).
- Same lease with
fairValuesuch that PV/FV ≥ 90% classifies Finance; month-1 posted JE set: Dr Interest 1,643.55 + Dr Lease liability 8,356.45 / Cr Lease clearing 10,000.00, and Dr ROU amortization expense 9,130.84 / Cr Accumulated ROU amortization 9,130.84. - Same lease classified Operating (tests all false) posts a single $10,000.00 lease cost and reduces liability 8,356.45 / accumulated ROU amortization 8,356.45; total expense over 36 months equals $360,000.00 under both classifications.
- Payment-timing Advance and quarterly frequency produce correct PV (annuity-due / quarterly rate) — unit tests on
buildLeaseSchedule(). - A 12-month lease with the short-term expedient creates no liability/ROU and posts straight-line expense via run lines of type
Short-Term. - Modification: extending the example lease by 12 months at month 12 with a revised rate creates schedule v2 from month 13, marks unposted v1 lines superseded (posted lines untouched), posts one ROU/liability adjustment JE equal to the liability delta, and the v2 schedule closes to $0.00.
- Partial termination reduces ROU proportionately and posts the gain/loss; full termination derecognizes both balances.
- Lessor operating: monthly run posts Dr Lease clearing / Cr Lease income straight-line; uneven payment terms accrue to the straight-line rent account. Lessor sales-type: activation generates a Draft commencement JE (not auto-posted) and a net-investment schedule; monthly interest income posts automatically; net investment closes to unguaranteed residual at term end.
- Inngest monthly job creates exactly one Draft
leaseRunper company per period (idempotent);postLeaseRunis blocked in Closed periods and allowed in Locked (source"accounting"). - Close checklist for a period with due unposted schedule lines shows "Post lease journals" failing (Warning, skippable with reason); it passes after posting.
- Disclosure service: maturity analysis buckets undiscounted payments by the next 5 fiscal years + thereafter and reconciles (total − imputed interest = liability balance); weighted-average term and rate computed liability-weighted split by classification; cash-paid summary splits operating/financing/short-term/variable.
- IFRS 16 generator (
ifrs16-lease) registered per the multi-book spec emits, for a posted operating-lease month, an adjustment-book JE reclassifying 10,000.00 operating cost into 1,643.55 interest + 9,130.84 amortization (net delta 774.39 in month 1); no delta for finance leases. -
pnpm run generate:types+ scoped typecheck pass; RLS verified on all new tables (4 policies each).
Risks
| Risk | Severity | Mitigation |
|---|---|---|
| Multi-book spec slips — IFRS delta has no generator surface | Med | §7 is read-only over persisted schedule columns; generator registers whenever multi-book lands, nothing else blocks. |
| Sales-type derecognition mispriced while costing (GAP-3) is incomplete | Med | v1 keeps the commencement JE as a system-drafted, user-posted entry; auto-post gated on GAP-3. |
| Rounding drift across 36–120 line schedules | Low | Last-line absorbs residual; unit tests assert exact closure to 0. |
| Enum values are irreversible | Low | Single 'Lease' source value; classification enums mirror the standards verbatim. |
| Index-linked escalations diverge ASC 842 vs IFRS 16 | Med | Modeled as Index Change events flagged IFRS-book-only; primary book keeps commencement-index measurement per ASC 842. |
Open Questions
HARD STOP: Do not proceed with implementation until these are answered.
- Scope: lessee-only vs full? — Resolved (Brad, 2026-07-04): "more ambitious — lessor included." Full lessee accounting incl. modifications/remeasurements + lessor classification with operating-lessor posting and net-investment schedules in v1; sales-type commencement JE system-drafted/user-posted until GAP-3 costing lands (§5).
- GL mapping:
accountDefaultcolumns vsleaseClass? — Resolved in-spec:leaseClass, on thefixedAssetClassprecedent (per-class account sets; see Design Decisions). - IFRS 16 treatment — Resolved in-spec: adjustment-book delta via the multi-book generator framework (
.ai/specs/2026-07-04-multi-book.md); schedule lines persist both expense patterns so the generator is a pure reader. - AP integration depth for lease payments: v1 posts the payment credit to a lease clearing account relieved by normal supplier invoices. Should activation optionally auto-create recurring purchase-invoice templates for the fixed payments (GAP-6 recurring-journal adjacency), or is clearing + manual invoicing acceptable for v1? (Non-blocking for schema; blocks the payments UX copy.) — Answer (Brad, 2026-07-04, ambition heuristic — be ambitious and thorough; back out at /plan stage if needed): Yes — activation auto-creates recurring purchase-invoice templates for fixed payments (riding the close-automation recurring machinery); the lease-clearing + manual-invoice path remains the fallback.
- Seeded account numbers: the chart blocks 1400/2400/7000 are partially occupied by fixed-asset seeds — confirm the exact numbers for the 9 new lease accounts at implementation (cosmetic, but seeds are hard to renumber later). — Answer (Brad, 2026-07-04, ambition heuristic — be ambitious and thorough; back out at /plan stage if needed): Seed dedicated new accounts; exact numbers assigned at plan stage after a chart-collision audit (mechanical).
Changelog
- 2026-07-04: Created — GAP-2 remediation spec. Scope resolved by Brad same day ("more ambitious"): full lessee (modifications/remeasurements included) + lessor (operating posting v1; sales-type/direct-financing schedules + interest posting v1, commencement JE drafted not auto-posted pending GAP-3) + IFRS 16 adjustment-book delta (consumes
.ai/specs/2026-07-04-multi-book.mdgenerator framework) + monthly Inngest-proposed lease runs + "Post lease journals" close task + disclosure services. Verified zero pre-existing lease code. - 2026-07-04: Remaining open questions resolved under the program ambition heuristic (ambitious scope now; back-out valves at plan stage).
- 2026-09-22: Lessor slice superseded by
.ai/specs/implemented/2026-09-22-revenue-recognition-rentals-and-contracts.mdPart I (rental agreements carry the lessor operating + sales-type accounting). Lessee scope unchanged.