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.
Lessee leases and the lease run — implementation plan
Spec: .ai/specs/2026-10-11-lessee-leases.md Research: .ai/research/2026-10-11-lessee-lease-accounting.md Run log: .ai/runs/2026-10-11-lessee-leases.md Branch: tirana
Plan decisions not in the spec
| # | Decision | Reason |
|---|---|---|
| P1 | The run pages stay at x+/revenue-recognition-run+/$runId* for both run types. Only the list and "new" routes are new (x+/accounting+/lease-runs*.tsx). The run page reads run.type for its title, breadcrumb and confirm texts. |
One set of post / reverse / recalculate / repeat / delete actions; the user sees two lists. |
| P2 | A leases view feeds the list (supplier name, current liability, next due date). |
Same as the rentalAgreements view. |
| P3 | A lease month runs from the commencement day: month m covers addMonths(commencement, m) to the day before addMonths(commencement, m + 1). periodDate is its last day. |
A mid-month commencement needs no proration; the run posts each row in the calendar month of its periodDate. |
| P4 | A payment's discount exponent k (months from commencement): Advance = months from commencement to periodStart; Arrears = months from commencement to the day after periodEnd; the purchase option and a termination penalty = the term length. |
One rule for edited rows and generated rows. |
| P5 | A last payment period shorter than the frequency is prorated by days (round(amount × days ÷ daysInFullPeriod, decimals)). |
Terms that do not divide evenly still close on endDate. |
| P6 | "Posted" for a lease month means its revenueRecognitionSchedule rows have status = 'Posted'. |
The enable's step 5 sets pre-cutover rows Posted without stamping leaseScheduleLine. |
| P7 | The ROU cost lives on lease.rouAssetCost; accumulated amortization is the sum of rouAmortization of Posted months. |
Termination and Purchase need both numbers; no GL read. |
| P8 | Payment rows can be edited only while the lease is Draft. After activation, rows change only through Modify, Terminate and Purchase. | The PV and the schedule read the rows. |
Progress
- Task 1: Add the enum migration
- Task 2: Add the lessee lease migration
- Task 3: Add RLS, audit, backup refs; apply and regenerate types
- Task 4: Fix the type fallout and register the new accounts and source type
- Task 5: Add the pure lease math (
lease-math.ts) - Task 6: Give the run server functions a run type
- Task 7: Give the run journal builder a run type and a lessee source
- Task 8: Make post, reverse and delete type-aware
- Task 9: Thread the run type through the legacy backfill
- Task 10: Add the Lease Runs list and make the run page type-aware
- Task 11: Add the lease run to the close wizard, the monthly job and the journal guards
- Task 12: Add the lease validators
- Task 13: Add the lease service functions
- Task 14: Add the
post-leaseserver function: activate and cancel - Task 15: Add Modify, Terminate and Purchase to
post-lease - Task 16: Add the lease list, new, shell, details and update routes
- Task 17: Add the payment row routes
- Task 18: Add the lifecycle routes
- Task 19: Build the lease UI components
- Task 20: Add the nav entry and paths
- Task 21: Add the Lease line type to the purchase invoice form
- Task 22: Post and void Lease lines
- Task 23: Release payment rows when a purchase invoice or line is deleted
- Task 24: Add the
create-lease-invoicesserver function - Task 25: Run lease invoicing, expiry and reminders from the daily job
- Task 26: Add the lease policy settings
- Task 27: Add the cutover open items
- Task 28: Add the Lease Liabilities report
- Task 29: Link journals to leases
- Task 30: Opening journal for a lease entered after the enable
- Task 31: Update AGENTS.md, rules and docs
- Task 32: Run the full verification sweep
- Task 33: Extract and translate the new strings
- Task 34: Verify in the browser
Dependencies
- Task 2 needs Task 1. Task 3 needs Task 2. Task 4 needs Task 3.
- Task 5 needs nothing. It can run in parallel with Tasks 1–4.
- Tasks 6–9 need Task 4. Task 7 is independent of Task 6. Task 8 needs Tasks 6 and 7. Task 9 needs Task 7.
- Task 10 needs Task 8. Task 11 needs Tasks 6 and 8.
- Task 12 needs Task 4. Task 13 needs Task 12.
- Task 14 needs Tasks 5, 7 and 13. Task 15 needs Task 14.
- Tasks 16–18 need Tasks 13–15. Task 19 needs Task 16. Task 20 is independent of Tasks 16–19 but lands with them.
- Task 21 needs Task 4. Task 22 needs Task 21. Task 23 needs Task 21.
- Task 24 needs Tasks 13 and 22. Task 25 needs Task 24.
- Tasks 26, 27, 28 and 29 need Task 14. They are independent of each other.
- Task 30 needs Task 14.
- Task 31 needs Tasks 1–29. Task 32 needs Task 31. Task 33 needs Task 32. Task 34 needs Task 33.
Merge notes (projects branch projects-wbs-research-spec, worktree kelowna)
- Both branches add
20261011…migrations. The branch that merges second re-stamps its migrations after the other's, then runspnpm --filter @carbon/checks clobbers. - Expect textual conflicts in
post-purchase-invoice/index.ts,scheduled/recurring-billing.ts,packages/notifications/src/index.ts,POSTING_POLICY,seed-data.ts,seed-companyandAccountDefaultsForm.tsx. Keep both sides. - The run page's Project Revenue card (projects branch) shows only when
run.type === "Revenue Recognition". - Task 6 step 3 states the merged
runRowSynthesizers(type, extra)signature.
Conventions for every task
- Read
.ai/lessons.mdsections "A migration file created while migrations are running is recorded as applied — empty", "A new FK on a busy table breaks bare PostgREST embeds of it (TS2589)" and "A sales invoice's documents…" (the opportunity lesson) before Task 1. - Never create or edit a migration file while
pnpm db:migrateorcrbn upruns. - In a server function, every Kysely read and write filters on
companyId. - Refusals the user must read throw
InvalidInputErrorfrom../errors. A missing record throwsNotFoundError. - Every new source file starts with its SPDX header. Run
pnpm --filter @carbon/checks license-headersafter you create files. Do not type the header by hand. - Never use JS
Date. UseYYYY-MM-DDstrings with the helpers in@carbon/database/revenue-schedule(parseIsoDate,formatIsoDate,addDays,monthEnd,daysBetweenInclusive) anddatetime/getCompanyTimeZonefor "today". - Never round with
Math.roundor.toFixed. Useroundfrom@carbon/database/precision(internal scale) andcurrency.decimalPlacesfor billed amounts. - Never rebuild the database. Never run a whole-repo typecheck.
- A database test skips without a local
SUPABASE_DB_URL. Before a database test, export the worktree's URL from.env.local(export SUPABASE_DB_URL=$(grep '^SUPABASE_DB_URL' .env.local | cut -d= -f2-)). A shell value overrides the worktree's. - Scoped checks:
pnpm exec turbo run typecheck --filter=<pkg>; testspnpm --filter <pkg> test; ERP testscd apps/erp && pnpm exec vitest run <file>. - UI copy goes through Lingui (
t\…`,). Read.claude/rules/i18n-lingui-system.md` before Task 16.
Task 1: Add the enum migration
Depends on: none Files:
- Create:
packages/database/supabase/migrations/<timestamp>_lessee-lease-enums.sql - Copy from (precedent):
packages/database/supabase/migrations/20261006220301_fleet-rental-lease-enums.sql
Steps:
- Run
pnpm db:migrate:new lessee-lease-enums. - Write this SQL into the new file:
-- Enums for lessee leases and the lease run.
-- Enum additions live alone: ADD VALUE cannot be used in the same transaction as the value.
-- Spec: .ai/specs/2026-10-11-lessee-leases.md
ALTER TYPE "payableLineType" ADD VALUE IF NOT EXISTS 'Lease';
ALTER TYPE "journalLineDocumentType" ADD VALUE IF NOT EXISTS 'Lease';
ALTER TYPE "journalEntrySourceType" ADD VALUE IF NOT EXISTS 'Lease Run';
ALTER TYPE "revenueScheduleType" ADD VALUE IF NOT EXISTS 'Amortization';
DO $leaseenums$
BEGIN
IF NOT EXISTS (SELECT 1 FROM pg_type WHERE typname = 'leaseStatus') THEN
CREATE TYPE "leaseStatus" AS ENUM ('Draft', 'Active', 'Expired', 'Terminated', 'Purchased', 'Cancelled');
END IF;
IF NOT EXISTS (SELECT 1 FROM pg_type WHERE typname = 'lesseeClassification') THEN
CREATE TYPE "lesseeClassification" AS ENUM ('Operating', 'Finance', 'Short-Term');
END IF;
IF NOT EXISTS (SELECT 1 FROM pg_type WHERE typname = 'leasePaymentFrequency') THEN
CREATE TYPE "leasePaymentFrequency" AS ENUM ('Monthly', 'Quarterly', 'Annual');
END IF;
IF NOT EXISTS (SELECT 1 FROM pg_type WHERE typname = 'leasePaymentStatus') THEN
CREATE TYPE "leasePaymentStatus" AS ENUM ('Pending', 'Invoiced', 'Skipped');
END IF;
IF NOT EXISTS (SELECT 1 FROM pg_type WHERE typname = 'leasePaymentType') THEN
CREATE TYPE "leasePaymentType" AS ENUM ('Rent', 'Purchase Option', 'Termination Penalty');
END IF;
IF NOT EXISTS (SELECT 1 FROM pg_type WHERE typname = 'leaseEventType') THEN
CREATE TYPE "leaseEventType" AS ENUM ('Modification', 'Termination', 'Purchase');
END IF;
IF NOT EXISTS (SELECT 1 FROM pg_type WHERE typname = 'runType') THEN
CREATE TYPE "runType" AS ENUM ('Revenue Recognition', 'Lease');
END IF;
END $leaseenums$;
Verify:
ls packages/database/supabase/migrations | tail -1
# Expected: <timestamp>_lessee-lease-enums.sql, with a timestamp newer than 20261010031417 and HHMMSS not 000000
Out of scope: tables, data. Do not apply yet.
Task 2: Add the lessee lease migration
Depends on: Task 1 Files:
- Create:
packages/database/supabase/migrations/<timestamp>_lessee-leases.sql - Copy from (precedent):
20261006220201_revenue-recognition-core.sqllines 6–152 (account defaults, accounts, backfill, sequence, close task);20261006220501_rental-agreements.sqllines 135–194 (table style);20260811123616_widen-purchasing-scale.sql(thepurchaseInvoiceLinesview);20261006221701_period-run-months.sql:47(the Draft index)
Steps:
- Run
pnpm db:migrate:new lessee-leases. - Write section 1, settings:
ALTER TABLE "companySettings"
ADD COLUMN IF NOT EXISTS "leaseIncrementalBorrowingRate" NUMERIC NOT NULL DEFAULT 6,
ADD COLUMN IF NOT EXISTS "leaseShortTermExpedient" BOOLEAN NOT NULL DEFAULT TRUE,
ADD COLUMN IF NOT EXISTS "leaseReminderDays" INTEGER NOT NULL DEFAULT 90;
- Write section 2, account defaults. Copy the
$rrfk$block (ADD COLUMN IF NOT EXISTS + FK loop) for these 7 columns:rightOfUseAssetAccount,accumulatedRightOfUseAmortizationAccount,leaseLiabilityAccount,operatingLeaseExpenseAccount,variableLeaseExpenseAccount,rightOfUseAmortizationExpenseAccount,leaseInterestExpenseAccount. Name the DO block$leasefk$. - Write section 3, accounts. Copy the
$rraccounts$block as$leaseaccounts$with these VALUES rows (number, name, class, accountType, incomeBalance, consolidatedRate, parent group name, sibling numbers):
| number | name | class | accountType | incomeBalance | consolidatedRate | parent | siblings |
|---|---|---|---|---|---|---|---|
| 1450 | Right-of-Use Assets | Asset | Other Asset | Balance Sheet | Current | Other Assets | 1410, 1420 |
| 1460 | Accumulated Amortization – Right-of-Use Assets | Asset | Other Asset | Balance Sheet | Current | Other Assets | 1410, 1420 |
| 2440 | Lease Liabilities | Liability | Long Term Liability | Balance Sheet | Current | Long-Term Liabilities | 2410, 2420 |
| 6140 | Operating Lease Expense | Expense | Expense | Income Statement | Average | Operating Expenses | 6100, 6110 |
| 6130 | Variable Lease Expense | Expense | Expense | Income Statement | Average | Operating Expenses | 6100, 6110 |
| 6330 | Amortization – Right-of-Use Assets | Expense | Other Expense | Income Statement | Average | Depreciation & Amortization | 6310, 6320 |
| 7020 | Interest Expense – Leases | Expense | Other Expense | Income Statement | Average | Other Expenses | 7010 |
If an accountType or consolidatedRate value above is not in its enum, STOP and report — read the seeded rows for 1420, 2410, 6110, 6320 and 7010 in packages/database/src/seed-data.ts and use their values.
5. Write section 4, backfill. Copy the $rrdefaults$ block as $leasedefaults$ with the 7 (column, number, name) rows from steps 3–4.
6. Write section 5, sequences, copying the rentalAgreement sequence insert twice: ('lease', 'Lease', 'LSE') and ('leaseRun', 'Lease Run', 'LR').
7. Write section 6, the close task. Copy the close-task insert with name 'Post lease journals', autoCheckKey 'unposted-lease-schedules', sortOrder 5, severity 'Warning'.
8. Write section 7, the tables. Use the spec's "Data Model Changes" SQL for lease, leasePayment, leaseScheduleLine and leaseEvent, with these additions:
- Every table:
createdBy/createdAt/updatedBy/updatedAtaudit columns,CONSTRAINT "<t>_pkey" PRIMARY KEY ("id", "companyId"), the company FKON DELETE CASCADE ON UPDATE CASCADE, andCREATE INDEX IF NOT EXISTSoncompanyId,createdByand every FK column. lease: add"invoiceFromDate" DATE NOT NULLand"rouAssetCost" NUMERIC; FKs(supplierId, companyId) → supplier,(locationId) → location,assignee → user;"customFields" JSONB.leasePayment,leaseScheduleLine,leaseEvent: FK("leaseId", "companyId") REFERENCES "lease"("id", "companyId") ON DELETE CASCADE.leasePayment: unique index("companyId", "leaseId", "dueDate", "paymentType"); index("companyId", "status", "dueDate").
- Write section 8, links:
ALTER TABLE "purchaseInvoiceLine"
ADD COLUMN IF NOT EXISTS "leaseId" TEXT,
ADD COLUMN IF NOT EXISTS "leasePaymentId" TEXT;
-- FKs: ("leaseId","companyId") → lease ON DELETE RESTRICT;
-- ("leasePaymentId","companyId") → leasePayment ON DELETE SET NULL ("leasePaymentId")
-- CHECK "purchaseInvoiceLine_lease_check":
-- ("invoiceLineType" = 'Lease') = ("leaseId" IS NOT NULL) AND ("leasePaymentId" IS NULL OR "leaseId" IS NOT NULL)
-- Indexes on leaseId and leasePaymentId.
ALTER TABLE "revenueRecognitionSchedule"
ADD COLUMN IF NOT EXISTS "leaseId" TEXT,
ADD COLUMN IF NOT EXISTS "leaseScheduleLineId" TEXT;
-- FKs: ("leaseId","companyId") → lease ON DELETE CASCADE;
-- ("leaseScheduleLineId","companyId") → leaseScheduleLine ON DELETE CASCADE
-- Index ("companyId","leaseId").
ALTER TABLE "revenueRecognitionRun"
ADD COLUMN IF NOT EXISTS "type" "runType" NOT NULL DEFAULT 'Revenue Recognition';
DROP INDEX IF EXISTS "revenueRecognitionRun_one_draft_per_period";
CREATE UNIQUE INDEX IF NOT EXISTS "revenueRecognitionRun_one_draft_per_period"
ON "revenueRecognitionRun" ("companyId", "type", "periodEnd")
WHERE "status" = 'Draft';
Write each FK as a guarded ALTER TABLE … ADD CONSTRAINT inside a DO block that checks pg_constraint, as 20261006220501 lines 380–387 do.
10. Write section 9, release rental rows from Draft revenue runs:
WITH released AS (
DELETE FROM "revenueRecognitionRunLine" l
USING "revenueRecognitionRun" r, "revenueRecognitionSchedule" s
WHERE l."runId" = r."id" AND l."companyId" = r."companyId"
AND r."status" = 'Draft' AND r."type" = 'Revenue Recognition'
AND s."id" = l."scheduleId" AND s."companyId" = l."companyId"
AND s."rentalAgreementLineId" IS NOT NULL
RETURNING l."scheduleId", l."companyId"
)
UPDATE "revenueRecognitionSchedule" s SET "runLineId" = NULL
FROM released
WHERE s."id" = released."scheduleId" AND s."companyId" = released."companyId";
DELETE FROM "revenueRecognitionRun" r
WHERE r."status" = 'Draft'
AND NOT EXISTS (
SELECT 1 FROM "revenueRecognitionRunLine" l
WHERE l."runId" = r."id" AND l."companyId" = r."companyId"
);
- Write section 10, the
purchaseInvoiceLinesview. Copy the latestCREATE OR REPLACE VIEW "purchaseInvoiceLines"from20260811123616_widen-purchasing-scale.sqlverbatim. Addls."leaseId" AS "leaseReadableId"andls."name" AS "leaseName"fromLEFT JOIN "lease" ls ON ls."id" = pl."leaseId" AND ls."companyId" = pl."companyId". KeepWITH(SECURITY_INVOKER=true). - Write section 11, the
leasesview:
CREATE OR REPLACE VIEW "leases" WITH(SECURITY_INVOKER=true) AS
SELECT
l.*,
s."name" AS "supplierName",
(SELECT p."dueDate" FROM "leasePayment" p
WHERE p."leaseId" = l."id" AND p."companyId" = l."companyId" AND p."status" = 'Pending'
ORDER BY p."dueDate" LIMIT 1) AS "nextDueDate",
COALESCE(
(SELECT sl."closingLiability" FROM "leaseScheduleLine" sl
JOIN "revenueRecognitionSchedule" rs
ON rs."leaseScheduleLineId" = sl."id" AND rs."companyId" = sl."companyId"
WHERE sl."leaseId" = l."id" AND sl."companyId" = l."companyId" AND rs."status" = 'Posted'
ORDER BY sl."periodDate" DESC LIMIT 1),
l."initialLiability"
) AS "currentLiability"
FROM "lease" l
JOIN "supplier" s ON s."id" = l."supplierId" AND s."companyId" = l."companyId";
- End the file with
NOTIFY pgrst, 'reload schema';.
Verify:
grep -c "CREATE TABLE IF NOT EXISTS" packages/database/supabase/migrations/*_lessee-leases.sql
# Expected: 4
grep -c "CREATE POLICY" packages/database/supabase/migrations/*_lessee-leases.sql
# Expected: 0
Out of scope: RLS policies (Task 3), demo datasets (spec: out of v1).
Task 3: Add RLS, audit, backup refs; apply and regenerate types
Depends on: Task 2 Files:
- Modify:
packages/database/src/authz/manifest.ts— four rules, alphabetical - Modify:
packages/database/src/audit.config.ts— aleaseentity - Modify:
packages/database/src/event-system/attachments.ts—lease: { events: true } - Modify:
packages/jobs/src/backups/id-refs.ts— no-FK id columns - Create (generated):
packages/database/supabase/migrations/<timestamp>_lessee-leases-rls.sql
Steps:
- Add to
manifest.ts, in alphabetical position:lease: company("purchasing", { read: "purchasing_view" }), leaseEvent: company("purchasing", { read: "purchasing_view" }), leasePayment: company("purchasing", { read: "purchasing_view" }), leaseScheduleLine: company("purchasing", { read: "purchasing_view" }), - Add to
audit.config.ts, besiderentalAgreement(lines 285–292):lease: { label: "Lease", tables: { lease: { role: "root" }, leasePayment: { entityIdColumn: "leaseId" } } }. Addlease: "Lease"andleasePayment: "Payment"to the table-label map (lines 735–736). - Add
lease: { events: true },toattachments.tsin alphabetical position. - Add to
ID_REF_COLUMNSinid-refs.ts:lease: ["fixedAssetId"],leaseEvent: ["fixedAssetId"],leasePayment: ["purchaseInvoiceLineId", "voidedPurchaseInvoiceId"]. - Run
pnpm db:migrate. - Run
pnpm --filter @carbon/database authz migration lessee-leases-rls. - Run
pnpm db:migrateagain to record the generated migration. - Run
pnpm run generate:types.
Verify:
grep -n '"leaseStatus"\|"Lease Run"\|leaseIncrementalBorrowingRate' packages/database/src/types.ts | head
# Expected: matches for all three
pnpm --filter @carbon/database exec vitest run src/authz/migration.test.ts
# Expected: passes
If pnpm db:migrate reports the enum migration as applied but types.ts lacks "Lease Run", run the lesson's query on supabase_migrations.schema_migrations, then STOP and report.
Out of scope: typecheck fixes (Task 4).
Task 4: Fix the type fallout and register the new accounts and source type
Depends on: Task 3 Files:
- Modify:
packages/database/src/seed-data.ts— 7 accounts, 7 defaults, 2 sequences, 1 close task - Modify:
packages/database/src/journal-posting-status.ts—OPTIONAL_DEFAULT_ROLES,OPTIONAL_DEFAULT_LABELS - Modify:
packages/database/src/accounting-cutover/shared.ts—ACCOUNT_DEFAULT_COLUMNS - Modify:
packages/database/src/run-journals.ts—REVENUE_LINE_DESCRIPTIONS.Amortization - Modify:
packages/ee/src/accounting/core/models.ts—POSTING_POLICY["Lease Run"] - Modify:
apps/erp/app/modules/accounting/accounting.models.ts— validators,journalEntrySourceTypes,revenueScheduleTypes - Modify:
apps/erp/app/modules/accounting/ui/AccountDefaults/AccountDefaultsForm.tsx— a "Leases (lessee)" group - Modify:
apps/erp/app/components/Icons.tsx—case "Lease Run" - Modify:
apps/erp/app/routes/x+/revenue-recognition-run+/$runId.tsx—sectionLabels.Amortization - Create:
packages/database/supabase/migrations/<timestamp>_lease-run-sync-policy.sql(only if step 8 finds stored settings)
Steps:
- In
seed-data.tsaccounts, add the 7 accounts of Task 2 step 4 after their siblings, each withkey= number andparentKeyfromother-assets,long-term-liabilities,operating-expenses,depreciation,other-expenses. - In
accountDefaults, add the 7 columns → numbers. - In
sequences, addlease(LSE) andleaseRun(LR) besiderentalAgreement. - In
periodCloseTaskDefinitions, add "Post lease journals" (unposted-lease-schedules,sortOrder: 5,Warning,required: true) after "Recognize revenue for the period". - Add the 7 columns to
OPTIONAL_DEFAULT_ROLES(alphabetical) and labels toOPTIONAL_DEFAULT_LABELS("Right-of-Use Assets", "Accumulated Amortization – ROU", "Lease Liabilities", "Operating Lease Expense", "Variable Lease Expense", "Amortization – ROU Assets", "Interest Expense – Leases"). - Add the 7 columns to
ACCOUNT_DEFAULT_COLUMNSbefore"migrationClearingAccount". - Add
Amortization: { debit: "Lease cost recognized", credit: "Right-of-use asset amortized" }toREVENUE_LINE_DESCRIPTIONS. - Add
"Lease Run": { representation: "journal", defaultEnabled: false, defaultGranularity: "individual" }toPOSTING_POLICYafterLease, with a comment "Lease runs. Off by default, as 'Revenue Recognition'." Then find where per-integrationsourceTypessettings are stored:grep -rn "sourceTypes" packages/ee/src/accounting --include=*.ts | grep -v test. If they are stored in a table or JSON column, create migrationlease-run-sync-policythat copies each storedsourceTypes."Revenue Recognition"object tosourceTypes."Lease Run"where"Lease Run"is absent. If the storage is not a single JSON column, STOP and report. - In
accounting.models.ts: addrightOfUseAssetAccount,accumulatedRightOfUseAmortizationAccount,leaseLiabilityAccounttodefaultBalanceSheetAccountValidatorandoperatingLeaseExpenseAccount,variableLeaseExpenseAccount,rightOfUseAmortizationExpenseAccount,leaseInterestExpenseAccounttodefaultIncomeAcountValidator(allz.string().optional()); add"Lease Run"tojournalEntrySourceTypes; add"Amortization"torevenueScheduleTypes. - In
AccountDefaultsForm.tsx, add a groupid: "leases", titlet\Leases (Lessee)`, afterfixed-assets, with the 7 fields. Copy the field shape ofnetInvestmentInLeasesAccount(label, description,badgeType); leave outtermId`. - In
Icons.tsx, addcase "Lease Run":falling through to the"Lease"icon. - In
$runId.tsx, addAmortization: t\Amortization`tosectionLabels`.
Verify:
pnpm exec turbo run typecheck --filter=@carbon/database --filter=@carbon/ee --filter=@carbon/server-functions --filter=erp
# Expected: 0 errors
pnpm --filter @carbon/ee test -- posting-policy
# Expected: passes
Out of scope: run engine behavior (Tasks 6–11).
Task 5: Add the pure lease math (lease-math.ts)
Depends on: none Files:
- Create:
packages/utils/src/lease-math.ts - Create:
packages/utils/src/lease-math.test.ts - Modify:
packages/utils/src/index.ts—export * from "./lease-math"; - Copy from (precedent):
packages/utils/src/lessor-lease.ts(presentValue,classifyLessorLease,buildLessorSchedule,wholeMonthsInTerm)
Steps:
- Import
roundfrom@carbon/database/precision, the date helpers from./revenue-schedule.ts, andclassifyLessorLease,wholeMonthsInTerm,Timingfrom./lessor-lease.ts. - Export
addMonths(date: string, months: number): string. It clamps the day to the target month's length (2027-01-31 + 1 → 2027-02-28). - Export
type LeasePaymentRowInput = { periodStart: string; periodEnd: string; dueDate: string; amount: number; paymentType: "Rent" | "Purchase Option" | "Termination Penalty" }. - Export
generateLeasePayments(args: { commencementDate: string; endDate: string; paymentAmount: number; frequency: "Monthly" | "Quarterly" | "Annual"; timing: Timing; annualEscalationPercent: number; purchaseOptionAmount: number; decimals: number }): LeasePaymentRowInput[]:- Step months = 1, 3 or 12. Period
istarts ataddMonths(commencement, i × step)and ends the day before the next start, capped atendDate. - Amount =
round(paymentAmount × (1 + e/100)^floor(monthsFromStart / 12), decimals). - A last period shorter than
stepmonths is prorated by days (plan decision P5). dueDate=periodStartfor Advance,periodEndfor Arrears.- If
purchaseOptionAmount > 0, append onePurchase Optionrow withperiodStart = periodEnd = dueDate = endDate.
- Step months = 1, 3 or 12. Period
- Export
paymentMonthIndex(row, commencementDate, timing, termMonths): numberper plan decision P4. - Export
presentValueOfPayments(args: { payments: { monthIndex: number; amount: number }[]; annualRate: number }): number=round(Σ amount × (1 + r)^−monthIndex),r = annualRate / 100 / 12. - Export
classifyLesseeLease(args: { termMonths: number; pvPayments: number; fairValue: number | null; economicLifeMonths: number | null; ownershipTransfers: boolean; purchaseOptionReasonablyCertain: boolean; specializedAsset: boolean; shortTermExpedient: boolean }, thresholds): { classification: "Operating" | "Finance" | "Short-Term"; tests; pvToFairValuePercent; termToLifePercent }. ReturnShort-TermwhenshortTermExpedient && termMonths <= 12 && !purchaseOptionReasonablyCertain. Otherwise callclassifyLessorLeaseand mapSale → Finance,Rental → Operating. - Export
type LesseeScheduleLine = { periodDate; openingLiability; paymentAmount; interestAmount; principalAmount; closingLiability; leaseCost; rouAmortization; closingRouAsset }. - Export
buildLesseeSchedule(args: { openingLiability: number; openingRouAsset: number; payments: { monthIndex: number; amount: number }[]; months: number; annualRate: number; timing: Timing; classification: "Operating" | "Finance"; amortizationMonths: number; periodDates: string[] }): LesseeScheduleLine[]:- Month
mpaysadvance= Σ Advance-type amounts withmonthIndex = mfirst, andarrears= Σ amounts withmonthIndex = m + 1last. (Pass each payment with its own index; the function needs only the index. For Advance timing aPurchase Optionrow has index =months, so it lands asarrearsof the last month.) interest = round((opening − advance) × r);closing = round(opening − advance + interest − arrears). The last month setsclosing = 0andinterestto the value that closes it.- Operating:
leaseCost = round((Σ payments + openingRouAsset − openingLiability) ÷ months), the last month absorbing;rouAmortization = leaseCost − interest. - Finance:
rouAmortization = round(openingRouAsset ÷ amortizationMonths); whenamortizationMonths = monthsthe last month takes the remainder;leaseCost = interest + rouAmortization. closingRouAssetruns down fromopeningRouAsset.
- Month
- Export
remeasureLease(args: { carryingLiability: number; carryingRouAsset: number; remainingPayments: { monthIndex: number; amount: number }[]; annualRate: number }): { liability: number; adjustment: number; rouAsset: number; gain: number }.liability= PV of the remaining payments;adjustment = liability − carryingLiability;rouAsset = carryingRouAsset + adjustment; when that is negative,gain = −rouAssetandrouAsset = 0. - Write tests (
describeper function):- The worked example: 36 rows of 10,000, Arrears, 6% → PV 328,710.16; schedule line 1 interest 1,643.55, principal 8,356.45, closing 320,353.71; line 36 closing 0; Operating month 1
leaseCost10,000 androuAmortization8,356.45; Finance month 1rouAmortization9,130.84; ΣleaseCost= 360,000 for both; finalclosingRouAsset0. - Advance timing: PV = arrears PV × 1.005 (±0.01).
- Quarterly: 12 rows; Annual: 3 rows.
- Escalation 3%: rows 13–24 are 10,300, rows 25–36 are 10,609.
- A 45-day last period is prorated.
- A purchase option of 20,000: PV = 345,423.06; Finance with
amortizationMonths = 84amortizes 4,112.18 a month. classifyLesseeLease: 12 months →Short-Term; fair value 340,000 →Finance; no inputs →Operating.remeasureLease: an increase adds to ROU; a decrease larger than ROU returns a gain.
- The worked example: 36 rows of 10,000, Arrears, 6% → PV 328,710.16; schedule line 1 interest 1,643.55, principal 8,356.45, closing 320,353.71; line 36 closing 0; Operating month 1
Verify:
pnpm --filter @carbon/utils test -- lease-math
# Expected: all tests pass
pnpm exec turbo run typecheck --filter=@carbon/utils
# Expected: 0 errors
Out of scope: journal lines (Task 14), lessor code (no behavior change in lessor-lease.ts).
Task 6: Give the run server functions a run type
Depends on: Task 4 Files:
- Create:
packages/server-functions/src/lib/run-type.ts - Modify:
packages/server-functions/src/propose-revenue-recognition-run/index.ts - Modify:
packages/server-functions/src/preview-revenue-recognition-run/index.ts - Modify:
packages/server-functions/src/recalculate-revenue-recognition-run/index.ts - Modify:
packages/server-functions/src/propose-revenue-recognition-run/run-test-fixture.ts—holdInDraftRuntakes a type - Modify:
packages/server-functions/src/__snapshots__/permissions-manifest.test.ts.snap(only if it changes) - Modify tests:
preview-revenue-recognition-run.test.ts,recalculate-revenue-recognition-run.test.ts
Steps:
- In
lib/run-type.ts, exporttype RunType = Database["public"]["Enums"]["runType"],RUN_SEQUENCE: Record<RunType, string> = { "Revenue Recognition": "revenueRecognitionRun", Lease: "leaseRun" }, andwhereRunType(qb, type). ForLeaseit addswhere(eb => eb.or([eb("rentalAgreementLineId", "is not", null), eb("leaseId", "is not", null)])); forRevenue Recognitionit addswhere("rentalAgreementLineId", "is", null).where("leaseId", "is", null). Type it over a Kysely select or update builder onrevenueRecognitionSchedule. - Add
type: RunTypetoRunProposalContext. - Replace the constant
RUN_ROW_SYNTHESIZERSwith a functionrunRowSynthesizers(type: RunType): RunRowSynthesizer[].Revenue Recognitionreturns[synthesizeContractRevenue];Leasereturns[synthesizeRentalAccruals]. Update every caller to callrunRowSynthesizers(ctx.type).- Merge note (projects branch
projects-wbs-research-spec): there the function isrunRowSynthesizers(extra), returning[synthesizeRentalAccruals, ...extra, synthesizeProjectRevenue, synthesizeContractRevenue]. The merged form isrunRowSynthesizers(type, extra):Revenue Recognition→[...extra, synthesizeProjectRevenue, synthesizeContractRevenue];Lease→[synthesizeRentalAccruals]. The project and Percent Complete synthesizers never run in a lease run. Every call site passes both the type andrevenueRunSynthesizers.
- Merge note (projects branch
- In
selectDueScheduleRows, applywhereRunType(…, ctx.type). - In
createRevenueRecognitionRunProposal, filter the Draft refusal ontype, draw the sequence fromRUN_SEQUENCE[type], and inserttype. Change the message to${draft.runId} is already a draft for this period. Recalculate it instead.(unchanged text, now per type). - Add
type: z.enum(["Revenue Recognition", "Lease"]).default("Revenue Recognition")to the propose and preview inputs. Pass it through. - In recalculate, select
typefrom the locked run and pass it to the synthesizers andselectDueScheduleRows. - Give
holdInDraftRunan optionaltype(defaultRevenue Recognition). - Add tests:
- preview with
type: "Lease"counts a due rental Accrual row; preview with the default type does not. - recalculate of a Lease Draft re-claims rental rows only.
- preview with
Verify:
pnpm --filter @carbon/server-functions test -- revenue-recognition-run permissions-manifest
# Expected: passes (review any snapshot diff before `-u`)
pnpm exec turbo run typecheck --filter=@carbon/server-functions
# Expected: 0 errors
Out of scope: posting (Task 8), lessee rows (written in Task 14).
Task 7: Give the run journal builder a run type and a lessee source
Depends on: Task 4 Files:
- Modify:
packages/database/src/run-journals.ts - Modify:
packages/database/src/run-journals.test.ts
Steps:
- Add
runType: "Revenue Recognition" | "Lease"to thebuildRecognitionJournalsargs. - Set the journal
sourceTypeto"Revenue Recognition"or"Lease Run"and the description toRevenue Recognition ${runReadableId}orLease Run ${runReadableId}. - Add
leaseIdandleaseScheduleLineIdtoRecognitionScheduleRow. - Add
leases: Map<string, { supplierId: string; locationId: string | null }>toRecognitionSources. - In
recognitionSource, after the contract branch, map a row withleaseIdtodocumentType: "Lease",documentId: leaseId, dimensions{ Supplier: supplierId, Location: locationId }. AddSupplierto the dimensions type (null for the other sources). - Rename the journal field
leaseScheduleLineIdstorentalLeaseScheduleLineIdsand addlesseeScheduleLineIds(fromrow.leaseScheduleLineId). Update the one consumer inaccounting.server.ts. - Add tests: a
Leaserun with one lessee Interest row and one Amortization row builds oneLease Runjournal withdocumentType "Lease", balanced, and both ids inlesseeScheduleLineIds.
Verify:
pnpm --filter @carbon/database test -- run-journals
# Expected: passes
Out of scope: reading the sources from the database (Task 8).
Task 8: Make post, reverse and delete type-aware
Depends on: Tasks 6, 7 Files:
- Modify:
apps/erp/app/modules/accounting/accounting.server.ts—postRevenueRecognitionRun,reverseRevenueRecognitionRun - Modify:
apps/erp/app/routes/x+/revenue-recognition-run+/$runId.post.tsx— the Supplier dimension
Steps:
- In
postRevenueRecognitionRun, selecttypewith the run. - Filter the unclaimed-due-rows check (lines 1163–1170) with the same predicate as
whereRunType(inline Kysely; the ERP cannot import the server-functions lib). - Run the unsynthesized-contract check (1175–1198) only when
run.type === "Revenue Recognition". - Select
s.leaseIdands.leaseScheduleLineIdwith the rows. Read the leases:selectFrom("lease").select(["id", "supplierId", "locationId"]).where("id", "in", leaseIds).where("companyId", "=", companyId). Put them insources.leases. - Pass
runType: run.typetobuildRecognitionJournals. - Add
SuppliertoRevenueRecognitionDimensionIdsand to the dimension map. In$runId.post.tsx, load the Supplier dimension the same way as Customer. - After the
rentalLeaseScheduleLinestamp (1401–1417), stampleaseScheduleLinewithjournal.lesseeScheduleLineIdsthe same way. - In
reverseRevenueRecognitionRun:- Filter the one-Draft check on
type. - Select
s.leaseScheduleLineId. ClearleaseScheduleLine.journalIdandpostedAtlike the rental block. - After the rows return to Planned, delete the run lines of rows that do NOT match the run's type. Set those rows'
runLineIdto null (spec §6, "Reverse Run releases the other family").
- Filter the one-Draft check on
deleteRevenueRecognitionRunneeds no change. Confirm it by reading it.
Verify:
pnpm exec turbo run typecheck --filter=erp
# Expected: 0 errors
Out of scope: the routes' Draft lookups (Task 10), the legacy backfill (Task 9).
Task 9: Thread the run type through the legacy backfill
Depends on: Task 7 Files:
- Modify:
packages/database/src/legacy-documents.ts—legacyRecognitionScheduleselectsrun.type - Modify:
packages/server-functions/src/activate-accounting/legacy/runs.ts— passrunType; stampleaseScheduleLine
Steps:
- In
legacyRecognitionSchedule(lines 1102–1145), select the run'stypeand add it to the returned row type. - In
buildLegacyRecognitionJournals(runs.ts 223–260), passrunTypeper run tobuildRecognitionJournals. - Beside the
rentalLeaseScheduleLinestamp (581–586), add aleaseScheduleLinestamp keyed byleaseScheduleLineId.
Verify:
pnpm --filter @carbon/server-functions test -- legacy-runs runs.test legacy-documents
# Expected: passes
Out of scope: new legacy behavior for lessee documents.
Task 10: Add the Lease Runs list and make the run page type-aware
Depends on: Task 8 Files:
- Create:
apps/erp/app/routes/x+/accounting+/lease-runs.tsx - Create:
apps/erp/app/routes/x+/accounting+/lease-runs.new.tsx - Modify:
apps/erp/app/routes/x+/accounting+/revenue-recognition-runs.tsx,revenue-recognition-runs.new.tsx— filter ontype - Modify:
apps/erp/app/routes/x+/revenue-recognition-run+/$runId.tsx,$runId.repeat.tsx,_layout.tsx— readtype - Modify:
apps/erp/app/modules/accounting/ui/RevenueRecognition/RevenueRecognitionRunsTable.tsx,RevenueRecognitionRunHeader.tsx— atypeprop / read - Modify:
apps/erp/app/modules/accounting/accounting.service.ts—getRevenueRecognitionRuns(…, type);getDeferredRevenueWaterfallexcludes lessee rows - Modify:
apps/erp/app/modules/accounting/ui/useAccountingSubmodules.tsx— "Lease Runs" - Modify:
apps/erp/app/utils/path.ts—leaseRuns,newLeaseRun - Copy from (precedent):
revenue-recognition-runs.tsx,revenue-recognition-runs.new.tsx
Steps:
- Add a
typeargument togetRevenueRecognitionRunsand.eq("type", type). - Copy
revenue-recognition-runs.tsxtolease-runs.tsxwithtype = "Lease", breadcrumbmsg\Lease Runs`, and the New Run actionpath.to.newLeaseRun. Filter its "latest run" read ontype`. - Copy
revenue-recognition-runs.new.tsxtolease-runs.new.tsx; filterexistingDraftontype; invokepropose-revenue-recognition-runwith{ periodEnd, type: "Lease" }; redirect topath.to.revenueRecognitionRun(id). - In the two revenue routes, filter on
type = 'Revenue Recognition'. - Give
RevenueRecognitionRunsTableatypeprop. Title:t\Lease Runs`ort`Revenue Recognition``. - In
$runId.tsx, selecttype. Use it for the breadcrumb (Lease Runs→path.to.leaseRuns), the page title and the header confirm texts ("lease run" vs "revenue recognition run"). - In
$runId.repeat.tsx, filterexistingDrafton the source run's type and passtypeto propose. - In
getDeferredRevenueWaterfall, add.is("leaseId", null). - Add
{ name: t\Lease Runs`, to: path.to.leaseRuns, role: "employee", icon: }` after Revenue Recognition in the Closing group. - Add
leaseRuns: \${x}/accounting/lease-runs`andnewLeaseRun: `${x}/accounting/lease-runs/new`topath.ts` in alphabetical position.
Verify:
pnpm exec turbo run typecheck --filter=erp
# Expected: 0 errors
Out of scope: the close wizard (Task 11).
Task 11: Add the lease run to the close wizard, the monthly job and the journal guards
Depends on: Tasks 6, 8 Files:
- Modify:
apps/erp/app/modules/accounting/accounting.service.ts—PeriodRunPreview,getPeriodRunPreview,computePeriodReadiness,getJournalEntryRelatedItemsrun lookup,reverseJournalEntry - Modify:
apps/erp/app/modules/accounting/accounting.models.ts—RUN_JOURNAL_SOURCES - Modify:
apps/erp/app/modules/accounting/ui/JournalEntries/JournalEntryHeader.tsx,JournalEntryDocuments.tsx - Modify:
apps/erp/app/routes/x+/accounting+/periods.$periodId.close.tsx - Modify:
packages/jobs/src/inngest/functions/scheduled/revenue-recognition-proposal.ts - Modify:
packages/server-functions/src/post-rental-agreement/validators.ts,post-rental-agreement/return-unit.ts,post-memo/index.ts— "lease run" wording - Modify:
apps/erp/app/modules/accounting/accounting.periods.test.ts
Steps:
PeriodRunPreviewbecomes{ revenue; lease; depreciation }.getPeriodRunPreviewinvokes the preview twice (typedefault and"Lease"). Update every caller and test fixture.- In
computePeriodReadiness, filterheldRevenueRowsonrun.type = 'Revenue Recognition'; addheldLeaseRowsthe same way forLease. Add a check{ autoCheckKey: "unposted-lease-schedules", severity: "Warning", label: "Lease entries a lease run would post by this period end, and lease Draft runs hold", failing, count, amount, due: runPreview.lease, draftRuns }. - In the close page: add action intent
create-lease-run(copycreate-revenue-run, typeLease, Draft check filtered ontype); addcase "unposted-lease-schedules"to the task description; map the intent; passrunType="lease"toPeriodRunDue; add a "Go to lease runs" link. ExtendPeriodRunDue'srunTypeunion with"lease"and its strings. - In the monthly job, propose twice per company: once per type, each with its own Draft check and step id (
rev-rec-${id},lease-run-${id}). - Add
"Lease Run": "lease"toRUN_JOURNAL_SOURCES. ConfirmJournalEntryHeaderreads the map, so the Reverse button hides. - In
getJournalEntryRelatedItems, take the run lookup whensourceTypeis"Revenue Recognition"or"Lease Run". Selecttypewith the run and returnkind: "revenueRecognitionRun"with arunTypefield. InJournalEntryDocuments.tsx, label it "Lease Run" whenrunType === "Lease". - Replace "revenue recognition run" with "lease run" in the three rental messages.
- Extend
accounting.periods.test.ts: a period with due lease rows failsunposted-lease-schedulesand passes with none.
Verify:
cd apps/erp && pnpm exec vitest run app/modules/accounting/accounting.periods.test.ts
# Expected: passes
pnpm exec turbo run typecheck --filter=erp --filter=@carbon/jobs --filter=@carbon/server-functions
# Expected: 0 errors
Out of scope: the external sync engine itself.
Task 12: Add the lease validators
Depends on: Task 4 Files:
- Modify:
apps/erp/app/modules/purchasing/purchasing.models.ts— a "Leases" section - Copy from (precedent):
rentalAgreementValidator(sales.models.ts:1416–1467),rentalAgreementLineClassificationValidator(1538)
Steps:
- Export option arrays from the DB enums:
leaseStatuses,lesseeClassifications,leasePaymentFrequencies,leasePaymentTimings(["Advance", "Arrears"]),leasePaymentStatuses. - Export
leaseValidator:id,leaseIdoptional;namerequired;description,supplierIdrequired;supplierLocationId,supplierContactId,locationId,assigneeoptional;commencementDate,endDaterequired;noticeDate,invoiceFromDateoptional;paymentAmount(≥ 0),paymentFrequency,paymentTiming,annualEscalationPercent(≥ 0, default 0),discountRate(≥ 0),currencyCode;fairValue,economicLifeMonthsoptional;ownershipTransfers,specializedAsset,purchaseOptionReasonablyCertain(zfd.checkbox());purchaseOptionAmountoptional. Refine: end ≥ commencement;noticeDate≤endDate;invoiceFromDate≥commencementDate; reasonably certain needspurchaseOptionAmount > 0. - Export
leasePaymentValidator:idoptional,leaseId,periodStart,periodEnd,dueDate,amount(≥ 0),paymentType(defaultRent). RefineperiodEnd ≥ periodStart. - Export
leaseClassificationValidator={ classification: z.enum(["Operating", "Finance"]), reason: min 1 }. - Export
leaseModifyValidator={ effectiveDate, endDate, discountRate, paymentAmount, paymentFrequency, annualEscalationPercent }(the remaining rows are regenerated from these terms from the effective date; row edits after a Modify are not in v1). - Export
leaseTerminateValidator={ terminationDate, penaltyAmount (≥ 0, default 0), notes optional }. - Export
leasePurchaseValidator={ exerciseDate, purchasePrice (≥ 0), fixedAssetClassId required, name required }. - Add a test file
purchasing.models.test.tscase for each refine.
Verify:
cd apps/erp && pnpm exec vitest run app/modules/purchasing/purchasing.models.test.ts
# Expected: passes
Out of scope: server-side rules (Task 14).
Task 13: Add the lease service functions
Depends on: Task 12 Files:
- Modify:
apps/erp/app/modules/purchasing/purchasing.service.ts— a "Leases" section - Modify:
apps/erp/app/modules/purchasing/purchasing.server.ts—generateLeaseInvoicesNow - Modify:
apps/erp/app/modules/purchasing/types.ts—Lease,LeasePayment,LeaseScheduleLine,LeaseEventrow types - Copy from (precedent): the rental agreement section of
sales.service.ts(8629–9135),generateRentalInvoicesNow(sales.server.ts:400)
Steps:
- Add, each
(client, …) → {data, error}, with@mcp read/create/update/deleteJSDoc tags like the rental ones:getLeases(client, companyId, args: GenericQueryFilters & { search })over theleasesview, search onnameandleaseId.getLease(client, id);insertLease(client, lease & { leaseId; companyId; createdBy; customFields? })returningid, leaseId;updateLease(client, lease & { id; updatedBy })refusing non-Draft by.eq("status", "Draft");deleteLease(client, id)with.eq("status", "Draft").getLeasePayments(client, leaseId)ordered bydueDate;upsertLeasePayment;deleteLeasePayment(both refuse unless the lease is Draft: read the lease first and return an error object).regenerateLeasePayments(client, args: { leaseId; companyId; userId; decimals }): reads the lease, deletes its payment rows, insertsgenerateLeasePayments(...)rows (statusSkippedwhendueDate < invoiceFromDate).getLeaseSchedule(client, leaseId)joined to itsrevenueRecognitionSchedulerows'statusandjournalId.getLeaseEvents(client, leaseId);getLeaseRelatedDocuments(client, leaseId)(purchase invoices frompurchaseInvoiceLine.leaseId, journals fromjournalLine.documentId).
- Add
generateLeaseInvoicesNow(db, { companyId, asOf, leaseId, userId })topurchasing.server.ts, copyinggenerateRentalInvoicesNowwith"create-lease-invoices". - Export the new functions from the module barrel if the barrel lists exports explicitly.
Verify:
pnpm exec turbo run typecheck --filter=erp
# Expected: 0 errors
pnpm run generate:mcp 2>/dev/null || true; git diff --stat apps/erp/app/routes/api+/mcp+/lib/
# Expected: the digest lists the new purchasing_* lease tools
Out of scope: activation (Task 14). generateLeaseInvoicesNow fails until Task 24; that is expected.
Task 14: Add the post-lease server function: activate and cancel
Depends on: Tasks 5, 7, 13 Files:
- Create:
packages/server-functions/src/post-lease/index.ts— definition and dispatch - Create:
packages/server-functions/src/post-lease/lease.ts—lockLease,loadLesseeAccounting,postLesseeJournal,writeSchedule - Create:
packages/server-functions/src/post-lease/lessee.ts— pure journal-line builders - Create:
packages/server-functions/src/post-lease/validators.ts— payload union and pure blockers - Create:
packages/server-functions/src/post-lease/lessee.test.ts,lease-test-fixture.ts,activate.test.ts - Modify:
packages/server-functions/src/invoke.ts— register"post-lease" - Modify:
packages/server-functions/src/__snapshots__/permissions-manifest.test.ts.snap - Copy from (precedent):
post-rental-agreement/index.ts(1045–1080),agreement.ts(lockAgreement55,loadLeaseAccounting170,postLeaseJournal262),lessor.ts(toPostingLines222),post-charge/post-charge-void.ts,rental-test-fixture.ts
Steps:
validators.ts:payloadValidator = z.discriminatedUnion("type", [activate {leaseId}, cancel {leaseId}, modify {leaseId, ...leaseModify}, terminate {leaseId, ...leaseTerminate}, purchase {leaseId, ...leasePurchase}]). Pure blockers:activateBlocker(lease, payments, baseCurrencyCode)("A lease needs at least one payment", "Leases in a foreign currency are not supported yet", "The lease is not a Draft").lessee.ts: copynaturalAmount,LegandtoPostingLinesfromlessor.tsand add"liability"(credit-positive) toAccountType. ExportcommencementLines({ liability, accounts })(Dr ROU / Cr Lease liability). Unit-test it balanced.lease.ts:lockLease(trx, companyId, id): copylockAgreement; DATE columns as::text; numerics viaNumber.loadLesseeAccounting(trx, { companyId, companyGroupId, today }): copyloadLeaseAccountingfor the 7 lessee defaults, plusassetGainOnDisposalAccount,assetLossOnDisposalAccount; dimensionsSupplier,Location. After the cutover a missing default throwsInvalidInputError("Set the lease (lessee) accounts in Accounting → Defaults").postLesseeJournal(trx, { accounting, companyId, userId, postingDate, description, lines, leaseId, tags: { supplierId, locationId } }): copypostLeaseJournalwithsourceType: "Lease",documentType: "Lease",documentId: leaseId,documentLineReference: null.writeSchedule(trx, { lease, lines, accounts, fromMonthIndex, userId }): insertleaseScheduleLinerows, then two PlannedrevenueRecognitionSchedulerows per line (typeInterestandAmortization,leaseId,leaseScheduleLineId,periodStart= the lease month's first day,periodEnd=scheduledDate=periodDate, debit/credit per spec §3). Skip a row whose amount is 0.
index.tsactivate:- Lock the lease; run
activateBlocker. - Read thresholds and
leaseShortTermExpedientfromcompanySettings; read payment rows. termMonths = wholeMonthsInTerm(commencementDate, endDate); payments →{ monthIndex, amount }withpaymentMonthIndex;pv = presentValueOfPayments.- Classify with
classifyLesseeLease, unlessclassificationOverrideis set. - If
Short-Term: setstatus Active,lesseeClassification,classificationInputs,activatedAt; stop. - Else: post
commencementLinesdatedcommencementDatethroughpostLesseeJournal; build the schedule withbuildLesseeSchedule(amortizationMonths=economicLifeMonthswhen ownership transfers or the purchase option is reasonably certain, elsetermMonths);writeSchedule; setinitialLiability = initialRouAsset = rouAssetCost = pv,commencementJournalId, status, classification,activatedAt. - If the company has a cutover and
commencementDateis before it, STOP withInvalidInputError("This lease started before accounting was set up. Opening balances for it are not supported yet.")— Task 30 replaces this refusal.
- Lock the lease; run
index.tscancel: allowed for Draft (delete the lease), or Active with noInvoicedpayment row and no Posted schedule row. For Active, void the commencement journal with a negated entry (copypost-charge-void.tssteps 1–7, descriptionVOID Lease ${leaseId}), delete the schedule rows (cascade deletes the Planned recognition rows), set statusCancelled. Refuse while a Draft run holds a row of the lease: "LR… holds this lease's entries; delete or recalculate it first".- Register
"post-lease": () => import("./post-lease")ininvoke.ts. Permissions{ update: "purchasing" }. lease-test-fixture.ts: copyrental-test-fixture.tsfor a supplier, a location, the 7 accounts + defaults, sequences (lease,journalEntry,fixedAsset,leaseRun), and one Draft lease with generated payment rows (the worked example).activate.test.ts(databaseTest): activation writes 36 schedule lines, 72 Planned rows, one journal Dr ROU 328,710.16 / Cr liability; a 12-month lease activates Short-Term with no journal; cancel of an untouched Active lease voids the journal.
Verify:
pnpm --filter @carbon/server-functions test -- post-lease permissions-manifest
# Expected: passes (review the snapshot diff, then `-u`)
pnpm exec turbo run typecheck --filter=@carbon/server-functions
# Expected: 0 errors
Out of scope: Modify / Terminate / Purchase (Task 15), the opening journal (Task 30).
Task 15: Add Modify, Terminate and Purchase to post-lease
Depends on: Task 14 Files:
- Modify:
packages/server-functions/src/post-lease/index.ts,lessee.ts,validators.ts - Create:
packages/server-functions/src/post-lease/lifecycle.test.ts - Copy from (precedent):
post-rental-agreement/return-unit.ts456–526 (fixed asset insert)
Steps:
- Add a shared pre-check
lifecycleBlocker. It refuses when any of these holds:- The lease is not Active.
- The effective date is not a lease-month boundary.
- A lease month before the effective date has a row that is not Posted (plan decision P6).
- A run holds a row of the lease from the effective month on (
runLineId is not null). The message names the run (LR…). - Purchase only: the lease is Short-Term. (Modify and Terminate allow Short-Term; they only change payment rows.)
- Compute the carrying amounts at the effective month
e:carryingLiability=closingLiabilityof monthe − 1, orinitialLiabilitywhene = 0.accumulated= ΣrouAmortizationof the Posted months.carryingRou=rouAssetCost − accumulated.
- Modify:
- Delete the Pending payment rows due on or after the effective date.
- Insert new rows from
generateLeasePaymentsover[effectiveDate, newEndDate]. - Call
remeasureLeaseat the new rate, with month indexes relative toe. - Reclassify with
classifyLesseeLease(new term, same inputs). - Post
remeasurementLines: Dr ROU / Cr liability for an increase; the reverse for a decrease; thegaintoassetGainOnDisposalAccount. - Delete the schedule lines from month
e. CallwriteSchedulefrom the new liability and ROU. - Update
endDate,discountRateand the terms. Add the adjustment torouAssetCost. - Insert a
leaseEvent. - If the lease is Short-Term, do only sub-steps 1, 2, 7 and 8: it has no schedule and no journal.
- Terminate:
- Delete the Pending payment rows due after the date.
- If
penaltyAmount > 0, insert aTermination Penaltyrow due on the date. - Post
terminationLines: Dr liabilitycarryingLiability − penalty, Dr accumulated, Cr ROUrouAssetCost, and the gain or loss. - Delete the schedule lines from month
e. - Set status
Terminated. Insert aleaseEvent. - If the lease is Short-Term, skip sub-steps 3 and 4: it has no schedule and no journal.
- Purchase:
- Delete the Pending payment rows due after the date and the
Purchase Optionrow. - Insert a
Purchase Optionrow forpurchasePrice, due on the date. - Insert the
fixedAsset. Copyreturn-unit.ts: sequencefixedAsset, the class fields,locationId= the lease's,status Active. - Set its
acquisitionCost=carryingRou + purchasePrice − carryingLiabilityandacquisitionDate=depreciationStartDate=exerciseDate. - Post
purchaseLines: Dr classassetAccountId(the cost), Dr accumulated, Cr ROUrouAssetCost, Dr liabilitycarryingLiability, Cr liabilitypurchasePrice. - Delete the schedule lines from month
e. - Set status
PurchasedandfixedAssetId. Insert aleaseEvent.
- Delete the Pending payment rows due after the date and the
- Unit-test each builder balanced, with the spec's numbers (termination at month 24 with a 5,000 penalty; purchase with a 20,000 option).
lifecycle.test.ts(databaseTest): post months 1–12 by setting their recognition rows toPosted; Modify at month 13 (extend 12 months, 7%) replaces only unposted lines and closes at 0; Modify is refused when a Draft run holds month 13; Terminate and Purchase write their events and statuses.
Verify:
pnpm --filter @carbon/server-functions test -- post-lease
# Expected: passes
Out of scope: partial termination, impairment (spec: out of v1).
Task 16: Add the lease list, new, shell, details and update routes
Depends on: Tasks 13–15 Files:
- Create:
apps/erp/app/routes/x+/purchasing+/leases.tsx - Create:
apps/erp/app/routes/x+/lease+/_layout.tsx,new.tsx,$id.tsx,$id._index.tsx,$id.details.tsx,$id.schedule.tsx,$id.events.tsx,update.tsx,$id.delete.tsx - Copy from (precedent):
x+/sales+/rental-agreements.tsx,x+/rental-agreement+/{_layout,new,$id,$id._index,$id.details,update,$id.delete}.tsx
Steps:
leases.tsx: copyrental-agreements.tsx;view: "purchasing";getLeases;LeasesTable;handle.breadcrumb msg\Leases``._layout.tsx: metaCarbon | Lease,handle { breadcrumb: msg\Purchasing`, to: path.to.purchasing, module: "purchasing" }`.new.tsx: loadercreate: "purchasing"returnsdefaultDiscountRate: companySettings.leaseIncrementalBorrowingRateand the base currency. Action: validateleaseValidator;getNextSequence(client, "lease", companyId);insertLeasewithinvoiceFromDate ?? commencementDate;regenerateLeasePayments; redirect topath.to.leaseDetails(id). Component: aValidatedFormcard withLeaseForm(Task 19).$id.tsx: loaderview: "purchasing"reads the lease (company check), payments, schedule, events, related documents and lease policy (leaseMajorPartThresholdPercent,leaseSubstantiallyAllThresholdPercent,leaseShortTermExpedient). Layout:PanelProvider>LeaseHeader>ResizablePanels explorer={<LeaseExplorer />} content={<RecordOutlet />} properties={<LeaseProperties />}. ExportLeaseRouteData.$id._index.tsx: redirect to details.$id.details.tsx:LeaseSummary; while Draft a "Accounting Treatment" card withLeaseClassificationPreview;LeasePayments.$id.schedule.tsx:LeaseSchedule.$id.events.tsx:LeaseEvents.update.tsx: copy the rentalupdate.tsxfield-by-field pattern withTERM_FIELDS= the lease validator's term fields andBOOLEAN_FIELDS= the three checkboxes; Draft only. When a payment-term field changes, callregenerateLeasePaymentsafter the update.$id.delete.tsx: Draft only,delete: "purchasing",deleteLease, redirect topath.to.leases.
Verify:
pnpm exec turbo run typecheck --filter=erp
# Expected: 0 errors
Out of scope: lifecycle actions (Task 18).
Task 17: Add the payment row routes
Depends on: Task 16 Files:
- Create:
apps/erp/app/routes/x+/lease+/$id.payments.new.tsx,$id.payments.$paymentId.tsx,$id.payments.$paymentId.delete.tsx,$id.payments.regenerate.tsx - Copy from (precedent):
x+/rental-agreement+/$id.charges.new.tsx,$id.charges.$chargeId.delete.tsx
Steps:
- Each action requires
update: "purchasing"and a Draft lease (read it, refuse with a flash otherwise). newand$paymentId: validateleasePaymentValidator;upsertLeasePayment; redirect torequestReferrer(request).delete:deleteLeasePayment.regenerate:regenerateLeasePaymentswith the currency'sdecimalPlaces; flash "Payments regenerated from the terms".
Verify:
pnpm exec turbo run typecheck --filter=erp
# Expected: 0 errors
Out of scope: editing rows after activation (plan decision P8).
Task 18: Add the lifecycle routes
Depends on: Task 16 Files:
- Create:
apps/erp/app/routes/x+/lease+/$id.activate.tsx,$id.status.tsx(cancel),$id.modify.tsx,$id.terminate.tsx,$id.purchase.tsx,$id.invoice.tsx,$id.classification.tsx - Copy from (precedent):
x+/rental-agreement+/$id.activate.tsx,$id.status.tsx,$id.invoice.tsx,$id.$lineId.classification.tsx
Steps:
activate,status(intentcancel),modify,terminate,purchase:update: "purchasing"; validate the matching validator;serverFns.system({ db: getDatabaseClient(), companyId, userId }).invoke("post-lease", { type, leaseId: id, ... }); flash the error withgetErrorMessage; redirect topath.to.leaseDetails(id).invoice:{ update: "purchasing", create: "invoicing" }; Active only;generateLeaseInvoicesNowwith today in the company time zone; flash "N invoices drafted".classification: copy the rental override route withupdate: "accounting", the service role, Draft only,.is("lesseeClassification", null)guard, and the audit entry.
Verify:
pnpm exec turbo run typecheck --filter=erp
# Expected: 0 errors
Out of scope: the modals' UI (Task 19).
Task 19: Build the lease UI components
Depends on: Task 16 Files:
- Create in
apps/erp/app/modules/purchasing/ui/Leases/:LeasesTable.tsx,LeaseForm.tsx,LeaseHeader.tsx,LeaseExplorer.tsx,LeaseProperties.tsx,LeaseSummary.tsx,LeasePayments.tsx,LeasePaymentForm.tsx,LeaseSchedule.tsx,LeaseEvents.tsx,LeaseStatus.tsx,LeaseClassificationPreview.tsx,LeaseModifyModal.tsx,LeaseTerminateModal.tsx,LeasePurchaseModal.tsx,index.ts - Copy from (precedent,
apps/erp/app/modules/sales/ui/Rentals/):RentalAgreementsTable,RentalAgreementDetailsForm,RentalAgreementHeader,RentalAgreementExplorer,RentalAgreementProperties,RentalAgreementSummary,RentalBillingPeriods,RentalAgreementChargeForm,RentalStatus,RentalLeaseClassification(LeaseClassificationPreview,LeaseClassificationPanel,LeaseClassificationOverrideModal)
Steps:
- Load the
carbon-designskill first. Use only components from@carbon/reactand~/components. LeasesTable: columnsleaseId(link),name,supplierName,status(LeaseStatus),lesseeClassification,commencementDate,endDate,paymentAmount(useCurrencyFormatter),currentLiability,nextDueDate. Primary action "New Lease" (create: purchasing).LeaseForm: the spec §1 fields in groups Party / What / Term / Payments / Measurement / Classification inputs;Supplier,Location,Employee(assignee) pickers from~/components/Form; money viaINPUT_FORMAT.moneyand percents viaINPUT_FORMAT.percentPointswithINPUT_STEP.*.LeaseHeader: status, classification badge, and actions by status — Draft: Activate (confirm modal showing PV, classification, commencement journal), Delete; Active: Invoice now, Modify, Terminate, Purchase (only with a purchase option), Cancel (only when allowed). Copy the rental header's dropdown layout.LeaseExplorer: a short list — Details, Payments, Schedule, Events.LeaseProperties: copyRentalAgreementProperties'PropertyForm+onUpdatepattern, posting topath.to.leaseUpdate;isDisabled = status !== "Draft" || !permissions.can("update", "purchasing").LeaseSummary: terms, treatment, liability and net ROU today (from the last Posted schedule line), next payment.LeasePayments: copyRentalBillingPeriods; while Draft show Add Row, edit (opensLeasePaymentForm), delete, and "Regenerate from terms" (confirm: "Edited rows will be replaced"); after activation show status and the invoice link. ShowSkippedas "Paid outside Carbon".LeaseSchedule: a table of the schedule lines with a Posted badge per row.LeaseEvents: event type, effective date, liability before → after, ROU before → after, gain/loss, journal link, fixed asset link.LeaseClassificationPreview: compute client-side withgenerateLeasePayments→presentValueOfPayments→classifyLesseeLease; render tests a–e like the rental panel; an "Override" button forupdate: accountingopens the override modal posting topath.to.leaseClassification(id).- The three modals:
ValidatedFormwith the Task 12 validators, posting to the Task 18 routes; Modify and Terminate show the effective date picker and a note "Effective dates must follow the last posted lease run".
Verify:
pnpm exec turbo run typecheck --filter=erp
# Expected: 0 errors
pnpm exec biome check apps/erp/app/modules/purchasing/ui/Leases
# Expected: no errors
Out of scope: new shared components.
Task 20: Add the nav entry and paths
Depends on: Task 16 Files:
- Modify:
apps/erp/app/modules/purchasing/ui/usePurchasingSubmodules.tsx - Modify:
apps/erp/app/utils/path.ts
Steps:
- Add
{ name: t\Leases`, to: path.to.leases, icon: , table: "lease" }` after Purchase Orders in the Manage group. - Add to
path.ts, alphabetically:lease,leaseActivate,leaseClassification,leaseDetails,leaseEvents,leaseInvoice,leaseModify,leasePayment(id, paymentId),leasePaymentDelete,leasePaymentNew,leasePaymentsRegenerate,leasePurchase,leaseSchedule,leaseStatus,leaseTerminate,leaseUpdate(${x}/lease/update),leases(${x}/purchasing/leases),newLease(${x}/lease/new),deleteLease(id).
Verify:
pnpm exec turbo run typecheck --filter=erp
# Expected: 0 errors
Out of scope: saved views setup for table: "lease" beyond the nav key. If table must be a registered table name and lease is not accepted, drop the table key and report.
Task 21: Add the Lease line type to the purchase invoice form
Depends on: Task 4 Files:
- Modify:
apps/erp/app/modules/invoicing/invoicing.models.ts— both line-type lists, the validator, a refine - Modify:
apps/erp/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceLineForm.tsx— a Lease tab - Modify:
apps/erp/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceExplorer.tsx,PurchaseInvoiceSummary.tsx— line labels - Modify:
apps/erp/app/modules/invoicing/invoicing.service.ts—getActiveLeasesForSupplier
Steps:
- Add
"Lease"topurchaseInvoiceLineType(line 13) and to the validator enum (line 150). AddleaseId,leasePaymentId(zfd.text(z.string().optional())). Refine: Lease needsleaseIdanddescription. Refine: a Lease line refusesprojectId("A lease line cannot be charged to a project"). The Lease tab shows no project field. - Add
getActiveLeasesForSupplier(client, companyId, supplierId)(status in (Active, Expired, Terminated, Purchased),id, leaseId, name). - In the form, add a tab
lease(only when not editing) with<Hidden name="invoiceLineType" value="Lease" />, a leaseComboboxloaded through a fetcher route or the invoice loader,description,quantityfixed at 1,supplierUnitPrice. A line withleasePaymentId(drafted by the job) opens read-only for amount and lease. - In the explorer and summary, label a Lease line
${leaseReadableId} · ${description}from thepurchaseInvoiceLinesview'sleaseReadableId.
Verify:
pnpm exec turbo run typecheck --filter=erp
# Expected: 0 errors
Out of scope: posting (Task 22).
Task 22: Post and void Lease lines
Depends on: Task 21 Files:
- Modify:
packages/server-functions/src/post-purchase-invoice/posting-lines.ts—kind: "lease",PurchaseInvoiceAccountDefaults - Modify:
packages/server-functions/src/post-purchase-invoice/index.ts— classificationcase "Lease", VOID release - Modify:
packages/server-functions/src/activate-accounting/legacy/purchase-invoice.ts—case "Lease" - Modify:
packages/server-functions/src/post-purchase-invoice/posting-lines.test.ts
Steps:
- Add
leaseLiabilityAccount,operatingLeaseExpenseAccount,variableLeaseExpenseAccounttoPurchaseInvoiceAccountDefaults. - Add
{ kind: "lease"; leaseId: string; account: { id: string; name: string; class: AccountClass } }to the posting-line union. Build it likeglAccount(lines 649–678), with the debit amountround(debit(accountTypeFromClass(line.account.class), total))(debitandaccountTypeFromClassfrom@carbon/database/ledger: a debit to the Liability-class lease liability stores a negative amount, a debit to an Expense stores a positive one). CreditpayableasglAccountdoes.documentType/documentIdstay the invoice's. - In
index.ts, load the leases of Lease lines (id, lesseeClassification).case "Lease": account =leaseLiabilityAccountwhen the line hasleasePaymentIdand the lease is Operating or Finance;operatingLeaseExpenseAccountwhen it hasleasePaymentIdand the lease is Short-Term;variableLeaseExpenseAccountwhen it has noleasePaymentId. A missing default throws "Set the lease (lessee) accounts in Accounting → Defaults". A Lease line with aprojectIdthrows "A lease line cannot be charged to a project"; setprojectId: nullon theleaseposting line. (The projects branch charges a project from any line withprojectId; this keeps Lease lines out of it.) - In the VOID transaction (from line 521), before the status update, set
leasePaymentrows withpurchaseInvoiceLineId inthe invoice's line ids tostatus: "Pending", purchaseInvoiceLineId: null, voidedPurchaseInvoiceId: invoiceId. Copypost-sales-invoice/index.ts:1694–1730. - Mirror step 3 in the legacy switch (
purchase-invoice.ts:438). - Add tests: a fixed Lease line debits the liability and credits AP 10,000; a Short-Term line debits operating lease expense; a variable line debits variable lease expense.
Verify:
pnpm --filter @carbon/server-functions test -- post-purchase-invoice
# Expected: passes
Out of scope: drafting invoices (Task 24).
Task 23: Release payment rows when a purchase invoice or line is deleted
Depends on: Task 21 Files:
- Modify:
apps/erp/app/modules/invoicing/invoicing.server.ts— two functions - Modify:
apps/erp/app/routes/x+/purchase-invoice+/$invoiceId.delete.tsx,$invoiceId.$lineId.delete.tsx - Modify:
apps/erp/app/routes/api+/mcp+/lib/mcp-blocked-tools.ts - Copy from (precedent):
deleteSalesInvoiceReleasingRentalsanddeleteSalesInvoiceLineReleasingRentals(sales.server.ts:527,627)
Steps:
- Add
deletePurchaseInvoiceReleasingLeases(db, { companyId, invoiceId, userId }): lock the invoiceforUpdate, refuse non-Draft, set its Lease lines'leasePaymentrows back toPendingwithpurchaseInvoiceLineId: null, delete the invoice. - Add
deletePurchaseInvoiceLineReleasingLeases(db, { companyId, invoiceId, lineId, userId })the same way for one line. - Make both routes call them with
getDatabaseClient()in a try/catch that flashes the error. - Add
"invoicing_deletePurchaseInvoice"and"invoicing_deletePurchaseInvoiceLine"to the blocked list, with a comment like the sales one.
Verify:
pnpm exec turbo run typecheck --filter=erp
# Expected: 0 errors
Out of scope: VOID (Task 22).
Task 24: Add the create-lease-invoices server function
Depends on: Tasks 13, 22 Files:
- Create:
packages/server-functions/src/create-lease-invoices/index.ts,create-lease-invoices.test.ts - Modify:
packages/server-functions/src/invoke.ts, the permissions snapshot - Copy from (precedent):
create-rental-invoices/index.ts(createRentalInvoicesForDuePeriods88,insertRentalInvoice541, definition 806–830);convert/index.ts:357–454(purchase invoice insert)
Steps:
- Input
{ asOf: YYYY-MM-DD, leaseId?: string }; permissions{ update: "purchasing", create: "invoicing" }. - Find Active leases (or ended leases with a Pending row) with a
Pendingpayment row due on or beforeasOf, optionally one lease. - Per lease, in its own transaction (failures collected like rentals): lock the lease; lock its due Pending rows; group them by
dueDate; for each group insert one Draft purchase invoice:invoiceIdfromgetNextSequence(trx, "purchaseInvoice", companyId);supplierId;invoiceSupplierId,paymentTermId, contact and location fromsupplierPayment;currencyCode= the lease's;exchangeRate1 (base currency only);locationId= the lease's;dateIssued= the group'sdueDate; totals from the rows;createdBy=userId.- a
purchaseInvoiceDeliveryrow withid= the invoice id (copyconvert). - one line per row:
invoiceLineType "Lease",leaseId,leasePaymentId,description=${lease.name} — ${periodStart} to ${periodEnd}(Purchase Option / Termination Penalty rows say so),quantity 1,supplierUnitPrice= amount,exchangeRate 1,locationId,sortOrder. - stamp the rows
Invoicedwith their line ids.
- Return
{ invoices: { invoiceId, leaseId }[], invoiceIds, failures }. - Register in
invoke.ts. - Test (
databaseTest, the Task 14 fixture): an Active lease with two rows due drafts two invoices with one Lease line each; a second run drafts none; a row due beforeinvoiceFromDate(statusSkipped) is never drafted.
Verify:
pnpm --filter @carbon/server-functions test -- create-lease-invoices permissions-manifest
# Expected: passes
Out of scope: posting the drafts (users post them).
Task 25: Run lease invoicing, expiry and reminders from the daily job
Depends on: Task 24 Files:
- Modify:
packages/jobs/src/inngest/functions/scheduled/recurring-billing.ts - Modify:
packages/jobs/src/invoicing/digest.ts,digest.test.ts - Create:
packages/jobs/src/invoicing/lease-reminders.ts,lease-reminders.test.ts - Modify:
packages/notifications/src/index.ts—LeaseCriticalDate - Modify:
packages/jobs/src/inngest/functions/notifications/notify.ts,content.ts - Modify:
apps/erp/app/components/Layout/Topbar/Notifications.tsx,apps/erp/app/routes/api+/link.ts
Steps:
- In
find-companies, add companies with an Active lease (hasLeases). - Add a step
lease-billing-${id}that invokescreate-lease-invoiceswith today in the company time zone. Push each draft as{ invoiceId, sourceId: leaseId, outcome: "drafted" }. Lease drafts skip the automation steps. - In
digest.ts: add"drafted"toInvoiceRunOutcome; exclude it fromposted; body${posted} posted, ${emailed} emailed, ${review} need review, ${drafted} drafted(omit the drafted clause when 0);documentIdsprefer review, then drafted, then posted. Extenddigest.test.ts. - In
digest-recipients, also readlease["id", "assignee", "createdBy"]; owner =assignee ?? createdBy. - In
lease-reminders.ts, export the puredueLeaseReminders(leases, today, leadDays)→{ leaseId, kind: "notice" | "end", date }[]for dates exactlyleadDaysaway or less and not yet reminded (noticeRemindedFor/endRemindedFor≠ date). Test it. - Add a step
lease-reminders-${id}: read Active leases withnoticeDateorendDate,leaseReminderDays; sendcarbon/notifywithevent: NotificationEvent.LeaseCriticalDate,documentId: lease.id, recipient = owner, plus the "Also notify" group; stampnoticeRemindedFor/endRemindedFor. - Add a step
lease-expiry-${id}: setExpiredon Active leases whose rows are all Posted and whose payment rows are allInvoicedorSkipped. - In
notifications/src/index.ts, addLeaseCriticalDate = "lease-critical-date"; topicPurchasing; email heading "Lease date coming up"; CTA "Open lease". Innotify.tsdestinations[InApp, Email]. Incontent.ts, the descriptionLease ${readableId}: ${body}. - In
Notifications.tsxandapi+/link.ts, linkLeaseCriticalDatetopath.to.leaseDetails(documentId). ForRecurringInvoicing, link to purchase invoices when the first document id is a purchase invoice (look it up), else keep the sales link.
Verify:
pnpm --filter @carbon/jobs test -- digest lease-reminders
# Expected: passes
pnpm exec turbo run typecheck --filter=@carbon/jobs --filter=@carbon/notifications --filter=erp
# Expected: 0 errors
Out of scope: automated posting of lease invoices.
Task 26: Add the lease policy settings
Depends on: Task 14 Files:
- Modify:
apps/erp/app/modules/settings/settings.service.ts—updateLeasePolicySettings - Modify:
apps/erp/app/routes/x+/settings+/accounting.tsx— validator, defaults, three inputs
Steps:
- Add
leaseIncrementalBorrowingRate,leaseShortTermExpedient,leaseReminderDaysto the service's settings type. - Add them to
leasePolicySettingsValidator(zfd.numeric(min 0),zfd.checkbox(),zfd.numeric(int, min 0)) and the form'sdefaultValues. - Add a
NumberInput"Incremental Borrowing Rate (%)" (INPUT_FORMAT.percentPoints), aBoolean"Short-term lease expedient", and aNumberInput"Lease reminder days". Rename the existing "Default Discount Rate" label to "Lessor Discount Rate (%)".
Verify:
pnpm exec turbo run typecheck --filter=erp
# Expected: 0 errors
Out of scope: per-class policies.
Task 27: Add the cutover open items
Depends on: Task 14 Files:
- Modify:
packages/database/src/accounting-cutover.ts—OpenItemType - Modify:
packages/database/src/accounting-cutover/open-items.ts—getLeaseLiabilityItems, wiring - Modify:
packages/database/src/accounting-cutover/trial-balance.ts— control accounts - Modify:
apps/erp/app/routes/x+/accounting+/activation.enable.tsx—AGGREGATE_ITEM_TYPES - Create:
packages/server-functions/src/activate-accounting/legacy/lessee-leases.test.ts - Copy from (precedent):
getLeaseNetInvestmentItems(open-items.ts:1164–1245),legacy-runs.test.ts:357–466
Steps:
- Add
"Lease Liability" | "Right-of-Use Asset" | "Accumulated ROU Amortization"toOpenItemType. - Add
getLeaseLiabilityItems(db, companyId, cutoverDate, defaults): Active / Expired / Terminated / Purchased leases withinitialLiability is not nullandcommencementDate < cutoverDate. Per lease:- liability =
closingLiabilityof the last schedule line withperiodDate < cutoverDate(DISTINCT ON), elseinitialLiability; itembasis "debit",original: -round(liability)onleaseLiabilityAccount. - ROU =
initialRouAsset+ ΣleaseEvent(rouAssetAfter − rouAssetBefore) witheffectiveDate < cutoverDate; itemoriginal: round(rou)onrightOfUseAssetAccount. - accumulated = Σ
rouAmortizationof lines withperiodDate < cutoverDate; itemoriginal: -round(accumulated)onaccumulatedRightOfUseAmortizationAccount. documentType: "Lease",documentId: lease.id. Skip zero items. A missing default throwsSet the <column> account default.- Leases ended (Terminated / Purchased) before the cutover produce no items.
- liability =
- Wire it into
openItemsForaftergetLeaseNetInvestmentItems. - Add the three lease defaults to
controlAccountIdsbesidenetInvestmentInLeasesAccount. - Add the three types to
AGGREGATE_ITEM_TYPESif Lease Net Investment is there. - Test with
activationFixture(): a lease with 12 schedule lines before the cutover yields three items equal to the rows.
Verify:
pnpm --filter @carbon/server-functions test -- lessee-leases legacy-runs
# Expected: passes
Out of scope: leases entered after the enable (Task 30).
Task 28: Add the Lease Liabilities report
Depends on: Task 14 Files:
- Modify:
apps/erp/app/modules/accounting/accounting.service.ts—getLeaseLiabilities - Create:
apps/erp/app/routes/x+/reports+/lease-liabilities.tsx - Modify:
apps/erp/app/routes/x+/accounting+/reports.tsx— hub card - Modify:
apps/erp/app/utils/path.ts—leaseLiabilities - Create:
apps/erp/app/modules/accounting/lease-liabilities.test.ts - Copy from (precedent):
getLeaseNetInvestment(accounting.service.ts:7899–8110),x+/reports+/lease-net-investment.tsx
Steps:
- Put the arithmetic in a pure
summarizeLeaseLiabilities(leases, lines, payments, { asOf, startMonth })inaccounting.utils.tsand call it fromgetLeaseLiabilities(client, companyId, { asOf, from, to })(@mcp read). - Per lease row:
leaseId,name,supplierName,classification,remainingMonths,discountRate,liability(closing of the last line withperiodDate <= asOf),currentPortion(Σ principal of lines in the next 12 months),nonCurrentPortion,netRou,maturityByFiscalYear(undiscounted Pending/Invoiced-after-asOf payments byfiscalYearAndPeriodFor; years beyond 5 summed as "Thereafter"). - Totals per classification: undiscounted total, imputed interest (= undiscounted − liability), weighted-average remaining term (years, weighted by liability), weighted-average rate (weighted by remaining undiscounted payments).
- Period costs for
[from, to]: operating lease cost, finance amortization, finance interest (posted rows bytype), short-term cost and variable cost (posted purchase invoice Lease lines), cash paid (posted Lease lines withleasePaymentId). - The route copies
lease-net-investment.tsx: asOf picker, the lease table withexportValueon every column, then two small tables (totals; period costs) with their own pickers forfrom/to. - Hub card
key "lease-liabilities", name "Lease Liabilities", description "Lessee lease balances, maturity analysis and lease cost", category Close Reports. - Test
summarizeLeaseLiabilitieswith two leases: maturity − imputed interest = Σ liability; the weighted averages match a hand calculation.
Verify:
cd apps/erp && pnpm exec vitest run app/modules/accounting/lease-liabilities.test.ts
# Expected: passes
Out of scope: posted current / non-current reclass (spec: out of v1).
Task 29: Link journals to leases
Depends on: Task 14 Files:
- Modify:
apps/erp/app/modules/accounting/accounting.service.ts—JournalSourceDocument.kind, aLeasebranch - Modify:
apps/erp/app/modules/accounting/ui/JournalEntries/JournalEntryDocuments.tsx—leasekind
Steps:
- Add
"lease"to thekindunion. - Copy the Rental Agreement branch (5928–5941) for
idsOf("Lease")fromleaseselectingid, leaseId. - Add
lease: { label: t\Lease`, to: path.to.leaseDetails, icon: "Lease" }`.
Verify:
pnpm exec turbo run typecheck --filter=erp
# Expected: 0 errors
Out of scope: run journals (Task 11).
Task 30: Opening journal for a lease entered after the enable
Depends on: Task 14 Files:
- Modify:
packages/server-functions/src/post-lease/index.ts,lessee.ts - Modify:
packages/server-functions/src/post-lease/activate.test.ts
Steps:
- Spec Q8 (resolved): when the company has a cutover and
commencementDate< cutover, the as-of date = the later of the cutover date and the first day of the earliest open accounting period. - Build the full schedule from commencement. Insert the lines; insert the recognition rows with
scheduledDate < asOfasstatus: "Posted",journalId: null. - Post one
Leasejournal dated the as-of date: Dr ROUrouAssetCost, Cr accumulated (Σ amortization before as-of), Cr liability (carrying at as-of), and the difference toretainedEarningsAccount. - Replace the Task 14 refusal with this path. Add a test.
Verify:
pnpm --filter @carbon/server-functions test -- post-lease
# Expected: passes
Out of scope: Migration Clearing (never posted by this path).
Task 31: Update AGENTS.md, rules and docs
Depends on: Tasks 1–29 Files:
- Modify:
apps/erp/app/modules/purchasing/AGENTS.md— a "Leases (sub-area)" section - Modify:
apps/erp/app/modules/accounting/AGENTS.md— run types, Lease Run source, Lease Liabilities report, lessee open items - Modify:
apps/erp/app/modules/sales/AGENTS.md— rental rows post in lease runs - Modify:
apps/erp/app/modules/invoicing/AGENTS.md(if present) — the Lease line type - Modify:
.claude/rules/fixed-asset-lifecycle.md— purchase option creates an asset - Create:
docs/content/docs/reference/leases.mdx - Modify:
docs/content/docs/reference/rental-agreements.mdx,accounting.mdx— lease runs - Modify:
docs/content/src/glossary/terms.ts— Lease (lessee), Right-of-Use Asset, Lease Liability, Lease Run - Modify:
AGENTS.md(root Task Router) — the lessee leases row
Steps:
- Load the
carbon-docsskill for the docs pages. Ground every claim in the code from Tasks 1–29. - Write the module AGENTS.md sections with the real file paths, tables and functions.
- Run the docs link check from
.claude/rules/changelog-authoring.md("Every internal link must resolve").
Verify:
pnpm --filter docs typecheck
# Expected: 0 errors
Out of scope: a changelog entry (separate, after merge).
Task 32: Run the full verification sweep
Depends on: Task 31 Files: none new
Steps:
pnpm --filter @carbon/checks license-headerspnpm run lintpnpm exec turbo run typecheck --filter=@carbon/database --filter=@carbon/utils --filter=@carbon/ee --filter=@carbon/server-functions --filter=@carbon/jobs --filter=@carbon/notifications --filter=erp --filter=docspnpm --filter @carbon/utils test,pnpm --filter @carbon/database test,pnpm --filter @carbon/server-functions test,pnpm --filter @carbon/jobs test,cd apps/erp && pnpm exec vitest run app/modules/accounting app/modules/purchasingpnpm db:check:datasetsandpnpm db:check:backups(afterpnpm db:migrate)pnpm --filter @carbon/checks clobbers
Verify:
# Every command above exits 0.
Out of scope: fixing unrelated pre-existing failures — report them.
Task 33: Extract and translate the new strings
Depends on: Task 32
Files: packages/locale/locales/*/*.po
Steps:
- Run the lingui extract command from
.claude/rules/i18n-lingui-system.md. - Run the
/translateskill.
Verify:
git diff --stat packages/locale/locales | tail -1
# Expected: the catalogs changed; /translate reports 0 missing
Out of scope: changing existing translations.
Task 34: Verify in the browser
Depends on: Task 33 Files: none
Steps:
- Ask the user for permission, then run
/authand/testagainst the worktree's ERP (never localhost:3000). - Flows:
- Purchasing → Leases → New Lease (36 months, $10,000 Monthly, Arrears, 6%); see 36 payment rows; edit row 4 to 0; regenerate.
- Activate; see Operating, liability $328,710.16 and the commencement journal.
- Invoice now (or wait for the job); post the drafted purchase invoice; open its journal (Dr Lease liability / Cr AP).
- Accounting → Lease Runs → New run for the first month; post it; see one Lease Run journal; Revenue Recognition has no run for the month.
- Close wizard for that period shows "Post lease journals" passing.
- Modify at month 2; Terminate on a second lease; Purchase on a third lease with a purchase option.
- Reports → Lease Liabilities shows the leases and reconciles.
- A rental agreement's accrual rows now appear in a Lease Run.
- Save screenshots under
.context/.
Verify: every flow passes in the /test result table.
Out of scope: load tests.