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.
Rental shipments and receipts — implementation plan
Spec: .ai/specs/2026-10-07-rental-shipments-and-receipts.md Research: .ai/research/rental-delivery-and-return.md Branch: rental-shipment-receipt
Spec status
The spec carries every planning correction (C1–C7, C9) and the answers to Q7
and Q8. This plan follows the spec. Q7 (a Sale line returns at the receipt's
location) and Q8 (a receipt holds Pending units, plus Release unit) are
in spec → Open Questions.
Plan decisions not in the spec
| # | Decision | Reason |
|---|---|---|
| P1 | Release refuses a Sale line: "<unit> is treated as a sale; return it on a rental receipt instead". The UI hides Release unit for a Sale line. |
Release passes no residual destination, and salesTypeReturnError refuses a Sale return without one (post-rental-agreement/lessor.ts:380-398). A Pending Sale line can still come back on a rental receipt, with Return To, on or after the end date. |
| P2 | Release refuses a unit that sits on an open (Draft or Pending) rental shipment or receipt. The message names the document. | Otherwise the unit is Returned while an open document still holds it, and Close refuses until someone deletes that line. |
| P3 | A per-unit shortcut ticks its unit when the unit is already on the Draft but unticked. | Spec Flow: "The shortcut always adds its unit ticked." A Pending unit sits unticked on a receipt by default. |
| P4 | returnResidual uses the given locationId for the stock ledger row, the new fleet asset and its Capitalization transfer. The journal's Location dimension tag keeps the agreement's location. |
The transfer records the same move as the asset. The spec keeps the journal "the same as today". |
Progress
- Task 1: Add the enum migration
- Task 2: Add the fixed-asset line migration
- Task 3: Apply the migrations, regenerate types and fix the nullable readers
- Task 4: Build the rental test fixture and pin today's return
- Task 5: Move the return body into
returnRentalUnit - Task 6: Add the pure rental document rules
- Task 7: Add the two
createcases - Task 8: Post a rental shipment
- Task 9: Void a rental shipment
- Task 10: Post a rental receipt and refuse its void
- Task 11: Add the Close guard
- Task 12: Add the ERP models, service reads and the line-documents helper
- Task 13: Add the rental branches to the inventory
newanddetailsroutes - Task 14: Load the rental lines and save their fields
- Task 15: Pass the posting date from the post routes
- Task 16: Turn the per-unit Deliver and Return routes into shortcuts
- Task 17: Show the rental units on the shipment page
- Task 18: Show the rental units on the receipt page
- Task 19: Add the source to tables, forms, document panels and traceability
- Task 20: Print a Delivery Ticket
- Task 21: Add Deliver and Return to the agreement header
- Task 22: Replace the
returntype withrelease - Task 23: Repoint the unit actions and add Release unit
- Task 24: Run the full verification sweep
- Task 25: Extract and translate the new strings
- Task 26: Update the docs
- Task 27: Verify in the browser
Dependencies
- Task 2 needs Task 1. Task 3 needs Task 2.
- Task 4 needs Task 3. Task 5 needs Task 4.
- Task 6 needs Task 3. Tasks 4–5 and Task 6 are independent of each other.
- Task 7 needs Tasks 3 and 6.
- Tasks 8, 10 and 11 need Tasks 5, 6 and 7. They are independent of each other. Task 9 needs Task 8.
- Task 12 needs Task 3. It is independent of Tasks 4–11.
- Task 13 needs Tasks 7 and 12. Task 14 needs Task 12. Task 15 needs Tasks 8 and 10.
- Task 16 needs Tasks 7 and 12.
- Tasks 17 and 18 need Tasks 14 and 15. Task 19 needs Tasks 12 and 13. Task 20 needs Tasks 12 and 14. Tasks 17–20 are independent of each other.
- Task 21 needs Task 16. Task 22 needs Tasks 10 and 16. Tasks 21 and 22 are independent of each other.
- Task 23 needs Tasks 16 and 22.
- Task 24 needs Tasks 1–23. Task 25 needs Task 24. Task 26 needs Tasks 22 and 23. Task 27 needs Tasks 24–26.
Conventions for every task
Read
.ai/lessons.mdsections "A migration file created while migrations are running…", "A new FK on a busy table breaks bare PostgREST embeds of it (TS2589)" and "Kysely writes in a server function bypass RLS…" before Task 1.In a server function, every Kysely read and write filters on
companyId.Refusals that 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 rebuild the database. Never run a whole-repo typecheck.
A database test skips without a local
SUPABASE_DB_URL. Run every database test with this prefix, from the repo root:export SUPABASE_DB_URL="$(grep '^SUPABASE_DB_URL=' .env.local | cut -d= -f2-)"If a database test reports "skipped", STOP and report. A skip proves nothing.
Task 1: Add the enum migration
Depends on: none Files:
- Create:
packages/database/supabase/migrations/<timestamp>_rental-documents-enums.sql - Copy from (precedent):
packages/database/supabase/migrations/20261006221201_contract-enums.sql:1-4
Steps:
🛑 Check that no
crbn up,crbn migrateorpnpm db:migrateruns now. A running migrate records a new empty file as applied.Run
pnpm db:migrate:new rental-documents-enums.Write this SQL into the new file. Write nothing else into it.
-- Rental shipments and receipts (.ai/specs/2026-10-07-rental-shipments-and-receipts.md). -- Enums only: an ADD VALUE cannot share a transaction with statements that use it. ALTER TYPE "shipmentSourceDocument" ADD VALUE IF NOT EXISTS 'Rental Agreement'; ALTER TYPE "receiptSourceDocument" ADD VALUE IF NOT EXISTS 'Rental Agreement';
Verify:
ls packages/database/supabase/migrations | tail -2
# Expected: the new file is last; its HHMMSS is not 000000; its timestamp is after 20261007171726.
grep -c "ADD VALUE IF NOT EXISTS 'Rental Agreement'" packages/database/supabase/migrations/*_rental-documents-enums.sql
# Expected: 2
Out of scope: Applying the migration (Task 3).
Task 2: Add the fixed-asset line migration
Depends on: Task 1 Files:
- Create:
packages/database/supabase/migrations/<timestamp>_rental-documents.sql - Copy from (precedent):
packages/database/supabase/migrations/20261007171726_rental-credit-memos.sql:24-33(idempotent constraints),20260908142501_returns-module.sql:52-60(Draft-uniqueness indexes)
Steps:
🛑 Check again that no migrate runs now.
Run
pnpm db:migrate:new rental-documents. The new file must sort after the Task 1 file.Write this SQL into the file:
-- Rental shipments and receipts (.ai/specs/2026-10-07-rental-shipments-and-receipts.md). -- A rental unit rides on the fixed-asset line tables. Exactly one source line per row. ALTER TABLE "shipmentFixedAssetLine" ALTER COLUMN "salesOrderLineId" DROP NOT NULL; ALTER TABLE "shipmentFixedAssetLine" ADD COLUMN IF NOT EXISTS "rentalAgreementLineId" TEXT; ALTER TABLE "shipmentFixedAssetLine" ADD COLUMN IF NOT EXISTS "meter" NUMERIC; DO $$ BEGIN ALTER TABLE "shipmentFixedAssetLine" ADD CONSTRAINT "shipmentFixedAssetLine_rentalAgreementLineId_fkey" FOREIGN KEY ("rentalAgreementLineId", "companyId") REFERENCES "rentalAgreementLine"("id", "companyId") ON DELETE CASCADE ON UPDATE CASCADE; EXCEPTION WHEN duplicate_object THEN NULL; END $$; DO $$ BEGIN ALTER TABLE "shipmentFixedAssetLine" ADD CONSTRAINT "shipmentFixedAssetLine_source_check" CHECK (num_nonnulls("salesOrderLineId", "rentalAgreementLineId") = 1); EXCEPTION WHEN duplicate_object THEN NULL; END $$; CREATE INDEX IF NOT EXISTS "shipmentFixedAssetLine_rentalAgreementLineId_idx" ON "shipmentFixedAssetLine" ("rentalAgreementLineId"); ALTER TABLE "receiptFixedAssetLine" ALTER COLUMN "purchaseOrderLineId" DROP NOT NULL; ALTER TABLE "receiptFixedAssetLine" ADD COLUMN IF NOT EXISTS "rentalAgreementLineId" TEXT; ALTER TABLE "receiptFixedAssetLine" ADD COLUMN IF NOT EXISTS "meter" NUMERIC; ALTER TABLE "receiptFixedAssetLine" ADD COLUMN IF NOT EXISTS "notes" TEXT; ALTER TABLE "receiptFixedAssetLine" ADD COLUMN IF NOT EXISTS "takeOutOfService" BOOLEAN NOT NULL DEFAULT false; ALTER TABLE "receiptFixedAssetLine" ADD COLUMN IF NOT EXISTS "outOfServiceReason" TEXT; ALTER TABLE "receiptFixedAssetLine" ADD COLUMN IF NOT EXISTS "residualDestination" TEXT; DO $$ BEGIN ALTER TABLE "receiptFixedAssetLine" ADD CONSTRAINT "receiptFixedAssetLine_residualDestination_check" CHECK ("residualDestination" IN ('Fleet', 'Inventory')); EXCEPTION WHEN duplicate_object THEN NULL; END $$; DO $$ BEGIN ALTER TABLE "receiptFixedAssetLine" ADD CONSTRAINT "receiptFixedAssetLine_rentalAgreementLineId_fkey" FOREIGN KEY ("rentalAgreementLineId", "companyId") REFERENCES "rentalAgreementLine"("id", "companyId") ON DELETE CASCADE ON UPDATE CASCADE; EXCEPTION WHEN duplicate_object THEN NULL; END $$; DO $$ BEGIN ALTER TABLE "receiptFixedAssetLine" ADD CONSTRAINT "receiptFixedAssetLine_source_check" CHECK (num_nonnulls("purchaseOrderLineId", "rentalAgreementLineId") = 1); EXCEPTION WHEN duplicate_object THEN NULL; END $$; DO $$ BEGIN ALTER TABLE "receiptFixedAssetLine" ADD CONSTRAINT "receiptFixedAssetLine_outOfService_check" CHECK (NOT "takeOutOfService" OR "outOfServiceReason" IS NOT NULL); EXCEPTION WHEN duplicate_object THEN NULL; END $$; CREATE INDEX IF NOT EXISTS "receiptFixedAssetLine_rentalAgreementLineId_idx" ON "receiptFixedAssetLine" ("rentalAgreementLineId"); -- One open Draft per agreement: backs the header's open-the-existing-draft behavior. CREATE UNIQUE INDEX IF NOT EXISTS "shipment_oneOpenDraftPerRentalAgreement_idx" ON "shipment" ("sourceDocumentId", "companyId") WHERE "status" = 'Draft' AND "sourceDocument" = 'Rental Agreement'; CREATE UNIQUE INDEX IF NOT EXISTS "receipt_oneOpenDraftPerRentalAgreement_idx" ON "receipt" ("sourceDocumentId", "companyId") WHERE "status" = 'Draft' AND "sourceDocument" = 'Rental Agreement';Do not add RLS policies. The tables keep their manifest rules (
packages/database/src/authz/manifest.ts:1219and:1383). The rules are per table, so new columns inherit them.migration.test.tshashes the rendered rules, which do not change. Do not write an authz migration.Do not add a
TABLE_RENAMESentry: nothing is renamed or dropped. Do not add anID_REF_COLUMNSentry:rentalAgreementLineIdhas a FK.
Verify:
grep -c "CREATE POLICY" packages/database/supabase/migrations/*_rental-documents.sql
# Expected: 0
grep -c "oneOpenDraftPerRentalAgreement_idx" packages/database/supabase/migrations/*_rental-documents.sql
# Expected: 2
Out of scope: The PK of the fixed-asset line tables stays ("id"). Do not change it.
Task 3: Apply the migrations, regenerate types and fix the nullable readers
Depends on: Task 2 Files:
- Modify:
packages/database/src/types.tsand the other generated files — by the generator only - Modify:
packages/server-functions/src/post-shipment/index.ts:630-638— filter sales-order rows - Modify:
packages/server-functions/src/post-receipt/index.ts:1891-1905— filter purchase-order rows - Modify:
packages/server-functions/src/convert/index.ts:1434-1437— skip a null line id - Modify:
apps/erp/app/routes/x+/shipment+/$shipmentId.tsx:76-104— filter sales-order rows - Modify:
apps/erp/app/routes/x+/receipt+/$receiptId.tsx:105-132— filter purchase-order rows
Steps:
Run
pnpm db:migrate. It applies both files and regenerates the types and swagger.Run
pnpm run generate:types.In
post-shipment/index.ts:630-635, addcompanyIdto themany(...)filter object.In
post-shipment/index.ts:636-638, buildshippedFaSoLineIdsfrom(shipmentFaLines ?? []).filter((r) => r.salesOrderLineId !== null).In
post-receipt/index.ts:1891-1896, addcompanyIdto themany(...)filter object.Directly after that read, narrow the rows once:
const poFaLines = (receiptFaLines ?? []).filter( (r): r is typeof r & { purchaseOrderLineId: string } => r.purchaseOrderLineId !== null );Replace each
receiptFaLines ?? []inpost-receipt/index.ts:1897-1905withpoFaLines.In
convert/index.ts:1435, addif (!lineId) continue;afterconst lineId = line.salesOrderLineId;.In
$shipmentId.tsx, add.not("salesOrderLineId", "is", null)to theshipmentFixedAssetLinequery at line 79-84.In
$receiptId.tsx, add.not("purchaseOrderLineId", "is", null)to thereceiptFixedAssetLinequery at line 107-112.Run the two typechecks below. Fix each error that the nullable order-line columns cause with a null check of the same shape.
If the
erptypecheck shows TS2589 ("excessively deep") in a file that embedsrentalAgreementLine,shipmentFixedAssetLineorreceiptFixedAssetLine, name the FK in that embed. Precedent: the TS2589 lesson in.ai/lessons.md.If the typecheck shows any other kind of error, STOP and report — do not improvise.
Verify:
grep -c '"Rental Agreement"' packages/database/src/types.ts
# Expected: at least 2 (both enums)
grep -c "takeOutOfService" packages/database/src/types.ts
# Expected: at least 3 (Row, Insert, Update of receiptFixedAssetLine)
pnpm exec turbo run typecheck --filter=@carbon/server-functions --concurrency=1
# Expected: Tasks: 1 successful (or more), 0 failed
pnpm exec turbo run typecheck --filter=erp
# Expected: 0 failed
pnpm db:check:datasets
# Expected: exit 0; every dataset passes
pnpm db:check:backups
# Expected: exit 0
If the enum check prints 0, the migration was recorded empty. Run
psql "$SUPABASE_DB_URL" -c "select version, array_length(statements,1) from supabase_migrations.schema_migrations order by version desc limit 3".
If a NULL count shows, STOP and report.
Out of scope: Any reader that already filters by .in("salesOrderLineId", …) or .in("purchaseOrderLineId", …), such as accounting.service.ts:8444-8455. .in() never matches null.
Task 4: Build the rental test fixture and pin today's return
Depends on: Task 3 Files:
- Create:
packages/server-functions/src/post-rental-agreement/rental-test-fixture.ts - Create:
packages/server-functions/src/post-rental-agreement/return-unit.test.ts - Copy from (precedent):
packages/server-functions/src/create-rental-invoices/create-rental-invoices.test.ts:21-185
Steps:
Create
rental-test-fixture.ts. Export this function:export async function rentalFixture(options?: { units?: number; // default 1 billingTiming?: "Advance" | "Arrears"; // default "Advance" }): Promise<{ db: Kysely<KyselyDatabase>; ctx: ServerFnContext; // ServerFnContext.system({ db, companyId, userId: "system" }) companyId: string; agreementId: string; agreementReadableId: string; // "RA-TEST" locationId: string; otherLocationId: string; lineIds: string[]; fixedAssetIds: string[]; fixedAssetReadableIds: string[]; // "FA-1", "FA-2", … trackedEntityIds: string[]; itemId: string; cleanup(): Promise<void>; }>;Insert these rows in one transaction with
app.sync_in_progressset, as the precedent does:companyGroup,company(timezoneAmerica/New_York),currencyUSD with 2 decimals,companySettings.sequencerows forshipment(prefixSHP-),receipt(prefixRCV-) andfixedAsset(prefixFA).- One
customer. Twolocationrows:locationIdandotherLocationId. - One
item: typePart,itemTrackingTypeSerial. - One
fixedAssetClass, then onefixedAssetper unit: statusActive,locationId, nameScissor lift N,fixedAssetIdFA-N,serialNumberSN-N. - One
trackedEntityper unit. SetfixedAsset.trackedEntityIdto it. - One
rentalAgreement:rentalAgreementIdRA-TEST, statusActive,startDate2026-09-01,endDatenull,billingCycleCalendar Month, thebillingTimingoption,discountRate0,currencyCodeUSD,locationId. - One
rentalAgreementLineper unit: statusPending,rateUnitMonth,rate300,lessorClassificationRental, itsfixedAssetIdandtrackedEntityId. - Two
rentalBillingPeriodrows per line:2026-09-01–2026-09-30(30 days, 300, due2026-09-01, statusInvoiced) and2026-10-01–2026-10-31(31 days, 300, due2026-10-01, statusPending).
Read the NOT NULL columns of
fixedAssetClass,fixedAssetandtrackedEntityinpackages/database/src/types.ts(Inserttypes). Fill only the required ones.Copy
cleanup()from the precedent (create-rental-invoices.test.ts:164-182).Create
return-unit.test.tswith onedatabaseTestnamed"an early return of an Advance unit re-cuts its periods":- Build
rentalFixture(). - Set the line
On RentwithdeliveredAt2026-09-01by a direct Kysely update. - Act through a local function
returnUnitOnSeptember20(f). For now it calls the default export of./indexwith{ type: "return", rentalAgreementId: f.agreementId, rentalAgreementLineId: f.lineIds[0], returnedAt: "2026-09-20" }. - Expect
result.errorto benull. - Read the line's periods:
periodStart::text,periodEnd::text,days,Number(amount),isAdjustment,status,rateUnitApplied,dueOn::text. Order byperiodStart, thenisAdjustment. - Read the line's
statusandreturnedAt::text. - Run
expect({ periods, line }).toMatchSnapshot(). - Call
f.cleanup()in afinally.
- Build
Verify:
export SUPABASE_DB_URL="$(grep '^SUPABASE_DB_URL=' .env.local | cut -d= -f2-)"
pnpm --filter @carbon/server-functions exec vitest run src/post-rental-agreement/return-unit.test.ts
# Expected: 1 passed; "1 written" snapshot on this first run
grep -c "isAdjustment\": true" packages/server-functions/src/post-rental-agreement/__snapshots__/return-unit.test.ts.snap
# Expected: 1 (the early-return adjustment row)
If the snapshot has no adjustment row, the fixture does not exercise an invoiced Advance period. STOP and report.
Out of scope: Any change to index.ts.
Task 5: Move the return body into returnRentalUnit
Depends on: Task 4
This task moves code and adds one optional input, locationId (spec Q7).
Without locationId, the output must stay byte-identical to today.
Files:
- Create:
packages/server-functions/src/post-rental-agreement/agreement.ts - Create:
packages/server-functions/src/post-rental-agreement/return-unit.ts - Modify:
packages/server-functions/src/post-rental-agreement/index.ts— import the moved code;returnUnitbecomes a wrapper
Steps:
Move these declarations from
index.tsintoagreement.ts, without edits, and export each one:type Db,type Trx,type Enums(index.ts:84-86)type AgreementRow(index.ts:93-109)lockAgreement(index.ts:116-154),currencyDecimals(:158-176),billingPeriodRow(:178-198)type LeaseAccountingandloadLeaseAccounting(:202-285)postLeaseJournal(:288-347),insertUnitActivity(:350-392)
Move each import that only these declarations use into
agreement.ts.In
return-unit.ts, export this type and function:export type RentalUnitReturn = { rentalAgreementLineId: string; returnedAt: string; // YYYY-MM-DD meterIn?: number | null; returnNotes?: string | null; takeOutOfService?: boolean; outOfServiceReason?: string | null; residualDestination?: ResidualDestination | null; }; /** Returns one unit of a locked, Active agreement. The caller locks the * agreement, checks it is Active and refuses a future return date. */ export async function returnRentalUnit( trx: Trx, args: { agreement: AgreementRow; unit: RentalUnitReturn; companyId: string; userId: string; today: string; /** Where a `Sale` line's residual lands (stock or new fleet asset). * Without it, the agreement's location, as today. */ locationId?: string; } ): Promise<{ fixedAssetId: string | null }>;Set the body of
returnRentalUnittoindex.ts:1065-1253: from therentalAgreementLineread to the end of the out-of-service update.In the moved body, rename
payload.tounit.. Return{ fixedAssetId: fleetAssetId }. Change nothing else.Move
returnResidualwith its doc comment (index.ts:1258-1655) intoreturn-unit.ts.Add
locationId: stringto theargstype ofreturnResidual.In
returnResidual, replaceagreement.locationIdwithargs.locationIdat exactly these 3 places:- the
fixedAssetinsert (index.ts:1489) - the
fixedAssetTransferinsert (index.ts:1520) - the
bookAdjustmentledger row (index.ts:1565)
- the
Leave
tags.locationId(index.ts:1409) onagreement.locationId. The journal stays the same as today (plan decision P4).In
returnRentalUnit, passlocationId: args.locationId ?? agreement.locationIdtoreturnResidual.Rewrite
returnUnitinindex.tsas this wrapper. It passes nolocationId:
async function returnUnit(
{ db, companyId, userId }: Scope,
payload: Extract<RentalAgreementPayload, { type: "return" }>,
today: string
): Promise<{ id: string }> {
const future = futureReturnError(payload.returnedAt, today);
if (future) throw new InvalidInputError(future);
return db.transaction().execute(async (trx) => {
const agreement = await lockAgreement(trx, companyId, payload.rentalAgreementId);
if (agreement.status !== "Active") {
throw new InvalidInputError(
`Rental agreement ${agreement.rentalAgreementId} is ${agreement.status}; units are returned from an Active agreement`
);
}
await returnRentalUnit(trx, { agreement, unit: payload, companyId, userId, today });
return { id: agreement.id };
});
}
- Remove the imports from
index.tsthat nothing uses any more. - Run
pnpm --filter @carbon/checks license-headers.
Verify:
export SUPABASE_DB_URL="$(grep '^SUPABASE_DB_URL=' .env.local | cut -d= -f2-)"
pnpm --filter @carbon/server-functions exec vitest run src/post-rental-agreement
# Expected: every test passes; return-unit.test.ts passes with NO "written" and NO "obsolete" snapshot
grep -c "agreement.locationId" packages/server-functions/src/post-rental-agreement/return-unit.ts
# Expected: 2 (the tags line and the fallback in returnRentalUnit)
pnpm exec turbo run typecheck --filter=@carbon/server-functions --concurrency=1
# Expected: 0 failed
grep -c "^export" packages/server-functions/src/post-rental-agreement/agreement.ts
# Expected: at least 9
Do not run vitest with -u in this task. A snapshot change means the move
changed behavior. If the snapshot fails, STOP and report.
Out of scope: Replacing the return type (Task 22). Any edit to the moved logic beyond steps 7–10.
Task 6: Add the pure rental document rules
Depends on: Task 3 Files:
- Modify:
packages/server-functions/src/post-rental-agreement/validators.ts— new fields object, validator and helpers - Modify:
packages/server-functions/src/post-rental-agreement/validators.test.ts— tests
Steps:
Split
returnValidator(validators.ts:45-63). Move its fields excepttypeandrentalAgreementIdintoconst unitReturnFields = { … }.Export
unitReturnValidator = z.object(unitReturnFields).refine(…). Use the existing out-of-service refine.Rebuild
returnValidatorasz.object({ type: z.literal("return"), ...unitReturnFields, ...scope }).refine(…). Keep the same refine.Add these exports:
/** The unit's name in a refusal: its asset number, else its asset name, else the line id. */ export function unitLabel( asset: { fixedAssetId: string | null; name: string | null } | undefined, lineId: string ): string; /** Why a delivery cannot be dated `deliveredOn`, or null. */ export function futureDeliveryError(deliveredOn: string, today: string): string | null; // returns "The delivery date cannot be in the future" when deliveredOn > today /** Why a rental shipment cannot be voided, or null. `accrual` is the worst * Accrual row of the unit: "Posted", "Draft run" (Planned with a runLineId), or null. */ export function rentalShipmentVoidBlocker( units: { label: string; status: Enums["rentalAgreementLineStatus"]; accrual: "Posted" | "Draft run" | null; }[] ): string | null; /** Why an agreement cannot close while a rental document is still open, or null. */ export function openRentalDocumentBlocker(args: { shipmentId: string | null; // readable id of an open shipment that has a line receiptId: string | null; // readable id of an open receipt that has a line }): string | null; /** Why a unit on a rental receipt cannot be returned, or null. * A receipt returns a Pending or an On Rent unit (spec Q8). */ export function receiptReturnError( label: string, status: Enums["rentalAgreementLineStatus"] ): string | null; /** Why a release date is refused, or null. */ export function futureReleaseError(releasedOn: string, today: string): string | null; // returns "The release date cannot be in the future" when releasedOn > today /** Why a unit cannot be released, or null (spec Q8, plan decisions P1 and P2). */ export function releaseBlocker(args: { label: string; status: Enums["rentalAgreementLineStatus"]; classification: Enums["lessorClassification"] | null; openDocument: string | null; // e.g. "shipment SHP-000004" or "receipt RCV-000002" }): string | null;Use these exact messages:
Helper Case Message rentalShipmentVoidBlockera unit is not On Rent`${label} is ${status}; a rental shipment can be voided only while every unit is On Rent`rentalShipmentVoidBlockeraccrual="Posted"`A posted revenue recognition run holds accrued rent for ${label}; the shipment cannot be voided`rentalShipmentVoidBlockeraccrual="Draft run"`A draft revenue recognition run holds accrued rent for ${label}; delete the run before voiding the shipment`openRentalDocumentBlockershipmentIdset`Shipment ${shipmentId} is still open; post or delete it before closing the agreement`openRentalDocumentBlockerreceiptIdset`Receipt ${receiptId} is still open; post or delete it before closing the agreement`receiptReturnErrorstatus not in RETURNABLE_LINE_STATUSES`${label} is ${status}; only a Pending or On Rent unit can be returned`releaseBlockerstatus not Pending`${label} is ${status}; only a Pending unit can be released`releaseBlockerclassification="Sale"`${label} is treated as a sale; return it on a rental receipt instead`releaseBlockeropenDocumentset`${label} is on ${openDocument}; remove it there before releasing the unit`In
rentalShipmentVoidBlocker, check the first unit that is notOn Rentfirst. Then check accruals in unit order.In
openRentalDocumentBlocker, check the shipment first.In
receiptReturnError, use the existingRETURNABLE_LINE_STATUSES(validators.ts:95-102). It already holdsPendingandOn Rent.In
releaseBlocker, check in this order: status, classification, open document.Add one test per message, one test for each null result, and 3
unitReturnValidatortests. Copy the shape of the existing return tests (validators.test.ts:33-110), withouttypeandrentalAgreementId.
Verify:
pnpm --filter @carbon/server-functions exec vitest run src/post-rental-agreement/validators.test.ts
# Expected: all tests pass, including the new ones
Out of scope: Removing returnValidator (Task 22).
Task 7: Add the two create cases
Depends on: Tasks 3, 6 Files:
- Modify:
packages/server-functions/src/create/index.ts— 2 union members (line 60), 2 permission rules (line 176), 2 cases beforecase "journalEntry"(line 3372) - Create:
packages/server-functions/src/create/rental-agreement.test.ts - Modify:
packages/server-functions/src/__snapshots__/permissions-manifest.test.ts.snap— byvitest -uonly - Copy from (precedent):
create/index.ts:2007-2221(shipmentFromSalesReturnOrder, the insert of the header) andcreate/index.ts:3031-3051(the asset-line insert)
Steps:
Add these members to
createInput:z.object({ type: z.literal("shipmentFromRentalAgreement"), rentalAgreementId: z.string(), rentalAgreementLineId: z.string().optional() }), z.object({ type: z.literal("receiptFromRentalAgreement"), rentalAgreementId: z.string(), rentalAgreementLineId: z.string().optional() }),Add
shipmentFromRentalAgreement: { create: "inventory" }andreceiptFromRentalAgreement: { create: "inventory" }topermissions.rules.Add
case "shipmentFromRentalAgreement". Run the whole case in onedb.transaction(). Do these steps in order:- Read
rentalAgreement(id,rentalAgreementId,status,customerId,locationId) byidandcompanyId,forUpdate(). If none, throwNotFoundError("Rental agreement not found"). - If
status !== "Active", throwInvalidInputErrorwith`Rental agreement ${rentalAgreementId} is ${status}; units are delivered from an Active agreement`. - Read the Draft shipment:
sourceDocument = 'Rental Agreement',sourceDocumentId = agreement.id,status = 'Draft',companyId,forUpdate(). - Read the line ids on open documents: join
shipmentFixedAssetLinetoshipment, where the shipment isDraftorPendingand has this source. - Read the candidate lines:
rentalAgreementLineof this agreement and company,status = 'Pending'. If a line id is given, read only that id. - If a line id is given and no
Pendingline matches, throwInvalidInputError("Only a Pending unit can be delivered").
- Read
Then branch:
Draft exists Line id given Action Result yes no nothing { id: draft.id }yes yes, already on the Draft and ticked nothing { id: draft.id }yes yes, already on the Draft and unticked set its shippedto true (plan decision P3){ id: draft.id }yes yes, on another open shipment throw InvalidInputError("The unit is already on an open shipment")— yes yes, not on a document insert 1 asset line into the Draft { id: draft.id }no either insert a Draft header and 1 asset line per candidate not on an open shipment { id: newId }no either, and no candidate is left throw InvalidInputError("No units to deliver")— Insert the header with these values. Leave
postingDateunset.{ shipmentId: await getNextSequence(trx, "shipment", companyId), sourceDocument: "Rental Agreement", sourceDocumentId: agreement.id, sourceDocumentReadableId: agreement.rentalAgreementId, customerId: agreement.customerId, locationId: agreement.locationId, status: "Draft", companyId, createdBy: userId }Insert each asset line as
{ shipmentId, rentalAgreementLineId, shipped: true, companyId, createdBy: userId }.Add
case "receiptFromRentalAgreement"with the same structure and these differences (spec Q8):Item Shipment case Receipt case Candidate status PendingPendingorOn RentHeader table and sequence shipmentreceipt(receiptIdfromgetNextSequence(trx, "receipt", companyId))customerIdset not set ( receipthas no such column)Asset line, no line id given shipmentFixedAssetLine,shipped: truereceiptFixedAssetLine:received: truefor anOn Rentunit,received: falsefor aPendingunit;residualDestinationleft nullAsset line, line id given shipped: truereceived: true, whether the unit isPendingorOn RentUnticked unit already on the Draft, line id given set shippedto trueset receivedto trueAgreement refusal units are delivered from an Active agreementunits are returned from an Active agreementLine refusal Only a Pending unit can be deliveredOnly a Pending or On Rent unit can be returnedOpen-document refusal The unit is already on an open shipmentThe unit is already on an open receiptEmpty refusal No units to deliverNo units to returnThe receipt case skips units on another open receipt only. A
Pendingunit can sit on an open shipment and an open receipt at once. The first document to post wins. The other one then refuses the unit by name.Create
create/rental-agreement.test.ts. UserentalFixture({ units: 5 })from Task 4. Write thesedatabaseTestcases:- A shipment without a line id: one Draft, 5 asset lines with
shipped = true,locationId=f.locationId,sourceDocumentReadableId=RA-TEST,postingDatenull. - A second call without a line id returns the same id. The shipment still has 5 lines.
- A raw Kysely insert of a second Draft
shipmentwith this source fails. The error message containsshipment_oneOpenDraftPerRentalAgreement_idx. - Set every line
Returned. A receipt fails withNo units to return. - Set 3 lines
On Rent. A receipt without a line id has 5 lines: 3 withreceived = true, 2Pendingunits withreceived = false. - In the same fixture, the receipt call with the line id of an unticked
Pendingunit returns the same receipt id. That line now hasreceived = true. - Set 2 lines
On Rentand delete the Draft shipment. A shipment then holds only the 3Pendingunits. - On a
Closedagreement, the shipment call fails withis Closed. - With no Draft receipt, the receipt call with the line id of a
Pendingunit creates a receipt with 1 line,received = true.
- A shipment without a line id: one Draft, 5 asset lines with
Update the permissions snapshot.
Verify:
export SUPABASE_DB_URL="$(grep '^SUPABASE_DB_URL=' .env.local | cut -d= -f2-)"
pnpm --filter @carbon/server-functions exec vitest run src/create/rental-agreement.test.ts
# Expected: 9 passed
pnpm --filter @carbon/server-functions exec vitest run src/permissions-manifest.test.ts -u
git diff --stat packages/server-functions/src/__snapshots__/permissions-manifest.test.ts.snap
# Expected: only the two new create rules in the diff
pnpm exec turbo run typecheck --filter=@carbon/server-functions --concurrency=1
# Expected: 0 failed
Out of scope: The ERP routes that call these cases (Tasks 13, 16).
Task 8: Post a rental shipment
Depends on: Tasks 5, 6, 7 Files:
- Modify:
packages/server-functions/src/post-shipment/index.ts— input (line 54),runsignature (line 64), new case beforedefault(line 3038) - Modify:
packages/server-functions/src/post-rental-agreement/agreement.ts— wideninsertUnitActivity - Create:
packages/server-functions/src/post-shipment/rental-agreement.ts - Create:
packages/server-functions/src/post-shipment/rental-agreement.test.ts - Copy from (precedent):
post-rental-agreement/index.ts:410-470(activate: lock, then read lines) and$id.$lineId.deliver.tsx:64-91(the out-of-service rule)
Steps:
Change
postShipmentInputto:export const postShipmentInput = z.object({ type: z.enum(["post", "void"]), shipmentId: z.string(), /** The delivery date of a rental shipment. Other sources ignore it. */ postingDate: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional() });Destructure
postingDateinrun(ctx, { type, shipmentId, postingDate }).In
agreement.ts, wideninsertUnitActivity:typeadds"Rental Delivery" | "Rental Return" | "Void Shipment".sourceDocumentadds"Shipment" | "Receipt".In
post-shipment/rental-agreement.ts, export:export async function postRentalShipment( db: Kysely<KyselyDatabase>, args: { shipmentId: string; companyId: string; userId: string; today: string; postingDate?: string } ): Promise<void>;Write its body as one
db.transaction(), in this order:- Set
deliveredOn = postingDate ?? today. IffutureDeliveryError(deliveredOn, today)returns a message, throw it asInvalidInputError. - Lock the shipment
forUpdate()byidandcompanyId. ReadshipmentId,sourceDocumentId,status. - Read the ticked asset lines:
shipped = true,rentalAgreementLineIdnot null. If none, throwInvalidInputError("Select at least one unit to deliver"). - Lock the agreement with
lockAgreement(trx, companyId, sourceDocumentId). If it is notActive, refuse with the Task 7 agreement message. - Lock the lines:
rentalAgreementLineby id list,companyId,forUpdate(). Readid,rentalAgreementId,status,fixedAssetId,trackedEntityId. - Read the assets:
fixedAssetid,fixedAssetId,name,outOfServiceSince,outOfServiceReasonby id list andcompanyId. - For each line in asset-line order, build
label = unitLabel(asset, line.id). - If a line is missing or belongs to another agreement, throw
NotFoundError("Rental agreement line not found"). - If a line is not
Pending, throw`${label} is ${status}; only a Pending unit can be delivered`. - If
outOfServiceSinceis set, throw`${label} is out of service: ${outOfServiceReason ?? "no reason given"}`. - Update each line:
status: "On Rent",deliveredAt: deliveredOn,meterOut: assetLine.meter,updatedBy,updatedAt: datetime.timestamp(). - For each line with a
trackedEntityId, callinsertUnitActivitywithtype: "Rental Delivery",direction: "input",sourceDocument: "Shipment", the shipment ids, andattributes: { Shipment: shipmentId, "Rental Agreement": agreement.id }. - Update the shipment:
status: "Posted",postingDate: deliveredOn,postedBy: userId.
- Set
In
post-shipment/index.ts, add beforedefault(line 3038):case "Rental Agreement": { await postRentalShipment(db, { shipmentId, companyId, userId, today, postingDate }); break; }Write no
itemLedger,costLedgeror journal row.Create
post-shipment/rental-agreement.test.ts. UserentalFixture({ units: 5 })and the Task 7createcase to make the shipment. Write thesedatabaseTestcases:- Untick 2 asset lines and set
meter120 on one ticked line. Post withpostingDate= company today minus 3 days (datetime.today("America/New_York").subtract({ days: 3 }).toString()). Expect: 3 linesOn Rentwith thatdeliveredAt, one withmeterOut120, 2 linesPending, the shipmentPostedwith thatpostingDate. - In the same case, expect 0
itemLedger, 0costLedgerand 0journalLinerows forf.companyId. Expect 3trackedActivityrows of typeRental Delivery. - A
postingDateof today plus 1 day fails withThe delivery date cannot be in the future. The shipment status isDraftafterwards. - Set
outOfServiceSinceandoutOfServiceReason=Hydraulic leakon one asset. The post fails, and the message containsHydraulic leak. - Set one ticked line
On Rentby a direct update. The post fails, and the message containsFA-andis On Rent. - Untick every line. The post fails with
Select at least one unit to deliver.
- Untick 2 asset lines and set
Add one more
databaseTestfor C1, the backdated accrual:- Use
rentalFixture({ billingTiming: "Arrears" }). Set both periodsPending. - Post a shipment with
postingDate2026-09-25. - Call
synthesizeRentalAccruals(exported from../propose-revenue-recognition-run) in a transaction withperiodEnd2026-10-31. Expect noAccrualrow with aperiodStartin September. - Call it again with
periodEnd2026-09-30. Expect oneAccrualrow from2026-09-25to2026-09-30.
- Use
Run
pnpm --filter @carbon/checks license-headers.
Verify:
export SUPABASE_DB_URL="$(grep '^SUPABASE_DB_URL=' .env.local | cut -d= -f2-)"
pnpm --filter @carbon/server-functions exec vitest run src/post-shipment/rental-agreement.test.ts
# Expected: 6 passed (cases 1–2 are one test)
pnpm exec turbo run typecheck --filter=@carbon/server-functions --concurrency=1
# Expected: 0 failed
Out of scope: The void case (Task 9). The Sales Order case.
Task 9: Void a rental shipment
Depends on: Task 8 Files:
- Modify:
packages/server-functions/src/post-shipment/rental-agreement.ts— addvoidRentalShipment - Modify:
packages/server-functions/src/post-shipment/index.ts— new void case beforedefault(line 4694) - Modify:
packages/server-functions/src/post-shipment/rental-agreement.test.ts— void tests - Copy from (precedent):
post-shipment/index.ts:3487-3530(theVoid Shipmentactivity)
Steps:
Export from
rental-agreement.ts:export async function voidRentalShipment( db: Kysely<KyselyDatabase>, args: { shipmentId: string; companyId: string; userId: string } ): Promise<void>;Write its body as one
db.transaction(), in this order:- Lock the shipment
forUpdate(). Read the ticked asset lines (shipped = true,rentalAgreementLineIdnot null). - Lock the agreement with
lockAgreement. - Lock the lines
forUpdate(). Read the assets for labels, as Task 8 does. - Read the
Accrualrows of the lines fromrevenueRecognitionSchedule:type = 'Accrual',companyId, line id list. SelectrentalAgreementLineId,status,runLineId. - For each unit, set
accrualto"Posted"if a row isPosted. Else set it to"Draft run"if aPlannedrow has arunLineId. Else set it to null. - If
rentalShipmentVoidBlocker(units)returns a message, throw it asInvalidInputError. - Delete the
PlannedAccrualrows of the lines that have norunLineId. - Update each line:
status: "Pending",deliveredAt: null,meterOut: null,updatedBy,updatedAt. - For each line with a
trackedEntityId, callinsertUnitActivitywithtype: "Void Shipment",direction: "input",sourceDocument: "Shipment", and the Task 8 attributes. - Update the shipment:
status: "Voided",updatedBy,updatedAt: datetime.timestamp().
- Lock the shipment
In
post-shipment/index.ts, add before the voiddefault(line 4694):case "Rental Agreement": { await voidRentalShipment(db, { shipmentId, companyId, userId }); break; }Add these
databaseTestcases:- Post, then void. Expect each delivered line
PendingwithdeliveredAtnull andmeterOutnull. Expect the shipmentVoided. - Post. Insert a
PostedAccrualrow for one delivered line. Read the NOT NULL columns ofrevenueRecognitionSchedulein20261006220201_revenue-recognition-core.sql:205-235. The void fails withA posted revenue recognition run holds accrued rent for FA-. The shipment staysPosted. - Post. Set one delivered line
Returnedby a direct update. The void fails withis Returned.
- Post, then void. Expect each delivered line
Verify:
export SUPABASE_DB_URL="$(grep '^SUPABASE_DB_URL=' .env.local | cut -d= -f2-)"
pnpm --filter @carbon/server-functions exec vitest run src/post-shipment/rental-agreement.test.ts
# Expected: 9 passed
Out of scope: Voids of other sources.
Task 10: Post a rental receipt and refuse its void
Depends on: Tasks 5, 6, 7 Files:
- Modify:
packages/server-functions/src/post-receipt/index.ts— input (line 56),runsignature (line 66), void refusal (before line 280), new case beforedefault(line 3553), importInvalidInputError - Create:
packages/server-functions/src/post-receipt/rental-agreement.ts - Create:
packages/server-functions/src/post-receipt/rental-agreement.test.ts - Modify:
packages/server-functions/src/post-rental-agreement/return-unit.test.ts— act through the receipt - Copy from (precedent):
post-rental-agreement/index.tsreturnUnitwrapper (Task 5) for the lock order
Steps:
Change
postReceiptInputto:export const postReceiptInput = z.object({ type: z.enum(["post", "void"]).default("post"), receiptId: z.string(), /** The return date of a rental receipt. Other sources ignore it. */ postingDate: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional() });Destructure
postingDateinrun.In the void block, after the
invoicedcheck (index.ts:274-279), add:if (receiptHeader.sourceDocument === "Rental Agreement") { throw new InvalidInputError( "A rental return cannot be voided. Correct the unit by hand." ); }In
post-receipt/rental-agreement.ts, export:export async function postRentalReceipt( db: Kysely<KyselyDatabase>, args: { receiptId: string; companyId: string; userId: string; today: string; postingDate?: string } ): Promise<void>;Write its body as one
db.transaction(), in this order:- Set
returnedAt = postingDate ?? today. IffutureReturnError(returnedAt, today)returns a message, throw it asInvalidInputError. - Lock the receipt
forUpdate(). ReadreceiptId,sourceDocumentId,locationId. - Read the ticked asset lines:
received = true,rentalAgreementLineIdnot null. Readmeter,notes,takeOutOfService,outOfServiceReason,residualDestination. If none, throwInvalidInputError("Select at least one unit to return"). - Lock the agreement with
lockAgreement. If it is notActive, refuse with the Task 5 wrapper message. - Read the lines (
id,status,lessorClassification,trackedEntityId) and the assets for labels. - If
receiptReturnError(label, line.status)returns a message, throw it asInvalidInputError. A receipt returns aPendingor anOn Rentunit (spec Q8). - Parse each unit with
unitReturnValidator(Task 6):rentalAgreementLineId,returnedAt,meterIn: meter,returnNotes: notes,takeOutOfService,outOfServiceReason,residualDestination. On a parse error, throw`${label}: ${firstIssueMessage}`asInvalidInputError. - Call
returnRentalUnit(trx, { agreement, unit, companyId, userId, today, locationId: receipt.locationId ?? undefined })for each unit (spec Q7). - If the result's
fixedAssetIdis set and the receipt has alocationId, update thatfixedAsset:locationId,updatedBy,updatedAt. This also covers aPendingunit. - If the line is
Rentaland has atrackedEntityId, callinsertUnitActivitywithtype: "Rental Return",direction: "output",sourceDocument: "Receipt", andattributes: { Receipt: receiptId, "Rental Agreement": agreement.id }. - Update the receipt:
status: "Posted",postingDate: returnedAt,postedBy: userId.
- Set
In
post-receipt/index.ts, add beforedefault(line 3553):case "Rental Agreement": { await postRentalReceipt(db, { receiptId, companyId, userId, today, postingDate }); break; }Create
post-receipt/rental-agreement.test.ts. UserentalFixture({ units: 3 }). Set the 3 linesOn RentwithdeliveredAt2026-09-01. Write thesedatabaseTestcases:- Create a receipt with the Task 7 case. Untick 2 lines. On the ticked line set
meter130,takeOutOfServicetrue,outOfServiceReasonHydraulic leak. Set the receiptlocationIdtof.otherLocationId. Post withpostingDate2026-09-20. - In the same case, expect these 5 facts:
- the line is
Returned, withreturnedAt2026-09-20andmeterIn130 - the asset
locationIdisf.otherLocationId fleetAssets.fleetStatusisIn Maintenance- 1
Rental Returnactivity exists - the receipt is
Posted, withpostingDate2026-09-20
- the line is
- Untick every line. The post fails with
Select at least one unit to return, and the receipt isDraftafterwards. - Post a receipt, then call with
type: "void". It fails withA rental return cannot be voided. Correct the unit by hand.The receipt staysPosted. - A
Saleline: setlessorClassificationSaleandinitialNetInvestment1000 on one line. LeaveresidualDestinationnull. The post fails, and the message names the missing destination (thesalesTypeReturnErrortext). - The same
Saleline withresidualDestinationInventory,endDate2026-09-20on the agreement, and anitemCostrow for the item. Set the receiptlocationIdtof.otherLocationId(spec Q7). Expect 1itemLedgerrow:entryTypePositive Adjmt.,documentTypeRental Agreement, quantity 1,locationId=f.otherLocationId. - A
Pendingunit (spec Q8). UserentalFixture({ units: 2 }). Set line 1On RentwithdeliveredAt2026-09-01. Leave line 2Pending.- Create a receipt. Expect line 2's asset line with
received = false. - Post with
postingDate2026-09-20. Expect line 1Returnedand line 2 stillPending. - Create a second receipt. Tick line 2. Post with
postingDate2026-09-25. - Expect line 2
ReturnedwithreturnedAt2026-09-25. Expect noPendingbilling period of line 2 that starts after2026-09-25.
- Create a receipt. Expect line 2's asset line with
- Create a receipt with the Task 7 case. Untick 2 lines. On the ticked line set
If case 6 needs more setup than an
itemCostrow (for example a lease schedule), STOP and report.In
return-unit.test.ts, change onlyreturnUnitOnSeptember20:- Create a receipt with the Task 7 case and
rentalAgreementLineId. - Post it with
postingDate2026-09-20. - Keep the test name and every assertion.
- Create a receipt with the Task 7 case and
Run
pnpm --filter @carbon/checks license-headers.
Verify:
export SUPABASE_DB_URL="$(grep '^SUPABASE_DB_URL=' .env.local | cut -d= -f2-)"
pnpm --filter @carbon/server-functions exec vitest run src/post-receipt/rental-agreement.test.ts
# Expected: 6 passed (cases 1–2 are one test)
pnpm --filter @carbon/server-functions exec vitest run src/post-rental-agreement/return-unit.test.ts
# Expected: 1 passed, NO "written" and NO "obsolete" snapshot — the receipt path re-cuts exactly as the old path did
pnpm exec turbo run typecheck --filter=@carbon/server-functions --concurrency=1
# Expected: 0 failed
Do not run vitest with -u. If the pinning snapshot fails, STOP and report.
Out of scope: The default case of the post switch: leave it as it is.
Task 11: Add the Close guard
Depends on: Tasks 5, 6, 7 Files:
- Modify:
packages/server-functions/src/post-rental-agreement/index.ts—close(index.ts:1725-1764before Task 5) - Create:
packages/server-functions/src/post-rental-agreement/close.test.ts
Steps:
In
close, after theActivecheck and BEFOREloadSettlementState, read the first open shipment with a line:const openShipment = await trx .selectFrom("shipment as s") .innerJoin("shipmentFixedAssetLine as l", (join) => join.onRef("l.shipmentId", "=", "s.id").onRef("l.companyId", "=", "s.companyId") ) .select("s.shipmentId") .where("s.companyId", "=", companyId) .where("s.sourceDocument", "=", "Rental Agreement") .where("s.sourceDocumentId", "=", agreement.id) .where("s.status", "in", ["Draft", "Pending"]) .orderBy("s.createdAt") .executeTakeFirst();Read
openReceiptthe same way fromreceiptandreceiptFixedAssetLine.Throw
openRentalDocumentBlocker({ shipmentId: openShipment?.shipmentId ?? null, receiptId: openReceipt?.receiptId ?? null })asInvalidInputErrorwhen it returns a message.Create
close.test.tswith onedatabaseTest:- Use
rentalFixture(). Set the lineOn Rent. - Create a receipt with the Task 7 case.
- Call the default export of
./indexwith{ type: "close", rentalAgreementId }. - Expect the error message to contain
Receipt RCV-andis still open.
- Use
Verify:
export SUPABASE_DB_URL="$(grep '^SUPABASE_DB_URL=' .env.local | cut -d= -f2-)"
pnpm --filter @carbon/server-functions exec vitest run src/post-rental-agreement/close.test.ts
# Expected: 1 passed
Out of scope: cancel. The FK cascade already removes a deleted Pending line from a Draft shipment.
Task 12: Add the ERP models, service reads and the line-documents helper
Depends on: Task 3 Files:
- Modify:
apps/erp/app/modules/inventory/inventory.models.ts— source arrays (:95-106,:353-362), 2 validators - Modify:
apps/erp/app/modules/inventory/inventory.models.test.ts— validator tests - Modify:
apps/erp/app/modules/inventory/inventory.service.ts— 2 reads aftergetShipmentTracking(:1423) - Modify:
apps/erp/app/modules/inventory/types.ts— 2 types - Modify:
apps/erp/app/modules/sales/sales.service.ts— 1 read aftergetRentalAgreementDeposits(:9582) - Modify:
apps/erp/app/modules/sales/sales.utils.tsandsales.utils.test.ts—rentalLineDocuments - Copy from (precedent):
inventory.service.ts:1423-1433(getShipmentTracking),sales.service.ts:1777-1834(getSalesOrderRelatedItems)
Steps:
Add
"Rental Agreement"toreceiptSourceDocumentTypeand toshipmentSourceDocumentType.Add these validators to
inventory.models.ts:const meterValue = z .string() .refine( (v) => v === "" || (Number.isFinite(Number(v)) && Number(v) >= 0), { message: "Enter a meter reading of 0 or more" } ); export const shipmentFixedAssetLineUpdateValidator = z.discriminatedUnion("field", [ z.object({ id: z.string().min(1), field: z.literal("shipped"), value: z.enum(["true", "false"]) }), z.object({ id: z.string().min(1), field: z.literal("serialNumber"), value: z.string() }), z.object({ id: z.string().min(1), field: z.literal("meter"), value: meterValue }) ]); export const receiptFixedAssetLineUpdateValidator = z.discriminatedUnion("field", [ z.object({ id: z.string().min(1), field: z.literal("received"), value: z.enum(["true", "false"]) }), z.object({ id: z.string().min(1), field: z.literal("serialNumber"), value: z.string() }), z.object({ id: z.string().min(1), field: z.literal("meter"), value: meterValue }), z.object({ id: z.string().min(1), field: z.literal("notes"), value: z.string() }), // "" takes the unit off the out-of-service list; any other text is the reason. z.object({ id: z.string().min(1), field: z.literal("outOfService"), value: z.string() }), z.object({ id: z.string().min(1), field: z.literal("residualDestination"), value: z.enum(["", "Fleet", "Inventory"]) }) ]);Add tests to
inventory.models.test.ts: a meter of-1fails,""and"120"pass, an unknownfieldfails.Add to
inventory.service.ts:/** @mcp read */ export async function getRentalShipmentLines( client: SupabaseClient<Database>, shipmentId: string, companyId: string ) { return client .from("shipmentFixedAssetLine") .select( "id, shipped, meter, rentalAgreementLineId, rentalAgreementLine!shipmentFixedAssetLine_rentalAgreementLineId_fkey(id, status, lessorClassification, fixedAsset(id, fixedAssetId, name, serialNumber), item(name, readableIdWithRevision), trackedEntity(readableId))" ) .eq("shipmentId", shipmentId) .eq("companyId", companyId) .not("rentalAgreementLineId", "is", null) .order("createdAt"); }Add
getRentalReceiptLineswith the same shape. It readsreceiptFixedAssetLinewithreceived,meter,notes,takeOutOfService,outOfServiceReason,residualDestination, and the embed throughreceiptFixedAssetLine_rentalAgreementLineId_fkey.If PostgREST refuses the embed of
fixedAsset,itemortrackedEntityfromrentalAgreementLine, name its FK. Copy the name frompackages/database/src/types.ts.Add to
inventory/types.ts:export type RentalShipmentLine = { id: string; rentalAgreementLineId: string; shipped: boolean; meter: number | null; unitName: string; assetReadableId: string | null; serialNumber: string | null; lineStatus: Database["public"]["Enums"]["rentalAgreementLineStatus"]; }; export type RentalReceiptLine = Omit<RentalShipmentLine, "shipped"> & { received: boolean; notes: string | null; takeOutOfService: boolean; outOfServiceReason: string | null; residualDestination: "Fleet" | "Inventory" | null; lessorClassification: Database["public"]["Enums"]["lessorClassification"] | null; };Add to
sales.service.ts:/** @mcp read */ export async function getRentalAgreementRelatedDocuments( client: SupabaseClient<Database>, rentalAgreementId: string, companyId: string ) { const [shipments, receipts] = await Promise.all([ client .from("shipment") .select("id, shipmentId, status, postingDate, shipmentFixedAssetLine(rentalAgreementLineId, shipped)") .eq("sourceDocument", "Rental Agreement") .eq("sourceDocumentId", rentalAgreementId) .eq("companyId", companyId) .order("createdAt"), client .from("receipt") .select("id, receiptId, status, postingDate, receiptFixedAssetLine(rentalAgreementLineId, received)") .eq("sourceDocument", "Rental Agreement") .eq("sourceDocumentId", rentalAgreementId) .eq("companyId", companyId) .order("createdAt") ]); return { data: { shipments: shipments.data ?? [], receipts: receipts.data ?? [] }, error: shipments.error ?? receipts.error }; }Add to
sales.utils.ts:/** The last Posted shipment that delivered the unit and the last Posted receipt that returned it. */ export function rentalLineDocuments( lineId: string, shipments: { id: string; shipmentId: string; status: string; shipmentFixedAssetLine: { rentalAgreementLineId: string | null; shipped: boolean }[] }[], receipts: { id: string; receiptId: string; status: string; receiptFixedAssetLine: { rentalAgreementLineId: string | null; received: boolean }[] }[] ): { shipment: { id: string; shipmentId: string } | null; receipt: { id: string; receiptId: string } | null; };Add 3 tests to
sales.utils.test.ts: no documents, a Posted shipment with the unit ticked, a Draft shipment ignored.Regenerate the MCP manifest digest.
Verify:
pnpm --filter erp exec vitest run app/modules/inventory/inventory.models.test.ts app/modules/sales/sales.utils.test.ts
# Expected: all pass
pnpm run generate:mcp && pnpm check:manifest
# Expected: check:manifest exits 0
pnpm exec turbo run typecheck --filter=erp
# Expected: 0 failed
Out of scope: Callers of these reads (Tasks 14, 16).
Task 13: Add the rental branches to the inventory new and details routes
Depends on: Tasks 7, 12 Files:
- Modify:
apps/erp/app/routes/x+/shipment+/new.tsx— new case beforedefault(line 271) - Modify:
apps/erp/app/routes/x+/receipt+/new.tsx— new case beforedefault(line 131) - Modify:
apps/erp/app/routes/x+/shipment+/$shipmentId.details.tsx— refuse a source change (lines 61-67), widen the cast (lines 278-281) - Modify:
apps/erp/app/routes/x+/receipt+/$receiptId.details.tsx— refuse a source change (lines 56-62), widen the cast (lines 179-181) - Copy from (precedent):
receipt+/new.tsx:56-111(theSales Return Orderbranch)
Steps:
In
shipment+/new.tsx, addcase "Rental Agreement":. Copyreceipt+/new.tsx:56-111with these changes:- The Draft lookup reads
shipmentwith.eq("sourceDocument", "Rental Agreement"). - If a Draft exists,
throw redirect(path.to.shipmentDetails(draft.id)). - The invoke is
{ type: "shipmentFromRentalAgreement", rentalAgreementId: sourceDocumentId }. - Each failure redirects to
path.to.rentalAgreementDetails(sourceDocumentId). The fallback text is"Failed to create shipment".
- The Draft lookup reads
In
receipt+/new.tsx, add the same case withreceipt,receiptFromRentalAgreement,path.to.receiptDetailsand"Failed to create receipt".In
$shipmentId.details.tsx, beforeif (shipmentDataHasChanged), add:const sourceChanged = currentShipment.data.sourceDocument !== d.sourceDocument || currentShipment.data.sourceDocumentId !== d.sourceDocumentId; const isRental = currentShipment.data.sourceDocument === "Rental Agreement" || d.sourceDocument === "Rental Agreement"; if (isRental && sourceChanged) { return data( {}, await flash(request, error(null, "A rental shipment keeps its rental agreement. Create it from the agreement.")) ); }Change
if (shipmentDataHasChanged)toif (shipmentDataHasChanged && !isRental). A location change on a rental shipment then saves throughupsertShipment.Add
| "Rental Agreement"to the cast at lines 278-281.Do steps 3–5 in
$receiptId.details.tsx. Use the text"A rental receipt keeps its rental agreement. Create it from the agreement.".
Verify:
pnpm exec turbo run typecheck --filter=erp
# Expected: 0 failed
grep -c "Rental Agreement" apps/erp/app/routes/x+/shipment+/new.tsx apps/erp/app/routes/x+/receipt+/new.tsx
# Expected: at least 2 per file
Out of scope: The source picker in the form (Task 19).
Task 14: Load the rental lines and save their fields
Depends on: Task 12 Files:
- Modify:
apps/erp/app/routes/x+/shipment+/$shipmentId.tsx— rental branch after line 104, returnrentalLines(lines 106-116) - Modify:
apps/erp/app/routes/x+/receipt+/$receiptId.tsx— rental branch after line 132, returnrentalLines(lines 134-154) - Modify:
apps/erp/app/routes/x+/shipment+/fixed-asset-lines.update.tsx— validator andmeter - Modify:
apps/erp/app/routes/x+/receipt+/fixed-asset-lines.update.tsx— validator and 4 new fields - Copy from (precedent):
$shipmentId.tsx:76-104(the service-role read)
Steps:
In
$shipmentId.tsx, declarelet rentalLines: RentalShipmentLine[] = [];.If
shipment.data.sourceDocument === "Rental Agreement", callgetRentalShipmentLines(getCarbonServiceRole(), shipmentId, companyId). Use the service role:rentalAgreementLineneedssales_view, which an inventory user may not hold.On an error, redirect to
path.to.shipmentswith the flash"Failed to load the rental units".Map each row:
Field Value rentalAgreementLineIdrow.rentalAgreementLineId!unitNamefixedAsset?.name ?? item?.name ?? "Rental unit"assetReadableIdfixedAsset?.fixedAssetId ?? nullserialNumberfixedAsset?.serialNumber ?? trackedEntity?.readableId ?? nulllineStatusrentalAgreementLine.statusmeterrow.meter === null ? null : Number(row.meter)Return
rentalLineswith the other loader values.Do steps 1–5 in
$receiptId.tsxwithgetRentalReceiptLinesandRentalReceiptLine. Map the 5 receipt fields andlessorClassificationas they are.In
shipment+/fixed-asset-lines.update.tsx, parseObject.fromEntries(await request.formData())withshipmentFixedAssetLineUpdateValidator.safeParse.On a parse failure, return
data({ error: parsed.error.issues[0]?.message }, { status: 400 }).Build the update from the parsed field:
fieldUpdate shipped{ shipped: value === "true" }serialNumber`{ serialNumber: value meter{ meter: value === "" ? null : Number(value) }Keep the existing service-role write with
.eq("id", id).eq("companyId", companyId). AddupdatedBy: userIdto the update.In
receipt+/fixed-asset-lines.update.tsx, do steps 7–10 withreceiptFixedAssetLineUpdateValidatorand this map:fieldUpdate received{ received: value === "true" }serialNumber`{ serialNumber: value meter{ meter: value === "" ? null : Number(value) }notes`{ notes: value.trim() outOfServicevalue.trim() === "" ? { takeOutOfService: false, outOfServiceReason: null } : { takeOutOfService: true, outOfServiceReason: value.trim() }residualDestination`{ residualDestination: value
Verify:
pnpm exec turbo run typecheck --filter=erp
# Expected: 0 failed
Out of scope: The UI that sends these fields (Tasks 17, 18). A Draft-status guard on these routes.
Task 15: Pass the posting date from the post routes
Depends on: Tasks 8, 10 Files:
- Modify:
apps/erp/app/routes/x+/shipment+/$shipmentId.post.tsx— readpostingDate(near line 50), pass it (lines 372-377) - Modify:
apps/erp/app/routes/x+/receipt+/$receiptId.post.tsx— readpostingDate(near line 37), pass it (lines 221-225)
Steps:
In
$shipmentId.post.tsx, after theacknowledgedread, add:const postingDateValue = formData.get("postingDate"); const postingDate = typeof postingDateValue === "string" && postingDateValue !== "" ? postingDateValue : undefined;Change the invoke to
{ type: "post", shipmentId, postingDate }.Do steps 1–2 in
$receiptId.post.tsx. The invoke becomes{ receiptId, postingDate }.Leave the rule evaluation as it is. A rental document has no
shipmentLineorreceiptLinerows, so the storage and sales rules see no lines.
Verify:
pnpm exec turbo run typecheck --filter=erp
# Expected: 0 failed
grep -c "postingDate" "apps/erp/app/routes/x+/shipment+/\$shipmentId.post.tsx" "apps/erp/app/routes/x+/receipt+/\$receiptId.post.tsx"
# Expected: at least 2 per file
Out of scope: The void routes. They call post-shipment / post-receipt unchanged.
Task 16: Turn the per-unit Deliver and Return routes into shortcuts
Depends on: Tasks 7, 12 Files:
- Modify:
apps/erp/app/routes/x+/rental-agreement+/$id.$lineId.deliver.tsx— replace the action - Modify:
apps/erp/app/routes/x+/rental-agreement+/$id.$lineId.return.tsx— replace the action - Modify:
apps/erp/app/routes/x+/rental-agreement+/$id.tsx— load the related documents (lines 65-83, 162-177) - Modify:
apps/erp/app/modules/sales/ui/Rentals/types.ts—RentalAgreementRouteData(line 68) - Copy from (precedent):
receipt+/new.tsx:87-111(invoke and error flash)
Steps:
Replace the whole action of
$id.$lineId.deliver.tsxwith:export async function action({ request, params }: ActionFunctionArgs) { assertIsPost(request); const { companyId, userId } = await requirePermissions(request, { update: "sales", create: "inventory" }); const { id, lineId } = params; if (!id) throw notFound("id not found"); if (!lineId) throw notFound("lineId not found"); const result = await serverFns .system({ db: getDatabaseClient(), companyId, userId }) .invoke("create", { type: "shipmentFromRentalAgreement", rentalAgreementId: id, rentalAgreementLineId: lineId }); if (result.error || !result.data) { throw redirect( requestReferrer(request) ?? path.to.rentalAgreementDetails(id), await flash(request, error(result.error, getErrorMessage(result.error, "Failed to create the shipment"))) ); } throw redirect(path.to.shipmentDetails(result.data.id)); }Replace the action of
$id.$lineId.return.tsxthe same way withreceiptFromRentalAgreement,path.to.receiptDetailsand"Failed to create the receipt". Thecreatecase accepts aPendingor anOn Rentunit and adds it ticked (spec Q8).- Task 23 copies the old body of this route for the release route. It reads that body from commit
11a7a60999withgit show.
- Task 23 copies the old body of this route for the release route. It reads that body from commit
Remove the imports that the old actions used and the new ones do not.
In
$id.tsx, addgetRentalAgreementRelatedDocuments(client, id, companyId)to thePromise.allat lines 65-83.Return
shipments: related.data.shipmentsandreceipts: related.data.receiptsfrom the loader. Onrelated.error, keep the empty lists and do not fail the page.In
types.ts, add toRentalAgreementRouteData:shipments: RentalAgreementShipment[]; receipts: RentalAgreementReceipt[];Derive the two types from
getRentalAgreementRelatedDocuments:type RelatedDocuments = NonNullable< Awaited<ReturnType<typeof getRentalAgreementRelatedDocuments>>["data"] >; export type RentalAgreementShipment = RelatedDocuments["shipments"][number]; export type RentalAgreementReceipt = RelatedDocuments["receipts"][number];
Verify:
pnpm exec turbo run typecheck --filter=erp
# Expected: 0 failed
grep -c "post-rental-agreement" "apps/erp/app/routes/x+/rental-agreement+/\$id.\$lineId.return.tsx"
# Expected: 0
Out of scope: The buttons that post to these routes (Tasks 21, 22).
Task 17: Show the rental units on the shipment page
Depends on: Tasks 14, 15 Files:
- Modify:
apps/erp/app/modules/inventory/ui/Shipments/ShipmentLines.tsx— route-data type (lines 91-105), hide the lines card (lines 238-299), new card and item - Modify:
apps/erp/app/modules/inventory/ui/Shipments/ShipmentHeader.tsx—canPost(lines 54-59) - Modify:
apps/erp/app/modules/inventory/ui/Shipments/ShipmentPostModal.tsx— route data (lines 46-53), empty check (lines 119-134), date field, submit (lines 350-354) - Copy from (precedent):
ShipmentLines.tsx:300-395(ShipmentFixedAssetLineItem),apps/erp/app/modules/sales/ui/Rentals/RentalAgreementDetailsForm.tsx:213-226(a date field with a bound)
Steps:
- Add
rentalLines: RentalShipmentLine[]to the route-data type inShipmentLines.tsx. - Set
const isRental = routeData?.shipment?.sourceDocument === "Rental Agreement";. - Render the "Shipment Lines" card (lines 238-299) only when
!isRental. - Add a "Rental Units" card after the "Fixed Assets" card. Copy the card at lines 300-324. It renders
ShipmentRentalLineItemfor eachrentalLinesrow. - Create
ShipmentRentalLineItemin the same file. CopyShipmentFixedAssetLineItem(lines 330-395) with these changes:- It shows the
shippedcheckbox,unitName, thenassetReadableIdandserialNumberin small muted text. - It has no serial
Input, no storage-unit picker and no tracking form. - It shows a
NumberFieldlabelled "Meter". It submitsfieldmeteron blur when the value changed. An empty field sends"".
- It shows the
- In
ShipmentHeader.tsx, readrentalLinesfrom the same route data.canPostis also true when arentalLinesrow hasshipped. - In
ShipmentPostModal.tsx, addrentalLines: { id: string; shipped: boolean }[]to the route data. - Treat a ticked rental line as "not empty" in the check at lines 119-134.
- If the source is
Rental Agreement, render aDatePickerfrom@carbon/reactabove the alerts:- label "Delivered on"
value={parseDate(postingDate)}, withconst companyToday = useCompanyToday();andconst [postingDate, setPostingDate] = useState(companyToday);maxValue={parseDate(companyToday)}onChange={(d) => d && setPostingDate(d.toString())}
- In the submit (lines 350-354), build a
FormData. SetpostingDateon it only for a rental shipment. - Import
useCompanyTodayfrom~/hooks. ImportparseDatefrom@internationalized/date, which the file already imports. - Wrap every new visible string in
<Trans>ort`…`.
Verify:
pnpm exec turbo run typecheck --filter=erp
# Expected: 0 failed
pnpm exec biome check apps/erp/app/modules/inventory/ui/Shipments
# Expected: no errors
Out of scope: ShipmentFixedAssetLineItem for sales-order assets: do not change it.
Task 18: Show the rental units on the receipt page
Depends on: Tasks 14, 15 Files:
- Modify:
apps/erp/app/modules/inventory/ui/Receipts/ReceiptLines.tsx— route-data type (lines 102-123), hide the lines card (lines 249-300), new card and item - Modify:
apps/erp/app/modules/inventory/ui/Receipts/ReceiptHeader.tsx—canPost(lines 56-62) - Modify:
apps/erp/app/modules/inventory/ui/Receipts/ReceiptPostModal.tsx— route data (lines 43-50), empty check (lines 86-101), Return To check, date field, submit (lines 230-234) - Copy from (precedent):
ReceiptLines.tsx:301-396(ReceiptFixedAssetLineItem),apps/erp/app/modules/sales/ui/Rentals/RentalAgreementReturnForm.tsx:124-161(the Return To choice and the out-of-service fields),apps/erp/app/modules/sales/ui/Quotes/QuoteSummary.tsx(RadioGroupfrom@carbon/react)
Steps:
Add
rentalLines: RentalReceiptLine[]to the route-data type. SetisRentalas Task 17 does.Render the "Receipt Lines" card only when
!isRental. Add a "Rental Units" card that rendersReceiptRentalLineItem.Create
ReceiptRentalLineItem. CopyReceiptFixedAssetLineItem. It shows these controls, each saved throughpath.to.receiptFixedAssetLineUpdate:Control fieldSaves receivedcheckboxreceivedon change "Meter" NumberFieldmeteron blur, when changed "Notes" Textareanoteson blur, when changed "Take out of service" Checkboxplus a "Reason"InputoutOfServiceunticking sends ""at once; ticking shows the input, and a non-empty reason saves on blur"Return To" RadioGroup(Fleet / Inventory), only whenlessorClassification === "Sale"residualDestinationon change Keep the tick of "Take out of service" in local state, seeded from
takeOutOfService. Under the ticked box with no saved reason, show the helper text "Enter a reason to take the unit out of service".If
lineStatus === "Pending", show aBadge"Not delivered" next to the unit name (spec Q8). Thecreatecase leaves such a row unticked.In
ReceiptHeader.tsx,canPostis also true when arentalLinesrow hasreceived.In
ReceiptPostModal.tsx, addrentalLinesto the route data. Treat a received rental line as "not empty".For each received rental line with
lessorClassification === "Sale"and noresidualDestination, add a validation error:t`Choose Return To for ${unitName}`. The existing errors list disables the Post button.Add the date field as Task 17 step 9 does, with the label "Returned on".
Set
postingDateon the submittedFormDataonly for a rental receipt.
Verify:
pnpm exec turbo run typecheck --filter=erp
# Expected: 0 failed
pnpm exec biome check apps/erp/app/modules/inventory/ui/Receipts
# Expected: no errors
Out of scope: The Void button. ReceiptHeader.tsx:52-54 already shows it only for Purchase Order and Sales Return Order.
Task 19: Add the source to tables, forms, document panels and traceability
Depends on: Tasks 12, 13 Files:
- Modify:
apps/erp/app/modules/inventory/ui/Shipments/ShipmentsTable.tsx— link case (switch at line 117) - Modify:
apps/erp/app/modules/inventory/ui/Receipts/ReceiptsTable.tsx— link case (switch at line 117) - Modify:
apps/erp/app/modules/inventory/ui/Shipments/ShipmentForm/useShipmentForm.tsx— case (switch at lines 55-153) - Modify:
apps/erp/app/modules/inventory/ui/Shipments/ShipmentForm/ShipmentForm.tsx— source fields (lines 74-99) - Modify:
apps/erp/app/modules/inventory/ui/Receipts/ReceiptForm/useReceiptForm.tsx— case (switch at lines 53-118) - Modify:
apps/erp/app/modules/inventory/ui/Receipts/ReceiptForm/ReceiptForm.tsx— source fields (lines 69-93) - Modify:
apps/erp/app/modules/inventory/ui/Shipments/ShipmentDocuments.tsx—PACKING_SLIP_SOURCES(lines 33-38),useSourceDocument(lines 47-106) - Modify:
apps/erp/app/modules/inventory/ui/Receipts/ReceiptDocuments.tsx—useSourceDocument(lines 58-101), supplier row (line 165) - Modify:
apps/erp/app/modules/inventory/ui/Traceability/utils.ts—sourceLinkHref(lines 739-762) - Copy from (precedent):
ShipmentsTable.tsx:128-135(theSales Orderlink case),ShipmentDocuments.tsx:94-105(theSales Return Ordercase)
Steps:
In both tables, add
case "Rental Agreement":. It renders aHyperlinktopath.to.rentalAgreementDetails(row.original.sourceDocumentId!)withsourceDocumentReadableId.In
useShipmentForm.tsxanduseReceiptForm.tsx, addcase "Rental Agreement": break;. The initial option already holds the agreement's readable id.In
ShipmentForm.tsx, setconst isRental = initialValues.sourceDocument === "Rental Agreement";.Filter the
Selectoptions: drop"Rental Agreement"unlessisRental.Set
isReadOnly={isPosted || isRental}on the sourceSelectand the sourceCombobox.Do steps 3–5 in
ReceiptForm.tsx.In
ShipmentDocuments.tsx, add"Rental Agreement"toPACKING_SLIP_SOURCES.In both
useSourceDocumentswitches, add a"Rental Agreement"case. Copy theSales Return Ordercase. Link topath.to.rentalAgreementDetails(id), gate onpermissions.can("view", "sales"), and use the label "Rental Agreement".In
ReceiptDocuments.tsxline 165, hide the supplier row for a rental receipt too:const isSalesReturn = … || receipt.sourceDocument === "Rental Agreement". If that variable also gatesReturnCustomerRow(lines 433-438), use a second variable for the supplier row only.In
sourceLinkHref, add this case beforedefault:case "Rental Agreement": return `/x/rental-agreement/${id}/details`;
Verify:
pnpm exec turbo run typecheck --filter=erp
# Expected: 0 failed
grep -c "Rental Agreement" apps/erp/app/modules/inventory/ui/Traceability/utils.ts apps/erp/app/modules/inventory/ui/Shipments/ShipmentsTable.tsx apps/erp/app/modules/inventory/ui/Receipts/ReceiptsTable.tsx
# Expected: at least 1 per file
Out of scope: A customer row on the rental receipt. receipt has no customerId.
Task 20: Print a Delivery Ticket
Depends on: Tasks 12, 14 Files:
- Modify:
packages/documents/src/pdf/blocks/packingSlip/types.ts—title,rentalUnitsonPackingSlipData - Modify:
packages/documents/src/pdf/blocks/packingSlip/HeaderBlock.tsx— line 12 - Modify:
packages/documents/src/pdf/blocks/packingSlip/LineItemsBlock.tsx— rental rows - Modify:
packages/documents/src/pdf/PackingSlipPDF.tsx— props (lines 23-40),data(lines 82-101) - Modify:
apps/erp/app/routes/file+/shipment+/$id[.]pdf.tsx— new case beforedefault(line 596) - Copy from (precedent):
$id[.]pdf.tsx:123-240(theSales Ordercase)
Steps:
In
types.ts, export:export type PackingSlipRentalUnit = { id: string; name: string; assetReadableId: string | null; serialNumber: string | null; };Add
title: stringandrentalUnits?: PackingSlipRentalUnit[]toPackingSlipData.In
HeaderBlock.tsx, changetitle="Packing Slip"totitle={data.title}.In
PackingSlipPDF.tsx, addrentalUnits?: PackingSlipRentalUnit[]toPackingSlipProps. PuttitleandrentalUnitsintodata.In
LineItemsBlock.tsx, ifdata.rentalUnitshas rows, render one row per unit and return:- Description column:
name, thenassetReadableIdin the small grey text. - Qty column:
1. - A
Serialcolumn:serialNumber. - Use the same zebra and border styles as the shipment rows.
- Description column:
In
$id[.]pdf.tsx, addcase "Rental Agreement":. Copy theSales Ordercase with these changes:- Read the agreement with
getRentalAgreement(serviceRole, shipment.data.sourceDocumentId, companyId). - Read the customer and the customer location from
rentalAgreement.customerIdandcustomerLocationId. - Read the units with
getRentalShipmentLines(serviceRole, id, companyId). Keep onlyshippedrows. Map them with the Task 14 rules toPackingSlipRentalUnit. - Pass
sourceDocument="Rental Agreement",sourceDocumentId={rentalAgreement.rentalAgreementId},title="Delivery Ticket",rentalUnits,trackedEntities={[]}. - Set the PDF meta subject to "Delivery Ticket".
- Pass
paymentTermandshippingMethodthe way theOutbound Transfercase does (lines 483-595) when the agreement has none.
- Read the agreement with
Pass
title="Packing Slip"explicitly in every other case, sodata.titleis always set.
Verify:
pnpm exec turbo run typecheck --filter=@carbon/documents
# Expected: 0 failed
pnpm --filter @carbon/documents test
# Expected: all pass
pnpm exec turbo run typecheck --filter=erp
# Expected: 0 failed
Out of scope: The packing-slip template editor.
Task 21: Add Deliver and Return to the agreement header
Depends on: Task 16 Files:
- Modify:
apps/erp/app/modules/sales/ui/Rentals/RentalAgreementHeader.tsx— props (lines 43-46), buttons (inside theHStackat line 190) - Modify:
apps/erp/app/routes/x+/rental-agreement+/$id.tsx— passshipmentsandreceiptsto the header (lines 196-202) - Copy from (precedent):
apps/erp/app/modules/sales/ui/SalesOrder/SalesOrderHeader.tsx:506-577(Ship / Shipments),apps/erp/app/modules/sales/ui/SalesReturnOrders/SalesReturnOrderHeader.tsx:77-89(submit to the create route)
Steps:
Add
"shipments" | "receipts"to thePickinRentalAgreementHeaderProps. Pass both from$id.tsx.Add
const submit = useSubmit();and these two functions. Copy the shape ofSalesReturnOrderHeader.tsx:77-89:deliver()postssourceDocumentRental AgreementandsourceDocumentIdidtopath.to.newShipment.returnUnits()posts the same topath.to.newReceipt.
Set these flags:
const canMoveUnits = canUpdate && permissions.can("create", "inventory"); const hasPendingUnit = lines.some((line) => line.status === "Pending"); const hasUnitOnRent = …; // already exists at line 85Before the Invoice button, render the delivery control when
isActive && canMoveUnits:- If
shipments.length === 0, render aButton"Deliver" withLuTruck, disabled when!hasPendingUnit. It callsdeliver(). - Else render a "Shipments"
DropdownMenu. CopySalesOrderHeader.tsx:506-555. "New Shipment" is disabled when!hasPendingUnitand callsdeliver(). Each shipment row links topath.to.shipment(shipment.id)and showsShipmentStatus.
- If
After it, render the return control the same way:
- "Return" with
LuPackageCheck, disabled when!hasUnitOnRent && !hasPendingUnit, callsreturnUnits(). A receipt also holdsPendingunits (spec Q8). - The "Receipts" dropdown has "New Receipt", disabled on the same rule, and links to
path.to.receipt(receipt.id)withReceiptStatus.
- "Return" with
Import
ShipmentStatusfrom~/modules/inventory/ui/ShipmentsandReceiptStatusfrom~/modules/inventory/ui/Receipts.Use the variant
primaryfor Deliver whenhasPendingUnit, elsesecondary. Usesecondaryfor Return.
Verify:
pnpm exec turbo run typecheck --filter=erp
# Expected: 0 failed
pnpm exec biome check apps/erp/app/modules/sales/ui/Rentals/RentalAgreementHeader.tsx
# Expected: no errors
Out of scope: Close and Cancel buttons.
Task 22: Replace the return type with release
Depends on: Tasks 10, 16 Files:
- Modify:
packages/server-functions/src/post-rental-agreement/validators.ts— replacereturnValidatorwithreleaseValidator - Modify:
packages/server-functions/src/post-rental-agreement/validators.test.ts— replace thetype: "return"tests - Modify:
packages/server-functions/src/post-rental-agreement/index.ts— replacecase "return"and thereturnUnitwrapper; header comment (lines 60-81) - Create:
packages/server-functions/src/post-rental-agreement/release.test.ts - Copy from (precedent): the
returnUnitwrapper written in Task 5, and the open-document query of Task 11
Steps:
Run
grep -rn 'type: "return"' apps/erp/app packages/jobs/src. If a caller still sendstype: "return"topost-rental-agreement, STOP and report. (post-asset-transferalso has areturntype; ignore its callers.)In
validators.ts, deletereturnValidator. KeepunitReturnFieldsandunitReturnValidator. Keep the out-of-service refine onunitReturnValidator.Add and export, then put it into
payloadValidatorin place ofreturnValidator:/** A Pending unit that never left the yard: stop its billing at * `returnedAt` and free the unit, with no document (spec Q8). */ export const releaseValidator = z.object({ type: z.literal("release"), rentalAgreementLineId: z.string().min(1), returnedAt: calendarDate, ...scope });Keep
RETURNABLE_LINE_STATUSES.returnRentalUnitandreceiptReturnErroruse it.In
index.ts, replace thereturnUnitwrapper withreleaseUnit. Write its body in this order:- If
futureReleaseError(payload.returnedAt, today)returns a message, throw it asInvalidInputError. - Open
db.transaction(). Lock the agreement withlockAgreement. - If the agreement is not
Active, throw`Rental agreement ${agreement.rentalAgreementId} is ${agreement.status}; units are released from an Active agreement`. - Read the line
forUpdate():id,status,lessorClassification,fixedAssetId, byid,rentalAgreementId = agreement.idandcompanyId. If none, throwNotFoundError("Rental agreement line not found"). - Read the asset (
fixedAssetId,name) forunitLabel. - Find the first open document that holds the line. Copy the Task 11 queries and add
.where("l.rentalAgreementLineId", "=", line.id). SetopenDocumentto`shipment ${shipmentId}`, else`receipt ${receiptId}`, else null. - If
releaseBlocker({ label, status, classification, openDocument })returns a message, throw it asInvalidInputError. - Call
returnRentalUnit(trx, { agreement, unit: { rentalAgreementLineId: line.id, returnedAt: payload.returnedAt }, companyId, userId, today }). Pass nolocationId, no meter, no notes and no out-of-service fields. - Return
{ id: agreement.id }.
- If
In the dispatch, replace
case "return"withcase "release". It computestodayexactly as the old case did and callsreleaseUnit.Release passes no residual destination. So a
Saleline can never passsalesTypeReturnError. Step 5.7 refuses it first with a clear message (plan decision P1).In the header comment, replace the
returnparagraph with these 2 lines:- "A unit comes back through a rental receipt (
post-receipt), which callsreturnRentalUnit." - "release: a Pending unit that never left the yard stops billing at the release date and is free again."
- "A unit comes back through a rental receipt (
Update the doc comment above
postRentalAgreement(/** Activates, returns a unit of, closes or cancels …): it activates, releases a unit of, closes or cancels.In
validators.test.ts, delete each test that parsestype: "return". Add 2releasetests: it needs the line id and aYYYY-MM-DDdate; it stripsmeterIn.Create
release.test.ts. UserentalFixture()from Task 4 (the line isPending, Advance billing, September invoiced, October pending). Write thesedatabaseTestcases:- Release with
returnedAt2026-09-20. Expect the lineReturnedwithreturnedAt2026-09-20. Expect noPendingperiod that starts after2026-09-20. Expect 1isAdjustmentrow. ExpectfleetAssets.fleetStatus=Available. ExpectfixedAsset.locationIdunchanged. - Set the line
On Rent. The release fails withis On Rent; only a Pending unit can be released. - A
returnedAtof company today plus 1 day fails withThe release date cannot be in the future. - Set
lessorClassificationSale. The release fails withis treated as a sale; return it on a rental receipt instead. - Create a Draft shipment with the Task 7 case. The release fails with
is on shipment SHP-.
- Release with
Verify:
export SUPABASE_DB_URL="$(grep '^SUPABASE_DB_URL=' .env.local | cut -d= -f2-)"
pnpm --filter @carbon/server-functions exec vitest run src/post-rental-agreement src/post-receipt src/post-shipment src/create
# Expected: all pass, release.test.ts has 5 passed; return-unit.test.ts with no snapshot change
grep -c 'literal("return")' packages/server-functions/src/post-rental-agreement/validators.ts
# Expected: 0
pnpm --filter @carbon/server-functions exec vitest run src/permissions-manifest.test.ts
# Expected: passes with no snapshot change (still update: sales)
pnpm exec turbo run typecheck --filter=@carbon/server-functions --concurrency=1
# Expected: 0 failed
Out of scope: The activate, close and cancel types. The release UI (Task 23).
Task 23: Repoint the unit actions and add Release unit
Depends on: Tasks 16, 22 Files:
- Modify:
apps/erp/app/utils/path.ts— addrentalAgreementLineReleaseafterrentalAgreementLineReturn(lines 2174-2175) - Create:
apps/erp/app/routes/x+/rental-agreement+/$id.$lineId.release.tsx - Modify:
apps/erp/app/modules/sales/sales.models.ts— replacerentalAgreementReturnValidator(lines 1528-1566) withrentalAgreementReleaseValidator - Rename:
apps/erp/app/modules/sales/ui/Rentals/RentalAgreementReturnForm.tsx→RentalAgreementReleaseForm.tsx(git mv), then cut it down - Modify:
apps/erp/app/modules/sales/ui/Rentals/index.ts— the form's import and export (lines 15, 54) - Modify:
apps/erp/app/modules/sales/ui/Rentals/useRentalLineActions.tsx— action type (line 13), state (lines 15-26, 63-82), modals (lines 92-139) - Modify:
apps/erp/app/modules/sales/ui/Rentals/RentalAgreementLineSummary.tsx— Release button in the footer (after lines 97-106); Delivered / Returned rows (lines 76-81) - Modify:
apps/erp/app/modules/sales/ui/Rentals/RentalAgreementExplorer.tsx— Release item after the Return item (lines 213-220) - Modify:
apps/erp/app/modules/sales/ui/Rentals/RentalAgreementSummary.tsx—SummaryLine(lines 190-295) - Copy from (precedent):
git show 11a7a60999:'apps/erp/app/routes/x+/rental-agreement+/$id.$lineId.return.tsx'(the route at commit11a7a60999, before Task 16),SalesReturnOrderHeader.tsx:77-89(submit)
Steps:
In
path.ts, add:rentalAgreementLineRelease: (id: string, lineId: string) => generatePath(`${x}/rental-agreement/${id}/${lineId}/release`),In
sales.models.ts, replacerentalAgreementReturnValidatorwith:export const rentalAgreementReleaseValidator = z.object({ rentalAgreementLineId: z .string() .min(1, { message: "Rental agreement line is required" }), returnedAt: z.string().min(1, { message: "Release date is required" }) });Keep
rentalResidualDestinations. Task 12's receipt validator and Task 18 use it.Create
$id.$lineId.release.tsx. Copy the old return route fromgit show. Change it like this:- Permissions:
{ update: "sales" }. - Validate with
rentalAgreementReleaseValidator. - Drop the line re-read and the
isSalesTypebranch. The server function checks the line. - Invoke
{ type: "release", rentalAgreementId: id, rentalAgreementLineId: lineId, returnedAt }. - On error, flash
getErrorMessage(result.error, "Failed to release the unit"). - On success, flash
"Unit released". - Redirect to
requestReferrer(request) ?? path.to.rentalAgreementDetails(id), as the old route did.
- Permissions:
Run
git mvto rename the form toRentalAgreementReleaseForm.tsx. Rename the component and its props type.In the form, keep the
ValidatedForm, the fetcher, theHiddenline id and theDatePicker. Delete the meter, notes, out-of-service and Return To fields and theisSalesTypehidden field.Set the
DatePickerlabel to "Release date". PassmaxValue={parseDate(today)}, withtodayfromuseCompanyToday().Set the modal title to
t`Release ${unitLabel}`. Add the text "The unit never left the yard. Billing stops on the release date, and the unit is free again." Set the submit label to "Release unit".Update
index.tsto import and exportRentalAgreementReleaseForm.In
useRentalLineActions.tsx:- Add
"release"toRentalLineAction. AddcanReleaseandreleaseDisabledtoRentalLineActionState. - Set
canReturn = isActive && (line.status === "On Rent" || line.status === "Pending")(spec Q8). - Set
canRelease = isActive && line.status === "Pending" && line.lessorClassification !== "Sale"(plan decision P1). - Set
canSellonisActive && line.status === "On Rent", not oncanReturn, so aPendingunit is never offered Sell. - Set
const canMoveUnits = canUpdate && permissions.can("create", "inventory"). SetdeliverDisabledandreturnDisabledto!canMoveUnits. SetreleaseDisabledto!canUpdate. - Make
open("deliver", line)callsubmit(new FormData(), { method: "post", action: path.to.rentalAgreementLineDeliver(id, line.id) }). UseuseSubmitfromreact-router. - Make
open("return", line)post the same way topath.to.rentalAgreementLineReturn(id, line.id). - Make
open("release", line)set the pending action, asselldoes. - Delete the Deliver
Confirmand the return modal. Add a modal for"release":RentalAgreementReleaseFormwithaction={path.to.rentalAgreementLineRelease(id, pending.line.id)}andinitialValues={{ rentalAgreementLineId: pending.line.id, returnedAt: today }}. - Update the hook's doc comment: Deliver and Return open a document; Release unit opens a date modal.
- Add
In
RentalAgreementLineSummary.tsx, add a "Release unit"Buttonafter the Return button. Show it whenstate.canRelease. Usevariant="secondary",leftIcon={<LuCircleSlash />}andisDisabled={state.releaseDisabled}.In
RentalAgreementExplorer.tsx, add a "Release unit"DropdownMenuItemafter the Return item, with the same rule.In
RentalAgreementSummary.tsxandRentalAgreementLineSummary.tsx, readshipmentsandreceiptsfromuseRouteData<RentalAgreementRouteData>(path.to.rentalAgreement(id)).Call
rentalLineDocuments(line.id, shipments, receipts)for each unit.In
SummaryLine, show aLinktopath.to.shipment(shipment.id)labelled withshipmentId, and one topath.to.receipt(receipt.id)labelled withreceiptId, when each exists.In
RentalAgreementLineSummary, put the same links next to the "Delivered" and "Returned" dates.If
grep -rn "rentalAgreementReturnValidator\|RentalAgreementReturnForm" apps/erp/appfinds a user, STOP and report.
Verify:
pnpm exec turbo run typecheck --filter=erp
# Expected: 0 failed
grep -rn "rentalAgreementReturnValidator\|RentalAgreementReturnForm" apps/erp/app | wc -l
# Expected: 0
grep -c "rentalAgreementLineRelease" apps/erp/app/utils/path.ts
# Expected: 1
pnpm run generate:mcp && pnpm check:manifest
# Expected: check:manifest exits 0
pnpm exec biome check apps/erp/app/modules/sales/ui/Rentals
# Expected: no errors
Out of scope: The Sell action and its route.
Task 24: Run the full verification sweep
Depends on: Tasks 1–23 Files:
- Modify: only files that a check below fixes
Steps:
- Run
pnpm --filter @carbon/checks license-headers. - Run each command below in order.
- Fix a failure only when its cause is a file this plan changed. Otherwise STOP and report.
Verify:
pnpm run lint
# Expected: exit 0
pnpm exec turbo run typecheck --filter=@carbon/server-functions --filter=@carbon/documents --filter=erp --concurrency=1
# Expected: 0 failed
export SUPABASE_DB_URL="$(grep '^SUPABASE_DB_URL=' .env.local | cut -d= -f2-)"
pnpm --filter @carbon/server-functions test
# Expected: 0 failed; the rental tests report "passed", not "skipped"
pnpm --filter erp test
# Expected: 0 failed
pnpm --filter @carbon/checks test
# Expected: 0 failed
pnpm check:manifest
# Expected: exit 0
pnpm db:check:datasets
# Expected: exit 0
pnpm db:check:backups
# Expected: exit 0
pnpm build:erp
# Expected: build succeeds; no "Server-only module referenced by client"
Out of scope: A whole-repo typecheck.
Task 25: Extract and translate the new strings
Depends on: Task 24 Files:
- Modify:
packages/locale/locales/*/*.po— by the extractor and the/translateskill only
Steps:
- Run
pnpm lingui:extract. - Invoke the
/translateskill to fill the emptymsgstrentries. - Run
pnpm lingui:clean.
Verify:
pnpm lingui:check
# Expected: exit 0
git status --short packages/locale/locales | head
# Expected: only .po files changed; no compiled .mjs files
Out of scope: Server-function error messages. They are English only.
Task 26: Update the docs
Depends on: Tasks 22, 23 Files:
- Modify:
apps/erp/app/modules/sales/AGENTS.md— Rentals section (lines 125, 140, 147, 150, 156, 159) - Modify:
apps/erp/app/modules/inventory/AGENTS.md— Receipt and Shipment concepts (lines 10-11), data model (lines 51-52) - Modify:
packages/server-functions/AGENTS.md— thepost-rental-agreementmention (around line 134) - Modify:
.claude/rules/shipments-receipts-ui-patterns.md— the rental source andPACKING_SLIP_SOURCES - Modify:
.claude/rules/fixed-asset-lifecycle.md— the Deliver and return lines (lines 449-470) - Modify:
docs/content/docs/reference/rental-agreements.mdx— lines 55-67, 225, 295, 312 - Modify:
docs/content/docs/reference/shipments.mdxanddocs/content/docs/reference/receipts.mdx— the source document field
Do not edit the spec. It already carries the planning corrections.
Steps:
- Load the
carbon-docsskill before you edit an.mdxfile. - In
sales/AGENTS.md, state these facts:- Deliver and Return go through a rental shipment and a rental receipt (
createtypesshipmentFromRentalAgreement/receiptFromRentalAgreement). post-shipmentandpost-receiptown theRental Agreementsource. They take an optionalpostingDate.$id.$lineId.deliver/returnare shortcuts that open a one-unit document. They needupdate: salesandcreate: inventory.returnRentalUnit(post-rental-agreement/return-unit.ts) holds the return body. It takes an optionallocationId: a rental receipt passes its own location, so aSaleline's residual lands there (spec Q7).- A rental receipt holds every
On Rentunit ticked and everyPendingunit unticked (spec Q8). post-rental-agreementhas noreturntype. Itsreleasetype ends aPendingunit with no document. It refuses aSaleline and a unit on an open rental document. The route is$id.$lineId.release(update: sales).- Close refuses while an open rental document has a line.
- Rentals safety line 156: no app code writes a line status; Deliver is no longer the exception.
- Deliver and Return go through a rental shipment and a rental receipt (
- In
inventory/AGENTS.md, addRental Agreementto both source lists. DescriberentalAgreementLineId,meterand the receipt condition columns on the fixed-asset line tables. - In
server-functions/AGENTS.md, listpost-rental-agreementasactivate/release/close/cancelif the file lists its types. - In the two rules files, replace the old Deliver route facts with the document flow.
- In
rental-agreements.mdx:- Rewrite the Deliver and Return bullets (lines 60-61): a unit leaves on a shipment and comes back on a receipt.
- Link
[shipment](/docs/reference/shipments)and[receipt](/docs/reference/receipts). - Name the "Delivered on" and "Returned on" fields.
- State that a receipt lists the units not yet delivered, unticked. Ticking one stops its billing at the return date.
- Add a "Release unit" bullet: it ends a pending unit that never left the yard, at a date no later than today. It is not offered for a unit treated as a sale.
- State that a unit treated as a sale and returned to inventory goes into stock at the receipt's location.
- Add the Close refusal "Shipment … is still open; post or delete it before closing the agreement" to the troubleshooting list.
- In
shipments.mdxandreceipts.mdx, add the rental agreement to the source document field. State that a rental unit posts no inventory or journal entry. - Note for the release: the changelog entry, written later with
/changelog-entry, must say that delivery now needs inventory create permission.
Verify:
pnpm --filter docs typecheck
# Expected: exit 0
cd docs && for l in $(grep -oh "](/docs/[^)]*)" content/docs/reference/rental-agreements.mdx content/docs/reference/shipments.mdx content/docs/reference/receipts.mdx | sed 's|](/docs/||;s|)||' | sort -u); do [ -f "content/docs/$l.mdx" ] || [ -f "content/docs/$l/index.mdx" ] || echo "MISSING $l"; done; cd ..
# Expected: no MISSING line
grep -c "updates the line directly" apps/erp/app/modules/sales/AGENTS.md
# Expected: 0
Out of scope: The changelog entry itself.
Task 27: Verify in the browser
Depends on: Tasks 24, 25, 26 Files:
- Create:
.ai/playbooks/entry — by the/testskill only
Steps:
- Ask the user for permission to drive the browser.
- Invoke the
/testskill with this plan's acceptance table below as the test list. - Use the
/authskill to sign in. - Set up an Active agreement with 5 serial fleet units. Use the agreement setup wizard, or
pnpm db:seed:devdata if it has rentals. - For the release rows, use a second Active agreement with 1
Pendingunit. Release it with a date 2 days ago. Then check the Billing Periods card and the fleet register. - Run each row of the coverage table that names Task 27.
- On any failure, use the
/errorskill and STOP. Report the row and the screenshot path.
Verify:
Every coverage row that names Task 27 is PASS in the /test report.
Out of scope: Fixing failures in this task.
Acceptance coverage
| Spec acceptance criterion | Tasks |
|---|---|
| Deliver on RA-1 with 5 Pending units creates one Draft rental shipment with 5 ticked lines at RA-1's location | 7, 13, 21, 27 |
Untick 2, Delivered on = 3 days ago, meter 120 on one, post: 3 lines On Rent with that deliveredAt, meterOut 120; 2 stay Pending |
8, 14, 15, 17, 27 |
No new itemLedger, costLedger or journalLine row; one Rental Delivery activity per tracked unit |
8 |
| A second Deliver creates a Draft with the 2 remaining units; Deliver while the Draft exists opens it | 7, 13, 21, 27 |
Two Draft rental shipments for one agreement fail on shipment_oneOpenDraftPerRentalAgreement_idx |
2, 7 |
post-shipment refuses a unit that another document delivered, and names the unit |
8 |
post-shipment refuses a Delivered on date in the future |
6, 8, 17 |
post-shipment refuses an out-of-service unit and names the reason |
8 |
| Return with 3 units On Rent creates a Draft receipt with 3 lines; receiving 1 at location B with "Hydraulic leak" makes it Returned, moves the asset to B and shows In Maintenance | 7, 10, 18, 27 |
| A returned Advance-billed Rental line gets the same early-return adjustment as today; a test pins the periods against the old path | 4, 5, 10 |
A Sale line cannot post without Return To; with Inventory it writes the same itemLedger row and journal as today |
10, 18 |
| The per-unit Return shortcut creates a one-unit Draft receipt that posts in 2 clicks | 7, 16, 23, 27 |
Voiding a rental shipment returns its units to Pending and clears deliveredAt and meterOut; a posted Accrual row blocks the void |
6, 9, 27 |
post-receipt refuses to void a rental receipt with the exact message |
10 |
| Close refuses an agreement with a Draft rental receipt that has a line, and names the receipt | 6, 11 |
| Inventory → Shipments lists the rental shipment with source "Rental Agreement", linked to the agreement | 12, 19, 27 |
| The rental shipment's PDF prints a Delivery Ticket with the 3 delivered units and their serial numbers | 20, 27 |
A sales order shipment with a fixed-asset line posts as before; rentalAgreementLineId stays null |
3, 24, 27 |
A Sale line returned to Inventory on a receipt at location B books its itemLedger row at B (spec Q7) |
5, 10 |
A Pending unit released with a backdated date stops billing and frees the unit |
6, 22, 23, 27 |
A Pending unit on a receipt is unticked by default; ticking it and posting returns it |
7, 10, 18, 27 |
Release is refused for a line that is not Pending and for a future date |
6, 22, 23 |
Self-check
- STE-80 review pass done. Instructions stay within 20 words and facts within 25. No passive hides its actor. Sequences are numbered lists. Each concept has one term ("rental shipment", "rental receipt", "asset line", "unit", "release"). No "etc.", "various", "as appropriate" or "TBD".
- Every task has exact paths, exact commands and an expected output.
- Both migration tasks follow the hard rules, and Task 3 runs
generate:typesafter them. - Every UI task names its precedent file.
- No whole-repo typecheck.
- Every acceptance criterion maps to a task, and the last task is browser verification through
/test.